repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
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/benkoehlL/Qiskit_Playground
benkoehlL
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit import numpy as np import os from matplotlib.pyplot import draw, show import shutil ''' LaTex_folder = str(os.getcwd())+'/Latex_quantum_gates/circuits/' if not os.path.exists(LaTex_folder): os.makedirs(LaTex_folder) ## A decomposition of the CU(theta,phi,lambda, alpha) qr = QuantumRegister(2,name='q') circuit = QuantumCircuit(qr) circuit.rz(np.pi/2,qr[1]) # angle (lambda+pi)/2 circuit.cx(qr[0],qr[1]) circuit.rz(-np.pi/2,qr[1]) # angle -(lambda+pi)/2 circuit.ry(np.pi/4,qr[1]) # angle theta/2 circuit.cx(qr[0],qr[1]) circuit.ry(-np.pi/4,qr[1]) # angle -theta/2 circuit.rz(np.pi/8,qr[1]) # angle (phi+pi)/2 circuit.cx(qr[0],qr[1]) circuit.rz(-np.pi/8,qr[1]) # angle -(phi+pi)/2 circuit.cx(qr[0],qr[1]) # global phase gate to target qubit circuit.x(qr[1]) circuit.u(0,0,np.pi/16,qr[1]) # angle alpha circuit.x(qr[1]) circuit.u(0,0,np.pi/16,qr[1]) # angle alpha LaTex_code = circuit.draw(output='latex_source', initial_state=True, justify=None) # draw the circuit f_name = 'CU_Gate.tex' with open(LaTex_folder+f_name, 'w') as f: f.write(LaTex_code) ## The qiskit CU-gate circuit = QuantumCircuit(qr) circuit.cu(np.pi/4,np.pi/8,np.pi/2,np.pi/16,qr[0],qr[1]) LaTex_code = circuit.draw(output='latex_source', initial_state=True, justify=None) # draw the circuit f_name = 'CU_Gate_compact.tex' with open(LaTex_folder+f_name, 'w') as f: f.write(LaTex_code) ''' QASM_folder = str(os.getcwd())+'/OpenQASM_pictures/' if not os.path.exists(QASM_folder): os.makedirs(QASM_folder) n= 5 qr = QuantumRegister(n,name='q') cr = ClassicalRegister(n,name='c') circuit = QuantumCircuit(qr, cr) for q in qr: circuit.h(q) for i in range(len(qr)): circuit.cx(qr[i],qr[(i+1)%len(qr)]) circuit.u(np.pi/8,np.pi/4,0,qr[0]) circuit.rx(np.pi/2,qr[0]) circuit.ccx(qr[0],qr[1],qr[2]) circuit.toffoli(qr[0],qr[1],qr[2]) circuit.measure(qr,cr) circuit.sdg(qr[0]) qasm = circuit.qasm() print(qasm)
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!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/abbarreto/qiskit2
abbarreto
%run init.ipynb %run init.ipynb p = symbols('p') Ubf = Matrix([[sqrt(1-p),-sqrt(p),0,0],[0,0,sqrt(p),sqrt(1-p)],[0,0,sqrt(1-p),-sqrt(p)],[sqrt(p),sqrt(1-p),0,0]]) Ubf Ubf*Ubf.T, Ubf.T*Ubf g = symbols('gamma') Uad = Matrix([[sqrt(1-g),0,0,sqrt(g)],[0,1,0,0],[0,0,1,0],[-sqrt(g),0,0,sqrt(1-g)]]) Uad, Uad*Uad.T, Uad.T*Uad
https://github.com/rickapocalypse/final_paper_qiskit_sat
rickapocalypse
from qiskit import * import matplotlib.pyplot as plt from qiskit.visualization import plot_histogram from qiskit.tools.monitor import job_monitor from qiskit import IBMQ from qiskit.ignis.mitigation.measurement import (complete_meas_cal, CompleteMeasFitter) IBMQ.load_account() nqbit = 3 circuit = QuantumCircuit(nqbit, nqbit) circuit.h(0) circuit.cx(0,1) circuit.cx(1,2) circuit.measure(range(nqbit), range(nqbit)) simulator = Aer.get_backend('qasm_simulator') sim_result = execute(circuit, backend= simulator, shots = 1024).result() plot_histogram(sim_result.get_counts(circuit)) IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') device = provider.get_backend('ibmq_lima') job = execute(circuit, backend = device, shots = 1024) print(job.job_id()) job_monitor(job) device_result = job.result() plot_histogram(device_result.get_counts(circuit)) cal_circuits,state_labels = complete_meas_cal(qr = circuit.qregs[0], circlabel = 'measerrormitigationcal') cal_job = execute(cal_circuits, backend = device, shots = 1024, optimization_level = 0) print(cal_job.job_id()) job_monitor(cal_job) cal_results = cal_job.result() plot_histogram(cal_results.get_counts(cal_circuits[3])) meas_fitter = CompleteMeasFitter(cal_results, state_labels) meas_filter = meas_fitter.filter mitigated_result = meas_filter.apply(device_result) device_counts = device_result.get_counts(circuit) mitigated_counts = mitigated_result.get_counts(circuit) plot_histogram([device_counts, mitigated_counts], legend = ['dispositivo , ruido', 'dispositivo, mitigado']) circuit2 =QuantumCircuit(3,3) circuit2.x(1) circuit2.h(0) circuit2.cx(0,1) circuit2.cx(1,2) circuit2.measure([0,1,2],[0,1,2]) sim_counts = execute(circuit2, backend=simulator,shots=1024).result().get_counts(circuit2) device_counts_2 = execute(circuit2, backend= device, shots= 1024).result().get_counts(circuit2) plot_histogram(device_counts_2) device_mitigated_counts_2 = meas_filter.apply(device_counts_2) plot_histogram([device_mitigated_counts_2,sim_counts]) plt.show()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
p = 0.2 import numpy as np from qiskit.circuit import QuantumCircuit class BernoulliA(QuantumCircuit): """A circuit representing the Bernoulli A operator.""" def __init__(self, probability): super().__init__(1) # circuit on 1 qubit theta_p = 2 * np.arcsin(np.sqrt(probability)) self.ry(theta_p, 0) class BernoulliQ(QuantumCircuit): """A circuit representing the Bernoulli Q operator.""" def __init__(self, probability): super().__init__(1) # circuit on 1 qubit self._theta_p = 2 * np.arcsin(np.sqrt(probability)) self.ry(2 * self._theta_p, 0) def power(self, k): # implement the efficient power of Q q_k = QuantumCircuit(1) q_k.ry(2 * k * self._theta_p, 0) return q_k A = BernoulliA(p) Q = BernoulliQ(p) from qiskit.algorithms import EstimationProblem problem = EstimationProblem( state_preparation=A, # A operator grover_operator=Q, # Q operator objective_qubits=[0], # the "good" state Psi1 is identified as measuring |1> in qubit 0 ) from qiskit.primitives import Sampler sampler = Sampler() from qiskit.algorithms import AmplitudeEstimation ae = AmplitudeEstimation( num_eval_qubits=3, # the number of evaluation qubits specifies circuit width and accuracy sampler=sampler, ) ae_result = ae.estimate(problem) print(ae_result.estimation) import matplotlib.pyplot as plt # plot estimated values gridpoints = list(ae_result.samples.keys()) probabilities = list(ae_result.samples.values()) plt.bar(gridpoints, probabilities, width=0.5 / len(probabilities)) plt.axvline(p, color="r", ls="--") plt.xticks(size=15) plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15) plt.title("Estimated Values", size=15) plt.ylabel("Probability", size=15) plt.xlabel(r"Amplitude $a$", size=15) plt.ylim((0, 1)) plt.grid() plt.show() print("Interpolated MLE estimator:", ae_result.mle) ae_circuit = ae.construct_circuit(problem) ae_circuit.decompose().draw( "mpl", style="iqx" ) # decompose 1 level: exposes the Phase estimation circuit! from qiskit import transpile basis_gates = ["h", "ry", "cry", "cx", "ccx", "p", "cp", "x", "s", "sdg", "y", "t", "cz"] transpile(ae_circuit, basis_gates=basis_gates, optimization_level=2).draw("mpl", style="iqx") from qiskit.algorithms import IterativeAmplitudeEstimation iae = IterativeAmplitudeEstimation( epsilon_target=0.01, # target accuracy alpha=0.05, # width of the confidence interval sampler=sampler, ) iae_result = iae.estimate(problem) print("Estimate:", iae_result.estimation) iae_circuit = iae.construct_circuit(problem, k=3) iae_circuit.draw("mpl", style="iqx") from qiskit.algorithms import MaximumLikelihoodAmplitudeEstimation mlae = MaximumLikelihoodAmplitudeEstimation( evaluation_schedule=3, # log2 of the maximal Grover power sampler=sampler, ) mlae_result = mlae.estimate(problem) print("Estimate:", mlae_result.estimation) from qiskit.algorithms import FasterAmplitudeEstimation fae = FasterAmplitudeEstimation( delta=0.01, # target accuracy maxiter=3, # determines the maximal power of the Grover operator sampler=sampler, ) fae_result = fae.estimate(problem) print("Estimate:", fae_result.estimation) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Tests for Layer2Q implementation. """ import unittest from random import randint import test.python.transpiler.aqc.fast_gradient.utils_for_testing as tut import numpy as np import qiskit.transpiler.synthesis.aqc.fast_gradient.layer as lr from qiskit.transpiler.synthesis.aqc.fast_gradient.pmatrix import PMatrix from qiskit.test import QiskitTestCase class TestLayer2q(QiskitTestCase): """ Tests for Layer2Q class. """ max_num_qubits = 5 # maximum number of qubits in tests num_repeats = 50 # number of repetitions in tests def setUp(self): super().setUp() np.random.seed(0x0696969) def test_layer2q_matrix(self): """ Tests: (1) the correctness of Layer2Q matrix construction; (2) matrix multiplication interleaved with permutations. """ mat_kind = "complex" _eps = 100.0 * np.finfo(float).eps max_rel_err = 0.0 for n in range(2, self.max_num_qubits + 1): dim = 2**n iden = tut.eye_int(n) for j in range(n): for k in range(n): if j == k: continue m_mat = tut.rand_matrix(dim=dim, kind=mat_kind) t_mat, g_mat = tut.make_test_matrices4x4(n=n, j=j, k=k, kind=mat_kind) lmat = lr.Layer2Q(num_qubits=n, j=j, k=k, g4x4=g_mat) g2, perm, inv_perm = lmat.get_attr() self.assertTrue(m_mat.dtype == t_mat.dtype == g_mat.dtype == g2.dtype) self.assertTrue(np.all(g_mat == g2)) self.assertTrue(np.all(iden[perm].T == iden[inv_perm])) g_mat = np.kron(tut.eye_int(n - 2), g_mat) # T == P^t @ G @ P. err = tut.relative_error(t_mat, iden[perm].T @ g_mat @ iden[perm]) self.assertLess(err, _eps, "err = {:0.16f}".format(err)) max_rel_err = max(max_rel_err, err) # Multiplication by permutation matrix of the left can be # replaced by row permutations. tm = t_mat @ m_mat err1 = tut.relative_error(iden[perm].T @ g_mat @ m_mat[perm], tm) err2 = tut.relative_error((g_mat @ m_mat[perm])[inv_perm], tm) # Multiplication by permutation matrix of the right can be # replaced by column permutations. mt = m_mat @ t_mat err3 = tut.relative_error(m_mat @ iden[perm].T @ g_mat @ iden[perm], mt) err4 = tut.relative_error((m_mat[:, perm] @ g_mat)[:, inv_perm], mt) self.assertTrue( err1 < _eps and err2 < _eps and err3 < _eps and err4 < _eps, "err1 = {:f}, err2 = {:f}, " "err3 = {:f}, err4 = {:f}".format(err1, err2, err3, err4), ) max_rel_err = max(max_rel_err, err1, err2, err3, err4) def test_pmatrix_class(self): """ Test the class PMatrix. """ _eps = 100.0 * np.finfo(float).eps mat_kind = "complex" max_rel_err = 0.0 for n in range(2, self.max_num_qubits + 1): dim = 2**n tmp1 = np.ndarray((dim, dim), dtype=np.cfloat) tmp2 = tmp1.copy() for _ in range(self.num_repeats): j0 = randint(0, n - 1) k0 = (j0 + randint(1, n - 1)) % n j1 = randint(0, n - 1) k1 = (j1 + randint(1, n - 1)) % n j2 = randint(0, n - 1) k2 = (j2 + randint(1, n - 1)) % n j3 = randint(0, n - 1) k3 = (j3 + randint(1, n - 1)) % n j4 = randint(0, n - 1) k4 = (j4 + randint(1, n - 1)) % n t0, g0 = tut.make_test_matrices4x4(n=n, j=j0, k=k0, kind=mat_kind) t1, g1 = tut.make_test_matrices4x4(n=n, j=j1, k=k1, kind=mat_kind) t2, g2 = tut.make_test_matrices4x4(n=n, j=j2, k=k2, kind=mat_kind) t3, g3 = tut.make_test_matrices4x4(n=n, j=j3, k=k3, kind=mat_kind) t4, g4 = tut.make_test_matrices4x4(n=n, j=j4, k=k4, kind=mat_kind) c0 = lr.Layer2Q(num_qubits=n, j=j0, k=k0, g4x4=g0) c1 = lr.Layer2Q(num_qubits=n, j=j1, k=k1, g4x4=g1) c2 = lr.Layer2Q(num_qubits=n, j=j2, k=k2, g4x4=g2) c3 = lr.Layer2Q(num_qubits=n, j=j3, k=k3, g4x4=g3) c4 = lr.Layer2Q(num_qubits=n, j=j4, k=k4, g4x4=g4) m_mat = tut.rand_matrix(dim=dim, kind=mat_kind) ttmtt = t0 @ t1 @ m_mat @ np.conj(t2).T @ np.conj(t3).T pmat = PMatrix(n) pmat.set_matrix(m_mat) pmat.mul_left_q2(layer=c1, temp_mat=tmp1) pmat.mul_left_q2(layer=c0, temp_mat=tmp1) pmat.mul_right_q2(layer=c2, temp_mat=tmp1) pmat.mul_right_q2(layer=c3, temp_mat=tmp1) alt_ttmtt = pmat.finalize(temp_mat=tmp1) err1 = tut.relative_error(alt_ttmtt, ttmtt) self.assertLess(err1, _eps, "relative error: {:f}".format(err1)) prod = np.cfloat(np.trace(ttmtt @ t4)) alt_prod = pmat.product_q2(layer=c4, tmp1=tmp1, tmp2=tmp2) err2 = abs(alt_prod - prod) / abs(prod) self.assertLess(err2, _eps, "relative error: {:f}".format(err2)) max_rel_err = max(max_rel_err, err1, err2) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
https://github.com/muehlhausen/vqls-bachelor-thesis
muehlhausen
from qiskit import ( QuantumCircuit, QuantumRegister, ClassicalRegister, IBMQ, Aer, execute, transpile, assemble ) from qiskit.circuit import Gate, Instruction from qiskit.quantum_info.operators import Operator from qiskit.extensions import ZGate, YGate, XGate, IGate from scipy.optimize import ( minimize, basinhopping, differential_evolution, shgo, dual_annealing ) import random import numpy as np import cmath from typing import List, Set, Dict, Tuple, Optional, Union """ ######### Global Parameters Those parameters are required by almost all functions but do not need to be changed during runtime. As one might want to change them between program executions it is sensible to have them accesible and in one place. """ class GlobalParameters: def _init_alpha_randomly(self) -> List[float]: """ This function initalizes alpha randomly. """ # how many parameters are required n_alpha_i = self.n_qubits + self.n_layers * (self.n_qubits-1) * 2 alpha_rand = [float(random.randint(0, 6283))/1000 for _ in range(n_alpha_i)] return alpha_rand def _decompose_asGate(self, gate: str) -> List[Gate]: """ This function returns a list of Gate-Objects of length n_qubits. The first item is the Gate applied to the first qubit, the last item is the Gate applied to the last qubit. """ dec_asGate: List[Gate] = [] for i in range(self.n_qubits): temp = QuantumCircuit(self.n_qubits) if gate == "Z": temp.z(i) elif gate == "Y": temp.y(i) elif gate == "X": temp.x(i) elif gate == "Id": temp.x(i) temp.x(i) elif gate == "ZY": temp.z(i) temp.y(i) elif gate == "YZ": temp.y(i) temp.z(i) temp.to_gate() dec_asGate.append(temp) return dec_asGate def _decompositions(self): """ This helper function is used to prepare some lists with standard decompositions that might be used to set together A. Those lists are stored in the class. """ # ZY Gates self.decomposition_asGate_YZ = self._decompose_asGate("YZ") self.decomposition_adjoint_YZ = self._decompose_asGate("ZY") # Identity Gates self.decomposition_asGate_Id = self._decompose_asGate("Id") self.decomposition_adjoint_Id = self.decomposition_asGate_Id def __init__(self, n_qubits: int, n_layers: int, coefficients: List[complex], IBMQ_TOKEN: str, COBYLA_maxiter: int = 150, IBMQ_shots: int = 4096, IBMQ_backend: str = 'statevector_simulator', method_minimization: str = 'COBYLA', ): self.n_qubits = n_qubits # alpha has form: [[0th sublayer], [1st sublayer], [2nd sublayer], ... ] self.n_layers = n_layers self.n_sublayers = 1 + 2 * self.n_layers self.coefficients = coefficients self.coefficients_conjugate = [np.conjugate(coeff) for coeff in self.coefficients] self.COBYLA_maxiter = COBYLA_maxiter self.method_minimization = method_minimization """ Preparing IBMQ """ self.IBMQ_load_account = IBMQ.enable_account(IBMQ_TOKEN) self.IBMQ_account = IBMQ.save_account(IBMQ_TOKEN) self.IBMQ_provider = IBMQ.load_account() self.IBMQ_backend = self.IBMQ_provider.backend.ibmq_manila self.IBMQ_shots = IBMQ_shots # initialize the parameters for the Ansatz randomly self.alpha_0 = self._init_alpha_randomly() self._decompositions() """ Only things below this line require user interaction in the classes code (normally). """ """ The following lines present an example on how to define A and its decomposition. """ self.decomposition_asGate = self.decomposition_asGate_Id self.decomposition_adjoint = self.decomposition_adjoint_Id # This instance of the class is imported and used by all other modules. # Use it to model your physcal problem. # To change A or its decomposition you have to modify the code of the class itself. params = GlobalParameters( n_qubits=4, n_layers=2, coefficients=[complex(0, 0), complex(0, 0), complex(1, 0), complex(0, 0)], IBMQ_TOKEN="Insert your token here!", COBYLA_maxiter=100, IBMQ_shots=8192 )
https://github.com/entropicalabs/OpenQAOA-Challenge---Qiskit-Fall-Fest-2022-Mexico
entropicalabs
from openqaoa.problems.problem import NumberPartition np = NumberPartition(numbers=[1,2,3]) np_qubo = np.get_qubo_problem() # visualize the QUBO form on a graph from openqaoa.utilities import plot_graph, graph_from_hamiltonian #extract Hamiltonain cost_hamil = np_qubo.hamiltonian #convert Hamiltonian to graph cost_gr = graph_from_hamiltonian(cost_hamil) #plot the graph plot_graph(cost_gr) from openqaoa.workflows.optimizer import QAOA # Initialise QAOA using the default values q = QAOA() # Complile the QAOA workflow q.compile(np_qubo) # Optimise the problem! q.optimize() q.results.plot_probabilities() # Initialise QAOA q = QAOA() q.compile(np_qubo) q.variate_params # Initialise QAOA q = QAOA() q.set_circuit_properties(p=1, param_type='standard', init_type='rand') q.compile(np_qubo) q.variate_params import numpy def my_submission_function(p): """ Note that the number of betas and gammas depend on the number of layers `p`! Also, in OpenQAOA there are several parametrisation techiques which will change the structure of the return of `my_submission_function` For more details: https://el-openqaoa.readthedocs.io/en/latest/notebooks/05_advanced_parameterization.html """ return { 'betas' : [numpy.random.randn() for i in range(p)], 'gammas' : [numpy.random.randn() for i in range(p)]} p = 2 q_submission = QAOA() q_submission.set_circuit_properties(p=p, param_type='standard', init_type='custom', variational_params_dict=my_submission_function(2)) my_submission_function(2) q_submission.compile(np_qubo) q_submission.optimize() q_submission.results.plot_cost() q_submission.results.plot_probabilities() np_input = [numpy.random.randint(30) for i in range(10)] np_input
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# A jupyter notebook is composed by one or more cells. # A cell is used to write and execute your codes. # A cell is also used to write descriptions, notes, formulas, etc. # You can format your descriptions by using HTML or LaTex codes. # During this tutorial, you are expected to write only python codes. # Interested readers may also use HTML and LaTex, but it is not necesary to complete this tutorial. # # We explain basic usage of cells in Jupyter notebooks here # # This is the first cell in this notebook. # You can write Python code here, # and then EXECUTE/RUN it by # 1) pressing SHIFT+ENTER # 2) clicking "Run" on the menu # here is a few lines of python codes print("hello world") str="*" for i in range(5): print(str) str+="*" # after executing this cell, you will see the outcomes immedeately after this cell # you may change the range above and re-run this cell # after executing this cell, you can continue with the next cell # This is the second cell. # # When you double click after the last cell, a new cell appears automatically. # It automatically happens when you execute the last cell as well. # # By using menu item "Insert", you may also add a new cell before or after the selected cell. # When a cell is selected, you may delete it by using menu item "Edit". # # As you may notice, there are other editing options under "Edit", # for example, copy/cut-paste cells and split-merge cells.
https://github.com/bayesian-randomized-benchmarking/qiskit-advocates-bayes-RB
bayesian-randomized-benchmarking
import numpy as np import copy import qiskit_experiments as qe import qiskit.circuit.library as circuits rb = qe.randomized_benchmarking # for retrieving gate calibration from datetime import datetime import qiskit.providers.aer.noise.device as dv # import the bayesian packages import pymc3 as pm import arviz as az import bayesian_fitter as bf simulation = True # make your choice here if simulation: from qiskit.providers.aer import AerSimulator from qiskit.test.mock import FakeParis backend = AerSimulator.from_backend(FakeParis()) else: from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = provider.get_backend('ibmq_lima') # type here hardware backend import importlib importlib.reload(bf) lengths = np.arange(1, 1000, 100) num_samples = 10 seed = 1010 qubits = [0] # Run an RB experiment on qubit 0 exp1 = rb.StandardRB(qubits, lengths, num_samples=num_samples, seed=seed) expdata1 = exp1.run(backend) # View result data print(expdata1) physical_qubits = [0] nQ = len(qubits) scale = (2 ** nQ - 1) / 2 ** nQ interleaved_gate ='' # retrieve from the frequentist model (fm) analysis # some values,including priors, for the bayesian analysis perr_fm, popt_fm, epc_est_fm, epc_est_fm_err, experiment_type = bf.retrieve_from_lsf(expdata1) EPG_dic = expdata1._analysis_results[0]['EPG'][qubits[0]] # get count data Y = bf.get_GSP_counts(expdata1._data, len(lengths),range(num_samples)) shots = bf.guess_shots(Y) #build model pooled_model = bf.get_bayesian_model(model_type="pooled",Y=Y,shots=shots,m_gates=lengths, mu_AB=[popt_fm[0],popt_fm[2]],cov_AB=[perr_fm[0],perr_fm[2]], alpha_ref=popt_fm[1], alpha_lower=popt_fm[1]-6*perr_fm[1], alpha_upper=min(1.-1.E-6,popt_fm[1]+6*perr_fm[1])) pm.model_to_graphviz(pooled_model) trace_p = bf.get_trace(pooled_model, target_accept = 0.95) # backend's recorded EPG print(rb.RBUtils.get_error_dict_from_backend(backend, qubits)) bf.RB_bayesian_results(pooled_model, trace_p, lengths, epc_est_fm, epc_est_fm_err, experiment_type, scale, num_samples, Y, shots, physical_qubits, interleaved_gate, backend, EPG_dic = EPG_dic) #build model original_model = bf.get_bayesian_model(model_type="h_sigma",Y=Y,shots=shots,m_gates=lengths, mu_AB=[popt_fm[0],popt_fm[2]],cov_AB=[perr_fm[0],perr_fm[2]], alpha_ref=popt_fm[1], alpha_lower=popt_fm[1]-6*perr_fm[1], alpha_upper=min(1.-1.E-6,popt_fm[1]+6*perr_fm[1]), sigma_theta=0.001,sigma_theta_l=0.0005,sigma_theta_u=0.0015) pm.model_to_graphviz(original_model) trace_o = bf.get_trace(original_model, target_accept = 0.95) # backend's recorded EPG print(rb.RBUtils.get_error_dict_from_backend(backend, qubits)) bf.RB_bayesian_results(original_model, trace_o, lengths, epc_est_fm, epc_est_fm_err, experiment_type, scale, num_samples, Y, shots, physical_qubits, interleaved_gate, backend, EPG_dic = EPG_dic)
https://github.com/Glebegor/Quantum-programming-algorithms
Glebegor
import numpy as np import networkx as nx import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble from qiskit.quantum_info import Statevector from qiskit.aqua.algorithms import NumPyEigensolver from qiskit.quantum_info import Pauli from qiskit.aqua.operators import op_converter from qiskit.aqua.operators import WeightedPauliOperator from qiskit.visualization import plot_histogram from qiskit.providers.aer.extensions.snapshot_statevector import * from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost from utils import mapeo_grafo from collections import defaultdict from operator import itemgetter from scipy.optimize import minimize import matplotlib.pyplot as plt LAMBDA = 10 SEED = 10 SHOTS = 10000 # returns the bit index for an alpha and j def bit(i_city, l_time, num_cities): return i_city * num_cities + l_time # e^(cZZ) def append_zz_term(qc, q_i, q_j, gamma, constant_term): qc.cx(q_i, q_j) qc.rz(2*gamma*constant_term,q_j) qc.cx(q_i, q_j) # e^(cZ) def append_z_term(qc, q_i, gamma, constant_term): qc.rz(2*gamma*constant_term, q_i) # e^(cX) def append_x_term(qc,qi,beta): qc.rx(-2*beta, qi) def get_not_edge_in(G): N = G.number_of_nodes() not_edge = [] for i in range(N): for j in range(N): if i != j: buffer_tupla = (i,j) in_edges = False for edge_i, edge_j in G.edges(): if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)): in_edges = True if in_edges == False: not_edge.append((i, j)) return not_edge def get_classical_simplified_z_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # z term # z_classic_term = [0] * N**2 # first term for l in range(N): for i in range(N): z_il_index = bit(i, l, N) z_classic_term[z_il_index] += -1 * _lambda # second term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_jl z_jl_index = bit(j, l, N) z_classic_term[z_jl_index] += _lambda / 2 # third term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_ij z_ij_index = bit(i, j, N) z_classic_term[z_ij_index] += _lambda / 2 # fourth term not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 4 # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) z_classic_term[z_jlplus_index] += _lambda / 4 # fifthy term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) z_classic_term[z_il_index] += weight_ij / 4 # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) z_classic_term[z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) z_classic_term[z_il_index] += weight_ji / 4 # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) z_classic_term[z_jlplus_index] += weight_ji / 4 return z_classic_term def tsp_obj_2(x, G,_lambda): # obtenemos el valor evaluado en f(x_1, x_2,... x_n) not_edge = get_not_edge_in(G) N = G.number_of_nodes() tsp_cost=0 #Distancia weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # x_il x_il_index = bit(edge_i, l, N) # x_jlplus l_plus = (l+1) % N x_jlplus_index = bit(edge_j, l_plus, N) tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij # add order term because G.edges() do not include order tuples # # x_i'l x_il_index = bit(edge_j, l, N) # x_j'lplus x_jlplus_index = bit(edge_i, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji #Constraint 1 for l in range(N): penal1 = 1 for i in range(N): x_il_index = bit(i, l, N) penal1 -= int(x[x_il_index]) tsp_cost += _lambda * penal1**2 #Contstraint 2 for i in range(N): penal2 = 1 for l in range(N): x_il_index = bit(i, l, N) penal2 -= int(x[x_il_index]) tsp_cost += _lambda*penal2**2 #Constraint 3 for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # x_il x_il_index = bit(i, l, N) # x_j(l+1) l_plus = (l+1) % N x_jlplus_index = bit(j, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda return tsp_cost def get_classical_simplified_zz_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # zz term # zz_classic_term = [[0] * N**2 for i in range(N**2) ] # first term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) # z_jl z_jl_index = bit(j, l, N) zz_classic_term[z_il_index][z_jl_index] += _lambda / 2 # second term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) # z_ij z_ij_index = bit(i, j, N) zz_classic_term[z_il_index][z_ij_index] += _lambda / 2 # third term not_edge = get_not_edge_in(G) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4 # fourth term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4 return zz_classic_term def get_classical_simplified_hamiltonian(G, _lambda): # z term # z_classic_term = get_classical_simplified_z_term(G, _lambda) # zz term # zz_classic_term = get_classical_simplified_zz_term(G, _lambda) return z_classic_term, zz_classic_term def get_cost_circuit(G, gamma, _lambda): N = G.number_of_nodes() N_square = N**2 qc = QuantumCircuit(N_square,N_square) z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda) # z term for i in range(N_square): if z_classic_term[i] != 0: append_z_term(qc, i, gamma, z_classic_term[i]) # zz term for i in range(N_square): for j in range(N_square): if zz_classic_term[i][j] != 0: append_zz_term(qc, i, j, gamma, zz_classic_term[i][j]) return qc def get_mixer_operator(G,beta): N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) for n in range(N**2): append_x_term(qc, n, beta) return qc def get_QAOA_circuit(G, beta, gamma, _lambda): assert(len(beta)==len(gamma)) N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) # init min mix state qc.h(range(N**2)) p = len(beta) for i in range(p): qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda)) qc = qc.compose(get_mixer_operator(G, beta[i])) qc.barrier(range(N**2)) qc.snapshot_statevector("final_state") qc.measure(range(N**2),range(N**2)) return qc def invert_counts(counts): return {k[::-1] :v for k,v in counts.items()} # Sample expectation value def compute_tsp_energy_2(counts, G): energy = 0 get_counts = 0 total_counts = 0 for meas, meas_count in counts.items(): obj_for_meas = tsp_obj_2(meas, G, LAMBDA) energy += obj_for_meas*meas_count total_counts += meas_count mean = energy/total_counts return mean def get_black_box_objective_2(G,p): backend = Aer.get_backend('qasm_simulator') sim = Aer.get_backend('aer_simulator') # function f costo def f(theta): beta = theta[:p] gamma = theta[p:] # Anzats qc = get_QAOA_circuit(G, beta, gamma, LAMBDA) result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result() final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0] state_vector = Statevector(final_state_vector) probabilities = state_vector.probabilities() probabilities_states = invert_counts(state_vector.probabilities_dict()) expected_value = 0 for state,probability in probabilities_states.items(): cost = tsp_obj_2(state, G, LAMBDA) expected_value += cost*probability counts = result.get_counts() mean = compute_tsp_energy_2(invert_counts(counts),G) return mean return f def crear_grafo(cantidad_ciudades): pesos, conexiones = None, None mejor_camino = None while not mejor_camino: pesos, conexiones = rand_graph(cantidad_ciudades) mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False) G = mapeo_grafo(conexiones, pesos) return G, mejor_costo, mejor_camino def run_QAOA(p,ciudades, grafo): if grafo == None: G, mejor_costo, mejor_camino = crear_grafo(ciudades) print("Mejor Costo") print(mejor_costo) print("Mejor Camino") print(mejor_camino) print("Bordes del grafo") print(G.edges()) print("Nodos") print(G.nodes()) print("Pesos") labels = nx.get_edge_attributes(G,'weight') print(labels) else: G = grafo intial_random = [] # beta, mixer Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,np.pi)) # gamma, cost Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,2*np.pi)) init_point = np.array(intial_random) obj = get_black_box_objective_2(G,p) res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True}) print(res_sample) if __name__ == '__main__': # Run QAOA parametros: profundidad p, numero d ciudades, run_QAOA(5, 3, None)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=invalid-name """Tests for Operator matrix linear operator class.""" import unittest import logging import copy from test import combine import numpy as np from ddt import ddt from numpy.testing import assert_allclose import scipy.linalg as la from qiskit import QiskitError from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit.library import HGate, CHGate, CXGate, QFT from qiskit.test import QiskitTestCase from qiskit.transpiler.layout import Layout, TranspileLayout from qiskit.quantum_info.operators import Operator, ScalarOp from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.compiler.transpiler import transpile from qiskit.circuit import Qubit from qiskit.circuit.library import Permutation, PermutationGate logger = logging.getLogger(__name__) class OperatorTestCase(QiskitTestCase): """Test utils for Operator""" # Pauli-matrix unitaries UI = np.eye(2) UX = np.array([[0, 1], [1, 0]]) UY = np.array([[0, -1j], [1j, 0]]) UZ = np.diag([1, -1]) UH = np.array([[1, 1], [1, -1]]) / np.sqrt(2) @classmethod def rand_rho(cls, n): """Return random density matrix""" seed = np.random.randint(0, np.iinfo(np.int32).max) logger.debug("rand_rho default_rng seeded with seed=%s", seed) rng = np.random.default_rng(seed) psi = rng.random(n) + 1j * rng.random(n) rho = np.outer(psi, psi.conj()) rho /= np.trace(rho) return rho @classmethod def rand_matrix(cls, rows, cols=None, real=False): """Return a random matrix.""" seed = np.random.randint(0, np.iinfo(np.int32).max) logger.debug("rand_matrix default_rng seeded with seed=%s", seed) rng = np.random.default_rng(seed) if cols is None: cols = rows if real: return rng.random(size=(rows, cols)) return rng.random(size=(rows, cols)) + 1j * rng.random(size=(rows, cols)) def simple_circuit_no_measure(self): """Return a unitary circuit and the corresponding unitary array.""" qr = QuantumRegister(3) circ = QuantumCircuit(qr) circ.h(qr[0]) circ.x(qr[1]) circ.ry(np.pi / 2, qr[2]) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = Operator(np.kron(y90, np.kron(self.UX, self.UH))) return circ, target def simple_circuit_with_measure(self): """Return a unitary circuit with measurement.""" qr = QuantumRegister(2) cr = ClassicalRegister(2) circ = QuantumCircuit(qr, cr) circ.h(qr[0]) circ.x(qr[1]) circ.measure(qr, cr) return circ @ddt class TestOperator(OperatorTestCase): """Tests for Operator linear operator class.""" def test_init_array_qubit(self): """Test subsystem initialization from N-qubit array.""" # Test automatic inference of qubit subsystems mat = self.rand_matrix(8, 8) op = Operator(mat) assert_allclose(op.data, mat) self.assertEqual(op.dim, (8, 8)) self.assertEqual(op.input_dims(), (2, 2, 2)) self.assertEqual(op.output_dims(), (2, 2, 2)) self.assertEqual(op.num_qubits, 3) op = Operator(mat, input_dims=8, output_dims=8) assert_allclose(op.data, mat) self.assertEqual(op.dim, (8, 8)) self.assertEqual(op.input_dims(), (2, 2, 2)) self.assertEqual(op.output_dims(), (2, 2, 2)) self.assertEqual(op.num_qubits, 3) def test_init_array(self): """Test initialization from array.""" mat = np.eye(3) op = Operator(mat) assert_allclose(op.data, mat) self.assertEqual(op.dim, (3, 3)) self.assertEqual(op.input_dims(), (3,)) self.assertEqual(op.output_dims(), (3,)) self.assertIsNone(op.num_qubits) mat = self.rand_matrix(2 * 3 * 4, 4 * 5) op = Operator(mat, input_dims=[4, 5], output_dims=[2, 3, 4]) assert_allclose(op.data, mat) self.assertEqual(op.dim, (4 * 5, 2 * 3 * 4)) self.assertEqual(op.input_dims(), (4, 5)) self.assertEqual(op.output_dims(), (2, 3, 4)) self.assertIsNone(op.num_qubits) def test_init_array_except(self): """Test initialization exception from array.""" mat = self.rand_matrix(4, 4) self.assertRaises(QiskitError, Operator, mat, input_dims=[4, 2]) self.assertRaises(QiskitError, Operator, mat, input_dims=[2, 4]) self.assertRaises(QiskitError, Operator, mat, input_dims=5) def test_init_operator(self): """Test initialization from Operator.""" op1 = Operator(self.rand_matrix(4, 4)) op2 = Operator(op1) self.assertEqual(op1, op2) def test_circuit_init(self): """Test initialization from a circuit.""" # Test tensor product of 1-qubit gates circuit = QuantumCircuit(3) circuit.h(0) circuit.x(1) circuit.ry(np.pi / 2, 2) op = Operator(circuit) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = np.kron(y90, np.kron(self.UX, self.UH)) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of Controlled-Phase gate lam = np.pi / 4 circuit = QuantumCircuit(2) circuit.cp(lam, 0, 1) op = Operator(circuit) target = np.diag([1, 1, 1, np.exp(1j * lam)]) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of controlled-H gate circuit = QuantumCircuit(2) circuit.ch(0, 1) op = Operator(circuit) target = np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1])) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_instruction_init(self): """Test initialization from a circuit.""" gate = CXGate() op = Operator(gate).data target = gate.to_matrix() global_phase_equivalent = matrix_equal(op, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) gate = CHGate() op = Operator(gate).data had = HGate().to_matrix() target = np.kron(had, np.diag([0, 1])) + np.kron(np.eye(2), np.diag([1, 0])) global_phase_equivalent = matrix_equal(op, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_circuit_init_except(self): """Test initialization from circuit with measure raises exception.""" circuit = self.simple_circuit_with_measure() self.assertRaises(QiskitError, Operator, circuit) def test_equal(self): """Test __eq__ method""" mat = self.rand_matrix(2, 2, real=True) self.assertEqual(Operator(np.array(mat, dtype=complex)), Operator(mat)) mat = self.rand_matrix(4, 4) self.assertEqual(Operator(mat.tolist()), Operator(mat)) def test_data(self): """Test Operator representation string property.""" mat = self.rand_matrix(2, 2) op = Operator(mat) assert_allclose(mat, op.data) def test_to_matrix(self): """Test Operator to_matrix method.""" mat = self.rand_matrix(2, 2) op = Operator(mat) assert_allclose(mat, op.to_matrix()) def test_dim(self): """Test Operator dim property.""" mat = self.rand_matrix(4, 4) self.assertEqual(Operator(mat).dim, (4, 4)) self.assertEqual(Operator(mat, input_dims=[4], output_dims=[4]).dim, (4, 4)) self.assertEqual(Operator(mat, input_dims=[2, 2], output_dims=[2, 2]).dim, (4, 4)) def test_input_dims(self): """Test Operator input_dims method.""" op = Operator(self.rand_matrix(2 * 3 * 4, 4 * 5), input_dims=[4, 5], output_dims=[2, 3, 4]) self.assertEqual(op.input_dims(), (4, 5)) self.assertEqual(op.input_dims(qargs=[0, 1]), (4, 5)) self.assertEqual(op.input_dims(qargs=[1, 0]), (5, 4)) self.assertEqual(op.input_dims(qargs=[0]), (4,)) self.assertEqual(op.input_dims(qargs=[1]), (5,)) def test_output_dims(self): """Test Operator output_dims method.""" op = Operator(self.rand_matrix(2 * 3 * 4, 4 * 5), input_dims=[4, 5], output_dims=[2, 3, 4]) self.assertEqual(op.output_dims(), (2, 3, 4)) self.assertEqual(op.output_dims(qargs=[0, 1, 2]), (2, 3, 4)) self.assertEqual(op.output_dims(qargs=[2, 1, 0]), (4, 3, 2)) self.assertEqual(op.output_dims(qargs=[2, 0, 1]), (4, 2, 3)) self.assertEqual(op.output_dims(qargs=[0]), (2,)) self.assertEqual(op.output_dims(qargs=[1]), (3,)) self.assertEqual(op.output_dims(qargs=[2]), (4,)) self.assertEqual(op.output_dims(qargs=[0, 2]), (2, 4)) self.assertEqual(op.output_dims(qargs=[2, 0]), (4, 2)) def test_reshape(self): """Test Operator reshape method.""" op = Operator(self.rand_matrix(8, 8)) reshaped1 = op.reshape(input_dims=[8], output_dims=[8]) reshaped2 = op.reshape(input_dims=[4, 2], output_dims=[2, 4]) self.assertEqual(op.output_dims(), (2, 2, 2)) self.assertEqual(op.input_dims(), (2, 2, 2)) self.assertEqual(reshaped1.output_dims(), (8,)) self.assertEqual(reshaped1.input_dims(), (8,)) self.assertEqual(reshaped2.output_dims(), (2, 4)) self.assertEqual(reshaped2.input_dims(), (4, 2)) def test_reshape_num_qubits(self): """Test Operator reshape method with num_qubits.""" op = Operator(self.rand_matrix(8, 8), input_dims=(4, 2), output_dims=(2, 4)) reshaped = op.reshape(num_qubits=3) self.assertEqual(reshaped.num_qubits, 3) self.assertEqual(reshaped.output_dims(), (2, 2, 2)) self.assertEqual(reshaped.input_dims(), (2, 2, 2)) def test_reshape_raise(self): """Test Operator reshape method with invalid args.""" op = Operator(self.rand_matrix(3, 3)) self.assertRaises(QiskitError, op.reshape, num_qubits=2) def test_copy(self): """Test Operator copy method""" mat = np.eye(2) with self.subTest("Deep copy"): orig = Operator(mat) cpy = orig.copy() cpy._data[0, 0] = 0.0 self.assertFalse(cpy == orig) with self.subTest("Shallow copy"): orig = Operator(mat) clone = copy.copy(orig) clone._data[0, 0] = 0.0 self.assertTrue(clone == orig) def test_is_unitary(self): """Test is_unitary method.""" # X-90 rotation X90 = la.expm(-1j * 0.5 * np.pi * np.array([[0, 1], [1, 0]]) / 2) self.assertTrue(Operator(X90).is_unitary()) # Non-unitary should return false self.assertFalse(Operator([[1, 0], [0, 0]]).is_unitary()) def test_to_operator(self): """Test to_operator method.""" op1 = Operator(self.rand_matrix(4, 4)) op2 = op1.to_operator() self.assertEqual(op1, op2) def test_conjugate(self): """Test conjugate method.""" matr = self.rand_matrix(2, 4, real=True) mati = self.rand_matrix(2, 4, real=True) op = Operator(matr + 1j * mati) uni_conj = op.conjugate() self.assertEqual(uni_conj, Operator(matr - 1j * mati)) def test_transpose(self): """Test transpose method.""" matr = self.rand_matrix(2, 4, real=True) mati = self.rand_matrix(2, 4, real=True) op = Operator(matr + 1j * mati) uni_t = op.transpose() self.assertEqual(uni_t, Operator(matr.T + 1j * mati.T)) def test_adjoint(self): """Test adjoint method.""" matr = self.rand_matrix(2, 4, real=True) mati = self.rand_matrix(2, 4, real=True) op = Operator(matr + 1j * mati) uni_adj = op.adjoint() self.assertEqual(uni_adj, Operator(matr.T - 1j * mati.T)) def test_compose_except(self): """Test compose different dimension exception""" self.assertRaises(QiskitError, Operator(np.eye(2)).compose, Operator(np.eye(3))) self.assertRaises(QiskitError, Operator(np.eye(2)).compose, 2) def test_compose(self): """Test compose method.""" op1 = Operator(self.UX) op2 = Operator(self.UY) targ = Operator(np.dot(self.UY, self.UX)) self.assertEqual(op1.compose(op2), targ) self.assertEqual(op1 & op2, targ) targ = Operator(np.dot(self.UX, self.UY)) self.assertEqual(op2.compose(op1), targ) self.assertEqual(op2 & op1, targ) def test_dot(self): """Test dot method.""" op1 = Operator(self.UY) op2 = Operator(self.UX) targ = Operator(np.dot(self.UY, self.UX)) self.assertEqual(op1.dot(op2), targ) self.assertEqual(op1 @ op2, targ) targ = Operator(np.dot(self.UX, self.UY)) self.assertEqual(op2.dot(op1), targ) self.assertEqual(op2 @ op1, targ) def test_compose_front(self): """Test front compose method.""" opYX = Operator(self.UY).compose(Operator(self.UX), front=True) matYX = np.dot(self.UY, self.UX) self.assertEqual(opYX, Operator(matYX)) opXY = Operator(self.UX).compose(Operator(self.UY), front=True) matXY = np.dot(self.UX, self.UY) self.assertEqual(opXY, Operator(matXY)) def test_compose_subsystem(self): """Test subsystem compose method.""" # 3-qubit operator mat = self.rand_matrix(8, 8) mat_a = self.rand_matrix(2, 2) mat_b = self.rand_matrix(2, 2) mat_c = self.rand_matrix(2, 2) op = Operator(mat) op1 = Operator(mat_a) op2 = Operator(np.kron(mat_b, mat_a)) op3 = Operator(np.kron(mat_c, np.kron(mat_b, mat_a))) # op3 qargs=[0, 1, 2] targ = np.dot(np.kron(mat_c, np.kron(mat_b, mat_a)), mat) self.assertEqual(op.compose(op3, qargs=[0, 1, 2]), Operator(targ)) self.assertEqual(op.compose(op3([0, 1, 2])), Operator(targ)) self.assertEqual(op & op3([0, 1, 2]), Operator(targ)) # op3 qargs=[2, 1, 0] targ = np.dot(np.kron(mat_a, np.kron(mat_b, mat_c)), mat) self.assertEqual(op.compose(op3, qargs=[2, 1, 0]), Operator(targ)) self.assertEqual(op & op3([2, 1, 0]), Operator(targ)) # op2 qargs=[0, 1] targ = np.dot(np.kron(np.eye(2), np.kron(mat_b, mat_a)), mat) self.assertEqual(op.compose(op2, qargs=[0, 1]), Operator(targ)) self.assertEqual(op & op2([0, 1]), Operator(targ)) # op2 qargs=[2, 0] targ = np.dot(np.kron(mat_a, np.kron(np.eye(2), mat_b)), mat) self.assertEqual(op.compose(op2, qargs=[2, 0]), Operator(targ)) self.assertEqual(op & op2([2, 0]), Operator(targ)) # op1 qargs=[0] targ = np.dot(np.kron(np.eye(4), mat_a), mat) self.assertEqual(op.compose(op1, qargs=[0]), Operator(targ)) self.assertEqual(op & op1([0]), Operator(targ)) # op1 qargs=[1] targ = np.dot(np.kron(np.eye(2), np.kron(mat_a, np.eye(2))), mat) self.assertEqual(op.compose(op1, qargs=[1]), Operator(targ)) self.assertEqual(op & op1([1]), Operator(targ)) # op1 qargs=[2] targ = np.dot(np.kron(mat_a, np.eye(4)), mat) self.assertEqual(op.compose(op1, qargs=[2]), Operator(targ)) self.assertEqual(op & op1([2]), Operator(targ)) def test_dot_subsystem(self): """Test subsystem dot method.""" # 3-qubit operator mat = self.rand_matrix(8, 8) mat_a = self.rand_matrix(2, 2) mat_b = self.rand_matrix(2, 2) mat_c = self.rand_matrix(2, 2) op = Operator(mat) op1 = Operator(mat_a) op2 = Operator(np.kron(mat_b, mat_a)) op3 = Operator(np.kron(mat_c, np.kron(mat_b, mat_a))) # op3 qargs=[0, 1, 2] targ = np.dot(mat, np.kron(mat_c, np.kron(mat_b, mat_a))) self.assertEqual(op.dot(op3, qargs=[0, 1, 2]), Operator(targ)) self.assertEqual(op.dot(op3([0, 1, 2])), Operator(targ)) # op3 qargs=[2, 1, 0] targ = np.dot(mat, np.kron(mat_a, np.kron(mat_b, mat_c))) self.assertEqual(op.dot(op3, qargs=[2, 1, 0]), Operator(targ)) self.assertEqual(op.dot(op3([2, 1, 0])), Operator(targ)) # op2 qargs=[0, 1] targ = np.dot(mat, np.kron(np.eye(2), np.kron(mat_b, mat_a))) self.assertEqual(op.dot(op2, qargs=[0, 1]), Operator(targ)) self.assertEqual(op.dot(op2([0, 1])), Operator(targ)) # op2 qargs=[2, 0] targ = np.dot(mat, np.kron(mat_a, np.kron(np.eye(2), mat_b))) self.assertEqual(op.dot(op2, qargs=[2, 0]), Operator(targ)) self.assertEqual(op.dot(op2([2, 0])), Operator(targ)) # op1 qargs=[0] targ = np.dot(mat, np.kron(np.eye(4), mat_a)) self.assertEqual(op.dot(op1, qargs=[0]), Operator(targ)) self.assertEqual(op.dot(op1([0])), Operator(targ)) # op1 qargs=[1] targ = np.dot(mat, np.kron(np.eye(2), np.kron(mat_a, np.eye(2)))) self.assertEqual(op.dot(op1, qargs=[1]), Operator(targ)) self.assertEqual(op.dot(op1([1])), Operator(targ)) # op1 qargs=[2] targ = np.dot(mat, np.kron(mat_a, np.eye(4))) self.assertEqual(op.dot(op1, qargs=[2]), Operator(targ)) self.assertEqual(op.dot(op1([2])), Operator(targ)) def test_compose_front_subsystem(self): """Test subsystem front compose method.""" # 3-qubit operator mat = self.rand_matrix(8, 8) mat_a = self.rand_matrix(2, 2) mat_b = self.rand_matrix(2, 2) mat_c = self.rand_matrix(2, 2) op = Operator(mat) op1 = Operator(mat_a) op2 = Operator(np.kron(mat_b, mat_a)) op3 = Operator(np.kron(mat_c, np.kron(mat_b, mat_a))) # op3 qargs=[0, 1, 2] targ = np.dot(mat, np.kron(mat_c, np.kron(mat_b, mat_a))) self.assertEqual(op.compose(op3, qargs=[0, 1, 2], front=True), Operator(targ)) # op3 qargs=[2, 1, 0] targ = np.dot(mat, np.kron(mat_a, np.kron(mat_b, mat_c))) self.assertEqual(op.compose(op3, qargs=[2, 1, 0], front=True), Operator(targ)) # op2 qargs=[0, 1] targ = np.dot(mat, np.kron(np.eye(2), np.kron(mat_b, mat_a))) self.assertEqual(op.compose(op2, qargs=[0, 1], front=True), Operator(targ)) # op2 qargs=[2, 0] targ = np.dot(mat, np.kron(mat_a, np.kron(np.eye(2), mat_b))) self.assertEqual(op.compose(op2, qargs=[2, 0], front=True), Operator(targ)) # op1 qargs=[0] targ = np.dot(mat, np.kron(np.eye(4), mat_a)) self.assertEqual(op.compose(op1, qargs=[0], front=True), Operator(targ)) # op1 qargs=[1] targ = np.dot(mat, np.kron(np.eye(2), np.kron(mat_a, np.eye(2)))) self.assertEqual(op.compose(op1, qargs=[1], front=True), Operator(targ)) # op1 qargs=[2] targ = np.dot(mat, np.kron(mat_a, np.eye(4))) self.assertEqual(op.compose(op1, qargs=[2], front=True), Operator(targ)) def test_power(self): """Test power method.""" X90 = la.expm(-1j * 0.5 * np.pi * np.array([[0, 1], [1, 0]]) / 2) op = Operator(X90) self.assertEqual(op.power(2), Operator([[0, -1j], [-1j, 0]])) self.assertEqual(op.power(4), Operator(-1 * np.eye(2))) self.assertEqual(op.power(8), Operator(np.eye(2))) def test_expand(self): """Test expand method.""" mat1 = self.UX mat2 = np.eye(3, dtype=complex) mat21 = np.kron(mat2, mat1) op21 = Operator(mat1).expand(Operator(mat2)) self.assertEqual(op21.dim, (6, 6)) assert_allclose(op21.data, Operator(mat21).data) mat12 = np.kron(mat1, mat2) op12 = Operator(mat2).expand(Operator(mat1)) self.assertEqual(op12.dim, (6, 6)) assert_allclose(op12.data, Operator(mat12).data) def test_tensor(self): """Test tensor method.""" mat1 = self.UX mat2 = np.eye(3, dtype=complex) mat21 = np.kron(mat2, mat1) op21 = Operator(mat2).tensor(Operator(mat1)) self.assertEqual(op21.dim, (6, 6)) assert_allclose(op21.data, Operator(mat21).data) mat12 = np.kron(mat1, mat2) op12 = Operator(mat1).tensor(Operator(mat2)) self.assertEqual(op12.dim, (6, 6)) assert_allclose(op12.data, Operator(mat12).data) def test_power_except(self): """Test power method raises exceptions if not square.""" op = Operator(self.rand_matrix(2, 3)) # Non-integer power raises error self.assertRaises(QiskitError, op.power, 0.5) def test_add(self): """Test add method.""" mat1 = self.rand_matrix(4, 4) mat2 = self.rand_matrix(4, 4) op1 = Operator(mat1) op2 = Operator(mat2) self.assertEqual(op1._add(op2), Operator(mat1 + mat2)) self.assertEqual(op1 + op2, Operator(mat1 + mat2)) self.assertEqual(op1 - op2, Operator(mat1 - mat2)) def test_add_except(self): """Test add method raises exceptions.""" op1 = Operator(self.rand_matrix(2, 2)) op2 = Operator(self.rand_matrix(3, 3)) self.assertRaises(QiskitError, op1._add, op2) def test_add_qargs(self): """Test add method with qargs.""" mat = self.rand_matrix(8, 8) mat0 = self.rand_matrix(2, 2) mat1 = self.rand_matrix(2, 2) op = Operator(mat) op0 = Operator(mat0) op01 = Operator(np.kron(mat1, mat0)) with self.subTest(msg="qargs=[0]"): value = op + op0([0]) target = op + Operator(np.kron(np.eye(4), mat0)) self.assertEqual(value, target) with self.subTest(msg="qargs=[1]"): value = op + op0([1]) target = op + Operator(np.kron(np.kron(np.eye(2), mat0), np.eye(2))) self.assertEqual(value, target) with self.subTest(msg="qargs=[2]"): value = op + op0([2]) target = op + Operator(np.kron(mat0, np.eye(4))) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 1]"): value = op + op01([0, 1]) target = op + Operator(np.kron(np.eye(2), np.kron(mat1, mat0))) self.assertEqual(value, target) with self.subTest(msg="qargs=[1, 0]"): value = op + op01([1, 0]) target = op + Operator(np.kron(np.eye(2), np.kron(mat0, mat1))) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 2]"): value = op + op01([0, 2]) target = op + Operator(np.kron(mat1, np.kron(np.eye(2), mat0))) self.assertEqual(value, target) with self.subTest(msg="qargs=[2, 0]"): value = op + op01([2, 0]) target = op + Operator(np.kron(mat0, np.kron(np.eye(2), mat1))) self.assertEqual(value, target) def test_sub_qargs(self): """Test subtract method with qargs.""" mat = self.rand_matrix(8, 8) mat0 = self.rand_matrix(2, 2) mat1 = self.rand_matrix(2, 2) op = Operator(mat) op0 = Operator(mat0) op01 = Operator(np.kron(mat1, mat0)) with self.subTest(msg="qargs=[0]"): value = op - op0([0]) target = op - Operator(np.kron(np.eye(4), mat0)) self.assertEqual(value, target) with self.subTest(msg="qargs=[1]"): value = op - op0([1]) target = op - Operator(np.kron(np.kron(np.eye(2), mat0), np.eye(2))) self.assertEqual(value, target) with self.subTest(msg="qargs=[2]"): value = op - op0([2]) target = op - Operator(np.kron(mat0, np.eye(4))) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 1]"): value = op - op01([0, 1]) target = op - Operator(np.kron(np.eye(2), np.kron(mat1, mat0))) self.assertEqual(value, target) with self.subTest(msg="qargs=[1, 0]"): value = op - op01([1, 0]) target = op - Operator(np.kron(np.eye(2), np.kron(mat0, mat1))) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 2]"): value = op - op01([0, 2]) target = op - Operator(np.kron(mat1, np.kron(np.eye(2), mat0))) self.assertEqual(value, target) with self.subTest(msg="qargs=[2, 0]"): value = op - op01([2, 0]) target = op - Operator(np.kron(mat0, np.kron(np.eye(2), mat1))) self.assertEqual(value, target) def test_multiply(self): """Test multiply method.""" mat = self.rand_matrix(4, 4) val = np.exp(5j) op = Operator(mat) self.assertEqual(op._multiply(val), Operator(val * mat)) self.assertEqual(val * op, Operator(val * mat)) self.assertEqual(op * val, Operator(mat * val)) def test_multiply_except(self): """Test multiply method raises exceptions.""" op = Operator(self.rand_matrix(2, 2)) self.assertRaises(QiskitError, op._multiply, "s") self.assertRaises(QiskitError, op.__rmul__, "s") self.assertRaises(QiskitError, op._multiply, op) self.assertRaises(QiskitError, op.__rmul__, op) def test_negate(self): """Test negate method""" mat = self.rand_matrix(4, 4) op = Operator(mat) self.assertEqual(-op, Operator(-1 * mat)) def test_equiv(self): """Test negate method""" mat = np.diag([1, np.exp(1j * np.pi / 2)]) phase = np.exp(-1j * np.pi / 4) op = Operator(mat) self.assertTrue(op.equiv(phase * mat)) self.assertTrue(op.equiv(Operator(phase * mat))) self.assertFalse(op.equiv(2 * mat)) def test_reverse_qargs(self): """Test reverse_qargs method""" circ1 = QFT(5) circ2 = circ1.reverse_bits() state1 = Operator(circ1) state2 = Operator(circ2) self.assertEqual(state1.reverse_qargs(), state2) def test_drawings(self): """Test draw method""" qc1 = QFT(5) op = Operator.from_circuit(qc1) with self.subTest(msg="str(operator)"): str(op) for drawtype in ["repr", "text", "latex_source"]: with self.subTest(msg=f"draw('{drawtype}')"): op.draw(drawtype) with self.subTest(msg=" draw('latex')"): op.draw("latex") def test_from_circuit_constructor_no_layout(self): """Test initialization from a circuit using the from_circuit constructor.""" # Test tensor product of 1-qubit gates circuit = QuantumCircuit(3) circuit.h(0) circuit.x(1) circuit.ry(np.pi / 2, 2) op = Operator.from_circuit(circuit) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = np.kron(y90, np.kron(self.UX, self.UH)) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of Controlled-Phase gate lam = np.pi / 4 circuit = QuantumCircuit(2) circuit.cp(lam, 0, 1) op = Operator.from_circuit(circuit) target = np.diag([1, 1, 1, np.exp(1j * lam)]) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of controlled-H gate circuit = QuantumCircuit(2) circuit.ch(0, 1) op = Operator.from_circuit(circuit) target = np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1])) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_from_circuit_constructor_reverse_embedded_layout(self): """Test initialization from a circuit with an embedded reverse layout.""" # Test tensor product of 1-qubit gates circuit = QuantumCircuit(3) circuit.h(2) circuit.x(1) circuit.ry(np.pi / 2, 0) circuit._layout = TranspileLayout( Layout({circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2}), {qubit: index for index, qubit in enumerate(circuit.qubits)}, ) op = Operator.from_circuit(circuit) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = np.kron(y90, np.kron(self.UX, self.UH)) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of Controlled-Phase gate lam = np.pi / 4 circuit = QuantumCircuit(2) circuit.cp(lam, 1, 0) circuit._layout = TranspileLayout( Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}), {qubit: index for index, qubit in enumerate(circuit.qubits)}, ) op = Operator.from_circuit(circuit) target = np.diag([1, 1, 1, np.exp(1j * lam)]) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of controlled-H gate circuit = QuantumCircuit(2) circuit.ch(1, 0) circuit._layout = TranspileLayout( Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}), {qubit: index for index, qubit in enumerate(circuit.qubits)}, ) op = Operator.from_circuit(circuit) target = np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1])) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_from_circuit_constructor_reverse_embedded_layout_from_transpile(self): """Test initialization from a circuit with an embedded final layout.""" # Test tensor product of 1-qubit gates circuit = QuantumCircuit(3) circuit.h(0) circuit.x(1) circuit.ry(np.pi / 2, 2) output = transpile(circuit, initial_layout=[2, 1, 0]) op = Operator.from_circuit(output) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = np.kron(y90, np.kron(self.UX, self.UH)) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_from_circuit_constructor_reverse_embedded_layout_from_transpile_with_registers(self): """Test initialization from a circuit with an embedded final layout.""" # Test tensor product of 1-qubit gates qr = QuantumRegister(3, name="test_reg") circuit = QuantumCircuit(qr) circuit.h(0) circuit.x(1) circuit.ry(np.pi / 2, 2) output = transpile(circuit, initial_layout=[2, 1, 0]) op = Operator.from_circuit(output) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = np.kron(y90, np.kron(self.UX, self.UH)) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_from_circuit_constructor_reverse_embedded_layout_and_final_layout(self): """Test initialization from a circuit with an embedded final layout.""" # Test tensor product of 1-qubit gates qr = QuantumRegister(3, name="test_reg") circuit = QuantumCircuit(qr) circuit.h(2) circuit.x(1) circuit.ry(np.pi / 2, 0) circuit._layout = TranspileLayout( Layout({circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2}), {qubit: index for index, qubit in enumerate(circuit.qubits)}, Layout({circuit.qubits[0]: 1, circuit.qubits[1]: 2, circuit.qubits[2]: 0}), ) circuit.swap(0, 1) circuit.swap(1, 2) op = Operator.from_circuit(circuit) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = np.kron(y90, np.kron(self.UX, self.UH)) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_from_circuit_constructor_reverse_embedded_layout_and_manual_final_layout(self): """Test initialization from a circuit with an embedded final layout.""" # Test tensor product of 1-qubit gates qr = QuantumRegister(3, name="test_reg") circuit = QuantumCircuit(qr) circuit.h(2) circuit.x(1) circuit.ry(np.pi / 2, 0) circuit._layout = TranspileLayout( Layout({circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2}), {qubit: index for index, qubit in enumerate(circuit.qubits)}, ) final_layout = Layout({circuit.qubits[0]: 1, circuit.qubits[1]: 2, circuit.qubits[2]: 0}) circuit.swap(0, 1) circuit.swap(1, 2) op = Operator.from_circuit(circuit, final_layout=final_layout) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = np.kron(y90, np.kron(self.UX, self.UH)) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_from_circuit_constructor_reverse_embedded_layout_ignore_set_layout(self): """Test initialization from a circuit with an ignored embedded reverse layout.""" # Test tensor product of 1-qubit gates circuit = QuantumCircuit(3) circuit.h(2) circuit.x(1) circuit.ry(np.pi / 2, 0) circuit._layout = TranspileLayout( Layout({circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2}), {qubit: index for index, qubit in enumerate(circuit.qubits)}, ) op = Operator.from_circuit(circuit, ignore_set_layout=True).reverse_qargs() y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = np.kron(y90, np.kron(self.UX, self.UH)) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of Controlled-Phase gate lam = np.pi / 4 circuit = QuantumCircuit(2) circuit.cp(lam, 1, 0) circuit._layout = TranspileLayout( Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}), {qubit: index for index, qubit in enumerate(circuit.qubits)}, ) op = Operator.from_circuit(circuit, ignore_set_layout=True).reverse_qargs() target = np.diag([1, 1, 1, np.exp(1j * lam)]) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of controlled-H gate circuit = QuantumCircuit(2) circuit.ch(1, 0) circuit._layout = TranspileLayout( Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}), {qubit: index for index, qubit in enumerate(circuit.qubits)}, ) op = Operator.from_circuit(circuit, ignore_set_layout=True).reverse_qargs() target = np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1])) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_from_circuit_constructor_reverse_user_specified_layout(self): """Test initialization from a circuit with a user specified reverse layout.""" # Test tensor product of 1-qubit gates circuit = QuantumCircuit(3) circuit.h(2) circuit.x(1) circuit.ry(np.pi / 2, 0) layout = Layout({circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2}) op = Operator.from_circuit(circuit, layout=layout) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = np.kron(y90, np.kron(self.UX, self.UH)) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of Controlled-Phase gate lam = np.pi / 4 circuit = QuantumCircuit(2) circuit.cp(lam, 1, 0) layout = Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}) op = Operator.from_circuit(circuit, layout=layout) target = np.diag([1, 1, 1, np.exp(1j * lam)]) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of controlled-H gate circuit = QuantumCircuit(2) circuit.ch(1, 0) layout = Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}) op = Operator.from_circuit(circuit, layout=layout) target = np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1])) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_from_circuit_constructor_ghz_out_of_order_layout(self): """Test an out of order ghz state with a layout set.""" circuit = QuantumCircuit(5) circuit.h(3) circuit.cx(3, 4) circuit.cx(3, 2) circuit.cx(3, 0) circuit.cx(3, 1) circuit._layout = TranspileLayout( Layout( { circuit.qubits[3]: 0, circuit.qubits[4]: 1, circuit.qubits[2]: 2, circuit.qubits[0]: 3, circuit.qubits[1]: 4, } ), {qubit: index for index, qubit in enumerate(circuit.qubits)}, ) result = Operator.from_circuit(circuit) expected = QuantumCircuit(5) expected.h(0) expected.cx(0, 1) expected.cx(0, 2) expected.cx(0, 3) expected.cx(0, 4) expected_op = Operator(expected) self.assertTrue(expected_op.equiv(result)) def test_from_circuit_empty_circuit_empty_layout(self): """Test an out of order ghz state with a layout set.""" circuit = QuantumCircuit() circuit._layout = TranspileLayout(Layout(), {}) op = Operator.from_circuit(circuit) self.assertEqual(Operator([1]), op) def test_from_circuit_constructor_empty_layout(self): """Test an out of order ghz state with a layout set.""" circuit = QuantumCircuit(2) circuit.h(0) circuit.cx(0, 1) layout = Layout() with self.assertRaises(IndexError): Operator.from_circuit(circuit, layout=layout) def test_compose_scalar(self): """Test that composition works with a scalar-valued operator over no qubits.""" base = Operator(np.eye(2, dtype=np.complex128)) scalar = Operator(np.array([[-1.0 + 0.0j]])) composed = base.compose(scalar, qargs=[]) self.assertEqual(composed, Operator(-np.eye(2, dtype=np.complex128))) def test_compose_scalar_op(self): """Test that composition works with an explicit scalar operator over no qubits.""" base = Operator(np.eye(2, dtype=np.complex128)) scalar = ScalarOp(coeff=-1.0 + 0.0j) composed = base.compose(scalar, qargs=[]) self.assertEqual(composed, Operator(-np.eye(2, dtype=np.complex128))) def test_from_circuit_single_flat_default_register_transpiled(self): """Test a transpiled circuit with layout set from default register.""" circuit = QuantumCircuit(5) circuit.h(3) circuit.cx(3, 4) circuit.cx(3, 2) circuit.cx(3, 0) circuit.cx(3, 1) init_layout = Layout( { circuit.qubits[0]: 3, circuit.qubits[1]: 4, circuit.qubits[2]: 1, circuit.qubits[3]: 2, circuit.qubits[4]: 0, } ) tqc = transpile(circuit, initial_layout=init_layout) result = Operator.from_circuit(tqc) self.assertTrue(Operator.from_circuit(circuit).equiv(result)) def test_from_circuit_loose_bits_transpiled(self): """Test a transpiled circuit with layout set from loose bits.""" bits = [Qubit() for _ in range(5)] circuit = QuantumCircuit() circuit.add_bits(bits) circuit.h(3) circuit.cx(3, 4) circuit.cx(3, 2) circuit.cx(3, 0) circuit.cx(3, 1) init_layout = Layout( { circuit.qubits[0]: 3, circuit.qubits[1]: 4, circuit.qubits[2]: 1, circuit.qubits[3]: 2, circuit.qubits[4]: 0, } ) tqc = transpile(circuit, initial_layout=init_layout) result = Operator.from_circuit(tqc) self.assertTrue(Operator(circuit).equiv(result)) def test_from_circuit_multiple_registers_bits_transpiled(self): """Test a transpiled circuit with layout set from loose bits.""" regs = [QuantumRegister(1, name=f"custom_reg-{i}") for i in range(5)] circuit = QuantumCircuit() for reg in regs: circuit.add_register(reg) circuit.h(3) circuit.cx(3, 4) circuit.cx(3, 2) circuit.cx(3, 0) circuit.cx(3, 1) tqc = transpile(circuit, initial_layout=[3, 4, 1, 2, 0]) result = Operator.from_circuit(tqc) self.assertTrue(Operator(circuit).equiv(result)) def test_from_circuit_single_flat_custom_register_transpiled(self): """Test a transpiled circuit with layout set from loose bits.""" circuit = QuantumCircuit(QuantumRegister(5, name="custom_reg")) circuit.h(3) circuit.cx(3, 4) circuit.cx(3, 2) circuit.cx(3, 0) circuit.cx(3, 1) tqc = transpile(circuit, initial_layout=[3, 4, 1, 2, 0]) result = Operator.from_circuit(tqc) self.assertTrue(Operator(circuit).equiv(result)) def test_from_circuit_mixed_reg_loose_bits_transpiled(self): """Test a transpiled circuit with layout set from loose bits.""" bits = [Qubit(), Qubit()] circuit = QuantumCircuit() circuit.add_bits(bits) circuit.add_register(QuantumRegister(3, name="a_reg")) circuit.h(3) circuit.cx(3, 4) circuit.cx(3, 2) circuit.cx(3, 0) circuit.cx(3, 1) init_layout = Layout( { circuit.qubits[0]: 3, circuit.qubits[1]: 4, circuit.qubits[2]: 1, circuit.qubits[3]: 2, circuit.qubits[4]: 0, } ) tqc = transpile(circuit, initial_layout=init_layout) result = Operator.from_circuit(tqc) self.assertTrue(Operator(circuit).equiv(result)) def test_apply_permutation_back(self): """Test applying permutation to the operator, where the operator is applied first and the permutation second.""" op = Operator(self.rand_matrix(64, 64)) pattern = [1, 2, 0, 3, 5, 4] # Consider several methods of computing this operator and show # they all lead to the same result. # Compose the operator with the operator constructed from the # permutation circuit. op2 = op.copy() perm_op = Operator(Permutation(6, pattern)) op2 &= perm_op # Compose the operator with the operator constructed from the # permutation gate. op3 = op.copy() perm_op = Operator(PermutationGate(pattern)) op3 &= perm_op # Modify the operator using apply_permutation method. op4 = op.copy() op4 = op4.apply_permutation(pattern, front=False) self.assertEqual(op2, op3) self.assertEqual(op2, op4) def test_apply_permutation_front(self): """Test applying permutation to the operator, where the permutation is applied first and the operator second""" op = Operator(self.rand_matrix(64, 64)) pattern = [1, 2, 0, 3, 5, 4] # Consider several methods of computing this operator and show # they all lead to the same result. # Compose the operator with the operator constructed from the # permutation circuit. op2 = op.copy() perm_op = Operator(Permutation(6, pattern)) op2 = perm_op & op2 # Compose the operator with the operator constructed from the # permutation gate. op3 = op.copy() perm_op = Operator(PermutationGate(pattern)) op3 = perm_op & op3 # Modify the operator using apply_permutation method. op4 = op.copy() op4 = op4.apply_permutation(pattern, front=True) self.assertEqual(op2, op3) self.assertEqual(op2, op4) def test_apply_permutation_qudits_back(self): """Test applying permutation to the operator with heterogeneous qudit spaces, where the operator O is applied first and the permutation P second. The matrix of the resulting operator is the product [P][O] and corresponds to suitably permuting the rows of O's matrix. """ mat = np.array(range(6 * 6)).reshape((6, 6)) op = Operator(mat, input_dims=(2, 3), output_dims=(2, 3)) perm = [1, 0] actual = op.apply_permutation(perm, front=False) # Rows of mat are ordered to 00, 01, 02, 10, 11, 12; # perm maps these to 00, 10, 20, 01, 11, 21, # while the default ordering is 00, 01, 10, 11, 20, 21. permuted_mat = mat.copy()[[0, 2, 4, 1, 3, 5]] expected = Operator(permuted_mat, input_dims=(2, 3), output_dims=(3, 2)) self.assertEqual(actual, expected) def test_apply_permutation_qudits_front(self): """Test applying permutation to the operator with heterogeneous qudit spaces, where the permutation P is applied first and the operator O is applied second. The matrix of the resulting operator is the product [O][P] and corresponds to suitably permuting the columns of O's matrix. """ mat = np.array(range(6 * 6)).reshape((6, 6)) op = Operator(mat, input_dims=(2, 3), output_dims=(2, 3)) perm = [1, 0] actual = op.apply_permutation(perm, front=True) # Columns of mat are ordered to 00, 01, 02, 10, 11, 12; # perm maps these to 00, 10, 20, 01, 11, 21, # while the default ordering is 00, 01, 10, 11, 20, 21. permuted_mat = mat.copy()[:, [0, 2, 4, 1, 3, 5]] expected = Operator(permuted_mat, input_dims=(3, 2), output_dims=(2, 3)) self.assertEqual(actual, expected) @combine( dims=((2, 3, 4, 5), (5, 2, 4, 3), (3, 5, 2, 4), (5, 3, 4, 2), (4, 5, 2, 3), (4, 3, 2, 5)) ) def test_reverse_qargs_as_apply_permutation(self, dims): """Test reversing qargs by pre- and post-composing with reversal permutation. """ perm = [3, 2, 1, 0] op = Operator( np.array(range(120 * 120)).reshape((120, 120)), input_dims=dims, output_dims=dims ) op2 = op.reverse_qargs() op3 = op.apply_permutation(perm, front=True).apply_permutation(perm, front=False) self.assertEqual(op2, op3) def test_apply_permutation_exceptions(self): """Checks that applying permutation raises an error when dimensions do not match.""" op = Operator( np.array(range(24 * 30)).reshape((24, 30)), input_dims=(6, 5), output_dims=(2, 3, 4) ) with self.assertRaises(QiskitError): op.apply_permutation([1, 0], front=False) with self.assertRaises(QiskitError): op.apply_permutation([2, 1, 0], front=True) def test_apply_permutation_dimensions(self): """Checks the dimensions of the operator after applying permutation.""" op = Operator( np.array(range(24 * 30)).reshape((24, 30)), input_dims=(6, 5), output_dims=(2, 3, 4) ) op2 = op.apply_permutation([1, 2, 0], front=False) self.assertEqual(op2.output_dims(), (4, 2, 3)) op = Operator( np.array(range(24 * 30)).reshape((30, 24)), input_dims=(2, 3, 4), output_dims=(6, 5) ) op2 = op.apply_permutation([2, 0, 1], front=True) self.assertEqual(op2.input_dims(), (4, 2, 3)) if __name__ == "__main__": unittest.main()
https://github.com/DuarteSerranoR/qiskit_quantum_algorithms
DuarteSerranoR
from qiskit import * from qiskit.extensions import * from qiskit.tools.visualization import * def AND(inp1,inp2): """An AND gate. Parameters: inpt1 (str): Input 1, encoded in qubit 0. inpt2 (str): Input 2, encoded in qubit 1. Returns: QuantumCircuit: Output XOR circuit. str: Output value measured from qubit 2. """ qc = QuantumCircuit(3, 1) qc.reset(range(2)) if inp1=='1': qc.x(0) if inp2=='1': qc.x(1) qc.barrier() # this is where your program for quantum AND gate goes qc.ccx(0,1,2) # Toffoli gate qc.barrier() qc.measure(2, 0) # output from qubit 2 is measured # We'll run the program on a simulator backend = Aer.get_backend('aer_simulator') # Since the output will be deterministic, we can use just a single shot to get it job = backend.run(qc, shots=1, memory=True) output = job.result().get_memory()[0] return qc, output ## Test the function for inp1 in ['0', '1']: for inp2 in ['0', '1']: qc, output = AND(inp1, inp2) print('AND with inputs',inp1,inp2,'gives output',output) display(qc.draw()) print('\n') # run the cell to define AND gate for real quantum system from qiskit import * from qiskit.extensions import * from qiskit.tools.visualization import * from qiskit.tools.monitor import job_monitor from qiskit import IBMQ def AND(inp1, inp2, backend, layout): qc = QuantumCircuit(3, 1) qc.reset(range(3)) if inp1=='1': qc.x(0) if inp2=='1': qc.x(1) qc.barrier() qc.ccx(0, 1, 2) qc.barrier() qc.measure(2, 0) qc_trans = transpile(qc, backend, initial_layout=layout, optimization_level=3) job = backend.run(qc_trans, shots=8192) print(job.job_id()) job_monitor(job) output = job.result().get_counts() return qc_trans, output #IBMQ.save_account('') IBMQ.load_account() IBMQ.providers() provider = IBMQ.get_provider('ibm-q') provider.backends() backend_ex = provider.get_backend('ibmq_lima') backend_ex #from qiskit.providers.ibmq import least_busy #backends = provider.backends(filters = lambda x:x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational==True) #backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational==True)) # run this cell backend = provider.get_backend('ibmq_quito') layout=None output_all = [] qc_trans_all = [] prob_all = [] worst = 1 best = 0 for input1 in ['0','1']: for input2 in ['0','1']: qc_trans, output = AND(input1, input2, backend, layout) output_all.append(output) qc_trans_all.append(qc_trans) prob = output[str(int( input1=='1' and input2=='1' ))]/8192 prob_all.append(prob) print('\nProbability of correct answer for inputs',input1,input2) print('{:.2f}'.format(prob) ) print('---------------------------------') worst = min(worst,prob) best = max(best, prob) print('') print('\nThe highest of these probabilities was {:.2f}'.format(best)) print('The lowest of these probabilities was {:.2f}'.format(worst)) print('') print('Transpiled AND gate circuit for ibmq_vigo with input 0 0') print('\nThe circuit depth : {}'.format (qc_trans_all[0].depth())) print('# of nonlocal gates : {}'.format (qc_trans_all[0].num_nonlocal_gates())) print('Probability of correct answer : {:.2f}'.format(prob_all[0]) ) qc_trans_all[0].draw('mpl') print('') print('Transpiled AND gate circuit for ibmq_vigo with input 0 1') print('\nThe circuit depth : {}'.format (qc_trans_all[1].depth())) print('# of nonlocal gates : {}'.format (qc_trans_all[1].num_nonlocal_gates())) print('Probability of correct answer : {:.2f}'.format(prob_all[1]) ) qc_trans_all[1].draw('mpl') print('') print('Transpiled AND gate circuit for ibmq_vigo with input 1 0') print('\nThe circuit depth : {}'.format (qc_trans_all[2].depth())) print('# of nonlocal gates : {}'.format (qc_trans_all[2].num_nonlocal_gates())) print('Probability of correct answer : {:.2f}'.format(prob_all[2]) ) qc_trans_all[2].draw('mpl') print('') print('Transpiled AND gate circuit for ibmq_vigo with input 1 1') print('\nThe circuit depth : {}'.format (qc_trans_all[3].depth())) print('# of nonlocal gates : {}'.format (qc_trans_all[3].num_nonlocal_gates())) print('Probability of correct answer : {:.2f}'.format(prob_all[3]) ) qc_trans_all[3].draw('mpl')
https://github.com/weiT1993/qiskit_helper_functions
weiT1993
# 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/1chooo/Quantum-Oracle
1chooo
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")
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)) new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3) plot_circuit_layout(new_circ_lv3, backend)
https://github.com/Sanjay-995/Qiskit-Developer-Prep-Guide
Sanjay-995
#Import the required packages from qiskit import QuantumCircuit, Aer,execute from qiskit.visualization import * #Create a Quantum Circuit with 2 qubits and 2 classical bits qc_bell=QuantumCircuit(2,2) qc_bell.h(0) qc_bell.cx(0,1) #Measurement qc_bell.measure([0,1],[0,1]) qc_bell.draw('mpl') #Get the qasm simulator from Aer backend=Aer.get_backend('qasm_simulator') #Execute the circuit #shots= number of times the experiment/circuit is run job=execute(qc_bell,backend,shots=1024) #Get the job result: result() result=job.result() #Get the histogram data of the experiement counts=result.get_counts() print(counts) plot_histogram(counts,title="Bell State without noise") qc1_bell=QuantumCircuit(2) qc1_bell.h(0) qc1_bell.cx(0,1) qc1_bell.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc1_bell,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") qc2_bell=QuantumCircuit(2) qc2_bell.x(0) qc2_bell.h(0) qc2_bell.cx(0,1) qc2_bell.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc2_bell,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") plot_state_qsphere(sv,show_state_phases=True) qc3_bell=QuantumCircuit(2) qc3_bell.x(1) qc3_bell.h(0) qc3_bell.cx(0,1) qc3_bell.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc3_bell,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") qc4_bell=QuantumCircuit(2) qc4_bell.x(0) qc4_bell.x(1) qc4_bell.h(0) qc4_bell.cx(0,1) qc4_bell.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc4_bell,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") plot_state_qsphere(sv,show_state_phases=True) bell_1=QuantumCircuit(2) bell_1.h(0) bell_1.x(1) bell_1.cx(0,1) bell_1.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(bell_1,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") bell_2=QuantumCircuit(2) bell_2.cx(0,1) bell_2.h(0) bell_2.x(1) bell_2.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(bell_2,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") bell_3=QuantumCircuit(2) bell_3.h(0) bell_3.x(1) bell_3.cz(0,1) bell_3.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(bell_2,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") bell_4=QuantumCircuit(2) bell_4.h(0) bell_4.h(1) bell_4.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(bell_4,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") qc3=QuantumCircuit(3) qc3.h(0) qc3.cx(0,1) qc3.cx(0,2) qc3.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc3,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex")
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
# qc-grader should be 0.18.10 (or higher) import qc_grader qc_grader.__version__ # Imports import numpy as np import matplotlib.pyplot as plt from qiskit.circuit.library import EfficientSU2 from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit_ibm_runtime import QiskitRuntimeService from qiskit_transpiler_service.transpiler_service import TranspilerService # Import for grader from qc_grader.challenges.iqc_2024 import grade_lab3_ait_ex1, grade_lab3_ait_ex2 NUM_QUBITS = 61 circuit = EfficientSU2(NUM_QUBITS, entanglement="circular", reps=1).decompose() print(f"Original circuit -> Depth: {circuit.depth()}, CNOTs: {circuit.num_nonlocal_gates()}") circuit.draw(fold=-1, output="mpl", style="iqp", scale=0.2) # Load saved credentials service = QiskitRuntimeService() transpiler_ai_false = TranspilerService( # Add your code here backend_name="ibm_brisbane", ai="false", optimization_level=3, ) # Submit your answer using following code grade_lab3_ait_ex1(transpiler_ai_false) # Expected result type: TranspilerService circuit_ai_false = transpiler_ai_false.run(circuit) print(f"Transpiled without AI -> Depth: {circuit_ai_false.depth()}, CNOTs: {circuit_ai_false.num_nonlocal_gates()}") circuit_ai_false.draw(fold=-1, output="mpl", scale=0.2) transpiler_ai_true = TranspilerService( # Add your code here backend_name="ibm_brisbane", ai="true", optimization_level=3, ) # Submit your answer using following code grade_lab3_ait_ex2(transpiler_ai_true) # Expected result type: TranspilerService circuit_ai_true = transpiler_ai_true.run(circuit) print(f"Transpiled with AI -> Depth: {circuit_ai_true.depth()}, CNOTs: {circuit_ai_true.num_nonlocal_gates()}") circuit_ai_true.draw(fold=-1, output="mpl", scale=0.2) # Transpiling locally using Qiskit SDK service = QiskitRuntimeService() backend = service.backend("ibm_sherbrooke") pm = generate_preset_pass_manager(backend=backend, optimization_level=3) # Run and compile results num_qubits = [11, 21, 41, 61, 81] num_cnots_local = [] num_cnots_with_ai = [] num_cnots_without_ai = [] for nq in num_qubits: circuit = EfficientSU2(nq, entanglement="circular", reps=1).decompose() # Using the Transpiler locally on Qiskit circuit_local = pm.run(circuit) # Using the transpiler service without AI circuit_without_ai = transpiler_ai_false.run(circuit) # Using the transpiler service with AI circuit_with_ai = transpiler_ai_true.run(circuit) num_cnots_local.append(circuit_local.num_nonlocal_gates()) num_cnots_without_ai.append(circuit_without_ai.num_nonlocal_gates()) num_cnots_with_ai.append(circuit_with_ai.num_nonlocal_gates()) plt.plot(num_qubits, num_cnots_with_ai, '.-') plt.plot(num_qubits, num_cnots_without_ai, '.-') plt.plot(num_qubits, num_cnots_local, '--') plt.xlabel("Number of qubits") plt.ylabel("CNOT count") plt.legend(["Qiskit Transpiler Service with AI", "Qiskit Transpiler Service without AI", "Qiskit SDK"])
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.primitives import Estimator estimator = Estimator() import numpy as np from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SLSQP from qiskit.circuit.library import TwoLocal from qiskit.utils import algorithm_globals # we will iterate over these different optimizers optimizers = [COBYLA(maxiter=80), L_BFGS_B(maxiter=60), SLSQP(maxiter=60)] converge_counts = np.empty([len(optimizers)], dtype=object) converge_vals = np.empty([len(optimizers)], dtype=object) for i, optimizer in enumerate(optimizers): print("\rOptimizer: {} ".format(type(optimizer).__name__), end="") algorithm_globals.random_seed = 50 ansatz = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") counts = [] values = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) vqe = VQE(estimator, ansatz, optimizer, callback=store_intermediate_result) result = vqe.compute_minimum_eigenvalue(operator=H2_op) converge_counts[i] = np.asarray(counts) converge_vals[i] = np.asarray(values) print("\rOptimization complete "); import pylab pylab.rcParams["figure.figsize"] = (12, 8) for i, optimizer in enumerate(optimizers): pylab.plot(converge_counts[i], converge_vals[i], label=type(optimizer).__name__) pylab.xlabel("Eval count") pylab.ylabel("Energy") pylab.title("Energy convergence for various optimizers") pylab.legend(loc="upper right"); from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit.opflow import PauliSumOp numpy_solver = NumPyMinimumEigensolver() result = numpy_solver.compute_minimum_eigenvalue(operator=PauliSumOp(H2_op)) ref_value = result.eigenvalue.real print(f"Reference value: {ref_value:.5f}") pylab.rcParams["figure.figsize"] = (12, 8) for i, optimizer in enumerate(optimizers): pylab.plot( converge_counts[i], abs(ref_value - converge_vals[i]), label=type(optimizer).__name__, ) pylab.xlabel("Eval count") pylab.ylabel("Energy difference from solution reference value") pylab.title("Energy convergence for various optimizers") pylab.yscale("log") pylab.legend(loc="upper right"); from qiskit.algorithms.gradients import FiniteDiffEstimatorGradient estimator = Estimator() gradient = FiniteDiffEstimatorGradient(estimator, epsilon=0.01) algorithm_globals.random_seed = 50 ansatz = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") optimizer = SLSQP(maxiter=100) counts = [] values = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) vqe = VQE( estimator, ansatz, optimizer, callback=store_intermediate_result, gradient=gradient ) result = vqe.compute_minimum_eigenvalue(operator=H2_op) print(f"Value using Gradient: {result.eigenvalue.real:.5f}") pylab.rcParams["figure.figsize"] = (12, 8) pylab.plot(counts, values, label=type(optimizer).__name__) pylab.xlabel("Eval count") pylab.ylabel("Energy") pylab.title("Energy convergence using Gradient") pylab.legend(loc="upper right"); print(result) cost_function_evals = result.cost_function_evals initial_pt = result.optimal_point estimator1 = Estimator() gradient1 = FiniteDiffEstimatorGradient(estimator, epsilon=0.01) ansatz1 = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") optimizer1 = SLSQP(maxiter=1000) vqe1 = VQE( estimator1, ansatz1, optimizer1, gradient=gradient1, initial_point=initial_pt ) result1 = vqe1.compute_minimum_eigenvalue(operator=H2_op) print(result1) cost_function_evals1 = result1.cost_function_evals print() print( f"cost_function_evals is {cost_function_evals1} with initial point versus {cost_function_evals} without it." ) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from qiskit import ClassicalRegister, QuantumRegister from qiskit import QuantumCircuit, execute from qiskit.tools.visualization import plot_histogram #Set up the quantum and classical registers, and combine them into a circuit qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) #Create a superposition on the single quantum bit qc.measure(qr[0], cr[0]) #Measure the single bit, and store its value in the clasical bit from qiskit import register, available_backends, get_backend #Import the config file (Qconfig.py) to retrieve the API token and API url try: import sys sys.path.append('../') #Parent directory import Qconfig qx_config = { 'APItoken': Qconfig.APItoken, 'url': Qconfig.config['url']} except Exception as e: print(e) qx_config = { 'APItoken':'YOUR_TOKEN_HERE', 'url':'https://quantumexperience.ng.bluemix.net/api'} #Setup API register(qx_config['APItoken'], qx_config['url']) backend = 'ibmq_qasm_simulator' #Replace 'ibmq_qasm_simulator' with 'ibmqx5' to run on the quantum computer shots_sim = 100 #Adjust this number as desired, with effects as described above job_sim = execute(qc, backend, shots=shots_sim) #Run job on chosen backend for chosen number of shots stats_sim = job_sim.result().get_counts() #Retrieve results #Select '0' to represent 'laurel' if '0' not in stats_sim.keys(): stats_sim['laurel'] = 0 else: stats_sim['laurel'] = stats_sim.pop('0') #Which leaves '1' to represent 'yanny' if '1' not in stats_sim.keys(): stats_sim['yanny'] = 0 else: stats_sim['yanny'] = stats_sim.pop('1') plot_histogram(stats_sim) from pydub import AudioSegment from pydub.playback import play #Import two tracks laurel = AudioSegment.from_wav('laurel_or_yanny_audio_files/laurel.wav') yanny = AudioSegment.from_wav('laurel_or_yanny_audio_files/yanny.wav') play(laurel) #Listen to the laurel-specific track play(yanny) #Listen to the yanny-specific track #Modify the volumes based on the results of the experiment laurel = laurel + ((100*stats_sim['laurel']/shots_sim)-50) #Laurel yanny = yanny + ((100*stats_sim['yanny']/shots_sim)-50) #Yanny #Mix the two together and play the result mixed = laurel.overlay(yanny) play(mixed) mixed.export('laurel_or_yanny_audio_files/quantumLaurelYanny.wav', format='wav') print("Installed packages are as the following") !python --version print() !conda list 'qiskit|IBMQuantumExperience|numpy|scipy'
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
PabloMartinezAngerosa
from tsp_qaoa import test_solution from qiskit.visualization import plot_histogram import networkx as nx import numpy as np import json import csv # Array of JSON Objects header = ['instance', 'iteration', 'distance'] length_instances = 40 with open('qaoa_multiple_distance.csv', 'w', encoding='UTF8') as f: writer = csv.writer(f) # write the header writer.writerow(header) for instance in range(length_instances): job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution() # Sort the JSON data based on the value of the brand key UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["mean"]) index = -1 for sample in UNIFORM_CONVERGENCE_SAMPLE: mean = sample["mean"] index += 1 distance_p_ground_state = np.max(np.abs(UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"] - sample["probabilities"])) UNIFORM_CONVERGENCE_SAMPLE[index]["distance_pgs"] = distance_p_ground_state iteration = 0 for sample in UNIFORM_CONVERGENCE_SAMPLE: iteration += 1 mean = sample["mean"] distance = sample["distance_pgs"] writer.writerow([instance,iteration, distance])
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# You can make the bars more transparent to better see the ones that are behind # if they overlap. import numpy as np from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_city from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0,1) qc.ry(np.pi/3, 0) qc.rx(np.pi/5, 1) state = Statevector(qc) plot_state_city(state, alpha=0.6)
https://github.com/hritiksauw199/Qiskit-textbook-solutions
hritiksauw199
import matplotlib.pyplot as plt import numpy as np from qiskit import QuantumCircuit, Aer, transpile, assemble from qiskit.visualization import plot_histogram from math import gcd from numpy.random import randint import pandas as pd from fractions import Fraction def c_amod15(a, power): """Controlled multiplication by a mod 15""" if a not in [2,7,8,11,13]: raise ValueError("'a' must be 2,7,8,11 or 13") U = QuantumCircuit(4) for iteration in range(power): if a in [2,13]: U.swap(0,1) U.swap(1,2) U.swap(2,3) if a in [7,8]: U.swap(2,3) U.swap(1,2) U.swap(0,1) if a == 11: U.swap(1,3) U.swap(0,2) if a in [7,11,13]: for q in range(4): U.x(q) U = U.to_gate() U.name = "%i^%i mod 15" % (a, power) c_U = U.control() return c_U def qft_dagger(n): """n-qubit QFTdagger the first n qubits in circ""" qc = QuantumCircuit(n) # Don't forget the Swaps! for qubit in range(n//2): qc.swap(qubit, n-qubit-1) for j in range(n): for m in range(j): qc.cp(-np.pi/float(2**(j-m)), m, j) qc.h(j) qc.name = "QFT†" return qc # Specify variables n_count = 8 # number of counting qubits a = 2 # Create QuantumCircuit with n_count counting qubits # plus 4 qubits for U to act on qc = QuantumCircuit(n_count + 4, n_count) # Initialize counting qubits # in state |+> for q in range(n_count): qc.h(q) # And auxiliary register in state |1> qc.x(3+n_count) # Do controlled-U operations for q in range(n_count): qc.append(c_amod15(a, 2**q), # second one is power of 2 [q] + [i+n_count for i in range(4)]) # i+n_count will be 0+8, 1+8, 2+8, 3+8 where n_count = 8 # Do inverse-QFT qc.append(qft_dagger(n_count), range(n_count)) # Measure circuit qc.measure(range(n_count), range(n_count)) qc.draw(fold=-1) # -1 means 'do not fold' aer_sim = Aer.get_backend('aer_simulator') t_qc = transpile(qc, aer_sim) qobj = assemble(t_qc) results = aer_sim.run(qobj).result() counts = results.get_counts() plot_histogram(counts) rows, measured_phases = [], [] for output in counts: decimal = int(output, 2) # Convert (base 2) string to decimal phase = decimal/(2**n_count) # Find corresponding eigenvalue measured_phases.append(phase) # Add these values to the rows in our table: rows.append([f"{output}(bin) = {decimal:>3}(dec)", f"{decimal}/{2**n_count} = {phase:.2f}"]) # Print the rows in a table headers=["Register Output", "Phase"] df = pd.DataFrame(rows, columns=headers) print(df) rows = [] for phase in measured_phases: frac = Fraction(phase).limit_denominator(15) rows.append([phase, f"{frac.numerator}/{frac.denominator}", frac.denominator]) # Print as a table headers=["Phase", "Fraction", "Guess for r"] df = pd.DataFrame(rows, columns=headers) print(df) # Specify variables n_count = 8 # number of counting qubits a = 8 # Create QuantumCircuit with n_count counting qubits # plus 4 qubits for U to act on qc = QuantumCircuit(n_count + 4, n_count) # Initialize counting qubits # in state |+> for q in range(n_count): qc.h(q) # And auxiliary register in state |1> qc.x(3+n_count) # Do controlled-U operations for q in range(n_count): qc.append(c_amod15(a, 2**q), # second one is power of 2 [q] + [i+n_count for i in range(4)]) # i+n_count will be 0+8, 1+8, 2+8, 3+8 where n_count = 8 # Do inverse-QFT qc.append(qft_dagger(n_count), range(n_count)) # Measure circuit qc.measure(range(n_count), range(n_count)) qc.draw(fold=-1) # -1 means 'do not fold' aer_sim = Aer.get_backend('aer_simulator') t_qc = transpile(qc, aer_sim) qobj = assemble(t_qc) results = aer_sim.run(qobj).result() counts = results.get_counts() plot_histogram(counts) rows, measured_phases = [], [] for output in counts: decimal = int(output, 2) # Convert (base 2) string to decimal phase = decimal/(2**n_count) # Find corresponding eigenvalue measured_phases.append(phase) # Add these values to the rows in our table: rows.append([f"{output}(bin) = {decimal:>3}(dec)", f"{decimal}/{2**n_count} = {phase:.2f}"]) # Print the rows in a table headers=["Register Output", "Phase"] df = pd.DataFrame(rows, columns=headers) print(df) rows = [] for phase in measured_phases: frac = Fraction(phase).limit_denominator(15) rows.append([phase, f"{frac.numerator}/{frac.denominator}", frac.denominator]) # Print as a table headers=["Phase", "Fraction", "Guess for r"] df = pd.DataFrame(rows, columns=headers) print(df) # Specify variables n_count = 8 # number of counting qubits a = 11 # Create QuantumCircuit with n_count counting qubits # plus 4 qubits for U to act on qc = QuantumCircuit(n_count + 4, n_count) # Initialize counting qubits # in state |+> for q in range(n_count): qc.h(q) # And auxiliary register in state |1> qc.x(3+n_count) # Do controlled-U operations for q in range(n_count): qc.append(c_amod15(a, 2**q), # second one is power of 2 [q] + [i+n_count for i in range(4)]) # i+n_count will be 0+8, 1+8, 2+8, 3+8 where n_count = 8 # Do inverse-QFT qc.append(qft_dagger(n_count), range(n_count)) # Measure circuit qc.measure(range(n_count), range(n_count)) qc.draw(fold=-1) # -1 means 'do not fold' aer_sim = Aer.get_backend('aer_simulator') t_qc = transpile(qc, aer_sim) qobj = assemble(t_qc) results = aer_sim.run(qobj).result() counts = results.get_counts() plot_histogram(counts) rows, measured_phases = [], [] for output in counts: decimal = int(output, 2) # Convert (base 2) string to decimal phase = decimal/(2**n_count) # Find corresponding eigenvalue measured_phases.append(phase) # Add these values to the rows in our table: rows.append([f"{output}(bin) = {decimal:>3}(dec)", f"{decimal}/{2**n_count} = {phase:.2f}"]) # Print the rows in a table headers=["Register Output", "Phase"] df = pd.DataFrame(rows, columns=headers) print(df) rows = [] for phase in measured_phases: frac = Fraction(phase).limit_denominator(15) rows.append([phase, f"{frac.numerator}/{frac.denominator}", frac.denominator]) # Print as a table headers=["Phase", "Fraction", "Guess for r"] df = pd.DataFrame(rows, columns=headers) print(df) # Specify variables n_count = 8 # number of counting qubits a = 13 # Create QuantumCircuit with n_count counting qubits # plus 4 qubits for U to act on qc = QuantumCircuit(n_count + 4, n_count) # Initialize counting qubits # in state |+> for q in range(n_count): qc.h(q) # And auxiliary register in state |1> qc.x(3+n_count) # Do controlled-U operations for q in range(n_count): qc.append(c_amod15(a, 2**q), # second one is power of 2 [q] + [i+n_count for i in range(4)]) # i+n_count will be 0+8, 1+8, 2+8, 3+8 where n_count = 8 # Do inverse-QFT qc.append(qft_dagger(n_count), range(n_count)) # Measure circuit qc.measure(range(n_count), range(n_count)) qc.draw(fold=-1) # -1 means 'do not fold' aer_sim = Aer.get_backend('aer_simulator') t_qc = transpile(qc, aer_sim) qobj = assemble(t_qc) results = aer_sim.run(qobj).result() counts = results.get_counts() plot_histogram(counts) rows, measured_phases = [], [] for output in counts: decimal = int(output, 2) # Convert (base 2) string to decimal phase = decimal/(2**n_count) # Find corresponding eigenvalue measured_phases.append(phase) # Add these values to the rows in our table: rows.append([f"{output}(bin) = {decimal:>3}(dec)", f"{decimal}/{2**n_count} = {phase:.2f}"]) # Print the rows in a table headers=["Register Output", "Phase"] df = pd.DataFrame(rows, columns=headers) print(df) rows = [] for phase in measured_phases: frac = Fraction(phase).limit_denominator(15) rows.append([phase, f"{frac.numerator}/{frac.denominator}", frac.denominator]) # Print as a table headers=["Phase", "Fraction", "Guess for r"] df = pd.DataFrame(rows, columns=headers) print(df)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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. """HamiltonianGate tests""" import numpy as np from numpy.testing import assert_allclose import qiskit from qiskit.extensions.hamiltonian_gate import HamiltonianGate, UnitaryGate from qiskit.extensions.exceptions import ExtensionError from qiskit.test import QiskitTestCase from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Parameter from qiskit.quantum_info import Operator from qiskit.converters import circuit_to_dag, dag_to_circuit class TestHamiltonianGate(QiskitTestCase): """Tests for the HamiltonianGate class.""" def test_set_matrix(self): """Test instantiation""" hamiltonian = HamiltonianGate([[0, 1], [1, 0]], 1) self.assertEqual(hamiltonian.num_qubits, 1) def test_set_matrix_raises(self): """test non-unitary""" with self.assertRaises(ExtensionError): HamiltonianGate([[1, 0], [1, 1]], 1) def test_complex_time_raises(self): """test non-unitary""" with self.assertRaises(ExtensionError): HamiltonianGate([[1, 0], [1, 1]], 1j) def test_conjugate(self): """test conjugate""" ham = HamiltonianGate([[0, 1j], [-1j, 2]], np.pi / 4) np.testing.assert_array_almost_equal(ham.conjugate().to_matrix(), np.conj(ham.to_matrix())) def test_transpose(self): """test transpose""" ham = HamiltonianGate([[15, 1j], [-1j, -2]], np.pi / 7) np.testing.assert_array_almost_equal( ham.transpose().to_matrix(), np.transpose(ham.to_matrix()) ) def test_adjoint(self): """test adjoint operation""" ham = HamiltonianGate([[3, 4j], [-4j, -0.2]], np.pi * 0.143) np.testing.assert_array_almost_equal( ham.adjoint().to_matrix(), np.transpose(np.conj(ham.to_matrix())) ) class TestHamiltonianCircuit(QiskitTestCase): """Hamiltonian gate circuit tests.""" def test_1q_hamiltonian(self): """test 1 qubit hamiltonian""" qr = QuantumRegister(1, "q0") cr = ClassicalRegister(1, "c0") qc = QuantumCircuit(qr, cr) matrix = np.zeros((2, 2)) qc.x(qr[0]) theta = Parameter("theta") qc.append(HamiltonianGate(matrix, theta), [qr[0]]) qc = qc.bind_parameters({theta: 1}) # test of text drawer self.log.info(qc) dag = circuit_to_dag(qc) dag_nodes = dag.named_nodes("hamiltonian") self.assertTrue(len(dag_nodes) == 1) dnode = dag_nodes[0] self.assertIsInstance(dnode.op, HamiltonianGate) self.assertEqual(dnode.qargs, tuple(qc.qubits)) assert_allclose(dnode.op.to_matrix(), np.eye(2)) def test_error_and_deprecation_warning_on_qasm(self): """test that an error is thrown if the method `qasm` is called.""" matrix = np.zeros((2, 2)) hamiltonian_gate = HamiltonianGate(data=matrix, time=1) with self.assertRaises(ExtensionError): with self.assertWarns(DeprecationWarning): hamiltonian_gate.qasm() def test_2q_hamiltonian(self): """test 2 qubit hamiltonian""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) matrix = Operator.from_label("XY") qc.x(qr[0]) theta = Parameter("theta") uni2q = HamiltonianGate(matrix, theta) qc.append(uni2q, [qr[0], qr[1]]) qc2 = qc.bind_parameters({theta: -np.pi / 2}) dag = circuit_to_dag(qc2) nodes = dag.two_qubit_ops() self.assertEqual(len(nodes), 1) dnode = nodes[0] self.assertIsInstance(dnode.op, HamiltonianGate) self.assertEqual(dnode.qargs, (qr[0], qr[1])) # Equality based on Pauli exponential identity np.testing.assert_array_almost_equal(dnode.op.to_matrix(), 1j * matrix.data) qc3 = dag_to_circuit(dag) self.assertEqual(qc2, qc3) def test_3q_hamiltonian(self): """test 3 qubit hamiltonian on non-consecutive bits""" qr = QuantumRegister(4) qc = QuantumCircuit(qr) qc.x(qr[0]) matrix = Operator.from_label("XZY") theta = Parameter("theta") uni3q = HamiltonianGate(matrix, theta) qc.append(uni3q, [qr[0], qr[1], qr[3]]) qc.cx(qr[3], qr[2]) # test of text drawer self.log.info(qc) qc = qc.bind_parameters({theta: -np.pi / 2}) dag = circuit_to_dag(qc) nodes = dag.multi_qubit_ops() self.assertEqual(len(nodes), 1) dnode = nodes[0] self.assertIsInstance(dnode.op, HamiltonianGate) self.assertEqual(dnode.qargs, (qr[0], qr[1], qr[3])) np.testing.assert_almost_equal(dnode.op.to_matrix(), 1j * matrix.data) def test_qobj_with_hamiltonian(self): """test qobj output with hamiltonian""" qr = QuantumRegister(4) qc = QuantumCircuit(qr) qc.rx(np.pi / 4, qr[0]) matrix = Operator.from_label("XIZ") theta = Parameter("theta") uni = HamiltonianGate(matrix, theta, label="XIZ") qc.append(uni, [qr[0], qr[1], qr[3]]) qc.cx(qr[3], qr[2]) qc = qc.bind_parameters({theta: np.pi / 2}) qobj = qiskit.compiler.assemble(qc) instr = qobj.experiments[0].instructions[1] self.assertEqual(instr.name, "hamiltonian") # Also test label self.assertEqual(instr.label, "XIZ") np.testing.assert_array_almost_equal( np.array(instr.params[0]).astype(np.complex64), matrix.data ) def test_decomposes_into_correct_unitary(self): """test 2 qubit hamiltonian""" qc = QuantumCircuit(2) matrix = Operator.from_label("XY") theta = Parameter("theta") uni2q = HamiltonianGate(matrix, theta) qc.append(uni2q, [0, 1]) qc = qc.bind_parameters({theta: -np.pi / 2}).decompose() decomposed_ham = qc.data[0].operation self.assertEqual(decomposed_ham, UnitaryGate(Operator.from_label("XY")))
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/Simultonian/hamilutor-qiskit
Simultonian
from qiskit import QuantumCircuit from qiskit.opflow import PauliTrotterEvolution, X, Y, Z, I # For `eval` from ..utils.repr import qiskit_string_repr, qiskit_string_repr_pauli def trotter_from_terms(terms: list[tuple[str, float]]) -> QuantumCircuit: """ API that takes a list of terms that must be exponentiated in the specific order, that may or may not have repetitions. The coefficients are assumed to already account the time scaling. Input: - terms: list of pairs of pauli operator and the coefficient. Returns: Quantum Circuit with exponentiation in the defined ordered. """ num_qubits = len(terms[0][0]) final_circuit = QuantumCircuit(num_qubits) for term in terms: final_circuit = final_circuit.compose(trotter_from_term(term)) return final_circuit def trotter_from_term(term: tuple[str, float]) -> QuantumCircuit: pauli_op = eval(qiskit_string_repr_pauli(term)) evolution_op = pauli_op.exp_i() trotterized_op = PauliTrotterEvolution(trotter_mode="trotter").convert(evolution_op) return trotterized_op.to_circuit() def trotter(h: dict[str, float], t: float = 1.0, reps: int = 1) -> QuantumCircuit: """ API that takes Hamiltonian in a familiar format along with time and creates circuit that simulates the same using simple Trotterization. Input: - h: Hamiltonian in Pauli basis along with coefficients - t: Time - reps: The number of times to repeat trotterization steps. Returns: Quantum Circuit for simulation """ hamiltonian = eval(qiskit_string_repr(h)) # evolution operator evolution_op = ((t / reps) * hamiltonian).exp_i() # into circuit trotterized_op = PauliTrotterEvolution(trotter_mode="trotter", reps=reps).convert( evolution_op ) return trotterized_op.to_circuit()
https://github.com/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 test for visualizing device coupling maps""" import unittest from io import BytesIO from ddt import ddt, data from qiskit.providers.fake_provider import ( FakeProvider, FakeKolkata, FakeWashington, FakeKolkataV2, FakeWashingtonV2, ) from qiskit.visualization import ( plot_gate_map, plot_coupling_map, plot_circuit_layout, plot_error_map, ) from qiskit.utils import optionals from qiskit import QuantumRegister, QuantumCircuit from qiskit.transpiler.layout import Layout, TranspileLayout from .visualization import path_to_diagram_reference, QiskitVisualizationTestCase if optionals.HAS_MATPLOTLIB: import matplotlib.pyplot as plt if optionals.HAS_PIL: from PIL import Image @ddt @unittest.skipUnless(optionals.HAS_MATPLOTLIB, "matplotlib not available.") @unittest.skipUnless(optionals.HAS_PIL, "PIL not available") @unittest.skipUnless(optionals.HAS_SEABORN, "seaborn not available") class TestGateMap(QiskitVisualizationTestCase): """visual tests for plot_gate_map""" backends = list( filter( lambda x: not x.configuration().simulator and x.configuration().num_qubits in range(5, 21), FakeProvider().backends(), ) ) @data(*backends) def test_plot_gate_map(self, backend): """tests plotting of gate map of a device (20 qubit, 16 qubit, 14 qubit and 5 qubit)""" n = backend.configuration().n_qubits img_ref = path_to_diagram_reference(str(n) + "bit_quantum_computer.png") fig = plot_gate_map(backend) with BytesIO() as img_buffer: fig.savefig(img_buffer, format="png") img_buffer.seek(0) self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2) plt.close(fig) @data(*backends) def test_plot_circuit_layout(self, backend): """tests plot_circuit_layout for each device""" layout_length = int(backend._configuration.n_qubits / 2) qr = QuantumRegister(layout_length, "qr") circuit = QuantumCircuit(qr) circuit._layout = TranspileLayout( Layout({qr[i]: i * 2 for i in range(layout_length)}), {qubit: index for index, qubit in enumerate(circuit.qubits)}, ) circuit._layout.initial_layout.add_register(qr) n = backend.configuration().n_qubits img_ref = path_to_diagram_reference(str(n) + "_plot_circuit_layout.png") fig = plot_circuit_layout(circuit, backend) with BytesIO() as img_buffer: fig.savefig(img_buffer, format="png") img_buffer.seek(0) self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.1) plt.close(fig) def test_plot_gate_map_no_backend(self): """tests plotting of gate map without a device""" n_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]] img_ref = path_to_diagram_reference(str(n_qubits) + "qubits.png") fig = plot_coupling_map( num_qubits=n_qubits, qubit_coordinates=qubit_coordinates, coupling_map=coupling_map ) with BytesIO() as img_buffer: fig.savefig(img_buffer, format="png") img_buffer.seek(0) self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2) plt.close(fig) def test_plot_error_map_backend_v1(self): """Test plotting error map with fake backend v1.""" backend = FakeKolkata() img_ref = path_to_diagram_reference("kolkata_error.png") fig = plot_error_map(backend) with BytesIO() as img_buffer: fig.savefig(img_buffer, format="png") img_buffer.seek(0) self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2) plt.close(fig) def test_plot_error_map_backend_v2(self): """Test plotting error map with fake backend v2.""" backend = FakeKolkataV2() img_ref = path_to_diagram_reference("kolkata_v2_error.png") fig = plot_error_map(backend) with BytesIO() as img_buffer: fig.savefig(img_buffer, format="png") img_buffer.seek(0) self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2) plt.close(fig) def test_plot_error_map_over_100_qubit(self): """Test plotting error map with large fake backend.""" backend = FakeWashington() img_ref = path_to_diagram_reference("washington_error.png") fig = plot_error_map(backend) with BytesIO() as img_buffer: fig.savefig(img_buffer, format="png") img_buffer.seek(0) self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2) plt.close(fig) def test_plot_error_map_over_100_qubit_backend_v2(self): """Test plotting error map with large fake backendv2.""" backend = FakeWashingtonV2() img_ref = path_to_diagram_reference("washington_v2_error.png") fig = plot_error_map(backend) with BytesIO() as img_buffer: fig.savefig(img_buffer, format="png") img_buffer.seek(0) self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2) plt.close(fig) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.visualization.timeline import draw as timeline_draw from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeBoeblingen backend = FakeBoeblingen() ghz = QuantumCircuit(5) ghz.h(0) ghz.cx(0,range(1,5)) circ = transpile(ghz, backend, scheduling_method="asap") timeline_draw(circ)
https://github.com/alpine-quantum-technologies/qiskit-aqt-provider-rc
alpine-quantum-technologies
# This code is part of Qiskit. # # (C) Alpine Quantum Technologies GmbH 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. """Dummy resources for testing purposes.""" import enum import random import time import uuid from dataclasses import dataclass, field from typing import Dict, List, Optional from qiskit import QuantumCircuit from typing_extensions import assert_never from qiskit_aqt_provider import api_models from qiskit_aqt_provider.aqt_provider import AQTProvider from qiskit_aqt_provider.aqt_resource import AQTResource class JobStatus(enum.Enum): """AQT job lifecycle labels.""" QUEUED = enum.auto() ONGOING = enum.auto() FINISHED = enum.auto() ERROR = enum.auto() CANCELLED = enum.auto() @dataclass class TestJob: # pylint: disable=too-many-instance-attributes """Job state holder for the TestResource.""" circuits: List[QuantumCircuit] shots: int status: JobStatus = JobStatus.QUEUED job_id: uuid.UUID = field(default_factory=lambda: uuid.uuid4()) time_queued: float = field(default_factory=time.time) time_submitted: float = 0.0 time_finished: float = 0.0 error_message: str = "error" results: Dict[str, List[List[int]]] = field(init=False) workspace: str = field(default="test-workspace", init=False) resource: str = field(default="test-resource", init=False) def __post_init__(self) -> None: """Calculate derived quantities.""" self.results = { str(circuit_index): [ random.choices([0, 1], k=circuit.num_clbits) for _ in range(self.shots) ] for circuit_index, circuit in enumerate(self.circuits) } def submit(self) -> None: """Submit the job for execution.""" self.time_submitted = time.time() self.status = JobStatus.ONGOING def finish(self) -> None: """The job execution finished successfully.""" self.time_finished = time.time() self.status = JobStatus.FINISHED def error(self) -> None: """The job execution triggered an error.""" self.time_finished = time.time() self.status = JobStatus.ERROR def cancel(self) -> None: """The job execution was cancelled.""" self.time_finished = time.time() self.status = JobStatus.CANCELLED def response_payload(self) -> api_models.JobResponse: """AQT API-compatible response for the current job status.""" if self.status is JobStatus.QUEUED: return api_models.Response.queued( job_id=self.job_id, workspace_id=self.workspace, resource_id=self.resource, ) if self.status is JobStatus.ONGOING: return api_models.Response.ongoing( job_id=self.job_id, workspace_id=self.workspace, resource_id=self.resource, finished_count=1, ) if self.status is JobStatus.FINISHED: return api_models.Response.finished( job_id=self.job_id, workspace_id=self.workspace, resource_id=self.resource, results=self.results, ) if self.status is JobStatus.ERROR: return api_models.Response.error( job_id=self.job_id, workspace_id=self.workspace, resource_id=self.resource, message=self.error_message, ) if self.status is JobStatus.CANCELLED: return api_models.Response.cancelled( job_id=self.job_id, workspace_id=self.workspace, resource_id=self.resource ) assert_never(self.status) # pragma: no cover class TestResource(AQTResource): # pylint: disable=too-many-instance-attributes """AQT computing resource with hooks for triggering different execution scenarios.""" __test__ = False # disable pytest collection def __init__( self, *, min_queued_duration: float = 0.0, min_running_duration: float = 0.0, always_cancel: bool = False, always_error: bool = False, error_message: str = "", ) -> None: """Initialize the testing resource. Args: min_queued_duration: minimum time in seconds spent by all jobs in the QUEUED state min_running_duration: minimum time in seconds spent by all jobs in the ONGOING state always_cancel: always cancel the jobs directly after submission always_error: always finish execution with an error error_message: the error message returned by failed jobs. Implies `always_error`. """ super().__init__( AQTProvider(""), workspace_id="test-workspace", resource_id="test", resource_name="test-resource", resource_type="simulator", ) self.job: Optional[TestJob] = None self.min_queued_duration = min_queued_duration self.min_running_duration = min_running_duration self.always_cancel = always_cancel self.always_error = always_error or error_message self.error_message = error_message or str(uuid.uuid4()) def submit(self, circuits: List[QuantumCircuit], shots: int) -> uuid.UUID: job = TestJob(circuits, shots, error_message=self.error_message) if self.always_cancel: job.cancel() self.job = job return job.job_id def result(self, job_id: uuid.UUID) -> api_models.JobResponse: if self.job is None or self.job.job_id != job_id: # pragma: no cover raise api_models.UnknownJobError(str(job_id)) now = time.time() if ( self.job.status is JobStatus.QUEUED and (now - self.job.time_queued) > self.min_queued_duration ): self.job.submit() if ( self.job.status is JobStatus.ONGOING and (now - self.job.time_submitted) > self.min_running_duration ): if self.always_error: self.job.error() else: self.job.finish() return self.job.response_payload() class DummyResource(AQTResource): """A non-functional resource, for testing purposes.""" def __init__(self, token: str) -> None: super().__init__( AQTProvider(token), workspace_id="dummy", resource_id="dummy", resource_name="dummy", resource_type="simulator", )
https://github.com/qiskit-community/community.qiskit.org
qiskit-community
from qiskit import * # set up circuit (no measurements required) qc = QuantumCircuit(2) qc.x(0) # qubits numbered from the right, so qubit 0 is the qubit on the right qc.z(1) # and qubit 1 is on the left # set up simulator that returns unitary matrix backend = Aer.get_backend('unitary_simulator') # run the circuit to get the matrix gate = execute(qc,backend).result().get_unitary() # now we use some fanciness to display it in latex from IPython.display import display, Markdown, Latex gate_latex = '\\begin{pmatrix}' for line in gate: for element in line: gate_latex += str(element) + '&' gate_latex = gate_latex[0:-1] gate_latex += '\\\\' gate_latex = gate_latex[0:-2] gate_latex += '\end{pmatrix}' display(Markdown(gate_latex))
https://github.com/qiskit-community/prototype-zne
qiskit-community
# This code is part of Qiskit. # # (C) Copyright IBM 2022-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. """Zero Noise Extrapolation (ZNE) strategy configuration dataclass.""" from __future__ import annotations from collections.abc import Iterable, Iterator, Sequence from math import sqrt from typing import Any from warnings import warn from numpy import array from qiskit import QuantumCircuit from qiskit.primitives import EstimatorResult from .extrapolation import Extrapolator, LinearExtrapolator from .noise_amplification import MultiQubitAmplifier, NoiseAmplifier from .types import EstimatorResultData, Metadata # noqa: F401 from .utils.grouping import from_common_key, group_elements_gen, merge_dicts from .utils.typing import isreal, normalize_array from .utils.validation import quality class ZNEStrategy: """Zero Noise Extrapolation strategy. Args: noise_factors: An list of real valued noise factors that determine by what amount the circuits' noise is amplified. noise_amplifier: A noise amplification strategy implementing the :class:`NoiseAmplifier` interface. A dictionary of currently available options can be imported as ``NOISE_AMPLIFIER_LIBRARY``. extrapolator: An extrapolation strategy implementing the :class:`Extrapolator` interface. A dictionary of currently available options can be imported as ``EXTRAPOLATOR_LIBRARY``. Raises: TypeError: If input does not match the type specification. ValueError: If noise factors are empty or less than one. """ _DEFINING_ATTRS = ( "noise_factors", "noise_amplifier", "extrapolator", ) def __init__( self, noise_factors: Sequence[float] | None = None, noise_amplifier: NoiseAmplifier | None = None, extrapolator: Extrapolator | None = None, ) -> None: self.noise_factors = noise_factors self.noise_amplifier = noise_amplifier self.extrapolator = extrapolator def __repr__(self) -> str: attrs_str = ", ".join( f"{attr}={repr(getattr(self, attr))}" for attr in self._DEFINING_ATTRS ) return f"ZNEStrategy({attrs_str})" def __eq__(self, __o: object) -> bool: if not isinstance(__o, self.__class__): return False return all(getattr(self, attr) == getattr(__o, attr) for attr in self._DEFINING_ATTRS) def __bool__(self) -> bool: return not self.is_noop ################################################################################ ## CONSTRUCTORS ################################################################################ @classmethod def noop(cls) -> ZNEStrategy: """Construct a no-op ZNE strategy object.""" return cls(noise_factors=(1,)) ################################################################################ ## PROPERTIES ################################################################################ @quality(default=(1,)) def noise_factors(self, noise_factors: Sequence[float]) -> tuple[float, ...]: """Noise factors for ZNE. Validation logic defined as required by `quality`. """ if not isinstance(noise_factors, Sequence): raise TypeError( f"Expected `Sequence` noise factors, received `{type(noise_factors)}` instead." ) noise_factors = tuple(noise_factors) if not noise_factors: raise ValueError("Noise factors must not be empty.") if not all(isreal(nf) for nf in noise_factors): raise TypeError("Noise factors must be real valued.") if any(nf < 1 for nf in noise_factors): raise ValueError("Noise factors must be greater than or equal to one.") unsorted_noise_factors = noise_factors noise_factors = tuple(sorted(noise_factors)) if noise_factors != unsorted_noise_factors: warn("Unordered noise factors detected and rearranged.", UserWarning, stacklevel=3) duplicate_noise_factors = noise_factors noise_factors = tuple(sorted(set(noise_factors))) if noise_factors != duplicate_noise_factors: warn("Duplicate noise factors detected and erased.", UserWarning, stacklevel=3) return noise_factors @quality(default=MultiQubitAmplifier()) def noise_amplifier(self, noise_amplifier: NoiseAmplifier) -> NoiseAmplifier: """Noise amplifier strategy for ZNE. Validation logic defined as required by `quality`. """ if not isinstance(noise_amplifier, NoiseAmplifier): raise TypeError( f"Expected `NoiseAmplifier` object, received `{type(noise_amplifier)}` instead." ) return noise_amplifier @quality(default=LinearExtrapolator()) def extrapolator(self, extrapolator: Extrapolator) -> Extrapolator: """Extrapoaltor strategy for ZNE. Validation logic defined as required by `quality`. """ if not isinstance(extrapolator, Extrapolator): raise TypeError( f"Expected `Extrapolator` object, received `{type(extrapolator)}` instead." ) return extrapolator @property def num_noise_factors(self) -> int: """Number of noise factors.""" return len(self.noise_factors) @property def performs_noise_amplification(self) -> bool: """Checks if noise amplification is performed.""" return any(nf > 1 for nf in self.noise_factors) @property def performs_zne(self) -> bool: """Checks if zero noise extrapolation is performed.""" return self.performs_noise_amplification and self.num_noise_factors > 1 @property def is_noop(self) -> bool: """Checks if strategy is no-op.""" return not self.performs_noise_amplification and not self.performs_zne ################################################################################ ## NOISE AMPLIFICATION ################################################################################ def amplify_circuit_noise(self, circuit: QuantumCircuit, noise_factor: float) -> QuantumCircuit: """Noise amplification from :class:`~.noise_amplification.NoiseAmplifier`. Args: circuit: The original quantum circuit. noise_factor: The noise amplification factor by which to amplify the circuit noise. Returns: The noise amplified quantum circuit """ # TODO: caching return self.noise_amplifier.amplify_circuit_noise(circuit, noise_factor) # TODO: decouple indexing logic depending on this method # TODO: add validation def build_noisy_circuits( self, original_circuits: Iterable[QuantumCircuit] | QuantumCircuit, ) -> tuple[QuantumCircuit, ...]: """Construct noisy circuits for all noise factors from original circuits. Args: original_circuits: a :class:`~qiskit.circuit.QuantumCircuit` or a collection of :class:`~qiskit.circuit.QuantumCircuit`. Returns: A tuple containing the noise amplified circuits. """ def generate_noisy_circuits( original_circuits: Iterable[QuantumCircuit], ) -> Iterator[QuantumCircuit]: for circuit in original_circuits: # type: QuantumCircuit for noise_factor in self.noise_factors: # type: float yield self.amplify_circuit_noise(circuit, noise_factor) if isinstance(original_circuits, QuantumCircuit): original_circuits = [original_circuits] return tuple(generate_noisy_circuits(original_circuits)) # TODO: decouple indexing logic depending on this method def map_to_noisy_circuits(self, arg: Any) -> tuple | None: """Map arguments for original circuits to the corresponding arguments for noisy circuits. Args: arg: Additional non-circuit arguments such as observables or parameter values. Returns: A tuple of args corresponding to the noise amplified circuits or None. """ if arg is None: return arg if not isinstance(arg, Iterable): arg = [arg] mapped_arg: list = [] for element in arg: mapped_arg.extend(element for _ in range(self.num_noise_factors)) return tuple(mapped_arg) ################################################################################ ## EXTRAPOLATION ################################################################################ # TODO: add validation def mitigate_noisy_result(self, noisy_result: EstimatorResult) -> EstimatorResult: """Parse results from noisy circuits to error mitigated results. Args: noisy_result: The unmitigated results. Returns: The mitigated results after performing zero-noise-extrapolation. """ values: list[float] = [] metadata: list[Metadata] = [] for result_group in self._generate_noisy_result_groups(noisy_result): data = self._regression_data_from_result_group(result_group) val, err, meta = self.extrapolator.extrapolate_zero(*data) common_metadata: Metadata = {"std_error": err} # TODO: extract other common metadata zne_metadata: Metadata = self.build_zne_metadata(result_group, meta) values.append(val) metadata.append({**common_metadata, "zne": zne_metadata}) return EstimatorResult(values=array(values), metadata=list(metadata)) # TODO: decouple indexing logic depending on this method def _generate_noisy_result_groups( self, noisy_result: EstimatorResult ) -> Iterator[EstimatorResult]: """Generator function for grouping noisy results. Iteratively constructs an estimator result for each group of experiments containing the measurement results associated with every noise factor. Args: noisy_result: The estimator result with data from all the experiments performed. Yields: Estimator results grouping data for experiments with different noise factors, but same circuit-observable combinations. Raises: ValueError: If the number of performed experiments is not an integer multiple of the number of noise factors. """ if len(noisy_result.values) % self.num_noise_factors != 0: raise ValueError("Inconsistent number of noisy experiments and noise factors.") for group in group_elements_gen( [ {"values": v, "metadata": m} for v, m in zip(noisy_result.values, noisy_result.metadata) ], group_size=self.num_noise_factors, ): # type: tuple[EstimatorResultData, ...] values, metadata = zip(*[data.values() for data in group]) yield EstimatorResult(values=array(values), metadata=list(metadata)) def _regression_data_from_result_group( self, result_group: EstimatorResult ) -> tuple[list[float], list[float], list[float], list[float]]: """Build regression data from noisy result group. Args: result_group: Estimator result grouping data for experiments with different noise factors, but same circuit-observable combinations. Returns: Regression data """ if len(result_group.values) != self.num_noise_factors: raise ValueError("Inconsistent number of noisy experiments and noise factors.") x_data = list(self.noise_factors) # TODO: get actual noise factors achieved y_data = result_group.values.tolist() sigma_x = [1 for _ in x_data] sigma_y = [sqrt(md.get("variance", 1)) for md in result_group.metadata] return x_data, y_data, sigma_x, sigma_y # type: ignore # TODO: add validation def build_zne_metadata( self, result_group: EstimatorResult, extrapolation: Metadata | None = None ) -> Metadata: """Build ZNE metadata from extrapolation data. Args: result_group: The grouped noisy results for a single mitigated result. extrapolation: extrapolation metadata entries to include (e.g. extrapolation). Returns: Dictionary containing ZNE metadata. Raises: ValueError: If the number of experiments does not match the number of noise factors. """ if extrapolation is None: extrapolation = {} if len(result_group.values) != self.num_noise_factors: raise ValueError("Inconsistent number of noisy experiments and noise factors.") noise_amplification: Metadata = { "noise_amplifier": self.noise_amplifier, "noise_factors": self.noise_factors, "values": normalize_array(result_group.values), # TODO: simplify when tuple } for key in merge_dicts(result_group.metadata): value = from_common_key(result_group.metadata, key) noise_amplification.update({key: value}) extrapolation = { "extrapolator": self.extrapolator, **extrapolation, } return {"noise_amplification": noise_amplification, "extrapolation": extrapolation}
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
# -*- coding: utf-8 -*- # 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. """Utils for reading a user preference config files.""" import configparser import os from qiskit import exceptions DEFAULT_FILENAME = os.path.join(os.path.expanduser("~"), '.qiskit', 'settings.conf') class UserConfig: """Class representing a user config file The config file format should look like: [default] circuit_drawer = mpl """ def __init__(self, filename=None): """Create a UserConfig Args: filename (str): The path to the user config file. If one isn't specified ~/.qiskit/settings.conf is used. """ if filename is None: self.filename = DEFAULT_FILENAME else: self.filename = filename self.settings = {} self.config_parser = configparser.ConfigParser() def read_config_file(self): """Read config file and parse the contents into the settings attr.""" if not os.path.isfile(self.filename): return self.config_parser.read(self.filename) if 'default' in self.config_parser.sections(): circuit_drawer = self.config_parser.get('default', 'circuit_drawer') if circuit_drawer: if circuit_drawer not in ['text', 'mpl', 'latex', 'latex_source']: raise exceptions.QiskitUserConfigError( "%s is not a valid circuit drawer backend. Must be " "either 'text', 'mpl', 'latex', or 'latex_source'" % circuit_drawer) self.settings['circuit_drawer'] = circuit_drawer def get_config(): """Read the config file from the default location or env var It will read a config file at either the default location ~/.qiskit/settings.conf or if set the value of the QISKIT_SETTINGS env var. It will return the parsed settings dict from the parsed config file. Returns: dict: The settings dict from the parsed config file. """ filename = os.getenv('QISKIT_SETTINGS', DEFAULT_FILENAME) if not os.path.isfile(filename): return {} user_config = UserConfig(filename) user_config.read_config_file() return user_config.settings
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from qiskit import * IBMQ.load_accounts(hub=None) from qiskit.tools.monitor import job_monitor, backend_monitor, backend_overview q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[1]) qc.measure(q, c); from qiskit.providers.ibmq import least_busy backend = least_busy(IBMQ.backends(filters=lambda x: not x.configuration().simulator)) backend.name() job1 = execute(qc, backend) job_monitor(job1) job2 = execute(qc, backend) job_monitor(job2, interval=5) backend_monitor(backend) backend_overview()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np import matplotlib.pyplot as plt from IPython.display import display, clear_output from qiskit.primitives import Estimator from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.algorithms.observables_evaluator import estimate_observables from qiskit.algorithms.optimizers import COBYLA, SLSQP from qiskit.circuit import QuantumCircuit, Parameter from qiskit.circuit.library import TwoLocal from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit.utils import algorithm_globals from qiskit_nature.second_q.operators import FermionicOp from qiskit_nature.second_q.mappers import JordanWignerMapper def kronecker_delta_function(n: int, m: int) -> int: """An implementation of the Kronecker delta function. Args: n (int): The first integer argument. m (int): The second integer argument. Returns: Returns 1 if n = m, else returns 0. """ return int(n == m) def create_deuteron_hamiltonian( N: int, hbar_omega: float = 7.0, V_0: float = -5.68658111 ) -> SparsePauliOp: """Creates a version of the Deuteron Hamiltonian as a qubit operator. Args: N (int): An integer number that represents the dimension of the basis. hbar_omega (float, optional): The value of the product of hbar and omega. Defaults to 7.0. V_0 (float, optional): The value of the potential energy. Defaults to -5.68658111. Returns: SparsePauliOp: The qubit-space Hamiltonian that represents the Deuteron. """ hamiltonian_terms = {} for m in range(N): for n in range(N): label = "+_{} -_{}".format(str(n), str(m)) coefficient_kinect = (hbar_omega / 2) * ( (2 * n + 3 / 2) * kronecker_delta_function(n, m) - np.sqrt(n * (n + (1 / 2))) * kronecker_delta_function(n, m + 1) - np.sqrt((n + 1) * (n + (3 / 2)) * kronecker_delta_function(n, m - 1)) ) hamiltonian_terms[label] = coefficient_kinect coefficient_potential = ( V_0 * kronecker_delta_function(n, 0) * kronecker_delta_function(n, m) ) hamiltonian_terms[label] += coefficient_potential hamiltonian = FermionicOp(hamiltonian_terms, num_spin_orbitals=N) mapper = JordanWignerMapper() qubit_hamiltonian = mapper.map(hamiltonian) if not isinstance(qubit_hamiltonian, SparsePauliOp): qubit_hamiltonian = qubit_hamiltonian.primitive return qubit_hamiltonian deuteron_hamiltonians = [create_deuteron_hamiltonian(i) for i in range(1, 5)] for i, hamiltonian in enumerate(deuteron_hamiltonians): print("Deuteron Hamiltonian: H_{}".format(i + 1)) print(hamiltonian) print("\n") theta = Parameter(r"$\theta$") eta = Parameter(r"$\eta$") wavefunction = QuantumCircuit(1) wavefunction.ry(theta, 0) wavefunction.draw("mpl") wavefunction2 = QuantumCircuit(2) wavefunction2.x(0) wavefunction2.ry(theta, 1) wavefunction2.cx(1, 0) wavefunction2.draw("mpl") wavefunction3 = QuantumCircuit(3) wavefunction3.x(0) wavefunction3.ry(eta, 1) wavefunction3.ry(theta, 2) wavefunction3.cx(2, 0) wavefunction3.cx(0, 1) wavefunction3.ry(-eta, 1) wavefunction3.cx(0, 1) wavefunction3.cx(1, 0) wavefunction3.draw("mpl") ansatz = [wavefunction, wavefunction2, wavefunction3] reference_values = [] print("Exact binding energies calculated through numpy.linalg.eigh \n") for i, hamiltonian in enumerate(deuteron_hamiltonians): eigenvalues, eigenstates = np.linalg.eigh(hamiltonian.to_matrix()) reference_values.append(eigenvalues[0]) print("Exact binding energy for H_{}: {}".format(i + 1, eigenvalues[0])) print( "Results using Estimator for H_1, H_2 and H_3 with the ansatz given in the reference paper \n" ) for i in range(3): seed = 42 algorithm_globals.random_seed = seed vqe = VQE(Estimator(), ansatz=ansatz[i], optimizer=SLSQP()) vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i]) binding_energy = vqe_result.optimal_value print("Binding energy for H_{}: {} MeV".format(i + 1, binding_energy)) def callback(eval_count, parameters, mean, std): # Overwrites the same line when printing display("Evaluation: {}, Energy: {}, Std: {}".format(eval_count, mean, std)) clear_output(wait=True) counts.append(eval_count) values.append(mean) params.append(parameters) deviation.append(std) plots = [] for i in range(3): counts = [] values = [] params = [] deviation = [] seed = 42 algorithm_globals.random_seed = seed vqe = VQE(Estimator(), ansatz=ansatz[i], optimizer=COBYLA(), callback=callback) vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i]) plots.append([counts, values]) fig, ax = plt.subplots(nrows=3, ncols=1) fig.set_size_inches((12, 12)) for i, plot in enumerate(plots): ax[i].plot(plot[0], plot[1], "o-", label="COBYLA") ax[i].axhline( y=reference_values[i], color="k", linestyle="--", label=f"Reference Value: {reference_values[i]}", ) ax[i].legend() ax[i].set_xlabel("Cost Function Evaluations", fontsize=15) ax[i].set_ylabel(r"$\langle H_{} \rangle$ - Energy (MeV)".format(i + 1), fontsize=15) plt.show() twolocal_ansatzes = [] for i in range(1, 5): ansatz = TwoLocal( deuteron_hamiltonians[i - 1].num_qubits, ["rz", "ry"], "cx", entanglement="full", reps=i, initial_state=None, ) twolocal_ansatzes.append(ansatz) print("Results using Estimator for H_1, H_2, H_3 and H_4 with TwoLocal ansatz \n") seed = 42 algorithm_globals.random_seed = seed for i in range(4): vqe = VQE(Estimator(), ansatz=twolocal_ansatzes[i], optimizer=SLSQP()) vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i]) binding_energy = vqe_result.optimal_value print("Binding energy for H_{}:".format(i + 1), binding_energy, "MeV") seed = 42 algorithm_globals.random_seed = seed plots_tl = [] for i in range(4): counts = [] values = [] params = [] deviation = [] vqe = VQE( Estimator(), ansatz=twolocal_ansatzes[i], optimizer=SLSQP(), callback=callback, ) vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i]) plots_tl.append([counts, values]) fig, ax = plt.subplots(nrows=4, ncols=1) fig.set_size_inches((15, 15)) for i, plot in enumerate(plots_tl): ax[i].plot(plot[0], plot[1], "o-", label="COBYLA") ax[i].axhline( y=reference_values[i], color="k", linestyle="--", label=f"Reference Value: {reference_values[i]}", ) ax[i].legend() ax[i].set_xlabel("Cost Function Evaluations", fontsize=15) ax[i].set_ylabel(r"$\langle H_{} \rangle$ - Energy (MeV)".format(i + 1), fontsize=15) plt.show() def calculate_observables_exp_values( quantum_circuit: QuantumCircuit, observables: list, angles: list ) -> list: """Calculate the expectation value of an observable given the quantum circuit that represents the wavefunction and a list of parameters. Args: quantum_circuit (QuantumCircuit): A parameterized quantum circuit that represents the wavefunction of the system. observables (list): A list containing the observables that we want to know the expectation values. angles (list): A list with the values that will be used in the 'bind_parameters' method. Returns: list_exp_values (list): A list containing the expectation values of the observables given as input. """ list_exp_values = [] for observable in observables: exp_values = [] for angle in angles: qc = quantum_circuit.bind_parameters({theta: angle}) result = estimate_observables( Estimator(), quantum_state=qc, observables=[observable], ) exp_values.append(result[0][0]) list_exp_values.append(exp_values) return list_exp_values angles = list(np.linspace(-np.pi, np.pi, 100)) observables = [ Pauli("IZ"), Pauli("ZI"), Pauli("XX"), Pauli("YY"), deuteron_hamiltonians[1], ] h2_observables_exp_values = calculate_observables_exp_values(wavefunction2, observables, angles) fig, ax = plt.subplots(nrows=2, ncols=1) fig.set_size_inches((12, 12)) ax[0].plot(angles, h2_observables_exp_values[0], "o", label=r"$Z_0$") ax[0].plot(angles, h2_observables_exp_values[1], "o", label=r"$Z_1$") ax[0].plot(angles, h2_observables_exp_values[2], "o", label=r"$X_0X_1$") ax[0].plot(angles, h2_observables_exp_values[3], "o", label=r"$Y_0Y_1$") ax[0].axhline( y=1, color="k", linestyle="--", ) ax[0].axhline(y=-1, color="k", linestyle="--") ax[0].legend() ax[0].set_xlabel(r"Theta - $\theta$", fontsize=15) ax[0].set_ylabel(r"$\langle O \rangle $ - Operator Expectation Value", fontsize=15) ax[0].set_xticks( [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], labels=[r"$-\pi$", r"$-\pi/2$", "0", r"$\pi/2$", r"$\pi$"], ) ax[0].set_title( r"Expectation value of the observables $Z_0$, $Z_1$, $X_0X_1$ and $Y_0Y_1$ when we vary $\theta$ in the ansatz.", fontsize=15, ) ax[1].plot(angles, h2_observables_exp_values[4], "o") ax[1].axhline( y=reference_values[1], color="k", linestyle="--", label="Binding Energy: {} MeV".format(np.round(reference_values[1], 3)), ) ax[1].legend() ax[1].set_xlabel(r"Theta - $\theta$", fontsize=15) ax[1].set_ylabel(r"$\langle H_2 \rangle $ - Energy (MeV)", fontsize=15) ax[1].set_xticks( [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], labels=[r"$-\pi$", r"$-\pi/2$", "0", r"$\pi/2$", r"$\pi$"], ) ax[1].set_title( r"Behavior of the expectation value of $H_2$ when we vary $\theta$ in the ansatz.", fontsize=15 ) plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
mathelatics
import qiskit qiskit.__qiskit_version__ # useful additional packages import numpy as np import matplotlib.pyplot as plt %matplotlib inline # importing Qiskit from qiskit import BasicAer, IBMQ from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.compiler import transpile from qiskit.tools.monitor import job_monitor # import basic plot tools from qiskit.tools.visualization import plot_histogram # Load our saved IBMQ accounts IBMQ.load_account() n = 13 # the length of the first register for querying the oracle # Choose a type of oracle at random. With probability half it is constant, # and with the same probability it is balanced oracleType, oracleValue = np.random.randint(2), np.random.randint(2) if oracleType == 0: print("The oracle returns a constant value ", oracleValue) else: print("The oracle returns a balanced function") a = np.random.randint(1,2**n) # this is a hidden parameter for balanced oracle. # Creating registers # n qubits for querying the oracle and one qubit for storing the answer qr = QuantumRegister(n+1) #all qubits are initialized to zero # for recording the measurement on the first register cr = ClassicalRegister(n) circuitName = "DeutschJozsa" djCircuit = QuantumCircuit(qr, cr) # Create the superposition of all input queries in the first register by applying the Hadamard gate to each qubit. for i in range(n): djCircuit.h(qr[i]) # Flip the second register and apply the Hadamard gate. djCircuit.x(qr[n]) djCircuit.h(qr[n]) # Apply barrier to mark the beginning of the oracle djCircuit.barrier() if oracleType == 0:#If the oracleType is "0", the oracle returns oracleValue for all input. if oracleValue == 1: djCircuit.x(qr[n]) else: djCircuit.iden(qr[n]) else: # Otherwise, it returns the inner product of the input with a (non-zero bitstring) for i in range(n): if (a & (1 << i)): djCircuit.cx(qr[i], qr[n]) # Apply barrier to mark the end of the oracle djCircuit.barrier() # Apply Hadamard gates after querying the oracle for i in range(n): djCircuit.h(qr[i]) # Measurement djCircuit.barrier() for i in range(n): djCircuit.measure(qr[i], cr[i]) #draw the circuit djCircuit.draw(output='mpl',scale=0.5) backend = BasicAer.get_backend('qasm_simulator') shots = 1000 job = execute(djCircuit, backend=backend, shots=shots) results = job.result() answer = results.get_counts() plot_histogram(answer) backend = IBMQ.get_backend('ibmq_16_melbourne') djCompiled = transpile(djCircuit, backend=backend, optimization_level=1) djCompiled.draw(output='mpl',scale=0.5) job = execute(djCompiled, backend=backend, shots=1024) job_monitor(job) results = job.result() answer = results.get_counts() threshold = int(0.01 * shots) # the threshold of plotting significant measurements filteredAnswer = {k: v for k,v in answer.items() if v >= threshold} # filter the answer for better view of plots removedCounts = np.sum([ v for k,v in answer.items() if v < threshold ]) # number of counts removed filteredAnswer['other_bitstrings'] = removedCounts # the removed counts are assigned to a new index plot_histogram(filteredAnswer) print(filteredAnswer)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) ghz.draw(output='mpl')
https://github.com/InvictusWingsSRL/QiskitTutorials
InvictusWingsSRL
#Libraries needed to implement and simulate quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile, qasm2, qasm3 from qiskit_aer import Aer from qiskit.primitives import BackendSampler #Custem functions to simplify answers import Our_Qiskit_Functions as oq #a part of the library presented in arXiv:1903.04359v1. import numpy as np import math as m #Initialize backends simulators to visualize circuits S_simulator = Aer.backends(name='statevector_simulator')[0] M_simulator = Aer.backends(name='qasm_simulator')[0] q = QuantumRegister(2, name='q') test_g = QuantumCircuit(q, name = 'qc') test_g.h(q[0]) test_g.x(q[1]) test_g.cz(q[0],q[1]) test_g.x(q[1]) print('_________Initial state____________') oq.Wavefunction(test_g) f=oq.Blackbox_g_D(test_g, q) print('\n_____________After blackbox___________') oq.Wavefunction(test_g); q = QuantumRegister(2, name='q') deutsch_qc = QuantumCircuit(q, name = 'qc') deutsch_qc.h(q[0]) deutsch_qc.x(q[1]) deutsch_qc.h(q[1]) print('_________Initial state____________') oq.Wavefunction(deutsch_qc) deutsch_qc.draw() q = QuantumRegister(2, name='q') deutsch_qc = QuantumCircuit(q, name = 'qc') deutsch_qc.h(q[0]) deutsch_qc.x(q[1]) deutsch_qc.h(q[1]) print('_________Initial state____________') oq.Wavefunction(deutsch_qc) f=oq.Blackbox_g_D(deutsch_qc, q) print('\n_____________After blackbox___________') oq.Wavefunction(deutsch_qc) deutsch_qc.h(q[0]) deutsch_qc.h(q[1]) print('\n_____________After H^2___________') oq.Wavefunction(deutsch_qc); q = QuantumRegister(2, name='q') deutsch_qc = QuantumCircuit(q, name = 'qc') deutsch_qc.x(q[1]) deutsch_qc.h(q[0]) deutsch_qc.h(q[1]) print('_________Initial state____________') oq.Wavefunction(deutsch_qc) f=oq.Blackbox_g_D(deutsch_qc, q) print('\n_____________After blackbox___________') oq.Wavefunction(deutsch_qc) deutsch_qc.h(q[0]) #deutsch_qc.h(q[1]) print('\n_____________After H^2___________') oq.Wavefunction(deutsch_qc); q = QuantumRegister(2, name='q') c = ClassicalRegister(2, name='c') deutsch_qc = QuantumCircuit(q, c, name = 'qc') deutsch_qc.x(q[1]) f = oq.Deutsch(deutsch_qc, q) deutsch_qc.measure(q,c) Qubit0_M = list(oq.execute(deutsch_qc, M_simulator, shots = 1).result().get_counts(deutsch_qc).keys())[0][1] if Qubit0_M == '0': print('Measured state |0> therefore f is constant!') else: print('Measured state |1> therefore f is balanced!') print(' ') print('Hidden f: ',f) q = QuantumRegister(2, name='q') zero_CNOT = QuantumCircuit(q, name = 'qc') zero_CNOT.x(q[1]) zero_CNOT.h(q[0]) zero_CNOT.h(q[1]) print('_________Initial state____________') oq.Wavefunction(zero_CNOT) zero_CNOT.x(q[0]) print('_________X____________') oq.Wavefunction(zero_CNOT) zero_CNOT.cx(q[0],q[1]) print('_________CNOT____________') oq.Wavefunction(zero_CNOT) zero_CNOT.x(q[0]) print('_________X____________') oq.Wavefunction(zero_CNOT) zero_CNOT.draw(output='mpl')
https://github.com/zapatacomputing/qe-qiskit
zapatacomputing
################################################################################ # © Copyright 2021-2022 Zapata Computing Inc. ################################################################################ """Translations between Qiskit parameter expressions and intermediate expression trees. """ import operator from functools import lru_cache, reduce, singledispatch from numbers import Number import qiskit from orquestra.quantum.circuits.symbolic.expressions import ExpressionDialect, reduction from orquestra.quantum.circuits.symbolic.sympy_expressions import expression_from_sympy from ._symengine_expressions import expression_from_symengine @singledispatch def expression_from_qiskit(expression): """Parse Qiskit expression into intermediate expression tree.""" raise NotImplementedError( f"Expression {expression} of type {type(expression)} is currently not supported" ) @expression_from_qiskit.register def _number_identity(number: Number): return number @expression_from_qiskit.register def _expr_from_qiskit_param_expr( qiskit_expr: qiskit.circuit.parameterexpression.ParameterExpression, ): # At the moment of writing this the qiskit version that we use (0.23.2) as well # as the newest version 0.23.5) does not provide a better way to access symbolic # expression wrapped by ParameterExpression. inner_expr = qiskit_expr._symbol_expr try: return expression_from_symengine(inner_expr) except NotImplementedError: return expression_from_sympy(inner_expr) def integer_pow(base, exponent: int): """Exponentiation to the power of an integer exponent.""" if not isinstance(exponent, int): raise ValueError( f"Cannot convert expression {base} ** {exponent} to Qiskit. " "Only powers with integral exponent are convertible." ) if exponent < 0: if base != 0: base = 1 / base exponent = -exponent else: raise ValueError( f"Invalid power: cannot raise 0 to exponent {exponent} < 0." ) return reduce(operator.mul, exponent * [base], 1) @lru_cache(maxsize=None) def _qiskit_param_from_name(name): return qiskit.circuit.Parameter(name) QISKIT_DIALECT = ExpressionDialect( symbol_factory=lambda symbol: _qiskit_param_from_name(symbol.name), number_factory=lambda number: number, known_functions={ "add": reduction(operator.add), "mul": reduction(operator.mul), "div": operator.truediv, "sub": operator.sub, "pow": integer_pow, }, ) """Mapping from the intermediate expression tree into Qiskit symbolic expression atoms. Allows translating an expression into the Qiskit dialect. Can be used with `orquestra.quantum.circuits.symbolic.translations.translate_expression`. """
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.units import DistanceUnit from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver( atom="H 0 0 0; H 0 0 0.735", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) es_problem = driver.run() from qiskit_nature.second_q.mappers import JordanWignerMapper mapper = JordanWignerMapper() from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver numpy_solver = NumPyMinimumEigensolver() from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.algorithms.optimizers import SLSQP from qiskit.primitives import Estimator from qiskit_nature.second_q.circuit.library import HartreeFock, UCCSD ansatz = UCCSD( es_problem.num_spatial_orbitals, es_problem.num_particles, mapper, initial_state=HartreeFock( es_problem.num_spatial_orbitals, es_problem.num_particles, mapper, ), ) vqe_solver = VQE(Estimator(), ansatz, SLSQP()) vqe_solver.initial_point = [0.0] * ansatz.num_parameters from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.circuit.library import TwoLocal tl_circuit = TwoLocal( rotation_blocks=["h", "rx"], entanglement_blocks="cz", entanglement="full", reps=2, parameter_prefix="y", ) another_solver = VQE(Estimator(), tl_circuit, SLSQP()) from qiskit_nature.second_q.algorithms import GroundStateEigensolver calc = GroundStateEigensolver(mapper, vqe_solver) res = calc.solve(es_problem) print(res) calc = GroundStateEigensolver(mapper, numpy_solver) res = calc.solve(es_problem) print(res) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.drivers import GaussianForcesDriver from qiskit_nature.second_q.mappers import DirectMapper from qiskit_nature.second_q.problems import HarmonicBasis driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") basis = HarmonicBasis([2, 2, 2, 2]) vib_problem = driver.run(basis=basis) vib_problem.hamiltonian.truncation_order = 2 mapper = DirectMapper() solver_without_filter = NumPyMinimumEigensolver() solver_with_filter = NumPyMinimumEigensolver( filter_criterion=vib_problem.get_default_filter_criterion() ) gsc_wo = GroundStateEigensolver(mapper, solver_without_filter) result_wo = gsc_wo.solve(vib_problem) gsc_w = GroundStateEigensolver(mapper, solver_with_filter) result_w = gsc_w.solve(vib_problem) print(result_wo) print("\n\n") print(result_w) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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. """Tests for PTM quantum channel representation class.""" import copy import unittest import numpy as np from numpy.testing import assert_allclose from qiskit import QiskitError from qiskit.quantum_info.states import DensityMatrix from qiskit.quantum_info.operators.channel import PTM from .channel_test_case import ChannelTestCase class TestPTM(ChannelTestCase): """Tests for PTM channel representation.""" def test_init(self): """Test initialization""" mat4 = np.eye(4) / 2.0 chan = PTM(mat4) assert_allclose(chan.data, mat4) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) mat16 = np.eye(16) / 4 chan = PTM(mat16) assert_allclose(chan.data, mat16) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(chan.num_qubits, 2) # Wrong input or output dims should raise exception self.assertRaises(QiskitError, PTM, mat16, input_dims=2, output_dims=4) # Non multi-qubit dimensions should raise exception self.assertRaises(QiskitError, PTM, np.eye(6) / 2, input_dims=3, output_dims=2) def test_circuit_init(self): """Test initialization from a circuit.""" circuit, target = self.simple_circuit_no_measure() op = PTM(circuit) target = PTM(target) self.assertEqual(op, target) def test_circuit_init_except(self): """Test initialization from circuit with measure raises exception.""" circuit = self.simple_circuit_with_measure() self.assertRaises(QiskitError, PTM, circuit) def test_equal(self): """Test __eq__ method""" mat = self.rand_matrix(4, 4, real=True) self.assertEqual(PTM(mat), PTM(mat)) def test_copy(self): """Test copy method""" mat = np.eye(4) with self.subTest("Deep copy"): orig = PTM(mat) cpy = orig.copy() cpy._data[0, 0] = 0.0 self.assertFalse(cpy == orig) with self.subTest("Shallow copy"): orig = PTM(mat) clone = copy.copy(orig) clone._data[0, 0] = 0.0 self.assertTrue(clone == orig) def test_clone(self): """Test clone method""" mat = np.eye(4) orig = PTM(mat) clone = copy.copy(orig) clone._data[0, 0] = 0.0 self.assertTrue(clone == orig) def test_is_cptp(self): """Test is_cptp method.""" self.assertTrue(PTM(self.depol_ptm(0.25)).is_cptp()) # Non-CPTP should return false self.assertFalse(PTM(1.25 * self.ptmI - 0.25 * self.depol_ptm(1)).is_cptp()) def test_compose_except(self): """Test compose different dimension exception""" self.assertRaises(QiskitError, PTM(np.eye(4)).compose, PTM(np.eye(16))) self.assertRaises(QiskitError, PTM(np.eye(4)).compose, 2) def test_compose(self): """Test compose method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = PTM(self.ptmX) chan2 = PTM(self.ptmY) chan = chan1.compose(chan2) rho_targ = rho.evolve(PTM(self.ptmZ)) self.assertEqual(rho.evolve(chan), rho_targ) # 50% depolarizing channel chan1 = PTM(self.depol_ptm(0.5)) chan = chan1.compose(chan1) rho_targ = rho.evolve(PTM(self.depol_ptm(0.75))) self.assertEqual(rho.evolve(chan), rho_targ) # Compose random ptm1 = self.rand_matrix(4, 4, real=True) ptm2 = self.rand_matrix(4, 4, real=True) chan1 = PTM(ptm1, input_dims=2, output_dims=2) chan2 = PTM(ptm2, input_dims=2, output_dims=2) rho_targ = rho.evolve(chan1).evolve(chan2) chan = chan1.compose(chan2) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(rho.evolve(chan), rho_targ) chan = chan1 & chan2 self.assertEqual(chan.dim, (2, 2)) self.assertEqual(rho.evolve(chan), rho_targ) def test_dot(self): """Test dot method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = PTM(self.ptmX) chan2 = PTM(self.ptmY) rho_targ = rho.evolve(PTM(self.ptmZ)) self.assertEqual(rho.evolve(chan2.dot(chan1)), rho_targ) self.assertEqual(rho.evolve(chan2 @ chan1), rho_targ) # Compose random ptm1 = self.rand_matrix(4, 4, real=True) ptm2 = self.rand_matrix(4, 4, real=True) chan1 = PTM(ptm1, input_dims=2, output_dims=2) chan2 = PTM(ptm2, input_dims=2, output_dims=2) rho_targ = rho.evolve(chan1).evolve(chan2) self.assertEqual(rho.evolve(chan2.dot(chan1)), rho_targ) self.assertEqual(rho.evolve(chan2 @ chan1), rho_targ) def test_compose_front(self): """Test deprecated front compose method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = PTM(self.ptmX) chan2 = PTM(self.ptmY) chan = chan2.compose(chan1, front=True) rho_targ = rho.evolve(PTM(self.ptmZ)) self.assertEqual(rho.evolve(chan), rho_targ) # Compose random ptm1 = self.rand_matrix(4, 4, real=True) ptm2 = self.rand_matrix(4, 4, real=True) chan1 = PTM(ptm1, input_dims=2, output_dims=2) chan2 = PTM(ptm2, input_dims=2, output_dims=2) rho_targ = rho.evolve(chan1).evolve(chan2) chan = chan2.compose(chan1, front=True) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(rho.evolve(chan), rho_targ) def test_expand(self): """Test expand method.""" rho0, rho1 = np.diag([1, 0]), np.diag([0, 1]) rho_init = DensityMatrix(np.kron(rho0, rho0)) chan1 = PTM(self.ptmI) chan2 = PTM(self.ptmX) # X \otimes I chan = chan1.expand(chan2) rho_targ = DensityMatrix(np.kron(rho1, rho0)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # I \otimes X chan = chan2.expand(chan1) rho_targ = DensityMatrix(np.kron(rho0, rho1)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # Completely depolarizing chan_dep = PTM(self.depol_ptm(1)) chan = chan_dep.expand(chan_dep) rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) def test_tensor(self): """Test tensor method.""" rho0, rho1 = np.diag([1, 0]), np.diag([0, 1]) rho_init = DensityMatrix(np.kron(rho0, rho0)) chan1 = PTM(self.ptmI) chan2 = PTM(self.ptmX) # X \otimes I chan = chan2.tensor(chan1) rho_targ = DensityMatrix(np.kron(rho1, rho0)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # I \otimes X chan = chan1.tensor(chan2) rho_targ = DensityMatrix(np.kron(rho0, rho1)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # Completely depolarizing chan_dep = PTM(self.depol_ptm(1)) chan = chan_dep.tensor(chan_dep) rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) def test_power(self): """Test power method.""" # 10% depolarizing channel p_id = 0.9 depol = PTM(self.depol_ptm(1 - p_id)) # Compose 3 times p_id3 = p_id**3 chan3 = depol.power(3) targ3 = PTM(self.depol_ptm(1 - p_id3)) self.assertEqual(chan3, targ3) def test_add(self): """Test add method.""" mat1 = 0.5 * self.ptmI mat2 = 0.5 * self.depol_ptm(1) chan1 = PTM(mat1) chan2 = PTM(mat2) targ = PTM(mat1 + mat2) self.assertEqual(chan1._add(chan2), targ) self.assertEqual(chan1 + chan2, targ) targ = PTM(mat1 - mat2) self.assertEqual(chan1 - chan2, targ) def test_add_qargs(self): """Test add method with qargs.""" mat = self.rand_matrix(8**2, 8**2) mat0 = self.rand_matrix(4, 4) mat1 = self.rand_matrix(4, 4) op = PTM(mat) op0 = PTM(mat0) op1 = PTM(mat1) op01 = op1.tensor(op0) eye = PTM(self.ptmI) with self.subTest(msg="qargs=[0]"): value = op + op0([0]) target = op + eye.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1]"): value = op + op0([1]) target = op + eye.tensor(op0).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[2]"): value = op + op0([2]) target = op + op0.tensor(eye).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 1]"): value = op + op01([0, 1]) target = op + eye.tensor(op1).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1, 0]"): value = op + op01([1, 0]) target = op + eye.tensor(op0).tensor(op1) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 2]"): value = op + op01([0, 2]) target = op + op1.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[2, 0]"): value = op + op01([2, 0]) target = op + op0.tensor(eye).tensor(op1) self.assertEqual(value, target) def test_sub_qargs(self): """Test subtract method with qargs.""" mat = self.rand_matrix(8**2, 8**2) mat0 = self.rand_matrix(4, 4) mat1 = self.rand_matrix(4, 4) op = PTM(mat) op0 = PTM(mat0) op1 = PTM(mat1) op01 = op1.tensor(op0) eye = PTM(self.ptmI) with self.subTest(msg="qargs=[0]"): value = op - op0([0]) target = op - eye.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1]"): value = op - op0([1]) target = op - eye.tensor(op0).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[2]"): value = op - op0([2]) target = op - op0.tensor(eye).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 1]"): value = op - op01([0, 1]) target = op - eye.tensor(op1).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1, 0]"): value = op - op01([1, 0]) target = op - eye.tensor(op0).tensor(op1) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 2]"): value = op - op01([0, 2]) target = op - op1.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[2, 0]"): value = op - op01([2, 0]) target = op - op0.tensor(eye).tensor(op1) self.assertEqual(value, target) def test_add_except(self): """Test add method raises exceptions.""" chan1 = PTM(self.ptmI) chan2 = PTM(np.eye(16)) self.assertRaises(QiskitError, chan1._add, chan2) self.assertRaises(QiskitError, chan1._add, 5) def test_multiply(self): """Test multiply method.""" chan = PTM(self.ptmI) val = 0.5 targ = PTM(val * self.ptmI) self.assertEqual(chan._multiply(val), targ) self.assertEqual(val * chan, targ) targ = PTM(self.ptmI * val) self.assertEqual(chan * val, targ) def test_multiply_except(self): """Test multiply method raises exceptions.""" chan = PTM(self.ptmI) self.assertRaises(QiskitError, chan._multiply, "s") self.assertRaises(QiskitError, chan.__rmul__, "s") self.assertRaises(QiskitError, chan._multiply, chan) self.assertRaises(QiskitError, chan.__rmul__, chan) def test_negate(self): """Test negate method""" chan = PTM(self.ptmI) targ = PTM(-self.ptmI) self.assertEqual(-chan, targ) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit.quantumcircuitdata import CircuitInstruction from qiskit.circuit import Measure from qiskit.circuit.library import HGate, CXGate qr = QuantumRegister(2) cr = ClassicalRegister(2) instructions = [ CircuitInstruction(HGate(), [qr[0]], []), CircuitInstruction(CXGate(), [qr[0], qr[1]], []), CircuitInstruction(Measure(), [qr[0]], [cr[0]]), CircuitInstruction(Measure(), [qr[1]], [cr[1]]), ] circuit = QuantumCircuit.from_instructions(instructions) circuit.draw("mpl")
https://github.com/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/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt plt.style.use("ggplot") from pprint import pprint import pickle import time import datetime %matplotlib inline with open("e2d1_raw.pkl", "rb") as f: raw = pickle.load(f) with open("e2d1_qrem.pkl", "rb") as f: qrem = pickle.load(f) with open("e2d1_zne.pkl", "rb") as f: zne = pickle.load(f) with open("e2d1_zne_pt.pkl", "rb") as f: zne_pt = pickle.load(f) num_steps_list = raw["num_steps_list"] raw_fid_list = raw["fid"] raw_stddev_list = raw["stddev"] num_steps_list = qrem["num_steps_list"] qrem_fid_list = qrem["fid"] qrem_stddev_list = qrem["stddev"] num_steps_list = zne["num_steps_list"] zne_fid_list = zne["fid"] zne_stddev_list = zne["stddev"] num_steps_list = zne_pt["num_steps_list"] zne_pt_fid_list = zne_pt["fid"] zne_pt_stddev_list = zne_pt["stddev"] plt.clf() plt.figure(dpi=200) plt.scatter(num_steps_list, raw_fid_list) plt.scatter(num_steps_list, qrem_fid_list) plt.scatter(num_steps_list, zne_fid_list) plt.scatter(num_steps_list, zne_pt_fid_list) limit = 13 plt.clf() plt.figure(dpi=200) plt.scatter(num_steps_list[:limit], raw_fid_list[:limit], marker="o") plt.scatter(num_steps_list[:limit], qrem_fid_list[:limit], marker="v") plt.scatter(num_steps_list[:limit], zne_fid_list[:limit], marker="x") plt.scatter(num_steps_list[:limit], zne_pt_fid_list[:limit], marker="*") plt.xlabel("number of trotter steps") plt.ylabel("state fidelity") plt.legend(("without error mitigations", "with QREM", "with QREM and ZNE", "with QREM, ZNE and Pauli Twirling")) plt.title("The effect of error mitigations") zne_pt_fid_list[12] import qiskit.tools.jupyter %qiskit_version_table
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) ### replaced cx gate ### qc.cy(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) qc.h(1) return qc
https://github.com/arnavdas88/QuGlassyIsing
arnavdas88
!pip install qiskit J = 4.0 B_x = 0.0 B_z = 0.0 import numpy as np from qiskit.providers.aer import AerSimulator, QasmSimulator from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit.aqua.operators import * from qiskit.aqua import set_qiskit_aqua_logging, QuantumInstance from qiskit.aqua.algorithms import NumPyMinimumEigensolver, VQE, NumPyEigensolver from qiskit.circuit import QuantumCircuit, ParameterVector from qiskit.visualization import plot_histogram Hamiltonian = J * (Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z) - B_z * (( Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ) ) - B_x * ( ( X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X )) ansatz = TwoLocal(num_qubits=36, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True) print(ansatz) backend = AerSimulator(method='matrix_product_state') quantum_instance = QuantumInstance(backend, shots = 8192, initial_layout = None, optimization_level = 3) optimizer = COBYLA(maxiter=10000, tol=0.000000001) vqe = VQE(Hamiltonian, ansatz, optimizer, include_custom = False) print('We are using:', quantum_instance.backend) vqe_result = vqe.run(quantum_instance) print(vqe['result']) plot_histogram(vqe_result['eigenstate']) import pickle filename = "2D_Ising_Model_CountsAF1.pkl" a = {'vqe_result': vqe_result} #This saves the data with open(filename, 'wb') as handle: pickle.dump(a, handle, protocol=pickle.HIGHEST_PROTOCOL) # This loads the data with open(filename, 'rb') as handle: b = pickle.load(handle)
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
# You can show the phase of each state and use # degrees instead of radians from qiskit.quantum_info import DensityMatrix import numpy as np from qiskit import QuantumCircuit from qiskit.visualization import plot_state_qsphere qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0,1) qc.ry(np.pi/3, 0) qc.rx(np.pi/5, 1) qc.z(1) matrix = DensityMatrix(qc) plot_state_qsphere(matrix, show_state_phases = True, use_degrees = True)
https://github.com/xtophe388/QISKIT
xtophe388
import qiskit qiskit.__qiskit_version__ from math import pi import numpy as np import scipy as sp import matplotlib.pyplot as plt %matplotlib inline # importing Qiskit from qiskit import BasicAer, IBMQ from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute from qiskit.tools.visualization import plot_histogram from qiskit.tools.monitor import job_monitor # Load saved IBMQ accounts IBMQ.load_account() # We first define controlled gates used in the IPEA def cu1fixed(qProg, c, t, a): qProg.u1(-a, t) qProg.cx(c, t) qProg.u1(a, t) qProg.cx(c, t) def cu5pi8(qProg, c, t): cu1fixed(qProg, c, t, -5.0*pi/8.0) # We then prepare quantum and classical registers and the circuit qr = QuantumRegister(2) cr = ClassicalRegister(4) circuitName="IPEAonSimulator" ipeaCircuit = QuantumCircuit(qr, cr) # Apply IPEA ipeaCircuit.h(qr[0]) for i in range(8): cu5pi8(ipeaCircuit, qr[0], qr[1]) ipeaCircuit.h(qr[0]) ipeaCircuit.measure(qr[0], cr[0]) ipeaCircuit.reset(qr[0]) ipeaCircuit.h(qr[0]) for i in range(4): cu5pi8(ipeaCircuit, qr[0], qr[1]) ipeaCircuit.u1(-pi/2, qr[0]).c_if(cr, 1) ipeaCircuit.h(qr[0]) ipeaCircuit.measure(qr[0], cr[1]) ipeaCircuit.reset(qr[0]) ipeaCircuit.h(qr[0]) for i in range(2): cu5pi8(ipeaCircuit, qr[0], qr[1]) ipeaCircuit.u1(-pi/4, qr[0]).c_if(cr, 1) ipeaCircuit.u1(-pi/2, qr[0]).c_if(cr, 2) ipeaCircuit.u1(-3*pi/4, qr[0]).c_if(cr, 3) ipeaCircuit.h(qr[0]) ipeaCircuit.measure(qr[0], cr[2]) ipeaCircuit.reset(qr[0]) ipeaCircuit.h(qr[0]) cu5pi8(ipeaCircuit, qr[0], qr[1]) ipeaCircuit.u1(-pi/8, qr[0]).c_if(cr, 1) ipeaCircuit.u1(-2*pi/8, qr[0]).c_if(cr, 2) ipeaCircuit.u1(-3*pi/8, qr[0]).c_if(cr, 3) ipeaCircuit.u1(-4*pi/8, qr[0]).c_if(cr, 4) ipeaCircuit.u1(-5*pi/8, qr[0]).c_if(cr, 5) ipeaCircuit.u1(-6*pi/8, qr[0]).c_if(cr, 6) ipeaCircuit.u1(-7*pi/8, qr[0]).c_if(cr, 7) ipeaCircuit.h(qr[0]) ipeaCircuit.measure(qr[0], cr[3]) backend = BasicAer.get_backend('qasm_simulator') shots = 1000 results = execute(ipeaCircuit, backend=backend, shots=shots).result() plot_histogram(results.get_counts()) # We then prepare quantum and classical registers and the circuit qr = QuantumRegister(5) cr = ClassicalRegister(5) realStep1Circuit = QuantumCircuit(qr, cr) # Apply IPEA realStep1Circuit.h(qr[0]) for i in range(8): cu5pi8(realStep1Circuit, qr[0], qr[1]) realStep1Circuit.h(qr[0]) realStep1Circuit.measure(qr[0], cr[0]) #connect to remote API to be able to use remote simulators and real devices print("Available backends:", [BasicAer.backends(), IBMQ.backends()]) backend = IBMQ.get_backend("ibmq_5_yorktown") shots = 1000 job_exp1 = execute(realStep1Circuit, backend=backend, shots=shots) job_monitor(job_exp1) results1 = job_exp1.result() plot_histogram(results1.get_counts()) realStep2Circuit = QuantumCircuit(qr, cr) # Apply IPEA realStep2Circuit.h(qr[0]) for i in range(4): cu5pi8(realStep2Circuit, qr[0], qr[1]) realStep2Circuit.u1(-pi/2, qr[0]) # Assuming the value of the measurement on Step 1 realStep2Circuit.h(qr[0]) realStep2Circuit.measure(qr[0], cr[0]) job_exp2 = execute(realStep2Circuit, backend=backend, shots=shots) job_monitor(job_exp1) results2 = job_exp2.result() plot_histogram(results2.get_counts()) realStep3Circuit = QuantumCircuit(qr, cr) # Apply IPEA realStep3Circuit.h(qr[0]) for i in range(2): cu5pi8(realStep3Circuit, qr[0], qr[1]) realStep3Circuit.u1(-3*pi/4, qr[0]) # Assuming the value of the measurement on Step 1 and Step 2 realStep3Circuit.h(qr[0]) realStep3Circuit.measure(qr[0], cr[0]) job_exp3 = execute(realStep3Circuit, backend=backend, shots=shots) job_monitor(job_exp3) results3 = job_exp3.result() plot_histogram(results3.get_counts()) realStep4Circuit = QuantumCircuit(qr, cr) # Apply IPEA realStep4Circuit.h(qr[0]) cu5pi8(realStep4Circuit, qr[0], qr[1]) realStep4Circuit.u1(-3*pi/8, qr[0]) # Assuming the value of the measurement on Step 1, 2, and 3 realStep4Circuit.h(qr[0]) realStep4Circuit.measure(qr[0], cr[0]) job_exp4 = execute(realStep4Circuit, backend=backend, shots=shots) job_monitor(job_exp4) results4 = job_exp4.result() plot_histogram(results4.get_counts())
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit top = QuantumCircuit(1) top.x(0); bottom = QuantumCircuit(2) bottom.cry(0.2, 0, 1); tensored = bottom.tensor(top) tensored.draw('mpl')
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt plt.style.use("ggplot") from pprint import pprint import pickle import time import datetime %matplotlib inline with open("e2d1_raw.pkl", "rb") as f: raw = pickle.load(f) with open("e2d1_qrem.pkl", "rb") as f: qrem = pickle.load(f) with open("e2d1_zne.pkl", "rb") as f: zne = pickle.load(f) with open("e2d1_zne_pt.pkl", "rb") as f: zne_pt = pickle.load(f) num_steps_list = raw["num_steps_list"] raw_fid_list = raw["fid"] raw_stddev_list = raw["stddev"] num_steps_list = qrem["num_steps_list"] qrem_fid_list = qrem["fid"] qrem_stddev_list = qrem["stddev"] num_steps_list = zne["num_steps_list"] zne_fid_list = zne["fid"] zne_stddev_list = zne["stddev"] num_steps_list = zne_pt["num_steps_list"] zne_pt_fid_list = zne_pt["fid"] zne_pt_stddev_list = zne_pt["stddev"] plt.clf() plt.figure(dpi=200) plt.scatter(num_steps_list, raw_fid_list) plt.scatter(num_steps_list, qrem_fid_list) plt.scatter(num_steps_list, zne_fid_list) plt.scatter(num_steps_list, zne_pt_fid_list) limit = 13 plt.clf() plt.figure(dpi=200) plt.scatter(num_steps_list[:limit], raw_fid_list[:limit], marker="o") plt.scatter(num_steps_list[:limit], qrem_fid_list[:limit], marker="v") plt.scatter(num_steps_list[:limit], zne_fid_list[:limit], marker="x") plt.scatter(num_steps_list[:limit], zne_pt_fid_list[:limit], marker="*") plt.xlabel("number of trotter steps") plt.ylabel("state fidelity") plt.legend(("without error mitigations", "with QREM", "with QREM and ZNE", "with QREM, ZNE and Pauli Twirling")) plt.title("The effect of error mitigations") zne_pt_fid_list[12] import qiskit.tools.jupyter %qiskit_version_table
https://github.com/108mk/Quantum_Algorithms_and_Qiskit
108mk
# initialization import numpy as np # importing Qiskit from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, assemble, transpile # import basic plot tools from qiskit.visualization import plot_histogram import matplotlib as mpl # set the length of the n-bit input string. n = 2 #----------This was the original case considered by David Duetzch-----------# # set the length of the n-bit input string. const_oracle = QuantumCircuit(n+1) output = np.random.randint(2) if output == 1: const_oracle.x(n) const_oracle.draw("mpl") balanced_oracle = QuantumCircuit(n+1) #------input a 2-bit string as of your choice!!!!!!!! b_str = "11" balanced_oracle = QuantumCircuit(n+1) # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) balanced_oracle.draw("mpl") # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() balanced_oracle.draw("mpl") # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Show oracle balanced_oracle.draw("mpl") dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) dj_circuit.draw("mpl") # Add oracle dj_circuit = QuantumCircuit.compose(dj_circuit,balanced_oracle) dj_circuit.draw("mpl") # Repeat H-gates for qubit in range(n): dj_circuit.h(qubit) dj_circuit.barrier() # Measure for i in range(n): dj_circuit.measure(i, i) # Display circuit dj_circuit.draw("mpl") # use local simulator aer_sim = Aer.get_backend('aer_simulator') qobj = assemble(dj_circuit, aer_sim) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) #---------CONCLUDING REMARKS---------------- ###--------THE ABOVE ALGORITHM CAN BE EXTENDED TO N-VARAIBLE CASE. IT IS CALLED DUETZCH-JOZSA ALGORITHM-----
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
# Importing Packages from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, transpile, assemble, QuantumRegister, ClassicalRegister from qiskit.visualization import plot_histogram from qiskit_textbook.tools import simon_oracle bb = input("Enter the input string:\n") ### Using in-built "simon_oracle" from QISKIT # importing Qiskit from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, transpile, assemble # import basic plot tools from qiskit.visualization import plot_histogram from qiskit_textbook.tools import simon_oracle n = len(bb) simon_circuit = QuantumCircuit(n*2, n) # Apply Hadamard gates before querying the oracle simon_circuit.h(range(n)) # Apply barrier for visual separation simon_circuit.barrier() simon_circuit += simon_oracle(bb) # Apply barrier for visual separation simon_circuit.barrier() # Apply Hadamard gates to the input register simon_circuit.h(range(n)) # Measure qubits simon_circuit.measure(range(n), range(n)) simon_circuit.draw(output="mpl") # use local simulator aer_sim = Aer.get_backend('aer_simulator') shots = 500 qobj = assemble(simon_circuit, shots=shots) results = aer_sim.run(qobj).result() counts = results.get_counts() print(counts) plot_histogram(counts) # Calculate the dot product of the results 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 = input("Enter a binary string:\n") # Actual b = 011 b_rev = b[::-1] flagbit = b_rev.find('1') n=len(b) q1=QuantumRegister(n,'q1') q2=QuantumRegister(n,'q2') c1=ClassicalRegister(n) qc = QuantumCircuit(q1,q2,c1) qc.barrier() qc.h(q1) qc.barrier() for i in range(n): qc.cx(q1[i],q2[i]) qc.barrier() if flagbit != -1: # print("test1") for ind, bit in enumerate(b_rev): # print("test2") if bit == "1": # print("test3") qc.cx(flagbit, q2[ind]) qc.barrier() qc.h(q1) qc.barrier() qc.measure(q1,c1) qc.draw("mpl") aer_sim = Aer.get_backend('aer_simulator') shots = 500 qobj = assemble(qc, shots=shots) results = aer_sim.run(qobj).result() counts = results.get_counts() print(counts) plot_histogram(counts) # Actual b = 011 b="1" b_rev = "1" flagbit = b_rev.find('1') n=len(b) q1=QuantumRegister(n,'q1') q2=QuantumRegister(n,'q2') c1=ClassicalRegister(n) qc = QuantumCircuit(q1,q2,c1) qc.barrier() qc.h(q1) qc.barrier() for i in range(n): qc.cx(q1[i],q2[i]) qc.barrier() if flagbit != -1: # print("test1") for ind, bit in enumerate(b_rev): # print("test2") if bit == "1": # print("test3") qc.cx(flagbit, q2[ind]) qc.barrier() qc.h(q1) qc.barrier() # qc.measure(q1,c1) # qc.draw("mpl") # Simulate the unitary usim = Aer.get_backend('aer_simulator') qc.save_unitary() qobj = assemble(qc) unitary = usim.run(qobj).result().get_unitary() # Display the results: array_to_latex(unitary, prefix="\\text{Circuit = } ")
https://github.com/alejomonbar/Bin-Packing-Problem
alejomonbar
import numpy as np import matplotlib.pyplot as plt from docplex.mp.model import Model from qiskit import BasicAer from qiskit.algorithms import QAOA, NumPyMinimumEigensolver from qiskit_optimization.algorithms import CplexOptimizer, MinimumEigenOptimizer from qiskit_optimization.algorithms.admm_optimizer import ADMMParameters, ADMMOptimizer from qiskit_optimization import QuadraticProgram from qiskit_optimization.converters import InequalityToEquality, IntegerToBinary, LinearEqualityToPenalty def data_bins(results, wj, n, m, l=0, simplify=False): """save the results on a dictionary with the three items, bins, items, and index. results (cplex.solve): results of the optimization wj: (array (1,m): weights of the items n: (int) number of items m: (int) number of bins """ if simplify: bins = np.ones((m,)) if m-l > 0: bins[m-l-1:m] = results[:m-l] items = np.zeros((m,n)) items[:,1:] = results[m-l:(m-1)*n+m-l].reshape(m,n-1) items[0,0] = 1 items = items.reshape(m,n) * wj return {"bins":bins, "items":items,"index":np.arange(m)} else: return {"bins":results[:m], "items":results[m:m+m*n].reshape(m,n) * wj, "index":np.arange(m)} def plot_bins(results, wj, n, m, l=0,simplify=False): """plot in a bar diagram the results of an optimization bin packing problem""" res = data_bins(results.x, wj, n, m, l, simplify) plt.figure() ind = res["index"] plt.bar(ind, res["items"][:,0], label=f"item {0}") suma = bottom=res["items"][:,0] for j in range(1,n): plt.bar(ind, res["items"][:,j], bottom=suma, label=f"item {j}") suma += res["items"][:,j] plt.hlines(Q,0-0.5,m-0.5,linestyle="--", color="r",label="Max W") plt.xticks(ind) plt.xlabel("Bin") plt.ylabel("Weight") plt.legend() np.random.seed(2) n = 3 # number of bins m = n # number of items Q = 40 # max weight of a bin wj = np.random.randint(1,Q,n) # Randomly picking the item weight # Construct model using docplex mdl = Model("BinPacking") x = mdl.binary_var_list([f"x{i}" for i in range(n)]) # list of variables that represent the bins e = mdl.binary_var_list([f"e{i//m},{i%m}" for i in range(n*m)]) # variables that represent the items on the specific bin objective = mdl.sum([x[i] for i in range(n)]) mdl.minimize(objective) for j in range(m): # First set of constraints: the items must be in any bin constraint0 = mdl.sum([e[i*m+j] for i in range(n)]) mdl.add_constraint(constraint0 == 1, f"cons0,{j}") for i in range(n): # Second set of constraints: weight constraints constraint1 = mdl.sum([wj[j] * e[i*m+j] for j in range(m)]) mdl.add_constraint(constraint1 <= Q * x[i], f"cons1,{i}") # Load quadratic program from docplex model qp = QuadraticProgram() qp.from_docplex(mdl) print(qp.export_as_lp_string()) # convert from DOcplex model to Qiskit Quadratic program qp = QuadraticProgram() qp.from_docplex(mdl) # Solving Quadratic Program using CPLEX cplex = CplexOptimizer() result = cplex.solve(qp) print(result) plot_bins(result, wj, n, m) # Construct model using docplex mdl = Model("BinPacking_simplify") l = int(np.ceil(np.sum(wj)/Q)) x = mdl.binary_var_list([f"x{i}" for i in range(m)]) # list of variables that represent the bins e = mdl.binary_var_list([f"e{i//m},{i%m}" for i in range(n*m)]) # variables that represent the items on the specific bin objective = mdl.sum([x[i] for i in range(n)]) mdl.minimize(objective) for j in range(m): # First set of constraints: the items must be in any bin constraint0 = mdl.sum([e[i*m+j] for i in range(n)]) mdl.add_constraint(constraint0 == 1, f"cons0,{j}") for i in range(n): # Second set of constraints: weight constraints constraint1 = mdl.sum([wj[j] * e[i*m+j] for j in range(m)]) mdl.add_constraint(constraint1 <= Q * x[i], f"cons1,{i}") # Load quadratic program from docplex model qp = QuadraticProgram() qp.from_docplex(mdl) # Simplifying the problem for i in range(l): qp = qp.substitute_variables({f"x{i}":1}) qp = qp.substitute_variables({"e0,0":1}) for i in range(1,m): qp = qp.substitute_variables({f"e{i},0":0}) print(qp.export_as_lp_string()) simplify_result = cplex.solve(qp) print(simplify_result) plot_bins(simplify_result, wj, n, m, l, simplify=True) ineq2eq = InequalityToEquality() qp_eq = ineq2eq.convert(qp) print(qp_eq.export_as_lp_string()) print(f"The number of variables is {qp_eq.get_num_vars()}") int2bin = IntegerToBinary() qp_eq_bin = int2bin.convert(qp_eq) print(qp_eq_bin.export_as_lp_string()) print(f"The number of variables is {qp_eq_bin.get_num_vars()}") lineq2penalty = LinearEqualityToPenalty() qubo = lineq2penalty.convert(qp_eq_bin) print(f"The number of variables is {qp_eq_bin.get_num_vars()}") print(qubo.export_as_lp_string()) result = cplex.solve(qubo) print(result) data_bins(result.x, wj, n, m, l=l, simplify=True) plot_bins(result, wj, n, m, l=l, simplify=True) from qiskit import Aer backend = Aer.get_backend("qasm_simulator") qaoa = MinimumEigenOptimizer(QAOA(reps=3, quantum_instance=backend)) result_qaoa = qaoa.solve(qubo) print(result_qaoa) plot_bins(result, wj, n, m, l, simplify=True) plt.title("QAOA solution", fontsize=18) # Proposal plt.figure() alpha = -2 x = np.linspace(-5,5,100) f = (-(x+alpha) + (x+alpha)**2) plt.plot(x,f) plt.grid() plt.xlabel("x") plt.ylabel("f(x)") # Construct model using docplex mdl = Model("binPackingMyApproach") x = mdl.binary_var_list([f"x{i}" for i in range(n)]) # list of variables that represent the bins e = mdl.binary_var_list([f"e{i//m},{i%n}" for i in range(n*m)]) # variables that represent the items on the specific bin objective = mdl.sum([x[i] for i in range(m)]) cons = 0 alpha = -10 for i in range(m): cons_1 = 0 cons_1 += Q*x[i] for j in range(n): cons_1 -= wj[j]*e[i*m+j] cons += (-(cons_1+alpha) + (cons_1+alpha)**2) mdl.minimize(objective + cons) for j in range(m): # First set of constraints: the items must be in any bin constraint0 = mdl.sum([e[i*m+j] for i in range(n)]) mdl.add_constraint(constraint0 == 1, f"cons0,{j}") # # Load quadratic program from docplex model qp = QuadraticProgram() qp.from_docplex(mdl) # Simplifying the problem for i in range(l): qp = qp.substitute_variables({f"x{i}":1}) qp = qp.substitute_variables({"e0,0":1}) for i in range(1,m): qp = qp.substitute_variables({f"e{i},0":0}) print(qp.export_as_lp_string()) print(f"The number of variables is {qp.get_num_vars()}") # Solving Quadratic Program using CPLEX cplex = CplexOptimizer() result = cplex.solve(qp) print(result) plot_bins(result, wj, n, m, l, simplify=True) qubo_myapp = lineq2penalty.convert(qp) result_myapp = qaoa.solve(qubo_myapp) print(result_myapp) plot_bins(result_myapp, wj, n, m, l, simplify=True) plt.title("QAOA solution") 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.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector qc = QuantumCircuit(2) qc.h(0) qc.x(1) state = Statevector(qc) plot_bloch_multivector(state)
https://github.com/AntonSimen06/qGAN
AntonSimen06
from qiskit import * from qiskit.visualization import * import matplotlib.pyplot as plt import numpy as np import math simulator = BasicAer.get_backend('qasm_simulator') prob_distr = [8, 40, 35, 20, 15, 10, 5, 5] #normalization prob_distr = [k/sum(prob_distr) for k in prob_distr] plt.bar(range(len(prob_distr)),prob_distr) def ansatz(param, num_layers): num_q = 3 qc = QuantumCircuit(num_q, num_q) for j in range(num_layers): for i in range(num_q): qc.ry(param[i + j*num_q], i) if j < num_layers-1: qc.cx(0,1) qc.cx(1,2) qc.cx(2,0) qc.barrier() qc.measure(range(num_q), range(num_q)) return qc ansatz(param = np.random.uniform(0, np.pi, 9), num_layers=3).draw('mpl',fold=-1) num_layers = 5 def loss_function(params): num_shots=1024 circ = ansatz(param=params, num_layers=num_layers) counts = execute(circ, backend=simulator, shots=num_shots).result().get_counts(circ) strings = ['000','001','010','011','100','101','110','111'] for i in strings: if i not in counts: counts[i] = 0 p = [counts[string]/num_shots for string in strings] """ cross_entropy = 0 for i in range(len(p)): if p[i]>0: cross_entropy -= prob_distr[i]*math.log2(p[i]) return cross_entropy """ return sum([(p[i] - prob_distr[i])**2 for i in range(len(prob_distr))]) #return sum([abs(p[i] - prob_distr[i]) for i in range(len(prob_distr))]) #return sum([ prob_distr[i]*math.log2(p[i]) for i in range(len(prob_distr))]) from qiskit.algorithms.optimizers import COBYLA,SLSQP,SPSA optimizer = COBYLA(250) ret = optimizer.optimize(num_vars=num_params, objective_function=loss_function, initial_point=np.ones(num_params)) num_shots = 1024 trained_circ = ansatz(param=ret[0], num_layers=num_layers) counts = execute(trained_circ, backend=simulator, shots=num_shots).result().get_counts(trained_circ) strings = ['000','001','010','011','100','101','110','111'] for k in strings: if k not in counts: counts[k]=0 counts = [counts[i]/1024 for i in strings] plt.plot(range(len(counts)),counts, color='r') plt.bar(range(len(prob_distr)), prob_distr) plt.legend(["qGAN approx.", "Reference"]) plt.title("Probability distributions") plt.grid()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver() problem = driver.run() fermionic_op = problem.hamiltonian.second_q_op() from qiskit_nature.second_q.mappers import JordanWignerMapper mapper = JordanWignerMapper() qubit_jw_op = mapper.map(fermionic_op) print(qubit_jw_op) from qiskit_nature.second_q.mappers import ParityMapper mapper = ParityMapper() qubit_p_op = mapper.map(fermionic_op) print(qubit_p_op) mapper = ParityMapper(num_particles=problem.num_particles) qubit_op = mapper.map(fermionic_op) print(qubit_op) tapered_mapper = problem.get_tapered_mapper(mapper) print(type(tapered_mapper)) qubit_op = tapered_mapper.map(fermionic_op) print(qubit_op) from qiskit_nature.second_q.circuit.library import HartreeFock hf_state = HartreeFock(2, (1, 1), JordanWignerMapper()) hf_state.draw() from qiskit_nature.second_q.mappers import InterleavedQubitMapper interleaved_mapper = InterleavedQubitMapper(JordanWignerMapper()) hf_state = HartreeFock(2, (1, 1), interleaved_mapper) hf_state.draw() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test executing multiple-register circuits on BasicAer.""" from qiskit import BasicAer, execute from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.quantum_info import Operator, Statevector, process_fidelity, state_fidelity from qiskit.test import QiskitTestCase class TestCircuitMultiRegs(QiskitTestCase): """QuantumCircuit Qasm tests.""" def test_circuit_multi(self): """Test circuit multi regs declared at start.""" qreg0 = QuantumRegister(2, "q0") creg0 = ClassicalRegister(2, "c0") qreg1 = QuantumRegister(2, "q1") creg1 = ClassicalRegister(2, "c1") circ = QuantumCircuit(qreg0, qreg1, creg0, creg1) circ.x(qreg0[1]) circ.x(qreg1[0]) meas = QuantumCircuit(qreg0, qreg1, creg0, creg1) meas.measure(qreg0, creg0) meas.measure(qreg1, creg1) qc = circ.compose(meas) backend_sim = BasicAer.get_backend("qasm_simulator") result = execute(qc, backend_sim, seed_transpiler=34342).result() counts = result.get_counts(qc) target = {"01 10": 1024} backend_sim = BasicAer.get_backend("statevector_simulator") result = execute(circ, backend_sim, seed_transpiler=3438).result() state = result.get_statevector(circ) backend_sim = BasicAer.get_backend("unitary_simulator") result = execute(circ, backend_sim, seed_transpiler=3438).result() unitary = Operator(result.get_unitary(circ)) self.assertEqual(counts, target) self.assertAlmostEqual(state_fidelity(Statevector.from_label("0110"), state), 1.0, places=7) self.assertAlmostEqual( process_fidelity(Operator.from_label("IXXI"), unitary), 1.0, places=7 )
https://github.com/Dpbm/scientific-research-1-quantum-oracles
Dpbm
%matplotlib inline from qiskit import QuantumCircuit, transpile from qiskit_aer import AerSimulator from qiskit.visualization import plot_histogram, array_to_latex from qiskit.quantum_info import Statevector import math from utils import get_image_path def show_unitary(qc): sim = AerSimulator() qc_unitary = qc.copy() qc_unitary.save_unitary() unitary = sim.run(transpile(qc_unitary, sim), shots=1000).result().get_unitary() display(array_to_latex(unitary, max_size=100000)) def plot_results(qc): sim = AerSimulator() result = sim.run(transpile(qc, sim), shots=1000).result().get_counts() display(plot_histogram(result)) _3_qubits_iterator = range(3) """ from 2 to 7 0010 0011 0100 0101 0110 0111 """ oracle = QuantumCircuit(4, name="oracle") #0010 oracle.barrier(label="2") oracle.x([0, 2, 3]) oracle.mcp(math.pi, list(range(1, 4)), 0) oracle.x([0, 2, 3]) #0011 oracle.barrier(label="3") oracle.x([2, 3]) oracle.mcp(math.pi, list(range(1, 4)), 0) oracle.x([2, 3]) #0100 oracle.barrier(label="4") oracle.x([0, 1, 3]) oracle.mcp(math.pi, list(range(1, 4)), 0) oracle.x([0, 1, 3]) #0101 oracle.barrier(label="5") oracle.x([1, 3]) oracle.mcp(math.pi, list(range(1, 4)), 0) oracle.x([1, 3]) #0110 oracle.barrier(label="6") oracle.x([0, 3]) oracle.mcp(math.pi, list(range(1, 4)), 0) oracle.x([0, 3]) #0111 oracle.barrier(label="7") oracle.x(3) oracle.mcp(math.pi, list(range(1, 4)), 0) oracle.x(3) oracle.barrier() display(oracle.draw('mpl')) show_unitary(oracle) def diffuser(n_qubits): iterator_n_qubits = range(n_qubits) diffuser = QuantumCircuit(n_qubits, name="diffuser") diffuser.h(iterator_n_qubits) diffuser.x(iterator_n_qubits) diffuser.h(0) diffuser.mct(list(range(1, n_qubits)), 0) diffuser.h(0) diffuser.x(iterator_n_qubits) diffuser.h(iterator_n_qubits) return diffuser qc_test_1 = QuantumCircuit(4) diffuser_test_1 = diffuser(4) iterator_4_qubits = range(4) qc_test_1.h(iterator_4_qubits) qc_test_1.append(oracle, iterator_4_qubits) qc_test_1.append(diffuser_test_1, iterator_4_qubits) qc_test_1.append(oracle, iterator_4_qubits) qc_test_1.append(diffuser_test_1, iterator_4_qubits) qc_test_1.append(oracle, iterator_4_qubits) qc_test_1.append(diffuser_test_1, iterator_4_qubits) qc_test_1.measure_all() display(qc_test_1.draw('mpl')) plot_results(qc_test_1) qc_test_2 = QuantumCircuit(3) qc_test_2.h(_3_qubits_iterator) qc_test_2.cz(2, 0) qc_test_2.cz(1, 2) qc_test_2.append(diffuser(3), _3_qubits_iterator) qc_test_2.measure_all() display(qc_test_2.draw('mpl')) plot_results(qc_test_2) oracle_less_than_4 = QuantumCircuit(3, name="<4") #000 oracle_less_than_4.x(_3_qubits_iterator) oracle_less_than_4.mcp(math.pi, [2, 1], 0) oracle_less_than_4.x(_3_qubits_iterator) #001 oracle_less_than_4.x(range(1, 3)) oracle_less_than_4.mcp(math.pi, [2, 1], 0) oracle_less_than_4.x(range(1, 3)) #010 oracle_less_than_4.x([0, 2]) oracle_less_than_4.mcp(math.pi, [2, 1], 0) oracle_less_than_4.x([0,2]) #011 oracle_less_than_4.x(2) oracle_less_than_4.mcp(math.pi, [2, 1], 0) oracle_less_than_4.x(2) display(oracle_less_than_4.draw('mpl')) show_unitary(oracle_less_than_4) oracle_less_than_6 = QuantumCircuit(3, name="<6") #000 oracle_less_than_6.x(_3_qubits_iterator) oracle_less_than_6.mcp(math.pi, [2, 1], 0) oracle_less_than_6.x(_3_qubits_iterator) #001 oracle_less_than_6.x(range(1, 3)) oracle_less_than_6.mcp(math.pi, [2, 1], 0) oracle_less_than_6.x(range(1, 3)) #010 oracle_less_than_6.x([0, 2]) oracle_less_than_6.mcp(math.pi, [2, 1], 0) oracle_less_than_6.x([0,2]) #011 oracle_less_than_6.x(2) oracle_less_than_6.mcp(math.pi, [2, 1], 0) oracle_less_than_6.x(2) #100 oracle_less_than_6.x(range(0, 2)) oracle_less_than_6.mcp(math.pi, [2, 1], 0) oracle_less_than_6.x(range(0, 2)) #101 oracle_less_than_6.x(1) oracle_less_than_6.mcp(math.pi, [2, 1], 0) oracle_less_than_6.x(1) display(oracle_less_than_6.draw('mpl')) show_unitary(oracle_less_than_6) grover_diffuser = diffuser(3) grover_oracle = QuantumCircuit(3, name="oracle") grover_oracle.append(oracle_less_than_4, _3_qubits_iterator) grover_oracle.append(oracle_less_than_6, _3_qubits_iterator) qc_test_3 = QuantumCircuit(3) qc_test_3.h(_3_qubits_iterator) qc_test_3.append(grover_oracle, _3_qubits_iterator) qc_test_3.append(grover_diffuser, _3_qubits_iterator) qc_test_3.measure_all() display(qc_test_3.draw('mpl')) plot_results(qc_test_3) add_two_oracle = QuantumCircuit(3, name="+2") add_two_oracle.cx(1, 2) add_two_oracle.x(1) add_two_oracle.cz(1, 2) add_two_oracle.z(1) display(add_two_oracle.draw('mpl')) show_unitary(add_two_oracle) oracle_2 = QuantumCircuit(3, name="oracle") oracle_2.append(oracle_less_than_4, _3_qubits_iterator) oracle_2.append(add_two_oracle, _3_qubits_iterator) display(oracle_2.draw('mpl')) show_unitary(oracle_2) qc = QuantumCircuit(3, name="oracle") qc.append(oracle_less_than_4, _3_qubits_iterator) qc.append(oracle_less_than_6, _3_qubits_iterator) qc.draw('mpl', filename=get_image_path("less_than.png")) show_unitary(qc)
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import * from qiskit.quantum_info import Statevector from math import pi qc=QuantumCircuit(3) qc.ccx(0,1,2) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for ccx gate print(result.get_unitary(qc, decimals=3)) state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(3) qc.x(0) qc.x(1) qc.ccx(0,1,2) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw(output='latex') from qiskit import * from qiskit.quantum_info import Statevector from math import pi qc=QuantumCircuit(3) qc.cswap(0,1,2) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for cswap gate print(result.get_unitary(qc, decimals=3)) state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(3) qc.x(0) qc.x(1) qc.cswap(0,1,2) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw(output='latex')
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np import pylab from qiskit_chemistry import QiskitChemistry # Input dictionary to configure Qiskit Chemistry for the chemistry problem. # Note: In order to allow this to run reasonably quickly it takes advantage # of the ability to freeze core orbitals and remove unoccupied virtual # orbitals to reduce the size of the problem. The result without this # will be more accurate but it takes rather longer to run. qiskit_chemistry_dict = { 'driver': {'name': 'PYSCF'}, 'PYSCF': {'atom': '', 'basis': 'sto3g'}, 'algorithm': {'name': 'ExactEigensolver'}, 'operator': {'name': 'hamiltonian', 'freeze_core': True, 'orbital_reduction': [-3, -2]}, } molecule = 'Li .0 .0 -{0}; H .0 .0 {0}' start = 1.25 # Start distance by = 0.5 # How much to increase distance by steps = 20 # Number of steps to increase by energies = np.empty(steps+1) distances = np.empty(steps+1) dipoles = np.empty(steps+1) print('Processing step __', end='') for i in range(steps+1): print('\b\b{:2d}'.format(i), end='', flush=True) d = start + i*by/steps qiskit_chemistry_dict['PYSCF']['atom'] = molecule.format(d/2) solver = QiskitChemistry() result = solver.run(qiskit_chemistry_dict) distances[i] = d energies[i] = result['energy'] dipoles[i] = result['total_dipole_moment'] print(' --- complete') print('Distances: ', distances) print('Energies:', energies) print('Dipole moments:', dipoles) pylab.plot(distances, energies) pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('LiH Ground State Energy') pylab.plot(distances, dipoles) pylab.xlabel('Interatomic distance') pylab.ylabel('Moment a.u') pylab.title('LiH Dipole Moment')
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/daimurat/qiskit-implementation
daimurat
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit,execute, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() from qiskit.visualization import plot_state_qsphere from qiskit.visualization import plot_bloch_multivector qc=QuantumCircuit(1) statevector_simulator = Aer.get_backend('statevector_simulator') result=execute(qc,statevector_simulator).result() statevector_results=result.get_statevector(qc) plot_bloch_multivector(statevector_results) plot_state_qsphere(statevector_results) qc.x(0) result=execute(qc,statevector_simulator).result() statevector_results=result.get_statevector(qc) plot_bloch_multivector(statevector_results) plot_state_qsphere(statevector_results) qc.h(0) result=execute(qc,statevector_simulator).result() statevector_results=result.get_statevector(qc) plot_bloch_multivector(statevector_results) plot_state_qsphere(statevector_results)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D %matplotlib inline n_instances = 10 class_1 = np.random.rand(n_instances//2, 3)/5 class_2 = (0.6, 0.1, 0.05) + np.random.rand(n_instances//2, 3)/5 data = np.concatenate((class_1, class_2)) colors = ["red"] * (n_instances//2) + ["green"] * (n_instances//2) fig = plt.figure() ax = fig.add_subplot(111, projection='3d', xticks=[], yticks=[], zticks=[]) ax.scatter(data[:, 0], data[:, 1], data[:, 2], c=colors); import itertools w = np.zeros((n_instances, n_instances)) for i, j in itertools.product(*[range(n_instances)]*2): w[i, j] = np.linalg.norm(data[i]-data[j]) from qiskit_aqua import get_aer_backend, QuantumInstance from qiskit_aqua.algorithms import QAOA from qiskit_aqua.components.optimizers import COBYLA from qiskit_aqua.translators.ising import maxcut qubit_operators, offset = maxcut.get_maxcut_qubitops(w) p = 1 optimizer = COBYLA() qaoa = QAOA(qubit_operators, optimizer, p, operator_mode='matrix') backend = get_aer_backend('statevector_simulator') quantum_instance = QuantumInstance(backend, shots=100) result = qaoa.run(quantum_instance) x = maxcut.sample_most_likely(result['eigvecs'][0]) graph_solution = maxcut.get_graph_solution(x) print('energy:', result['energy']) print('maxcut objective:', result['energy'] + offset) print('solution:', maxcut.get_graph_solution(x)) print('solution objective:', maxcut.maxcut_value(x, w)) import dimod J, h = {}, {} for i in range(n_instances): h[i] = 0 for j in range(i+1, n_instances): J[(i, j)] = w[i, j] model = dimod.BinaryQuadraticModel(h, J, 0.0, dimod.SPIN) sampler = dimod.SimulatedAnnealingSampler() response = sampler.sample(model, num_reads=10) print("Energy of samples:") for solution in response.data(): print("Energy:", solution.energy, "Sample:", solution.sample)
https://github.com/tomtuamnuq/compare-qiskit-ocean
tomtuamnuq
import os import shutil import time from random_lp.random_qp import RandomQP DIR = 'TEST_DATA' + "/" + time.strftime("%d_%m_%Y") def getPath(filename = "", directory = ""): return DIR + "/" + directory + "/" + filename DIR shutil.rmtree(getPath(directory = "DENSE"), ignore_errors=True) os.makedirs(getPath(directory = "DENSE")) # create dense random binary quadratic Programs # start with 10 variables and 5 constraints max_qubits = 200 var = 10 while True: cstr = int(var / 2) qp_bin = RandomQP.create_random_binary_prog("test_dense_" + str(var), cstr, var) qp_bin.write_to_lp_file(getPath(qp_bin.name, directory = "DENSE")) if qp_bin.complexity() > max_qubits : print(var) break if qp_bin.complexity() > 100 : var = var + 10 else: var = var + 5
https://github.com/qiskit-community/qiskit-toqm
qiskit-community
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import logging import qiskit_toqm.native as toqm from qiskit.circuit.library.standard_gates import SwapGate from qiskit.dagcircuit import DAGCircuit from qiskit.transpiler.basepasses import TransformationPass from qiskit.transpiler.exceptions import TranspilerError logger = logging.getLogger(__name__) class ToqmSwap(TransformationPass): r"""Map input circuit onto a backend topology via insertion of SWAPs. Implementation of the SWAP-based approach from Time-Optimal Qubit Mapping paper [1]. **References:** [1] Chi Zhang, Ari B. Hayes, Longfei Qiu, Yuwei Jin, Yanhao Chen, and Eddy Z. Zhang. 2021. Time-Optimal Qubit Mapping. In Proceedings of the 26th ACM International Conference on Architectural Support for Programming Languages and Operating Systems (ASPLOS ’21), April 19–23, 2021, Virtual, USA. ACM, New York, NY, USA, 14 pages. `<https://doi.org/10.1145/3445814.3446706>`_ """ def __init__( self, coupling_map, strategy): """ ToqmSwap initializer. Args: coupling_map (CouplingMap): CouplingMap of the target backend. strategy (typing.Callable[[List[toqm.GateOp], int, toqm.CouplingMap], toqm.ToqmResult]): A callable responsible for running the native ``ToqmMapper`` and returning a native ``ToqmResult``. """ super().__init__() if coupling_map is None: # We cannot construct a proper TOQM mapper without a coupling map, # but we gracefully handle construction without one, and then # assert that `run` is never called on this instance. return if coupling_map.size() > 127: raise TranspilerError("ToqmSwap currently supports a max of 127 qubits.") self.coupling_map = coupling_map self.toqm_strategy = strategy self.toqm_result = None def run(self, dag: DAGCircuit): """Run the ToqmSwap pass on `dag`. Args: dag (DAGCircuit): the directed acyclic graph to be mapped. Returns: DAGCircuit: A dag mapped to be compatible with the coupling_map. Raises: TranspilerError: if the coupling map or the layout are not compatible with the DAG """ if self.coupling_map is None: raise TranspilerError("TOQM swap not properly initialized.") if len(dag.qregs) != 1 or dag.qregs.get("q", None) is None: raise TranspilerError("TOQM swap runs on physical circuits only.") if len(dag.qubits) > self.coupling_map.size(): raise TranspilerError("More virtual qubits exist than physical.") reg = dag.qregs["q"] # Generate UIDs for each gate node from the original circuit so we can # look them up later when rebuilding the circuit. # Note: this is still sorted by topological order from above. uid_to_op_node = {uid: op for uid, op in enumerate(dag.topological_op_nodes())} # Create TOQM topological gate list def gates(): for uid, node in uid_to_op_node.items(): if len(node.qargs) == 2: yield toqm.GateOp(uid, node.op.name, reg.index(node.qargs[0]), reg.index(node.qargs[1])) elif len(node.qargs) == 1: yield toqm.GateOp(uid, node.op.name, reg.index(node.qargs[0])) else: raise TranspilerError(f"ToqmSwap only works with 1q and 2q gates! " f"Bad gate: {node.op.name} {node.qargs}") gate_ops = list(gates()) edges = {e for e in self.coupling_map.get_edges()} couplings = toqm.CouplingMap(self.coupling_map.size(), edges) self.toqm_result = self.toqm_strategy(gate_ops, dag.num_qubits(), couplings) # Preserve input DAG's name, regs, wire_map, etc. but replace the graph. mapped_dag = dag.copy_empty_like() for g in self.toqm_result.scheduledGates: if g.gateOp.type.lower() == "swap": mapped_dag.apply_operation_back(SwapGate(), qargs=[reg[g.physicalControl], reg[g.physicalTarget]]) continue original_op = uid_to_op_node[g.gateOp.uid] if g.physicalControl >= 0: mapped_dag.apply_operation_back(original_op.op, cargs=original_op.cargs, qargs=[ reg[g.physicalControl], reg[g.physicalTarget] ]) else: mapped_dag.apply_operation_back(original_op.op, cargs=original_op.cargs, qargs=[ reg[g.physicalTarget] ]) self._update_layout() return mapped_dag def _update_layout(self): layout = self.property_set['layout'] # Need to copy this mapping since layout updates # might overwrite original vbits we need to read! p2v = layout.get_physical_bits().copy() # Update the layout if TOQM made changes. ancilla_vbits = [] for vidx in range(self.toqm_result.numPhysicalQubits): pidx = self.toqm_result.inferredLaq[vidx] if pidx == -1: # bit is not mapped to physical qubit ancilla_vbits.append(p2v[vidx]) continue if pidx != vidx: # Bit was remapped! # First, we need to get the original virtual bit from the layout. vbit = p2v[vidx] # Then, map updated pidx from TOQM to original virtual bit. layout[pidx] = vbit # Map any unmapped physical bits to ancilla. for pidx, vidx in enumerate(self.toqm_result.inferredQal): if vidx < 0: # Current physical bit isn't mapped. Map it to an ancilla. layout[pidx] = ancilla_vbits.pop(0)
https://github.com/maryrbarros2/QuantumAlgorithms_Qiskit
maryrbarros2
from qiskit import QuantumCircuit, Aer, assemble from math import pi import numpy as np from qiskit.visualization import plot_histogram, plot_bloch_multivector qc = QuantumCircuit(3) # Apply H-gate to each qubit: for qubit in range(3): qc.h(qubit) # See the circuit: qc.draw() # Let's see the result svsim = Aer.get_backend('aer_simulator') qc.save_statevector() qobj = assemble(qc) final_state = svsim.run(qobj).result().get_statevector() # In Jupyter Notebooks we can display this nicely using Latex. # If not using Jupyter Notebooks you may need to remove the # array_to_latex function and use print(final_state) instead. from qiskit.visualization import array_to_latex array_to_latex(final_state, prefix="\\text{Statevector} = ") qc2 = QuantumCircuit(2) qc2.h(0) qc2.x(1) # See the circuit: qc2.draw() # Let's see the result svsim = Aer.get_backend('aer_simulator') qc2.save_statevector() qobj2 = assemble(qc2) final_state2 = svsim.run(qobj2).result().get_statevector() # In Jupyter Notebooks we can display this nicely using Latex. # If not using Jupyter Notebooks you may need to remove the # array_to_latex function and use print(final_state) instead. from qiskit.visualization import array_to_latex array_to_latex(final_state2, prefix="\\text{Statevector} = ") qc = QuantumCircuit(2) qc.h(0) qc.x(1) qc.draw() usim = Aer.get_backend('aer_simulator') qc.save_unitary() qobj = assemble(qc) unitary = usim.run(qobj).result().get_unitary() # In Jupyter Notebooks we can display this nicely using Latex. # If not using Jupyter Notebooks you may need to remove the # array_to_latex function and use print(unitary) instead. from qiskit.visualization import array_to_latex array_to_latex(unitary, prefix="\\text{Circuit = }\n") qc = QuantumCircuit(2) qc.x(1) qc.draw() # Simulate the unitary usim = Aer.get_backend('aer_simulator') qc.save_unitary() qobj = assemble(qc) unitary = usim.run(qobj).result().get_unitary() # Display the results: array_to_latex(unitary, prefix="\\text{Circuit = } ") qc = QuantumCircuit(2) # Apply CNOT qc.cx(0,1) # See the circuit: qc.draw() #Writting (and checking) the initial state |0+>: qc = QuantumCircuit(2) # Apply H-gate to the first: qc.h(0) # Let's see the result: svsim = Aer.get_backend('aer_simulator') qc.save_statevector() qobj = assemble(qc) final_state = svsim.run(qobj).result().get_statevector() # Print the statevector neatly: array_to_latex(final_state, prefix="\\text{Statevector = }") #Now,applying h to the |0+> state: qc = QuantumCircuit(2) # Apply H-gate to the first: qc.h(0) # Apply a CNOT: qc.cx(0,1) qc.draw() # Let's get the result: qc.save_statevector() qobj = assemble(qc) result = svsim.run(qobj).result() # Print the statevector neatly: final_state = result.get_statevector() array_to_latex(final_state, prefix="\\text{Statevector = }") plot_histogram(result.get_counts()) from qiskit.visualization import plot_state_qsphere plot_state_qsphere(final_state)
https://github.com/jakelishman/qiskit-qasm2
jakelishman
# 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. """These tests are the examples given in the arXiv paper describing OpenQASM 2. Specifically, there is a test for each subsection (except the description of 'qelib1.inc') in section 3 of https://arxiv.org/abs/1707.03429v2. The examples are copy/pasted from the source files there.""" # pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring import math import os import tempfile import ddt from qiskit import qasm2 from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister, Qubit from qiskit.circuit.library import U1Gate, U3Gate, CU1Gate from qiskit.test import QiskitTestCase from . import gate_builder def load(string, *args, **kwargs): # We're deliberately not using the context-manager form here because we need to use it in a # slightly odd pattern. # pylint: disable=consider-using-with temp = tempfile.NamedTemporaryFile(mode="w", delete=False) try: temp.write(string) # NamedTemporaryFile claims not to be openable a second time on Windows, so close it # (without deletion) so Rust can open it again. temp.close() return qasm2.load(temp.name, *args, **kwargs) finally: # Now actually clean up after ourselves. os.unlink(temp.name) @ddt.ddt class TestArxivExamples(QiskitTestCase): @ddt.data(qasm2.loads, load) def test_teleportation(self, parser): example = """\ // quantum teleportation example OPENQASM 2.0; include "qelib1.inc"; qreg q[3]; creg c0[1]; creg c1[1]; creg c2[1]; // optional post-rotation for state tomography gate post q { } u3(0.3,0.2,0.1) q[0]; h q[1]; cx q[1],q[2]; barrier q; cx q[0],q[1]; h q[0]; measure q[0] -> c0[0]; measure q[1] -> c1[0]; if(c0==1) z q[2]; if(c1==1) x q[2]; post q[2]; measure q[2] -> c2[0];""" parsed = parser(example) post = gate_builder("post", [], QuantumCircuit([Qubit()])) q = QuantumRegister(3, "q") c0 = ClassicalRegister(1, "c0") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(1, "c2") qc = QuantumCircuit(q, c0, c1, c2) qc.append(U3Gate(0.3, 0.2, 0.1), [q[0]], []) qc.h(q[1]) qc.cx(q[1], q[2]) qc.barrier(q) qc.cx(q[0], q[1]) qc.h(q[0]) qc.measure(q[0], c0[0]) qc.measure(q[1], c1[0]) qc.z(q[2]).c_if(c0, 1) qc.x(q[2]).c_if(c1, 1) qc.append(post(), [q[2]], []) qc.measure(q[2], c2[0]) self.assertEqual(parsed, qc) @ddt.data(qasm2.loads, load) def test_qft(self, parser): example = """\ // quantum Fourier transform OPENQASM 2.0; include "qelib1.inc"; qreg q[4]; creg c[4]; x q[0]; x q[2]; barrier q; h q[0]; cu1(pi/2) q[1],q[0]; h q[1]; cu1(pi/4) q[2],q[0]; cu1(pi/2) q[2],q[1]; h q[2]; cu1(pi/8) q[3],q[0]; cu1(pi/4) q[3],q[1]; cu1(pi/2) q[3],q[2]; h q[3]; measure q -> c;""" parsed = parser(example) qc = QuantumCircuit(QuantumRegister(4, "q"), ClassicalRegister(4, "c")) qc.x(0) qc.x(2) qc.barrier(range(4)) qc.h(0) qc.append(CU1Gate(math.pi / 2), [1, 0]) qc.h(1) qc.append(CU1Gate(math.pi / 4), [2, 0]) qc.append(CU1Gate(math.pi / 2), [2, 1]) qc.h(2) qc.append(CU1Gate(math.pi / 8), [3, 0]) qc.append(CU1Gate(math.pi / 4), [3, 1]) qc.append(CU1Gate(math.pi / 2), [3, 2]) qc.h(3) qc.measure(range(4), range(4)) self.assertEqual(parsed, qc) @ddt.data(qasm2.loads, load) def test_inverse_qft_1(self, parser): example = """\ // QFT and measure, version 1 OPENQASM 2.0; include "qelib1.inc"; qreg q[4]; creg c[4]; h q; barrier q; h q[0]; measure q[0] -> c[0]; if(c==1) u1(pi/2) q[1]; h q[1]; measure q[1] -> c[1]; if(c==1) u1(pi/4) q[2]; if(c==2) u1(pi/2) q[2]; if(c==3) u1(pi/2+pi/4) q[2]; h q[2]; measure q[2] -> c[2]; if(c==1) u1(pi/8) q[3]; if(c==2) u1(pi/4) q[3]; if(c==3) u1(pi/4+pi/8) q[3]; if(c==4) u1(pi/2) q[3]; if(c==5) u1(pi/2+pi/8) q[3]; if(c==6) u1(pi/2+pi/4) q[3]; if(c==7) u1(pi/2+pi/4+pi/8) q[3]; h q[3]; measure q[3] -> c[3];""" parsed = parser(example) q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c) qc.h(q) qc.barrier(q) qc.h(q[0]) qc.measure(q[0], c[0]) qc.append(U1Gate(math.pi / 2).c_if(c, 1), [q[1]]) qc.h(q[1]) qc.measure(q[1], c[1]) qc.append(U1Gate(math.pi / 4).c_if(c, 1), [q[2]]) qc.append(U1Gate(math.pi / 2).c_if(c, 2), [q[2]]) qc.append(U1Gate(math.pi / 4 + math.pi / 2).c_if(c, 3), [q[2]]) qc.h(q[2]) qc.measure(q[2], c[2]) qc.append(U1Gate(math.pi / 8).c_if(c, 1), [q[3]]) qc.append(U1Gate(math.pi / 4).c_if(c, 2), [q[3]]) qc.append(U1Gate(math.pi / 8 + math.pi / 4).c_if(c, 3), [q[3]]) qc.append(U1Gate(math.pi / 2).c_if(c, 4), [q[3]]) qc.append(U1Gate(math.pi / 8 + math.pi / 2).c_if(c, 5), [q[3]]) qc.append(U1Gate(math.pi / 4 + math.pi / 2).c_if(c, 6), [q[3]]) qc.append(U1Gate(math.pi / 8 + math.pi / 4 + math.pi / 2).c_if(c, 7), [q[3]]) qc.h(q[3]) qc.measure(q[3], c[3]) self.assertEqual(parsed, qc) @ddt.data(qasm2.loads, load) def test_inverse_qft_2(self, parser): example = """\ // QFT and measure, version 2 OPENQASM 2.0; include "qelib1.inc"; qreg q[4]; creg c0[1]; creg c1[1]; creg c2[1]; creg c3[1]; h q; barrier q; h q[0]; measure q[0] -> c0[0]; if(c0==1) u1(pi/2) q[1]; h q[1]; measure q[1] -> c1[0]; if(c0==1) u1(pi/4) q[2]; if(c1==1) u1(pi/2) q[2]; h q[2]; measure q[2] -> c2[0]; if(c0==1) u1(pi/8) q[3]; if(c1==1) u1(pi/4) q[3]; if(c2==1) u1(pi/2) q[3]; h q[3]; measure q[3] -> c3[0];""" parsed = parser(example) q = QuantumRegister(4, "q") c0 = ClassicalRegister(1, "c0") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(1, "c2") c3 = ClassicalRegister(1, "c3") qc = QuantumCircuit(q, c0, c1, c2, c3) qc.h(q) qc.barrier(q) qc.h(q[0]) qc.measure(q[0], c0[0]) qc.append(U1Gate(math.pi / 2).c_if(c0, 1), [q[1]]) qc.h(q[1]) qc.measure(q[1], c1[0]) qc.append(U1Gate(math.pi / 4).c_if(c0, 1), [q[2]]) qc.append(U1Gate(math.pi / 2).c_if(c1, 1), [q[2]]) qc.h(q[2]) qc.measure(q[2], c2[0]) qc.append(U1Gate(math.pi / 8).c_if(c0, 1), [q[3]]) qc.append(U1Gate(math.pi / 4).c_if(c1, 1), [q[3]]) qc.append(U1Gate(math.pi / 2).c_if(c2, 1), [q[3]]) qc.h(q[3]) qc.measure(q[3], c3[0]) self.assertEqual(parsed, qc) @ddt.data(qasm2.loads, load) def test_ripple_carry_adder(self, parser): example = """\ // quantum ripple-carry adder from Cuccaro et al, quant-ph/0410184 OPENQASM 2.0; include "qelib1.inc"; gate majority a,b,c { cx c,b; cx c,a; ccx a,b,c; } gate unmaj a,b,c { ccx a,b,c; cx c,a; cx a,b; } qreg cin[1]; qreg a[4]; qreg b[4]; qreg cout[1]; creg ans[5]; // set input states x a[0]; // a = 0001 x b; // b = 1111 // add a to b, storing result in b majority cin[0],b[0],a[0]; majority a[0],b[1],a[1]; majority a[1],b[2],a[2]; majority a[2],b[3],a[3]; cx a[3],cout[0]; unmaj a[2],b[3],a[3]; unmaj a[1],b[2],a[2]; unmaj a[0],b[1],a[1]; unmaj cin[0],b[0],a[0]; measure b[0] -> ans[0]; measure b[1] -> ans[1]; measure b[2] -> ans[2]; measure b[3] -> ans[3]; measure cout[0] -> ans[4];""" parsed = parser(example) majority_definition = QuantumCircuit([Qubit(), Qubit(), Qubit()]) majority_definition.cx(2, 1) majority_definition.cx(2, 0) majority_definition.ccx(0, 1, 2) majority = gate_builder("majority", [], majority_definition) unmaj_definition = QuantumCircuit([Qubit(), Qubit(), Qubit()]) unmaj_definition.ccx(0, 1, 2) unmaj_definition.cx(2, 0) unmaj_definition.cx(0, 1) unmaj = gate_builder("unmaj", [], unmaj_definition) cin = QuantumRegister(1, "cin") a = QuantumRegister(4, "a") b = QuantumRegister(4, "b") cout = QuantumRegister(1, "cout") ans = ClassicalRegister(5, "ans") qc = QuantumCircuit(cin, a, b, cout, ans) qc.x(a[0]) qc.x(b) qc.append(majority(), [cin[0], b[0], a[0]]) qc.append(majority(), [a[0], b[1], a[1]]) qc.append(majority(), [a[1], b[2], a[2]]) qc.append(majority(), [a[2], b[3], a[3]]) qc.cx(a[3], cout[0]) qc.append(unmaj(), [a[2], b[3], a[3]]) qc.append(unmaj(), [a[1], b[2], a[2]]) qc.append(unmaj(), [a[0], b[1], a[1]]) qc.append(unmaj(), [cin[0], b[0], a[0]]) qc.measure(b, ans[:4]) qc.measure(cout[0], ans[4]) self.assertEqual(parsed, qc) @ddt.data(qasm2.loads, load) def test_randomised_benchmarking(self, parser): example = """\ // One randomized benchmarking sequence OPENQASM 2.0; include "qelib1.inc"; qreg q[2]; creg c[2]; h q[0]; barrier q; cz q[0],q[1]; barrier q; s q[0]; cz q[0],q[1]; barrier q; s q[0]; z q[0]; h q[0]; barrier q; measure q -> c; """ parsed = parser(example) q = QuantumRegister(2, "q") c = ClassicalRegister(2, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.barrier(q) qc.cz(q[0], q[1]) qc.barrier(q) qc.s(q[0]) qc.cz(q[0], q[1]) qc.barrier(q) qc.s(q[0]) qc.z(q[0]) qc.h(q[0]) qc.barrier(q) qc.measure(q, c) self.assertEqual(parsed, qc) @ddt.data(qasm2.loads, load) def test_process_tomography(self, parser): example = """\ OPENQASM 2.0; include "qelib1.inc"; gate pre q { } // pre-rotation gate post q { } // post-rotation qreg q[1]; creg c[1]; pre q[0]; barrier q; h q[0]; barrier q; post q[0]; measure q[0] -> c[0];""" parsed = parser(example) pre = gate_builder("pre", [], QuantumCircuit([Qubit()])) post = gate_builder("post", [], QuantumCircuit([Qubit()])) qc = QuantumCircuit(QuantumRegister(1, "q"), ClassicalRegister(1, "c")) qc.append(pre(), [0]) qc.barrier(qc.qubits) qc.h(0) qc.barrier(qc.qubits) qc.append(post(), [0]) qc.measure(0, 0) self.assertEqual(parsed, qc) @ddt.data(qasm2.loads, load) def test_error_correction(self, parser): example = """\ // Repetition code syndrome measurement OPENQASM 2.0; include "qelib1.inc"; qreg q[3]; qreg a[2]; creg c[3]; creg syn[2]; gate syndrome d1,d2,d3,a1,a2 { cx d1,a1; cx d2,a1; cx d2,a2; cx d3,a2; } x q[0]; // error barrier q; syndrome q[0],q[1],q[2],a[0],a[1]; measure a -> syn; if(syn==1) x q[0]; if(syn==2) x q[2]; if(syn==3) x q[1]; measure q -> c;""" parsed = parser(example) syndrome_definition = QuantumCircuit([Qubit() for _ in [None] * 5]) syndrome_definition.cx(0, 3) syndrome_definition.cx(1, 3) syndrome_definition.cx(1, 4) syndrome_definition.cx(2, 4) syndrome = gate_builder("syndrome", [], syndrome_definition) q = QuantumRegister(3, "q") a = QuantumRegister(2, "a") c = ClassicalRegister(3, "c") syn = ClassicalRegister(2, "syn") qc = QuantumCircuit(q, a, c, syn) qc.x(q[0]) qc.barrier(q) qc.append(syndrome(), [q[0], q[1], q[2], a[0], a[1]]) qc.measure(a, syn) qc.x(q[0]).c_if(syn, 1) qc.x(q[2]).c_if(syn, 2) qc.x(q[1]).c_if(syn, 3) qc.measure(q, c) self.assertEqual(parsed, qc)
https://github.com/matteoacrossi/oqs-jupyterbook
matteoacrossi
import numpy as np import matplotlib.pyplot as plt from datetime import datetime import json import copy # Main qiskit imports from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute, Aer, IBMQ # Error mitigation from qiskit.ignis.mitigation.measurement import (complete_meas_cal, CompleteMeasFitter, MeasurementFilter) # Utility functions from qiskit.tools.jupyter import * from qiskit.tools.monitor import job_monitor from qiskit.providers.jobstatus import JobStatus # Shows a window in the upper left part with real-time information # on the status of the jobs running on the IBM Q device #%qiskit_job_watcher # We use ibmq_vigo IBMQ.load_account() backend = IBMQ.get_provider(hub='ibm-q', group='open', project='main').get_backend('ibmq_vigo') # Local simulator and vector simulator simulator = Aer.get_backend('qasm_simulator') from amplitude_damping import * SHOTS = 200 # 8192 # The values for R and corresponding times R_values = [0.2, 100.0, 200.0, 400.0] #R_values = [r*.05 for r in range(1,int(1/.05))] + [r * .4 for r in range(10,25)] + [r * 4. for r in range(10,100+1)] R_values = np.array(R_values) npoints = 400 t_values = {} for idx, R in enumerate(R_values): t_values[str(idx)] = np.linspace(0.0, 6.0 * np.pi / np.sqrt(abs(2.0 * R - 1.0)), npoints) #t_values = np.linspace(0.0,5.0,npoints) # We create the quantum circuits q = QuantumRegister(5, name="q") c = ClassicalRegister(1, name="c") ## Indices of the system and environment qubits sys = 1 env = 2 ## For values of R and thirty values of t for each circuits = {} for idx, R in enumerate(R_values): circuits[R] = [] for t in t_values[str(idx)]: circuits[R].append(initial_state(q, sys) +amplitude_damping_channel(q, c, sys, env, R, t)) # Calibration circuits cal_circuits, state_labels = complete_meas_cal([sys], q, c) circuits[0.2][1].draw(output='mpl') # Execute the circuits on the local simulator jobs_sim = {} for R in R_values: jobs_sim[R] = execute(circuits[R], backend = simulator, shots = SHOTS) # Analyse the outcomes populations_sim = {} for idx, R in enumerate(R_values): populations_sim[str(idx)] = [] # changed to str(i) to comply with bokeh bullshit current_job_res = jobs_sim[R].result() for i in range(npoints): counts = current_job_res.get_counts(i) sm = 0.0 if '1' in counts: sm += counts['1']/float(SHOTS) populations_sim[str(idx)].append(sm) # changed to str(i) to comply with bokeh bullshit # Plot the results fig_idx = 221 plt.figure(figsize=(10,12)) for idx, R in enumerate(R_values): plt.subplot(fig_idx) plt.plot(t_values[str(idx)], populations_sim[str(idx)]) # changed to str to comply with bokeh bullshit plt.xlabel('t') plt.ylabel('Population') fig_idx += 1 plt.grid() from bokeh.layouts import row, column from bokeh.models import ColumnDataSource, Slider, CustomJS, Text, DataRange1d, Title from bokeh.plotting import Figure, show from bokeh.io import output_notebook R_values_str = [str(i) for i in range(len(R_values))] R_values_str_R = ['R = {:.2f}'.format(R) for R in R_values] # truncate to two decimals # make a dictionary of form {'0': 0.0, '1': 0.2, .. } R_values_dict = {R_values_str[i]:R_values.round(2)[i] for i,_ in enumerate(R_values)} # rounding to two decimals ys = populations_sim rs = {R_values_str[i] : [R_values_str_R[i]] for i,_ in enumerate(R_values)} ts = t_values initial_r = R_values_str[-1] initial_r rs # Wrap the data in two ColumnDataSources #source_visible = ColumnDataSource(data=dict( # x = ts, y = ys[initial_r])) #source_available = ColumnDataSource(data=ys) source_visible = ColumnDataSource(data=dict( x = ts[initial_r], y = ys[initial_r])) source_available_x = ColumnDataSource(data=ts) source_available_y = ColumnDataSource(data=ys) # Define plot elements plot = Figure(plot_width=400, plot_height=400, x_range = DataRange1d(), y_range=(-.01, 1)) plot.line('x', 'y', source=source_visible, legend_label="ρ₁₁", line_width=3, line_alpha=0.6) # Add text text_source = ColumnDataSource({'r_value': [rs[initial_r]]}) r_available = ColumnDataSource(data=rs) text = Text(x=0, x_offset=315, y=.8, text='r_value', text_font_size='15pt', text_align='right') plot.add_glyph(text_source, text) # Add slider slider = Slider(value=int(initial_r), start=np.min([int(i) for i in ys.keys()]), end=np.max([int(i) for i in ys.keys()]), step=1, show_value = False, title = 'R') # Define CustomJS callback, which updates the plot based on selected function # by updating the source_visible ColumnDataSource. slider.callback = CustomJS( args=dict(source_visible=source_visible, source_available_x=source_available_x, source_available_y=source_available_y, text_source = text_source, r_available = r_available), code=""" var r_idx = cb_obj.value; // Get the data from the data sources var data_visible = source_visible.data; var data_available_x = source_available_x.data; var data_available_y = source_available_y.data; // Change y-axis data according to the selected value data_visible.x = data_available_x[r_idx]; data_visible.y = data_available_y[r_idx]; // text text_source.data = {'r_value': [String(r_available.data[r_idx])]}; // Update the plot source_visible.change.emit(); """) layout = column(plot,slider) output_notebook() show(layout) # Run the calibration job calibration_job = execute(cal_circuits, backend, shots=SHOTS) # Run the circuits and save the jobs jobs = {} jobs_data = [] for R in R_values: jobs[R] = execute(circuits[R], backend = backend, shots = SHOTS) job_data = {'jobid': jobs[R].job_id(), 'description': 'Amplitude damping channel for R = '+str(R), 'metadata': {'t_values': list(t_values[R]), 'R': R}} jobs_data.append(job_data) experiment_data = [{ "backend": backend.name(), "calibration": calibration_job.job_id(), "description": "Circuits for the simulation of the amplitude damping channel", "jobs": jobs_data }] filename = 'amplitude_damping_{}.json'.format( datetime.now().strftime(("%Y_%m_%d-%H_%M"))) with open(filename,'w') as file: json.dump(experiment_data, file) # List the available experiment files import glob print("Available experiment files:") for f in glob.glob('*.json'): print(f) # Load the experiment file filename = "amplitude_damping_2019_11_18-17_15.json" with open(filename, 'r') as file: experiment_data = json.load(file) print(experiment_data[0]['description']) print("Run on", experiment_data[0]['backend']) # Get the backend backend = IBMQ.get_provider(hub='ibm-q-university', group='turku', project='main').get_backend(experiment_data[0]['backend']) # Use the calibration job to implement the error mitigation calibration_job = backend.retrieve_job(experiment_data[0]['calibration']) meas_fitter = CompleteMeasFitter(calibration_job.result(), state_labels) meas_filter = meas_fitter.filter # Analyse the outcomes t_values = {} jobs = {} for job in experiment_data[0]['jobs']: R = job['metadata']['R'] t_values[R] = np.array(job['metadata']['t_values']) jobs[R] = backend.retrieve_job(job['jobid']) populations = {} for R in jobs: populations[R] = [] current_job_res = jobs[R].result() for i in range(npoints): counts = meas_filter.apply(current_job_res).get_counts(i) sm = 0.0 if '1' in counts: sm += counts['1']/float(SHOTS) populations[R].append(sm) # Plot the results fig_idx = 221 plt.figure(figsize=(10,12)) for R in R_values: plt.subplot(fig_idx) plt.plot(t_values[R], populations[R], label='Experiment') plt.plot(t_values[R], populations_sim[R], label='Simulation') plt.xlabel('t') plt.ylabel('Population') fig_idx += 1 plt.grid() plt.legend(); # Compute the channel capacity Qa_exp = {} Qa_sim = {} t_sim = np.linspace(0, 0.7, 200) for R in populations: Qa_exp[R] = [] for i in range(len(t_values[R])): Qa_exp[R].append(Qa(populations[R][i]/populations[R][0])) Qa_sim[R] = [] for t in t_sim: Qa_sim[R].append(Qa(c1(R, t)**2)) # Plot the results plt.figure(figsize=(7,8)) for i, R in enumerate(R_values[1:]): c = ['r', 'g', 'b'][i] plt.plot(t_values[R], Qa_exp[R], marker = 's', lw = 0, c = c, label=r'R = ' + str(R)) plt.plot(t_sim, Qa_sim[R], c = c, ls = '--') plt.xlim(0., 0.7) plt.ylim(0., 1.) plt.xlabel('t') plt.ylabel(r'$Q_a$') plt.legend(); plt.grid() jobs[0.2].properties().qubits jobs[0.2].properties().gates
https://github.com/AnuvabSen1/Quantum-Computing-Algorithms-Implemented-on-IBM-s-QSAM-Qiskit
AnuvabSen1
from qiskit import QuantumCircuit, Aer, execute, IBMQ from qiskit.utils import QuantumInstance import numpy as np from qiskit.algorithms import Shor IBMQ.enable_account('ENTER API TOKEN HERE') # Enter your API token here provider = IBMQ.get_provider(hub='ibm-q') backend = Aer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1000) my_shor = Shor(quantum_instance) result_dict = my_shor.factor(15) print(result_dict)
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
PabloMartinezAngerosa
from tsp_qaoa import test_solution from qiskit.visualization import plot_histogram import networkx as nx import numpy as np import json import csv # Array of JSON Objects header = ['instance','p','distance', 'mean'] length_p = 3 length_instances = 2 with open('qaoa_multiple_p_distance.csv', 'w', encoding='UTF8') as f: writer = csv.writer(f) # write the header writer.writerow(header) instance_index = 0 for instance in range(length_instances): instance_index += 1 first_p = False UNIFORM_CONVERGENCE_P = [] UNIFORM_CONVERGENCE_SAMPLE = [] for p in range(length_p): p = p+1 if first_p == False: print("Vuelve a llamar a test_solution") job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(p=p) first_p = True else: job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(grafo=G, p=p) # Sort the JSON data based on the value of the brand key UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["mean"]) convergence_min = UNIFORM_CONVERGENCE_SAMPLE[0] UNIFORM_CONVERGENCE_P.append({ "mean":convergence_min["mean"], "probabilities": convergence_min["probabilities"] }) cauchy_function_nk = UNIFORM_CONVERGENCE_P[len(UNIFORM_CONVERGENCE_P) - 1] p_index = 0 for p_state in UNIFORM_CONVERGENCE_P: p_index += 1 print(p_index) mean = p_state["mean"] print(p_state) print(mean) distance_p_cauchy_function_nk = np.max(np.abs(cauchy_function_nk["probabilities"] - p_state["probabilities"])) writer.writerow([instance_index, p_index, distance_p_cauchy_function_nk, mean])
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeBoeblingen backend = FakeBoeblingen() ghz = QuantumCircuit(5) ghz.h(0) ghz.cx(0,range(1,5)) circ = transpile(ghz, backend, scheduling_method="asap") circ.draw(output='mpl')
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 = [] gate_counts = [] non_local_gate_counts = [] levels = [str(x) for x in range(4)] for level in range(4): circ = transpile(ghz, backend, optimization_level=level) depths.append(circ.depth()) gate_counts.append(sum(circ.count_ops().values())) non_local_gate_counts.append(circ.num_nonlocal_gates()) fig, (ax1, ax2) = plt.subplots(2, 1) ax1.bar(levels, depths, label='Depth') ax1.set_xlabel("Optimization Level") ax1.set_ylabel("Depth") ax1.set_title("Output Circuit Depth") ax2.bar(levels, gate_counts, label='Number of Circuit Operations') ax2.bar(levels, non_local_gate_counts, label='Number of non-local gates') ax2.set_xlabel("Optimization Level") ax2.set_ylabel("Number of gates") ax2.legend() ax2.set_title("Number of output circuit gates") fig.tight_layout() plt.show()
https://github.com/urwin419/QiskitChecker
urwin419
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) ### removed cx gate ### return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) ### removed h gate ### return qc
https://github.com/Tojarieh97/VQE
Tojarieh97
from qiskit.opflow import X, Z, I, Y LiH_molecule_hamiltonian = -7.49894690201071*(I^I^I^I) + \ -0.0029329964409502266*(X^X^Y^Y) + \ 0.0029329964409502266*(X^Y^Y^X) + \ 0.01291078027311749*(X^Z^X^I) + \ -0.0013743761078958677*(X^Z^X^Z) + \ 0.011536413200774975*(X^I^X^I) + \ 0.0029329964409502266*(Y^X^X^Y) + \ -0.0029329964409502266*(Y^Y^X^X) + \ 0.01291078027311749*(Y^Z^Y^I) + \ -0.0013743761078958677*(Y^Z^Y^Z) + \ 0.011536413200774975*(Y^I^Y^I) + \ 0.16199475388004184*(Z^I^I^I) + \ 0.011536413200774975*(Z^X^Z^X) + \ 0.011536413200774975*(Z^Y^Z^Y) + \ 0.12444770133137588*(Z^Z^I^I) + \ 0.054130445793298836*(Z^I^Z^I) + \ 0.05706344223424907*(Z^I^I^Z) + \ 0.012910780273117487*(I^X^Z^X) + \ -0.0013743761078958677*(I^X^I^X) + \ 0.012910780273117487*(I^Y^Z^Y) + \ -0.0013743761078958677*(I^Y^I^Y) + \ 0.16199475388004186*(I^Z^I^I) + \ 0.05706344223424907*(I^Z^Z^I) + \ 0.054130445793298836*(I^Z^I^Z) + \ -0.013243698330265966*(I^I^Z^I) + \ 0.08479609543670981*(I^I^Z^Z) + \ -0.013243698330265952*(I^I^I^Z) print("========== LiH Molecule Hamiltonian for Four Qubits ==========\n") print(LiH_molecule_hamiltonian.to_matrix())
https://github.com/tstopa/Qiskit_for_high_schools
tstopa
from qiskit import IBMQ provider = IBMQ.load_account() from qiskit.tools.monitor import backend_overview backend_overview()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.providers.fake_provider import FakeManilaV2 from qiskit import transpile from qiskit.tools.visualization import plot_histogram # Get a fake backend from the fake provider backend = FakeManilaV2() # Create a simple circuit circuit = QuantumCircuit(3) circuit.h(0) circuit.cx(0,1) circuit.cx(0,2) circuit.measure_all() circuit.draw('mpl') # Transpile the ideal circuit to a circuit that can be directly executed by the backend transpiled_circuit = transpile(circuit, backend) transpiled_circuit.draw('mpl') # Run the transpiled circuit using the simulated fake backend job = backend.run(transpiled_circuit) counts = job.result().get_counts() plot_histogram(counts)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# let's print all numbers between 0 and 9 for i in range(10): print(i) # range(n) represents the list of all numbers from 0 to n-1 # i is the variable to take the values in the range(n) iteratively: 0, 1, ..., 9 in our example # let's write the same code in two lines for i in range(10): # do not forget to use colon print(i) # the second line is indented # that means the command in the second line will be executed inside the for-loop # any other code executed inside the for-loop must be intented in the same way #my_code_inside_for-loop_2 #my_code_inside_for-loop_3 #my_code_inside_for-loop_4 # now I am out of the scope of for-loop #my_code_outside_for-loop_1 #my_code_outside_for-loop_2 # let's calculate the summation 1+2+...+10 by using a for-loop # we use variable total for the total summation total = 0 for i in range(11): # do not forget to use colon total = total + i # total is updated by i in each iteration # alternatively the same assignment can shortly be written as total =+ i similar to languages C, C++, Java, etc. # now I am out of the scope of for-loop # let's print the latest value of total print(total) # let's calculate the summation 10+12+14+...+44 # we create a list having all numbers in the summation # for this purpose, this time we will use three parameters in range total = 0 for j in range(10,45,2): # the range is defined between 10 and 44, and the value of j will be increased by 2 after each iteration total += j # let's use the shorten version of total = total + j print(total) # let's calculate the summation 1+2+4+8+16+...+256 # remark that 256 = 2*2*...*2 (8 times) total = 0 current_number = 1 # this value will be multiplied by 2 after each iteration for k in range(9): total = total + current_number # current_number is 1 at the beginning, and its value will be doubled after each iteration current_number = 2 * current_number # let's double the value of the current_number for the next iteration # short version of the same assignment: current_number *= 2 as in the languages C, C++, Java, etc. # now I am out of the scope of for-loop # let's print the latest value of total print(total) # instead of a range, we can directly use a list for i in [1,10,100,1000,10000]: print(i) # instead of [...], we can also use (...) # but this time it is a tuple, not a list (keep in your mind that the values in a tuple cannot be changed) for i in (1,10,100,1000,10000): print(i) # let's create a range containing the multiples of 7 and between 10 and 91 for j in range(14,92,7): # 14 is the first multiple of 7 greater or equal to 10 # 91 should be in the range, and so we write 92 print(j) # let's create a range between 11 and 22 for i in range(11,23): print(i) # we can also use variables in range n = 5 for j in range(n,2*n): print(j) # we will print all numbers in {n,n+1,n+2,...,2n-1} # we can use a list of strings for name in ("Asja","Balvis","Fyodor"): print("Hello",name,":-)") # any range can be converted to a list L1 = list(range(10)) print(L1) L2 = list(range(55,200,11)) print(L2) # # your solution is here # # # your solution is here # # let's calculate the summation 1+2+4+8+...+256 by using a while-loop total = 0 i = 1 #while condition(s): # your_code1 # your_code2 # your_code3 while i < 257: # this loop iterates as long as i is less than 257 total = total + i i = i * 2 # i is doubled in each iteration, and so soon it will be greater than 256 print(total) # remember that we calculated this summation as 511 before L = [0,1,2,3,4,5,11] # this is a list containing 7 integer values i = 0 while i in L: # this loop will be iterated as long as i is in L print(i) i = i + 1 # the value of i iteratively increased, and so soon it will hit a value not in the list L # the loop is terminated after i is set to 6, because 6 is not in L # let's use negation in the condition of while-loop L = [10] # this list has a single element i = 0 while i not in L: # this loop will be iterated as long as i is not equal to 10 print(i) i = i+1 # the value of i will hit to 10 after ten iterations # let's rewrite the same loop by using a direct inequality i = 0 while i != 10: # "!=" is used for "not equal to" operator print(i) i=i+1 # let's rewrite the same loop by using negation of equality i = 0 while not (i == 10): # "==" is used for "equal to" operator print(i) i=i+1 # while-loop seems having more fun :-) # but we should be more careful when writing the condition(s)! # summation and n is zero at the beginning S = 0 n = 0 while S < 1000: # this loop will stop after S exceeds 999 (S = 1000 or S > 1000) n = n +1 S = S + n # let's print n and S print(n,S) # three examples for the operator "less than or equal to" #print (4 <= 5) #print (5 <= 5) #print (6 <= 5) # you may comment out the above three lines for executing and seeing the results # # your solution is here # # this is the code for including function randrange to our program from random import randrange # randrange(n) picks a number from the list [0,1,2,...,n-1] randomly #r = randrange(100) #print(r) # # your solution is here # # here is a schematic example for double nested loops #for i in range(10): # your_code1 # your_code2 # while j != 7: # your_code_3 # your_code_4 # # your solution is here #
https://github.com/abbarreto/qiskit4
abbarreto
from qiskit import * import numpy as np import math import qiskit nshots = 8192 IBMQ.load_account() 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 from qiskit.visualization import plot_histogram def qc_bb84(): qr = QuantumRegister(4) cr = ClassicalRegister(4) qc = QuantumCircuit(qr,cr) qc.h([1,2]) qc.measure([1,2],[1,2]) qc.x(0).c_if(cr[1],1) qc.h(0).c_if(cr[2],1) qc.barrier() qc.barrier() qc.h(3) qc.measure(qr[3],cr[3]) qc.h(0).c_if(cr[3],1) qc.measure(0,0) return qc qc_bb84_ = qc_bb84(); qc_bb84_.draw('mpl') nshots = 1 N = 100 counts = [] for j in range(0,N): job_sim = execute(qc, backend=simulator, shots=nshots) counts_sim = job_sim.result().get_counts(qc) counts.append(counts_sim) counts[0:5] counts_keys = [j for j in counts] counts_keys k=0;l=1;m=0;n=0 s= str(k)+str(l)+str(m)+str(n) s eo = [] # observavel escolhido por Alice e Bob (mesmo = 0, diferente=1) for j in range(0,N): for k in range(0,2): for l in range(0,2): for m in range(0,2): for n in range(0,2): s = str(n) + str(m) + str(l) + str(k) if counts[j][s] in counts and counts[j][s] == 1: if l==0 and m==0: eo.append(0) else: eo.append(1) eo qr = QuantumRegister(4)
https://github.com/SimoneGasperini/qiskit-symb
SimoneGasperini
"""Docstring.""" from qiskit import QuantumCircuit, execute, QuantumRegister, ClassicalRegister from qiskit_aer import Aer class Random: """Demo random.""" def __init__(self): """Demo random.""" self.pow = 2 self.qasm = Aer.get_backend("aer_simulator") def run(self, number: int) -> int: """Run method.""" nb_qubits = number print("Generate random number") circ = QuantumRegister(nb_qubits, "the number") meas = ClassicalRegister(nb_qubits, "measurement") quant_circ = QuantumCircuit(circ, meas) for i in range(0, nb_qubits): quant_circ.x(i) quant_circ.measure(circ, meas) job = execute(quant_circ, self.qasm, shots=1, memory=True) result_sim = job.result() memory = result_sim.get_memory() result = int(memory[0], 2) + 1 return result def __repr__(self): return f"Random(circuit of: {self.pow})"
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) ### removed h gate ### return qc
https://github.com/matheusmtta/Quantum-Computing
matheusmtta
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import * from qiskit.tools.visualization import plot_histogram from IPython.display import display, Math, Latex from qiskit.visualization import plot_state_qsphere def BuildBell(x, y): U = QuantumCircuit(2) U.h(0) U.cx(0, 1) if x == 1: U.cz(0, 1) if y == 1: U.x(1) U = U.to_gate() U.name = 'Build Bell' #ctl_U = U.control() make it a controlled gate return U backend = BasicAer.get_backend('statevector_simulator') n = 2 #bell state 00 [x, y] = [0, 0] b00 = QuantumCircuit(n, n) b00.append(BuildBell(x, y), range(n)) #bell state 01 [x, y] = [0, 1] b01 = QuantumCircuit(n, n) b01.append(BuildBell(x, y), range(n)) #bell state 10 [x, y] = [1, 0] b10 = QuantumCircuit(n, n) b10.append(BuildBell(x, y), range(n)) #bell state 11 [x, y] = [1, 1] b11 = QuantumCircuit(n, n) b11.append(BuildBell(x, y), range(n)) bqs00 = execute(b00, backend).result() bqs01 = execute(b01, backend).result() bqs10 = execute(b10, backend).result() bqs11 = execute(b11, backend).result() #GENERAL CIRCUIT b_00 bxy = QuantumCircuit(n, n) bxy.h(0) bxy.cx(0, 1) bxy.measure(range(n), range(n)) backend = BasicAer.get_backend('qasm_simulator') atp = 1024 res = execute(bxy, backend=backend, shots=atp).result() ans = res.get_counts() bxy.draw('mpl') plot_histogram(ans) plot_state_qsphere(bqs00.get_statevector(b00)) #bell state 00 qsphere plot_state_qsphere(bqs01.get_statevector(b01)) #bell state 01 qsphere plot_state_qsphere(bqs10.get_statevector(b10)) #bell state 10 qsphere plot_state_qsphere(bqs11.get_statevector(b11)) #bell state 11 qsphere
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=unused-argument """Waveform generators. A collection of functions that generate drawings from formatted input data. See py:mod:`qiskit.visualization.pulse_v2.types` for more info on the required data. In this module the input data is `types.PulseInstruction`. An end-user can write arbitrary functions that generate custom drawings. Generators in this module are called with the `formatter` and `device` kwargs. These data provides stylesheet configuration and backend system configuration. The format of generator is restricted to: ```python def my_object_generator(data: PulseInstruction, formatter: Dict[str, Any], device: DrawerBackendInfo) -> List[ElementaryData]: pass ``` Arbitrary generator function satisfying the above format can be accepted. Returned `ElementaryData` can be arbitrary subclasses that are implemented in the plotter API. """ from __future__ import annotations import re from fractions import Fraction from typing import Any import numpy as np from qiskit import pulse, circuit from qiskit.pulse import instructions, library from qiskit.visualization.exceptions import VisualizationError from qiskit.visualization.pulse_v2 import drawings, types, device_info def gen_filled_waveform_stepwise( data: types.PulseInstruction, formatter: dict[str, Any], device: device_info.DrawerBackendInfo ) -> list[drawings.LineData | drawings.BoxData | drawings.TextData]: """Generate filled area objects of the real and the imaginary part of waveform envelope. The curve of envelope is not interpolated nor smoothed and presented as stepwise function at each data point. Stylesheets: - The `fill_waveform` style is applied. Args: data: Waveform instruction data to draw. formatter: Dictionary of stylesheet settings. device: Backend configuration. Returns: List of `LineData`, `BoxData`, or `TextData` drawings. Raises: VisualizationError: When the instruction parser returns invalid data format. """ # generate waveform data waveform_data = _parse_waveform(data) channel = data.inst.channel # update metadata meta = waveform_data.meta qind = device.get_qubit_index(channel) meta.update({"qubit": qind if qind is not None else "N/A"}) if isinstance(waveform_data, types.ParsedInstruction): # Draw waveform with fixed shape xdata = waveform_data.xvals ydata = waveform_data.yvals # phase modulation if formatter["control.apply_phase_modulation"]: ydata = np.asarray(ydata, dtype=complex) * np.exp(1j * data.frame.phase) else: ydata = np.asarray(ydata, dtype=complex) return _draw_shaped_waveform( xdata=xdata, ydata=ydata, meta=meta, channel=channel, formatter=formatter ) elif isinstance(waveform_data, types.OpaqueShape): # Draw parametric pulse with unbound parameters # parameter name unbound_params = [] for pname, pval in data.inst.pulse.parameters.items(): if isinstance(pval, circuit.ParameterExpression): unbound_params.append(pname) pulse_data = data.inst.pulse if isinstance(pulse_data, library.SymbolicPulse): pulse_shape = pulse_data.pulse_type else: pulse_shape = "Waveform" return _draw_opaque_waveform( init_time=data.t0, duration=waveform_data.duration, pulse_shape=pulse_shape, pnames=unbound_params, meta=meta, channel=channel, formatter=formatter, ) else: raise VisualizationError("Invalid data format is provided.") def gen_ibmq_latex_waveform_name( data: types.PulseInstruction, formatter: dict[str, Any], device: device_info.DrawerBackendInfo ) -> list[drawings.TextData]: r"""Generate the formatted instruction name associated with the waveform. Channel name and ID string are removed and the rotation angle is expressed in units of pi. The controlled rotation angle associated with the CR pulse name is divided by 2. Note that in many scientific articles the controlled rotation angle implies the actual rotation angle, but in IQX backend the rotation angle represents the difference between rotation angles with different control qubit states. For example: - 'X90p_d0_abcdefg' is converted into 'X(\frac{\pi}{2})' - 'CR90p_u0_abcdefg` is converted into 'CR(\frac{\pi}{4})' Stylesheets: - The `annotate` style is applied. Notes: This generator can convert pulse names used in the IQX backends. If pulses are provided by the third party providers or the user defined, the generator output may be the as-is pulse name. Args: data: Waveform instruction data to draw. formatter: Dictionary of stylesheet settings. device: Backend configuration. Returns: List of `TextData` drawings. """ if data.is_opaque: return [] style = { "zorder": formatter["layer.annotate"], "color": formatter["color.annotate"], "size": formatter["text_size.annotate"], "va": "center", "ha": "center", } if isinstance(data.inst, pulse.instructions.Acquire): systematic_name = "Acquire" latex_name = None elif isinstance(data.inst, instructions.Delay): systematic_name = data.inst.name or "Delay" latex_name = None else: pulse_data = data.inst.pulse if pulse_data.name: systematic_name = pulse_data.name else: if isinstance(pulse_data, library.SymbolicPulse): systematic_name = pulse_data.pulse_type else: systematic_name = "Waveform" template = r"(?P<op>[A-Z]+)(?P<angle>[0-9]+)?(?P<sign>[pm])_(?P<ch>[dum])[0-9]+" match_result = re.match(template, systematic_name) if match_result is not None: match_dict = match_result.groupdict() sign = "" if match_dict["sign"] == "p" else "-" if match_dict["op"] == "CR": # cross resonance if match_dict["ch"] == "u": op_name = r"{\rm CR}" else: op_name = r"\overline{\rm CR}" # IQX name def is not standard. Echo CR is annotated with pi/4 rather than pi/2 angle_val = match_dict["angle"] frac = Fraction(int(int(angle_val) / 2), 180) if frac.numerator == 1: angle = rf"\pi/{frac.denominator:d}" else: angle = r"{num:d}/{denom:d} \pi".format( num=frac.numerator, denom=frac.denominator ) else: # single qubit pulse op_name = r"{{\rm {}}}".format(match_dict["op"]) angle_val = match_dict["angle"] if angle_val is None: angle = r"\pi" else: frac = Fraction(int(angle_val), 180) if frac.numerator == 1: angle = rf"\pi/{frac.denominator:d}" else: angle = r"{num:d}/{denom:d} \pi".format( num=frac.numerator, denom=frac.denominator ) latex_name = rf"{op_name}({sign}{angle})" else: latex_name = None text = drawings.TextData( data_type=types.LabelType.PULSE_NAME, channels=data.inst.channel, xvals=[data.t0 + 0.5 * data.inst.duration], yvals=[-formatter["label_offset.pulse_name"]], text=systematic_name, latex=latex_name, ignore_scaling=True, styles=style, ) return [text] def gen_waveform_max_value( data: types.PulseInstruction, formatter: dict[str, Any], device: device_info.DrawerBackendInfo ) -> list[drawings.TextData]: """Generate the annotation for the maximum waveform height for the real and the imaginary part of the waveform envelope. Maximum values smaller than the vertical resolution limit is ignored. Stylesheets: - The `annotate` style is applied. Args: data: Waveform instruction data to draw. formatter: Dictionary of stylesheet settings. device: Backend configuration. Returns: List of `TextData` drawings. """ if data.is_opaque: return [] style = { "zorder": formatter["layer.annotate"], "color": formatter["color.annotate"], "size": formatter["text_size.annotate"], "ha": "center", } # only pulses. if isinstance(data.inst, instructions.Play): # pulse operand = data.inst.pulse if isinstance(operand, (pulse.ParametricPulse, pulse.SymbolicPulse)): pulse_data = operand.get_waveform() else: pulse_data = operand xdata = np.arange(pulse_data.duration) + data.t0 ydata = pulse_data.samples else: return [] # phase modulation if formatter["control.apply_phase_modulation"]: ydata = np.asarray(ydata, dtype=complex) * np.exp(1j * data.frame.phase) else: ydata = np.asarray(ydata, dtype=complex) texts = [] # max of real part re_maxind = np.argmax(np.abs(ydata.real)) if np.abs(ydata.real[re_maxind]) > 0.01: # generator shows only 2 digits after the decimal point. if ydata.real[re_maxind] > 0: max_val = f"{ydata.real[re_maxind]:.2f}\n\u25BE" re_style = {"va": "bottom"} else: max_val = f"\u25B4\n{ydata.real[re_maxind]:.2f}" re_style = {"va": "top"} re_style.update(style) re_text = drawings.TextData( data_type=types.LabelType.PULSE_INFO, channels=data.inst.channel, xvals=[xdata[re_maxind]], yvals=[ydata.real[re_maxind]], text=max_val, styles=re_style, ) texts.append(re_text) # max of imag part im_maxind = np.argmax(np.abs(ydata.imag)) if np.abs(ydata.imag[im_maxind]) > 0.01: # generator shows only 2 digits after the decimal point. if ydata.imag[im_maxind] > 0: max_val = f"{ydata.imag[im_maxind]:.2f}\n\u25BE" im_style = {"va": "bottom"} else: max_val = f"\u25B4\n{ydata.imag[im_maxind]:.2f}" im_style = {"va": "top"} im_style.update(style) im_text = drawings.TextData( data_type=types.LabelType.PULSE_INFO, channels=data.inst.channel, xvals=[xdata[im_maxind]], yvals=[ydata.imag[im_maxind]], text=max_val, styles=im_style, ) texts.append(im_text) return texts def _draw_shaped_waveform( xdata: np.ndarray, ydata: np.ndarray, meta: dict[str, Any], channel: pulse.channels.PulseChannel, formatter: dict[str, Any], ) -> list[drawings.LineData | drawings.BoxData | drawings.TextData]: """A private function that generates drawings of stepwise pulse lines. Args: xdata: Array of horizontal coordinate of waveform envelope. ydata: Array of vertical coordinate of waveform envelope. meta: Metadata dictionary of the waveform. channel: Channel associated with the waveform to draw. formatter: Dictionary of stylesheet settings. Returns: List of drawings. Raises: VisualizationError: When the waveform color for channel is not defined. """ fill_objs: list[drawings.LineData | drawings.BoxData | drawings.TextData] = [] resolution = formatter["general.vertical_resolution"] # stepwise interpolation xdata: np.ndarray = np.concatenate((xdata, [xdata[-1] + 1])) ydata = np.repeat(ydata, 2) re_y = np.real(ydata) im_y = np.imag(ydata) time: np.ndarray = np.concatenate(([xdata[0]], np.repeat(xdata[1:-1], 2), [xdata[-1]])) # setup style options style = { "alpha": formatter["alpha.fill_waveform"], "zorder": formatter["layer.fill_waveform"], "linewidth": formatter["line_width.fill_waveform"], "linestyle": formatter["line_style.fill_waveform"], } try: color_real, color_imag = formatter["color.waveforms"][channel.prefix.upper()] except KeyError as ex: raise VisualizationError( f"Waveform color for channel type {channel.prefix} is not defined" ) from ex # create real part if np.any(re_y): # data compression re_valid_inds = _find_consecutive_index(re_y, resolution) # stylesheet re_style = {"color": color_real} re_style.update(style) # metadata re_meta = {"data": "real"} re_meta.update(meta) # active xy data re_xvals = time[re_valid_inds] re_yvals = re_y[re_valid_inds] # object real = drawings.LineData( data_type=types.WaveformType.REAL, channels=channel, xvals=re_xvals, yvals=re_yvals, fill=formatter["control.fill_waveform"], meta=re_meta, styles=re_style, ) fill_objs.append(real) # create imaginary part if np.any(im_y): # data compression im_valid_inds = _find_consecutive_index(im_y, resolution) # stylesheet im_style = {"color": color_imag} im_style.update(style) # metadata im_meta = {"data": "imag"} im_meta.update(meta) # active xy data im_xvals = time[im_valid_inds] im_yvals = im_y[im_valid_inds] # object imag = drawings.LineData( data_type=types.WaveformType.IMAG, channels=channel, xvals=im_xvals, yvals=im_yvals, fill=formatter["control.fill_waveform"], meta=im_meta, styles=im_style, ) fill_objs.append(imag) return fill_objs def _draw_opaque_waveform( init_time: int, duration: int, pulse_shape: str, pnames: list[str], meta: dict[str, Any], channel: pulse.channels.PulseChannel, formatter: dict[str, Any], ) -> list[drawings.LineData | drawings.BoxData | drawings.TextData]: """A private function that generates drawings of stepwise pulse lines. Args: init_time: Time when the opaque waveform starts. duration: Duration of opaque waveform. This can be None or ParameterExpression. pulse_shape: String that represents pulse shape. pnames: List of parameter names. meta: Metadata dictionary of the waveform. channel: Channel associated with the waveform to draw. formatter: Dictionary of stylesheet settings. Returns: List of drawings. """ fill_objs: list[drawings.LineData | drawings.BoxData | drawings.TextData] = [] fc, ec = formatter["color.opaque_shape"] # setup style options box_style = { "zorder": formatter["layer.fill_waveform"], "alpha": formatter["alpha.opaque_shape"], "linewidth": formatter["line_width.opaque_shape"], "linestyle": formatter["line_style.opaque_shape"], "facecolor": fc, "edgecolor": ec, } if duration is None or isinstance(duration, circuit.ParameterExpression): duration = formatter["box_width.opaque_shape"] box_obj = drawings.BoxData( data_type=types.WaveformType.OPAQUE, channels=channel, xvals=[init_time, init_time + duration], yvals=[ -0.5 * formatter["box_height.opaque_shape"], 0.5 * formatter["box_height.opaque_shape"], ], meta=meta, ignore_scaling=True, styles=box_style, ) fill_objs.append(box_obj) # parameter name func_repr = "{func}({params})".format(func=pulse_shape, params=", ".join(pnames)) text_style = { "zorder": formatter["layer.annotate"], "color": formatter["color.annotate"], "size": formatter["text_size.annotate"], "va": "bottom", "ha": "center", } text_obj = drawings.TextData( data_type=types.LabelType.OPAQUE_BOXTEXT, channels=channel, xvals=[init_time + 0.5 * duration], yvals=[0.5 * formatter["box_height.opaque_shape"]], text=func_repr, ignore_scaling=True, styles=text_style, ) fill_objs.append(text_obj) return fill_objs def _find_consecutive_index(data_array: np.ndarray, resolution: float) -> np.ndarray: """A helper function to return non-consecutive index from the given list. This drastically reduces memory footprint to represent a drawing, especially for samples of very long flat-topped Gaussian pulses. Tiny value fluctuation smaller than `resolution` threshold is removed. Args: data_array: The array of numbers. resolution: Minimum resolution of sample values. Returns: The compressed data array. """ try: vector = np.asarray(data_array, dtype=float) diff = np.diff(vector) diff[np.where(np.abs(diff) < resolution)] = 0 # keep left and right edges consecutive_l = np.insert(diff.astype(bool), 0, True) consecutive_r = np.append(diff.astype(bool), True) return consecutive_l | consecutive_r except ValueError: return np.ones_like(data_array).astype(bool) def _parse_waveform( data: types.PulseInstruction, ) -> types.ParsedInstruction | types.OpaqueShape: """A helper function that generates an array for the waveform with instruction metadata. Args: data: Instruction data set Raises: VisualizationError: When invalid instruction type is loaded. Returns: A data source to generate a drawing. """ inst = data.inst meta: dict[str, Any] = {} if isinstance(inst, instructions.Play): # pulse operand = inst.pulse if isinstance(operand, (pulse.ParametricPulse, pulse.SymbolicPulse)): # parametric pulse params = operand.parameters duration = params.pop("duration", None) if isinstance(duration, circuit.Parameter): duration = None if isinstance(operand, library.SymbolicPulse): pulse_shape = operand.pulse_type else: pulse_shape = "Waveform" meta["waveform shape"] = pulse_shape meta.update( { key: val.name if isinstance(val, circuit.Parameter) else val for key, val in params.items() } ) if data.is_opaque: # parametric pulse with unbound parameter if duration: meta.update( { "duration (cycle time)": inst.duration, "duration (sec)": inst.duration * data.dt if data.dt else "N/A", } ) else: meta.update({"duration (cycle time)": "N/A", "duration (sec)": "N/A"}) meta.update( { "t0 (cycle time)": data.t0, "t0 (sec)": data.t0 * data.dt if data.dt else "N/A", "phase": data.frame.phase, "frequency": data.frame.freq, "name": inst.name, } ) return types.OpaqueShape(duration=duration, meta=meta) else: # fixed shape parametric pulse pulse_data = operand.get_waveform() else: # waveform pulse_data = operand xdata = np.arange(pulse_data.duration) + data.t0 ydata = pulse_data.samples elif isinstance(inst, instructions.Delay): # delay xdata = np.arange(inst.duration) + data.t0 ydata = np.zeros(inst.duration) elif isinstance(inst, instructions.Acquire): # acquire xdata = np.arange(inst.duration) + data.t0 ydata = np.ones(inst.duration) acq_data = { "memory slot": inst.mem_slot.name, "register slot": inst.reg_slot.name if inst.reg_slot else "N/A", "discriminator": inst.discriminator.name if inst.discriminator else "N/A", "kernel": inst.kernel.name if inst.kernel else "N/A", } meta.update(acq_data) else: raise VisualizationError( "Unsupported instruction {inst} by " "filled envelope.".format(inst=inst.__class__.__name__) ) meta.update( { "duration (cycle time)": inst.duration, "duration (sec)": inst.duration * data.dt if data.dt else "N/A", "t0 (cycle time)": data.t0, "t0 (sec)": data.t0 * data.dt if data.dt else "N/A", "phase": data.frame.phase, "frequency": data.frame.freq, "name": inst.name, } ) return types.ParsedInstruction(xvals=xdata, yvals=ydata, meta=meta)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.algorithms import AmplificationProblem # the state we desire to find is '11' good_state = ['11'] # specify the oracle that marks the state '11' as a good solution oracle = QuantumCircuit(2) oracle.cz(0, 1) # define Grover's algorithm problem = AmplificationProblem(oracle, is_good_state=good_state) # now we can have a look at the Grover operator that is used in running the algorithm # (Algorithm circuits are wrapped in a gate to appear in composition as a block # so we have to decompose() the op to see it expanded into its component gates.) problem.grover_operator.decompose().draw(output='mpl') from qiskit.algorithms import Grover from qiskit.primitives import Sampler grover = Grover(sampler=Sampler()) result = grover.amplify(problem) print('Result type:', type(result)) print() print('Success!' if result.oracle_evaluation else 'Failure!') print('Top measurement:', result.top_measurement) from qiskit.quantum_info import Statevector oracle = Statevector.from_label('11') problem = AmplificationProblem(oracle, is_good_state=['11']) grover = Grover(sampler=Sampler()) result = grover.amplify(problem) print('Result type:', type(result)) print() print('Success!' if result.oracle_evaluation else 'Failure!') print('Top measurement:', result.top_measurement) problem.grover_operator.oracle.decompose().draw(output='mpl') from qiskit.circuit.library.phase_oracle import PhaseOracle from qiskit.exceptions import MissingOptionalLibraryError # `Oracle` (`PhaseOracle`) as the `oracle` argument expression = '(a & b)' try: oracle = PhaseOracle(expression) problem = AmplificationProblem(oracle) display(problem.grover_operator.oracle.decompose().draw(output='mpl')) except MissingOptionalLibraryError as ex: print(ex) import numpy as np # Specifying `state_preparation` # to prepare a superposition of |01>, |10>, and |11> oracle = QuantumCircuit(3) oracle.ccz(0, 1, 2) theta = 2 * np.arccos(1 / np.sqrt(3)) state_preparation = QuantumCircuit(3) state_preparation.ry(theta, 0) state_preparation.ch(0,1) state_preparation.x(1) state_preparation.h(2) # we only care about the first two bits being in state 1, thus add both possibilities for the last qubit problem = AmplificationProblem(oracle, state_preparation=state_preparation, is_good_state=['110', '111']) # state_preparation print('state preparation circuit:') problem.grover_operator.state_preparation.draw(output='mpl') grover = Grover(sampler=Sampler()) result = grover.amplify(problem) print('Success!' if result.oracle_evaluation else 'Failure!') print('Top measurement:', result.top_measurement) oracle = QuantumCircuit(5) oracle.ccz(0, 1, 2) oracle.draw(output='mpl') from qiskit.circuit.library import GroverOperator grover_op = GroverOperator(oracle, insert_barriers=True) grover_op.decompose().draw(output='mpl') grover_op = GroverOperator(oracle, reflection_qubits=[0, 1, 2], insert_barriers=True) grover_op.decompose().draw(output='mpl') # a list of binary strings good state oracle = QuantumCircuit(2) oracle.cz(0, 1) good_state = ['11', '00'] problem = AmplificationProblem(oracle, is_good_state=good_state) print(problem.is_good_state('11')) # a list of integer good state oracle = QuantumCircuit(2) oracle.cz(0, 1) good_state = [0, 1] problem = AmplificationProblem(oracle, is_good_state=good_state) print(problem.is_good_state('11')) from qiskit.quantum_info import Statevector # `Statevector` good state oracle = QuantumCircuit(2) oracle.cz(0, 1) good_state = Statevector.from_label('11') problem = AmplificationProblem(oracle, is_good_state=good_state) print(problem.is_good_state('11')) # Callable good state def callable_good_state(bitstr): if bitstr == "11": return True return False oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=good_state) print(problem.is_good_state('11')) # integer iteration oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=['11']) grover = Grover(iterations=1) # list iteration oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=['11']) grover = Grover(iterations=[1, 2, 3]) # using sample_from_iterations oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=['11']) grover = Grover(iterations=[1, 2, 3], sample_from_iterations=True) iterations = Grover.optimal_num_iterations(num_solutions=1, num_qubits=8) iterations def to_DIAMACS_CNF_format(bit_rep): return [index+1 if val==1 else -1 * (index + 1) for index, val in enumerate(bit_rep)] oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=['11'], post_processing=to_DIAMACS_CNF_format) problem.post_processing([1, 0, 1]) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Interlin-q/diskit
Interlin-q
import sys sys.path.append("..") from diskit import * import warnings warnings.filterwarnings("ignore") circuit_topo = Topology() circuit_topo.create_qmap(3, [2, 3, 3], "sys") circuit_topo.qmap, circuit_topo.emap print("Total Number of Qubits in Topology : ", circuit_topo.num_qubits()) print("Total Number of QPUs in Topology: ", circuit_topo.num_hosts()) Qubit1 = circuit_topo.qmap["sys1"][2] Qubit2 = circuit_topo.qmap["sys2"][1] print("{} and {} are adjacent".format(Qubit1, Qubit2) if circuit_topo.are_adjacent(Qubit1, Qubit2) else "{} and {} are not adjacent".format(Qubit1, Qubit2)) for qubit in circuit_topo.qubits: print("Qubit: {} --------- Host: {}".format(qubit, circuit_topo.get_host(qubit))) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/declanmillar/qiskit-simulation
declanmillar
# General imports import numpy as np # SciPy minimizer routine from scipy.optimize import minimize # Plotting functions import matplotlib.pyplot as plt # Pre-defined ansatz circuit and operator class for Hamiltonian from qiskit import QuantumCircuit from qiskit.circuit.library import EfficientSU2 from qiskit.quantum_info import SparsePauliOp # Qiskit Primitive imports from qiskit.primitives import BaseEstimatorV2, BackendEstimatorV2 as Estimator from qiskit.providers.fake_provider import GenericBackendV2 hamiltonian = SparsePauliOp.from_list( [("YZ", 0.3980), ("ZI", -0.3980), ("ZZ", -0.0113), ("XX", 0.1810)] ) ansatz = EfficientSU2(hamiltonian.num_qubits) ansatz.decompose().draw("mpl", style="iqp") num_params = ansatz.num_parameters num_params from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager backend = GenericBackendV2(hamiltonian.num_qubits) target = backend.target pm = generate_preset_pass_manager(target=target, optimization_level=3) ansatz_isa = pm.run(ansatz) ansatz_isa.draw(output="mpl", idle_wires=False, style="iqp") hamiltonian_isa = hamiltonian.apply_layout(layout=ansatz_isa.layout) def cost_func( params: np.ndarray, ansatz: QuantumCircuit, hamiltonian: SparsePauliOp, estimator: BaseEstimatorV2, history: dict, ) -> float: """Return estimate of energy from estimator Parameters: params: Array of ansatz parameters. ansatz: Parameterized ansatz circuit. hamiltonian: Operator representation of Hamiltonian. estimator: Estimator primitive instance. history: Dictionary for storing intermediate results. Returns: Energy estimate. """ pub = (ansatz, [hamiltonian], [params]) result = estimator.run(pubs=[pub]).result() energy = result[0].data.evs[0] history["iters"] += 1 history["prev_vector"] = params history["cost_history"].append(energy) print(f"Iters. done: {history['iters']} [Current cost: {energy}]") return energy history = { "prev_vector": None, "iters": 0, "cost_history": [], } x0 = 2 * np.pi * np.random.random(num_params) x0 estimator = Estimator(backend=backend) estimator.options.default_shots = 10000 res = minimize( cost_func, x0, args=(ansatz_isa, hamiltonian_isa, estimator, history), method="cobyla", ) res all(history["prev_vector"] == res.x) history["iters"] == res.nfev fig, ax = plt.subplots() ax.plot(range(history["iters"]), history["cost_history"]) ax.set_xlabel("Iterations") ax.set_ylabel("Cost") plt.draw() import qiskit qiskit.version.get_version_info() import qiskit_aer qiskit_aer.version.get_version_info()
https://github.com/Pitt-JonesLab/mirror-gates
Pitt-JonesLab
from qiskit import QuantumCircuit # from qiskit.test import QiskitTestCase from qiskit.transpiler import CouplingMap, PassManager from qiskit.transpiler.passes import ( Unroller, TrivialLayout, DenseLayout, ApplyLayout, SabreLayout, CountOpsLongestPath, Collect1qRuns, Collect2qBlocks, ConsolidateBlocks, SabreSwap, ) from qiskit.transpiler.passes import OptimizeSwapBeforeMeasure import numpy as np from qiskit.transpiler.passes import ( FullAncillaAllocation, EnlargeWithAncilla, ) from virtual_swap.sqiswap_equiv import sel from qiskit.transpiler.basepasses import TransformationPass from qiskit.converters import dag_to_circuit # this code is buggy, see https://github.com/Qiskit/qiskit-terra/pull/9375 # I can't use this version bc qiskit version missing DAGCircuit functionality from slam.utils.transpiler_pass.weyl_decompose import RootiSwapWeylDecomposition # from virtual_swap.vswap_verbose import VirtualSwap as VirtualSwapVerbose # from virtual_swap.vswap_simple import VirtualSwap as VirtualSwapSimple from virtual_swap.deprecated.cns_sa import VSwapPass as VirtualSwap # # build a toffoli # qc = QuantumCircuit(8) # qc.ccx(0, 1, 2) # qc.cx(1, 7) # qc.ccx(3, 4, 5) # qc.ccx(2, 5, 6) # # build a 2x2 square coupling map # coupling = CouplingMap.from_line(8) # # build a toffoli qc = QuantumCircuit(3) qc.ccx(0, 1, 2) linear = CouplingMap.from_line(10) a2a = CouplingMap.from_full(3) coupling = linear qc.decompose().draw("mpl") # # generate a QFT circuit # from qiskit.circuit.library import QFT # # qc = QuantumCircuit(16) # qc = QFT(8) # coupling = CouplingMap.from_grid(4,4) # generate network of random cnots n, M = 4, 25 N = n**2 qc = QuantumCircuit(N) for _ in range(M): qc.cx(*np.random.choice(N, 2, replace=False)) coupling = CouplingMap.from_grid(n, n) # coupling = CouplingMap.from_line(N + 1) # a2a = CouplingMap.from_full(N) qc.decompose().draw("mpl") from qiskit import transpile qc2 = transpile( qc, coupling_map=coupling, basis_gates=["cx", "u3", "swap", "iswap"], optimization_level=3, ) # from virtual_swap.sqiswap_equiv import sel # qc2 = transpile( # qc, coupling_map=coupling, basis_gates=["xx_plus_yy", "u3"], optimization_level=3 # ) # t0_pm = PassManager([Collect2qBlocks(), ConsolidateBlocks(force_consolidate=True)]) # # , RootiSwapWeylDecomposition()]) # t0_pm.append(RootiSwapWeylDecomposition()) # qc3 = t0_pm.run(qc2) # print(f"Total: {qc3.count_ops().get('riswap', 0)}") # print( # f"Depth: {qc3.depth(filter_function=lambda x: x.operation.name not in ['u3', 'u'])}" # ) qc2.draw(output="mpl") from qiskit import transpile qc2 = transpile( qc, coupling_map=coupling, basis_gates=["cx", "u3", "swap", "iswap"], optimization_level=3, ) # from virtual_swap.sqiswap_equiv import sel # qc2 = transpile( # qc, coupling_map=coupling, basis_gates=["xx_plus_yy", "u3"], optimization_level=3 # ) # t0_pm = PassManager([Collect2qBlocks(), ConsolidateBlocks(force_consolidate=True)]) # , RootiSwapWeylDecomposition()]) t0_pm = PassManager() t0_pm.append( SabreLayout(coupling, skip_routing=True), Unroller(["u", "cx", "iswap", "swap"]) ) qc3 = t0_pm.run(qc) print(f"Total: {qc3.count_ops().get('riswap', 0)}") print( f"Depth: {qc3.depth(filter_function=lambda x: x.operation.name not in ['u3', 'u'])}" ) qc3.draw(output="mpl") # run the pass pm = PassManager() # trivial vs the previously computed layout # pm.append([TrivialLayout(coupling)]) # pm.append([FullAncillaAllocation(coupling), EnlargeWithAncilla(), ApplyLayout()]) # # XXX # from qiskit.transpiler.passes import SetLayout # pm.append(SetLayout(layout=qc2._layout.initial_layout)) pm.property_set = t0_pm.property_set pm.append( VirtualSwap( coupling, visualize=True, ) ) pm.append(SabreSwap(coupling)) pm.append([OptimizeSwapBeforeMeasure()]) pm2 = PassManager() pm2.append( [Collect1qRuns(), Collect2qBlocks(), ConsolidateBlocks(force_consolidate=True)] ) pm2.append([RootiSwapWeylDecomposition()]) new_circ = pm.run(qc3) new_circ_decomp = pm2.run(new_circ) print(f"Total: {new_circ_decomp.count_ops().get('riswap', 0)}") print( f"Depth: {new_circ_decomp.depth(filter_function=lambda x: x.operation.name not in ['u3', 'u'])}" ) print(new_circ.draw()) new_circ_decomp.draw("mpl") # qc == qc2 == new_circ_decomp? # I check with Operator.equiv but false # idk why # from qiskit.circuit.library import XXPlusYYGate, SwapGate, CXGate # from qiskit.quantum_info import Operator # cx_decomp = QuantumCircuit(2) # cx_decomp.u(np.pi / 4, 0, np.pi / 2, 0) # cx_decomp.u(np.pi / 4, 0, np.pi / 2, 1) # cx_decomp.append(XXPlusYYGate(-np.pi / 2, 0), [0, 1]) # cx_decomp.u(np.pi / 4, 0, np.pi / 2, 0) # cx_decomp.u(np.pi / 4, 0, np.pi / 2, 1) # cx_decomp.append(XXPlusYYGate(-np.pi / 2), [0, 1]) # cx_decomp.u(np.pi / 4, 0, np.pi / 2, 0) # cx_decomp.u(np.pi / 4, 0, np.pi / 2, 1) # # sel.add_equivalence(CXGate(), cx_decomp) # assert Operator(CXGate()).equiv(Operator(cx_decomp)) # swap_decomp = QuantumCircuit(2) # swap_decomp.u(np.pi / 4, 0, np.pi / 2, 0) # swap_decomp.u(np.pi / 4, 0, np.pi / 2, 1) # swap_decomp.append(XXPlusYYGate(-np.pi / 2, 0), [0, 1]) # swap_decomp.u(np.pi / 4, 0, np.pi / 2, 0) # swap_decomp.u(np.pi / 4, 0, np.pi / 2, 1) # swap_decomp.append(XXPlusYYGate(-np.pi / 2), [0, 1]) # swap_decomp.u(np.pi / 4, 0, np.pi / 2, 0) # swap_decomp.u(np.pi / 4, 0, np.pi / 2, 1) # swap_decomp.append(XXPlusYYGate(-np.pi / 2), [0, 1]) # swap_decomp.u(np.pi / 4, 0, np.pi / 2, 0) # swap_decomp.u(np.pi / 4, 0, np.pi / 2, 1) # # sel.add_equivalence(SwapGate(), swap_decomp) # assert Operator(SwapGate()).equiv(Operator(swap_decomp))
https://github.com/lynnlangit/learning-quantum
lynnlangit
try: import cirq except ImportError: print("installing cirq...") !pip install --quiet cirq print("installed cirq.") import fractions import math import random import matplotlib.pyplot as plt import numpy as np import sympy from typing import Callable, List, Optional, Sequence, Union import cirq #import cirq_google print(cirq.google.Foxtail) # verify cirq, should print a circuit as shown belown # (0, 0)───(0, 1)───(0, 2)───(0, 3)───(0, 4)───(0, 5)───(0, 6)───(0, 7)───(0, 8)───(0, 9)───(0, 10) # │ │ │ │ │ │ │ │ │ │ │ # │ │ │ │ │ │ │ │ │ │ │ # (1, 0)───(1, 1)───(1, 2)───(1, 3)───(1, 4)───(1, 5)───(1, 6)───(1, 7)───(1, 8)───(1, 9)───(1, 10) def classical_order_finder(x: int, n: int) -> Optional[int]: # Make sure x is both valid and in Z_n. if x < 2 or x >= n or math.gcd(x, n) > 1: raise ValueError(f"Invalid x={x} for modulus n={n}.") # Determine the order. r, y = 1, x while y != 1: y = (x * y) % n r += 1 return r n = 15 # The multiplicative group is [1, 2, 4, 7, 8, 11, 13, 14]. x = 8 r = classical_order_finder(x, n) # Check that the order is indeed correct. print(f"x^r mod n = {x}^{r} mod {n} = {x**r % n}") class ModularExp(cirq.ArithmeticOperation): def __init__( self, target: Sequence[cirq.Qid], exponent: Union[int, Sequence[cirq.Qid]], base: int, modulus: int ) -> None: if len(target) < modulus.bit_length(): raise ValueError(f'Register with {len(target)} qubits is too small ' f'for modulus {modulus}') self.target = target self.exponent = exponent self.base = base self.modulus = modulus def registers(self) -> Sequence[Union[int, Sequence[cirq.Qid]]]: return self.target, self.exponent, self.base, self.modulus def with_registers( self, *new_registers: Union[int, Sequence['cirq.Qid']], ) -> cirq.ArithmeticOperation: if len(new_registers) != 4: raise ValueError(f'Expected 4 registers (target, exponent, base, ' f'modulus), but got {len(new_registers)}') target, exponent, base, modulus = new_registers if not isinstance(target, Sequence): raise ValueError( f'Target must be a qubit register, got {type(target)}') if not isinstance(base, int): raise ValueError( f'Base must be a classical constant, got {type(base)}') if not isinstance(modulus, int): raise ValueError( f'Modulus must be a classical constant, got {type(modulus)}') return ModularExp(target, exponent, base, modulus) def apply(self, *register_values: int) -> int: assert len(register_values) == 4 target, exponent, base, modulus = register_values if target >= modulus: return target return (target * base**exponent) % modulus def _circuit_diagram_info_( self, args: cirq.CircuitDiagramInfoArgs, ) -> cirq.CircuitDiagramInfo: assert args.known_qubits is not None wire_symbols: List[str] = [] t, e = 0, 0 for qubit in args.known_qubits: if qubit in self.target: if t == 0: if isinstance(self.exponent, Sequence): e_str = 'e' else: e_str = str(self.exponent) wire_symbols.append( f'ModularExp(t*{self.base}**{e_str} % {self.modulus})') else: wire_symbols.append('t' + str(t)) t += 1 if isinstance(self.exponent, Sequence) and qubit in self.exponent: wire_symbols.append('e' + str(e)) e += 1 return cirq.CircuitDiagramInfo(wire_symbols=tuple(wire_symbols)) n = 15 L = n.bit_length() # The target register has L qubits. target = cirq.LineQubit.range(L) # The exponent register has 2L + 3 qubits. exponent = cirq.LineQubit.range(L, 3 * L + 3) # Display the total number of qubits to factor this n. print(f"To factor n = {n} which has L = {L} bits, we need 3L + 3 = {3 * L + 3} qubits.") def make_order_finding_circuit(x: int, n: int) -> cirq.Circuit: L = n.bit_length() target = cirq.LineQubit.range(L) exponent = cirq.LineQubit.range(L, 3 * L + 3) return cirq.Circuit( cirq.X(target[L - 1]), cirq.H.on_each(*exponent), ModularExp(target, exponent, x, n), cirq.qft(*exponent, inverse=True), cirq.measure(*exponent, key='exponent'), ) n = 15 x = 7 circuit = make_order_finding_circuit(x, n) print(circuit) circuit = make_order_finding_circuit(x=5, n=6) res = cirq.sample(circuit, repetitions=8) print("Raw measurements:") print(res) print("\nInteger in exponent register:") print(res.data) def binary_labels(num_qubits): return [bin(x)[2:].zfill(num_qubits) for x in range(2 ** num_qubits)] # Refactor this plot to use this cell's output # q = cirq.LineQubit.range(3) # circuit = cirq.Circuit([cirq.H.on_each(*q), cirq.measure(*q)]) # result = cirq.Simulator().run(circuit, repetitions=100) # _ = cirq.vis.plot_state_histogram(result, plt.subplot(), title = 'Integer in exponent Register', xlabel = 'Integer', ylabel = 'Count', tick_label=binary_labels(3)) def process_measurement(result: cirq.Result, x: int, n: int) -> Optional[int]: # Read the output integer of the exponent register. exponent_as_integer = result.data["exponent"][0] exponent_num_bits = result.measurements["exponent"].shape[1] eigenphase = float(exponent_as_integer / 2**exponent_num_bits) # Run the continued fractions algorithm to determine f = s / r. f = fractions.Fraction.from_float(eigenphase).limit_denominator(n) if f.numerator == 0: return None r = f.denominator if x**r % n != 1: return None return r n = 6 x = 5 print(f"Finding the order of x = {x} modulo n = {n}\n") measurement = cirq.sample(circuit, repetitions=1) print("Raw measurements:") print(measurement) print("\nInteger in exponent register:") print(measurement.data) r = process_measurement(measurement, x, n) print("\nOrder r =", r) if r is not None: print(f"x^r mod n = {x}^{r} mod {n} = {x**r % n}") def quantum_order_finder(x: int, n: int) -> Optional[int]: if x < 2 or n <= x or math.gcd(x, n) > 1: raise ValueError(f'Invalid x={x} for modulus n={n}.') circuit = make_order_finding_circuit(x, n) measurement = cirq.sample(circuit) return process_measurement(measurement, x, n) def find_factor_of_prime_power(n: int) -> Optional[int]: for k in range(2, math.floor(math.log2(n)) + 1): c = math.pow(n, 1 / k) c1 = math.floor(c) if c1**k == n: return c1 c2 = math.ceil(c) if c2**k == n: return c2 return None def find_factor( n: int, order_finder: Callable[[int, int], Optional[int]] = quantum_order_finder, max_attempts: int = 30 ) -> Optional[int]: if sympy.isprime(n): print("n is prime!") return None if n % 2 == 0: return 2 c = find_factor_of_prime_power(n) if c is not None: return c for _ in range(max_attempts): x = random.randint(2, n - 1) c = math.gcd(x, n) if 1 < c < n: return c r = order_finder(x, n) if r is None: continue if r % 2 != 0: continue y = x**(r // 2) % n assert 1 < y < n c = math.gcd(y - 1, n) if 1 < c < n: return c print(f"Failed to find a non-trivial factor in {max_attempts} attempts.") # return None # test with non-prime numbers only n = 184572 p = find_factor(n, order_finder=classical_order_finder) q = n // p p * q == n print("If p * q == n is True, then this answer is correct.") print("The result of " + str(p) + " * " + str(q) + " = "+ str(n) + " is " + str(p * q == n)) # 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 # # https://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.
https://github.com/martynscn/Masters-Thesis-on-Quantum-Cryptography
martynscn
# This code has been adapted and modified from IBM Qiskit 2021 and # uses the constant optimized modular exponentiation circuit for mod 15 as contained # in https://arxiv.org/abs/1202.6614. import numpy as np import math from decimal import * import matplotlib.pyplot as plt from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit.visualization import plot_histogram from qiskit import Aer, transpile, assemble import pandas as pd from fractions import Fraction # # import math # from math import gcd # from numpy.random import randint # # # from decimal import * print("Imports Successful") from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" def my_mod(a,n): getcontext().prec = 27 return round((Decimal(a)/Decimal(n) - Decimal(a)//Decimal(n) ) * n) def constant_optimized_modular_exponentation_modulus15(a, power): if a not in [2,7,8,11,13]: raise ValueError("'a' must be 2,7,8,11 or 13") U = QuantumCircuit(4) for iteration in range(power): if a in [2,13]: U.swap(0,1) U.swap(1,2) U.swap(2,3) if a in [7,8]: U.swap(2,3) U.swap(1,2) U.swap(0,1) if a == 11: U.swap(1,3) U.swap(0,2) if a in [7,11,13]: for q in range(4): U.x(q) U = U.to_gate() U.name = "%i^%i mod 15" % (a, power) control_U = U.control() return control_U def inverse_qft(n): circuit = QuantumCircuit(n) for i in range(n//2): circuit.swap(i, n-1-i) for j in range(n): for m in range(j): circuit.cp(-np.pi/float(2**(j-m)), m, j) circuit.h(j) circuit.name = "QFT†" return circuit N = 15 a = 7 n_count = 8 counting_register = QuantumRegister(size = n_count, name = "counting_register") acting_register = QuantumRegister(size = 4, name="acting_register") classic_register = ClassicalRegister(size = n_count, name="classic_register") qc = QuantumCircuit(counting_register, acting_register ,classic_register) initial_state = [1,0] for q in range(8): qc.initialize(initial_state, q) qc.draw(output = 'mpl', filename = "Step0") for q in range(n_count): qc.h(q) qc.draw(output = 'mpl', filename = "Step1") qc.x(3+n_count) qc.draw(output = 'mpl', filename = "Step1b") for q in range(n_count): qc.append(constant_optimized_modular_exponentation_modulus15(a, 2**q), [q] + [i+n_count for i in range(4)]) qc.measure(range(n_count,n_count + 4), range(4)) qc.barrier() qc.draw(output = 'mpl', filename = "Step2") qc.append(inverse_qft(n_count), range(n_count)) qc.draw(output = 'mpl', filename = "Step3") # Measure circuit qc.measure(range(n_count), range(n_count)) qc.draw(output = 'mpl', filename = "Step4") qasm_sim = Aer.get_backend('qasm_simulator') t_qc = transpile(qc, qasm_sim) qobj = assemble(t_qc) results = qasm_sim.run(qobj).result() counts = results.get_counts() plot_histogram(counts) rows, measured_phases = [], [] for output in counts: decimal = int(output, 2) phase = decimal/(2**n_count) measured_phases.append(phase) rows.append([f"{output}(bin) = {decimal:>3}(dec)", f"{decimal}/{2**n_count} = {phase:.2f}"]) headers=["Register Output", "Phase"] df = pd.DataFrame(rows, columns=headers) df rows = [] for phase in measured_phases: frac = Fraction(phase).limit_denominator(15) rows.append([phase, f"{frac.numerator}/{frac.denominator}", frac.denominator]) headers=["Phase", "Fraction", "Guess for r"] df = pd.DataFrame(rows, columns=headers) my_period_r = max(df["Guess for r"]) print("My period (r) is %i" % my_period_r) # Confirm that the period is 4 xvals = np.arange(N) xvals = [x.item() for x in xvals] yvals = [my_mod(a**x, N) for x in xvals] fig, ax = plt.subplots(); ax.plot(xvals, yvals, linewidth=1, linestyle='dotted', marker='x'); ax.set(xlabel='$x$', ylabel='$%i^x$ mod $%i$' % (a, N), title="Example of Periodic Function in Shor's Algorithm"); try: r = yvals[1:].index(1) +1 plt.annotate(s = '', xy=(0,1), xytext=(r,1), arrowprops=dict(arrowstyle='<->')); plt.annotate(s = '$r=%i$' % r, xy=(r/3,1.5)); except ValueError: print('Could not find a period') first_shared_factor = math.gcd((7**(int(my_period_r/2)) + 1), 15) first_shared_factor second_shared_factor = math.gcd((7**(int(my_period_r/2)) - 1), 15) second_shared_factor %qiskit_copyright
https://github.com/UST-QuAntiL/qiskit-service
UST-QuAntiL
# ****************************************************************************** # Copyright (c) 2020-2021 University of Stuttgart # # See the NOTICE file(s) distributed with this work for additional # information regarding copyright ownership. # # 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. # ****************************************************************************** import base64 import datetime import json from qiskit import transpile, QuantumCircuit, Aer from qiskit.transpiler.exceptions import TranspilerError from qiskit.utils.measurement_error_mitigation import get_measured_qubits from qiskit_aer.noise import NoiseModel from rq import get_current_job from app import implementation_handler, aws_handler, ibmq_handler, db, app, ionq_handler, circuit_analysis from app.NumpyEncoder import NumpyEncoder from app.benchmark_model import Benchmark from app.generated_circuit_model import Generated_Circuit from app.result_model import Result def generate(impl_url, impl_data, impl_language, input_params, bearer_token): app.logger.info("Starting generate task...") job = get_current_job() generated_circuit_code = None if impl_url: generated_circuit_code = implementation_handler.prepare_code_from_url(impl_url, input_params, bearer_token) elif impl_data: generated_circuit_code = implementation_handler.prepare_code_from_data(impl_data, input_params) else: generated_circuit_object = Generated_Circuit.query.get(job.get_id()) generated_circuit_object.generated_circuit = json.dumps({'error': 'generating circuit failed'}) generated_circuit_object.complete = True db.session.commit() if generated_circuit_code: non_transpiled_depth_old = 0 generated_circuit_object = Generated_Circuit.query.get(job.get_id()) generated_circuit_object.generated_circuit = generated_circuit_code.qasm() non_transpiled_depth = generated_circuit_code.depth() while non_transpiled_depth_old < non_transpiled_depth: non_transpiled_depth_old = non_transpiled_depth generated_circuit_code = generated_circuit_code.decompose() non_transpiled_depth = generated_circuit_code.depth() generated_circuit_object.original_depth = non_transpiled_depth generated_circuit_object.original_width = circuit_analysis.get_width_of_circuit(generated_circuit_code) generated_circuit_object.original_total_number_of_operations = generated_circuit_code.size() generated_circuit_object.original_number_of_multi_qubit_gates = generated_circuit_code.num_nonlocal_gates() generated_circuit_object.original_number_of_measurement_operations = circuit_analysis.get_number_of_measurement_operations( generated_circuit_code) generated_circuit_object.original_number_of_single_qubit_gates = generated_circuit_object.original_total_number_of_operations - generated_circuit_object.original_number_of_multi_qubit_gates - generated_circuit_object.original_number_of_measurement_operations generated_circuit_object.original_multi_qubit_gate_depth, non_transpiled_circuit = circuit_analysis.get_multi_qubit_gate_depth( generated_circuit_code) generated_circuit_object.input_params = json.dumps(input_params) app.logger.info(f"Received input params for circuit generation: {generated_circuit_object.input_params}") generated_circuit_object.complete = True db.session.commit() def execute(correlation_id, provider, impl_url, impl_data, impl_language, transpiled_qasm, input_params, token, access_key_aws, secret_access_key_aws, qpu_name, optimization_level, noise_model, only_measurement_errors, shots, bearer_token, qasm_string, **kwargs): """Create database entry for result. Get implementation code, prepare it, and execute it. Save result in db""" app.logger.info("Starting execute task...") job = get_current_job() if provider == 'ibmq': backend = ibmq_handler.get_qpu(token, qpu_name, **kwargs) elif provider == 'ionq': backend = ionq_handler.get_qpu(token, qpu_name) elif provider == 'aws': backend = aws_handler.get_qpu(access_key=access_key_aws, secret_access_key=secret_access_key_aws, qpu_name=qpu_name, **kwargs) if not backend: result = Result.query.get(job.get_id()) result.result = json.dumps({'error': 'qpu-name or token wrong'}) result.complete = True db.session.commit() app.logger.info('Preparing implementation...') if transpiled_qasm: transpiled_circuits = [QuantumCircuit.from_qasm_str(qasm) for qasm in transpiled_qasm] else: if qasm_string: circuits = [implementation_handler.prepare_code_from_qasm(qasm) for qasm in qasm_string] elif impl_url and not correlation_id: if impl_language.lower() == 'openqasm': # list of circuits circuits = [implementation_handler.prepare_code_from_qasm_url(url, bearer_token) for url in impl_url] else: circuits = [implementation_handler.prepare_code_from_url(url, input_params, bearer_token) for url in impl_url] elif impl_data: impl_data = [base64.b64decode(data.encode()).decode() for data in impl_data] if impl_language.lower() == 'openqasm': circuits = [implementation_handler.prepare_code_from_qasm(data) for data in impl_data] else: circuits = [implementation_handler.prepare_code_from_data(data, input_params) for data in impl_data] if not circuits: result = Result.query.get(job.get_id()) result.result = json.dumps({'error': 'URL not found'}) result.complete = True db.session.commit() app.logger.info('Start transpiling...') if noise_model and provider == 'ibmq': noisy_qpu = ibmq_handler.get_qpu(token, noise_model, **kwargs) noise_model = NoiseModel.from_backend(noisy_qpu) properties = noisy_qpu.properties() configuration = noisy_qpu.configuration() coupling_map = configuration.coupling_map basis_gates = noise_model.basis_gates try: transpiled_circuits = transpile(circuits, noisy_qpu) except TranspilerError: result = Result.query.get(job.get_id()) result.result = json.dumps({'error': 'too many qubits required'}) result.complete = True db.session.commit() measurement_qubits = get_measurement_qubits_from_transpiled_circuit(transpiled_circuits) if only_measurement_errors: ro_noise_model = NoiseModel() for k, v in noise_model._local_readout_errors.items(): ro_noise_model.add_readout_error(v, k) noise_model = ro_noise_model backend = Aer.get_backend('aer_simulator') else: try: transpiled_circuits = transpile(circuits, backend=backend, optimization_level=optimization_level) except TranspilerError: result = Result.query.get(job.get_id()) result.result = json.dumps({'error': 'too many qubits required'}) result.complete = True db.session.commit() app.logger.info('Start executing...') if provider == 'aws' and not noise_model: # Note: AWS cannot handle such a noise model job_result = aws_handler.execute_job(transpiled_circuits, shots, backend) elif provider == 'ionq' and not noise_model: job_result = ionq_handler.execute_job(transpiled_circuits, shots, backend) else: # If we need a noise model, we have to use IBM Q job_result = ibmq_handler.execute_job(transpiled_circuits, shots, backend, noise_model) if job_result: result = Result.query.get(job.get_id()) result.result = json.dumps(job_result['counts']) # check if implementation contains post processing of execution results that has to be executed if correlation_id and (impl_url or impl_data): result.generated_circuit_id = correlation_id # prepare input data containing execution results and initial input params for generating the circuit generated_circuit = Generated_Circuit.query.get(correlation_id) input_params_for_post_processing = json.loads(generated_circuit.input_params) input_params_for_post_processing['counts'] = job_result['counts'] if impl_url: post_p_result = implementation_handler.prepare_code_from_url(url=impl_url[0], input_params=input_params_for_post_processing, bearer_token=bearer_token, post_processing=True) elif impl_data: post_p_result = implementation_handler.prepare_post_processing_code_from_data(data=impl_data[0], input_params=input_params_for_post_processing) result.post_processing_result = json.loads(post_p_result) result.complete = True db.session.commit() else: result = Result.query.get(job.get_id()) result.result = json.dumps({'error': 'execution failed'}) result.complete = True db.session.commit() def get_measurement_qubits_from_transpiled_circuit(transpiled_circuit): qubit_index, qubit_mappings = get_measured_qubits([transpiled_circuit]) measurement_qubits = [int(i) for i in list(qubit_mappings.keys())[0].split("_")] return measurement_qubits def convert_into_suitable_format(object): """Enables the serialization of the unserializable datetime.datetime format""" if isinstance(object, datetime.datetime): return object.__str__() def execute_benchmark(transpiled_qasm, token, qpu_name, shots): """Create database entry for result and benchmark. Get implementation code, prepare it, and execute it. Save result in db """ job = get_current_job() backend = ibmq_handler.get_qpu(token, qpu_name) if not backend: result = Result.query.get(job.get_id()) result.result = json.dumps({'error': 'qpu-name or token wrong'}) result.complete = True db.session.commit() app.logger.info('Preparing implementation...') transpiled_circuit = QuantumCircuit.from_qasm_str(transpiled_qasm) app.logger.info('Start executing...') job_result = ibmq_handler.execute_job(transpiled_circuit, shots, backend, None) if job_result: # once the job is finished save results in db result = Result.query.get(job.get_id()) result.result = json.dumps(job_result, default=convert_into_suitable_format) result.complete = True benchmark = Benchmark.query.get(job.get_id()) benchmark.result = json.dumps(job_result, default=convert_into_suitable_format) benchmark.counts = json.dumps(job_result['counts']) benchmark.complete = True db.session.commit() else: result = Result.query.get(job.get_id()) result.result = json.dumps({'error': 'execution failed'}) result.complete = True benchmark = Benchmark.query.get(job.get_id()) benchmark.complete = True db.session.commit() def calculate_calibration_matrix(token, qpu_name, shots): """Calculate the current calibration matrix for the given QPU and save the result in db""" job = get_current_job() backend = ibmq_handler.get_qpu(token, qpu_name) if backend: job_result = ibmq_handler.get_meas_fitter(token, qpu_name, shots) if job_result: result = Result.query.get(job.get_id()) result.result = json.dumps({'matrix': job_result.cal_matrix}, cls=NumpyEncoder) result.complete = True db.session.commit() else: result = Result.query.get(job.get_id()) result.result = json.dumps({'error': 'matrix calculation failed'}) result.complete = True db.session.commit() else: result = Result.query.get(job.get_id()) result.result = json.dumps({'error': 'qpu-name or token wrong'}) result.complete = True db.session.commit()
https://github.com/JackHidary/quantumcomputingbook
JackHidary
# Do the necessary imports import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer from qiskit.extensions import Initialize from qiskit.quantum_info import random_statevector, Statevector,partial_trace def trace01(out_vector): return Statevector([sum([out_vector[i] for i in range(0,4)]), sum([out_vector[i] for i in range(4,8)])]) def teleportation(): # Create random 1-qubit state psi = random_statevector(2) print(psi) init_gate = Initialize(psi) init_gate.label = "init" ## SETUP qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits crz = ClassicalRegister(1, name="crz") # and 2 classical registers crx = ClassicalRegister(1, name="crx") qc = QuantumCircuit(qr, crz, crx) # Don't modify the code above ## Put your code below # ---------------------------- qc.initialize(psi, qr[0]) qc.h(qr[1]) qc.cx(qr[1],qr[2]) qc.cx(qr[0],qr[1]) qc.h(qr[0]) qc.measure(qr[0],crz[0]) qc.measure(qr[1],crx[0]) qc.x(qr[2]).c_if(crx[0], 1) qc.z(qr[2]).c_if(crz[0], 1) # ---------------------------- # Don't modify the code below sim = Aer.get_backend('aer_simulator') qc.save_statevector() out_vector = sim.run(qc).result().get_statevector() result = trace01(out_vector) return psi, result # (psi,res) = teleportation() # print(psi) # print(res) # if psi == res: # print('1') # else: # print('0')
https://github.com/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/2lambda123/Qiskit-qiskit
2lambda123
# 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. """Test KAK over optimization""" import unittest import numpy as np from qiskit import QuantumCircuit, QuantumRegister, transpile from qiskit.circuit.library import CU1Gate from qiskit.test import QiskitTestCase class TestKAKOverOptim(QiskitTestCase): """Tests to verify that KAK decomposition does not over optimize. """ def test_cz_optimization(self): """Test that KAK does not run on a cz gate""" qr = QuantumRegister(2) qc = QuantumCircuit(qr) qc.cz(qr[0], qr[1]) cz_circ = transpile( qc, None, coupling_map=[[0, 1], [1, 0]], basis_gates=["u1", "u2", "u3", "id", "cx"], optimization_level=3, ) ops = cz_circ.count_ops() self.assertEqual(ops["u2"], 2) self.assertEqual(ops["cx"], 1) self.assertFalse("u3" in ops.keys()) def test_cu1_optimization(self): """Test that KAK does run on a cu1 gate and reduces the cx count from two to one. """ qr = QuantumRegister(2) qc = QuantumCircuit(qr) qc.append(CU1Gate(np.pi), [qr[0], qr[1]]) cu1_circ = transpile( qc, None, coupling_map=[[0, 1], [1, 0]], basis_gates=["u1", "u2", "u3", "id", "cx"], optimization_level=3, ) ops = cu1_circ.count_ops() self.assertEqual(ops["cx"], 1) if __name__ == "__main__": unittest.main()
https://github.com/alejomonbar/Quantum-Supply-Chain-Manager
alejomonbar
# !pip install --upgrade pip # !pip uninstall tensorflow --y # !pip install tensorflow import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # load csv file import pandas as pd # numpy to the seed import numpy as np # load csv fileframework to neural networks import tensorflow as tf #Method forthe neural network from keras.regularizers import l2 from keras.models import Sequential from keras.layers import Dense, Dropout #save as image the model summary from keras.utils.vis_utils import plot_model # librariesto plot import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns from sklearn.metrics import confusion_matrix, roc_curve, auc from sklearn.preprocessing import StandardScaler # demonstration of calculating metrics for a neural network model using sklearn from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score from sklearn.metrics import cohen_kappa_score from sklearn.metrics import roc_auc_score import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) data_train = pd.read_csv("fair_train.csv") X_train,y_train = data_train[data_train.columns[:16]].values, data_train[data_train.columns[16]].values data_test = pd.read_csv("classic_test.csv") X_test,y_test = data_test[data_test.columns[:16]].values, data_test[data_test.columns[16]].values (X_train.shape, y_train.shape),(X_test.shape, y_test.shape) np.random.seed(123) tf.random.set_seed(123) scale = StandardScaler() scale.fit(X_train) X_train_std = scale.transform(X_train) X_test_std = scale.transform(X_test) X_train_std[1], y_train[1] model = Sequential() model.add(Dense(25, input_dim=16, activation='relu', kernel_regularizer=l2(1e-6),kernel_initializer="glorot_normal")) model.add(Dropout(0.5)) model.add(Dense(8, activation='relu',kernel_regularizer=l2(1e-6), kernel_initializer="glorot_normal")) model.add(Dropout(0.5)) model.add(Dense(1, activation='sigmoid',kernel_regularizer=l2(1e-6), kernel_initializer="glorot_normal")) plot_model(model, to_file='model_plot.png', show_shapes=True, show_layer_names=True) # Compile model auc = tf.keras.metrics.AUC() model.compile(loss='binary_crossentropy', optimizer="Adam", metrics=['accuracy',auc]) model_history = model.fit(X_train_std, y_train, epochs=100, batch_size=32, validation_split=0.2, shuffle=True) train_pred = model.predict(X_train_std) test_pred = model.predict(X_test_std) y_train_pred = (model.predict(X_train_std) > 0.5).astype("int32") y_test_pred = (model.predict(X_test_std) > 0.5).astype("int32") accuracy = accuracy_score(y_train, y_train_pred) print('Accuracy: %f' % accuracy) # precision tp / (tp + fp) precision = precision_score(y_train, y_train_pred) print('Precision: %f' % precision) # recall: tp / (tp + fn) recall = recall_score(y_train, y_train_pred) print('Recall: %f' % recall) # f1: 2 tp / (2 tp + fp + fn) f1 = f1_score(y_train, y_train_pred) print('F1 score: %f' % f1) # kappa kappa = cohen_kappa_score(y_train, y_train_pred) print('Cohens kappa: %f' % kappa) # ROC AUC auc = roc_auc_score(y_train, y_train_pred) print('ROC AUC: %f' % auc) # confusion matrix train_matrix = confusion_matrix(y_train, y_train_pred) print(train_matrix) ax = sns.heatmap(train_matrix, annot=True, cmap='Blues', fmt='g') ax.set_title('Seaborn Confusion Matrix with labels\n\n'); ax.set_xlabel('\nPredicted Values') ax.set_ylabel('Actual Values '); ax.xaxis.set_ticklabels(['0','1']) ax.yaxis.set_ticklabels(['0','1']) ## Display the visualization of the Confusion Matrix. plt.show() accuracy = accuracy_score(y_test, y_test_pred) print('Accuracy: %f' % accuracy) # precision tp / (tp + fp) precision = precision_score(y_test, y_test_pred) print('Precision: %f' % precision) # recall: tp / (tp + fn) recall = recall_score(y_test, y_test_pred) print('Recall: %f' % recall) # f1: 2 tp / (2 tp + fp + fn) f1 = f1_score(y_test, y_test_pred) print('F1 score: %f' % f1) # kappa kappa = cohen_kappa_score(y_test, y_test_pred) print('Cohens kappa: %f' % kappa) # ROC AUC auc = roc_auc_score(y_test, y_test_pred) print('ROC AUC: %f' % auc) # confusion matrix test_matrix = confusion_matrix(y_test, y_test_pred) print(test_matrix) ax = sns.heatmap(test_matrix, annot=True, cmap='Blues', fmt='g') ax.set_title('Seaborn Confusion Matrix with labels\n\n'); ax.set_xlabel('\nPredicted Values') ax.set_ylabel('Actual Values '); ax.xaxis.set_ticklabels(['0','1']) ax.yaxis.set_ticklabels(['0','1']) ## Display the visualization of the Confusion Matrix. plt.show()
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import time import itertools import numpy as np from scipy.optimize import minimize, basinhopping from qiskit import * from qiskit.quantum_info import Statevector from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA from qiskit.opflow.state_fns import StateFn, CircuitStateFn from qiskit.providers.aer import StatevectorSimulator, AerSimulator import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator from matplotlib.colors import BoundaryNorm from modules.utils import * %matplotlib inline cmap = plt.get_cmap("plasma") #'viridis' import qiskit #%matplotlib inline print(qiskit.__version__) ### Preliminaries L = 5 num_trash = 2 logspace_size=50 name = f'VQE_Ising_L5_anti_-1_50x50' # _1e-3 # name of the data produced by this notebook filename = "data/params_" + name # name of the data file that is used L = 5 anti = -1. VQE_params = np.load(filename + ".npz", allow_pickle=True) gx_list = VQE_params['gx_list'] gz_list = VQE_params['gz_list'] opt_params = VQE_params['opt_params'] gx_vals = np.unique(gx_list) gz_vals = np.unique(gz_list) mag = QMag(L,anti) #magnetization operator (Qiskit) Smag = Mag(L,anti) #magnetization operator (numpy) # the ~ is the adjoint, but also it turns the is_measurement attribute to True ~StateFn(mag) # state is technically a circuit, that prepares the ground state via VQE circuit #state.draw() # uncomment to see, but is very long Qen=np.zeros(len(opt_params)); Sen=np.zeros(len(opt_params)) #energies Qmags=np.zeros(len(opt_params)); Smags=np.zeros(len(opt_params)) #magnetizations load = True if load: temp = np.load(filename + "_mags-Es.npz",allow_pickle=True) Qmags = temp["Qmags"] Qen = temp["Qen"] Sen = temp["Sen"] Smags = temp["Smags"] if not load: for j in range(len(opt_params)): gx = gx_list[j] gz = gz_list[j] H = QHIsing(L, anti, np.float32(gx), np.float32(gz)) # build Hamiltonian Op state = init_vqe(opt_params[j], L=L) StateFn(state) meas_outcome = ~StateFn(mag) @ StateFn(state) Qmags[j] = meas_outcome.eval() e_outcome = ~StateFn(H) @ StateFn(state) Qen[j] = e_outcome.eval() init_state, E, ham = ising_groundstate(L, anti, np.float(gx), np.float(gz)) Sen[j] = E Smags[j] = init_state.T.conj()@Smag@init_state #Magnetization with Numpy results np.savez(filename + "_mags-Es",Qmags=Qmags, Qen=Qen, Sen=Sen, Smags=Smags) # for large parameter space takes quite a while because of the exact diagonalization fig,ax = plt.subplots(figsize=(8,5)) cmap = plt.get_cmap("plasma") #'viridis' im = ax.pcolormesh(gz_vals, gx_vals, abs(Smags).reshape(len(gz_vals),len(gx_vals)), cmap=cmap) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Magnetization ED L %.0f anti %.0f" %(L, anti),fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) fig,ax = plt.subplots(figsize=(8,5)) cmap = plt.get_cmap("plasma") #'viridis' im = ax.pcolormesh(gz_vals, gx_vals, abs(Qmags).reshape(len(gz_vals),len(gx_vals)), cmap=cmap) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Magnetization VQE L %.0f anti %.0f" %(L, anti),fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) fig,ax = plt.subplots(figsize=(8,5)) cmap = plt.get_cmap("plasma") #'viridis' im = ax.pcolormesh(gz_vals, gx_vals, Sen.reshape(len(gz_vals),len(gx_vals)) - Qen.reshape(len(gz_vals),len(gx_vals)), cmap=cmap) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Difference in energy L %.0f anti %.0f" %(L, anti),fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) ############################################################################## ### II - Training ########################################################### ############################################################################## # Use Aer's qasm_simulator backend_sim = Aer.get_backend('qasm_simulator') thetas = np.random.uniform(0, 2*np.pi, 2*L+2) # initial parameters without feature encoding # thetas = np.random.uniform(0, 2*np.pi, (2*L+2, 2)) # initial parameters with feature encoding # linear entangler (as in scales linearly with trash qubits) def get_entangler_map(L, num_trash, i_permut=1): result = [] nums = list(range(L)) # here was the problem, it doesnt like when list elements are taken from numpy nums_compressed = nums.copy()[:L-num_trash] nums_trash = nums.copy()[-num_trash:] #print(nums, nums_compressed, nums_trash) # combine all trash qubits with themselves for trash_q in nums_trash[:-1]: result.append((trash_q+1,trash_q)) # combine each of the trash qubits with every n-th repeated = list(nums_trash) * (L-num_trash) # repeat the list of trash indices cyclicly for i in range(L-num_trash): result.append((repeated[i_permut + i], nums_compressed[i])) return result def QAE_Ansatz(thetas, L, num_trash, insert_barriers=False, parametrized_gate = "ry", entangling_gate = "cz"): entanglement = [get_entangler_map(L,num_trash,i_permut) for i_permut in range(num_trash)] circ = qiskit.circuit.library.TwoLocal(L, parametrized_gate, entangling_gate, entanglement, reps=num_trash, insert_barriers=insert_barriers, skip_final_rotation_layer=True ).assign_parameters(thetas[:-num_trash]) if insert_barriers: circ.barrier() for i in range(num_trash): circ.ry(thetas[L-i-1], L-i-1) #circ.ry(circuit.Parameter(f'θ{i}'), L-i-1) return circ def prepare_circuit(thetas, L=6, num_trash=2, init_state=None, measurement=True, vqe=True): qreg = QuantumRegister(L, 'q') creg = ClassicalRegister(num_trash, 'c') circ = QuantumCircuit(qreg, creg) circ += QAE_Ansatz(thetas, L, num_trash, insert_barriers=True)#.assign_parameters(thetas) # difference to bind? if measurement: for i in range(num_trash): circ.measure(qreg[L-i-1], creg[i]) if init_state is not None: if vqe: circ = init_vqe(init_state,L=L) + circ else: circ.initialize(init_state, qreg) return circ def feature_encoding(thetas, x): """ thetas: parameters to be optimized, x: Ising model parameter (eg. field) """ new_thetas = [] thetas = thetas.reshape((-1,2)) for theta in thetas: new_thetas.append(theta[0] * x + theta[1]) return new_thetas idx = 30 num_trash = 2 J, gx, gz = -1., gx_list[idx], gz_list[idx] # Ising parameters for which ground state should be compressed phi = opt_params[idx] # train on smallest lambda ;; this may grammatically be confusing, init_state = dictionary with unsorted parameters def run_circuit(thetas, L, num_trash, init_state, vqe=True, shots=100): circ = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe) # Execute the circuit on the qasm simulator. job_sim = execute(circ, backend_sim, shots=shots, seed_simulator=123, seed_transpiler=234) # fix seed to make it reproducible # Grab the results from the job. result_sim = job_sim.result() counts = result_sim.get_counts(circ) # print(counts) # mems = result_sim.get_memory(circ) # print(mems) return counts run_circuit(thetas, L, num_trash, phi)['11'] # translate to Rikes naming phis = opt_params gxs = gx_list gzs = gz_list def cost_function_single(thetas, L, num_trash, p, shots=1000, vqe=True, param_encoding=False, x=0): """ Optimizes circuit """ if vqe: init_state = phis[p] else: J, gx, gz = p init_state, _ = ising_groundstate(L, J, gx, gz) if param_encoding: thetas = feature_encoding(thetas, x) out = run_circuit(thetas, L, num_trash, init_state, vqe=vqe, shots=shots) cost = out.get('11', 0)*2 + out.get('01', 0) + out.get('10', 0) return cost/shots def cost_function(thetas, L, num_trash, ising_params, shots=1000, vqe=True, param_encoding=False, x=0): """ Optimizes circuit """ cost = 0. n_samples = len(ising_params) for i, p in enumerate(ising_params): if param_encoding: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, x[i]) else: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding) return cost/n_samples def optimize(ising_params, L=6, num_trash=2, thetas=None, shots=1000, max_iter=400, vqe=True, param_encoding=False, x=0, pick_optimizer = None): if thetas is None: n_params = (2*L+2)*2 if param_encoding else (2*L+2) thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding print("Initial cost: {:.3f}".format(cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x))) counts, values, accepted = [], [], [] def store_intermediate_result(eval_count, parameters, mean, std, ac): # counts.append(eval_count) values.append(mean) accepted.append(ac) # Initialize optimizer if pick_optimizer == "cobyla": optimizer = COBYLA(maxiter=max_iter, tol=0.0001) if pick_optimizer == "adam" or pick_optimizer == "ADAM": optimizer = qiskit.algorithms.optimizers.ADAM(maxiter=max_iter) # optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08) if pick_optimizer == "spsa" or pick_optimizer == None: optimizer = SPSA(maxiter=max_iter, #blocking=True, callback=store_intermediate_result, #learning_rate=1e-1, #perturbation=0.4 ) # recommended from qiskit (first iteraction takes quite long) # to reduce time figure out optimal learning rate and perturbation in advance start_time = time.time() ret = optimizer.optimize( num_vars=len(thetas), objective_function=(lambda thetas: cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x)), initial_point=thetas ) print("Time: {:.5f} sec".format(time.time()-start_time)) print(ret) return ret[0], values, accepted x,y = np.meshgrid(gx_vals, gz_vals) def run_inference(thetas, shots=1000, L=5): points = 50 J = -1.0 x,y = np.meshgrid(gx_vals, gz_vals) cost = np.zeros((len(gx_vals) * len(gz_vals))) Smags = np.zeros((len(gx_vals) * len(gz_vals))) shots = 1000 for i,p in enumerate(list(zip(gxs, gzs))): cost[i] = cost_function_single(thetas, L, num_trash, i, shots=shots) cost = cost.reshape((len(gx_vals), len(gz_vals))) return cost cmap = plt.get_cmap("plasma") def plot_result(cost): fig,axs = plt.subplots(ncols=2,figsize=(15,5)) nbins=100 ax = axs[0] im = ax.pcolormesh(x, y, cost, cmap=cmap, shading="auto") cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) ax.set_xscale("log") ax.set_yscale("log") ax.set_title(f"Loss",fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) for p in params: gz = gz_list[p] gx = gx_list[p] ax.plot(gz,gx,"o",label="training",color="cyan") ax = axs[1] im = ax.pcolormesh(gz_vals, gx_vals, abs(Qmags).reshape(len(gz_vals),len(gx_vals)), cmap=cmap, shading="auto") cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) ax.set_xscale("log") ax.set_yscale("log") ax.set_title("Magnetization VQE L %.0f anti %.0f" %(L, anti),fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) #reset random seed np.random.seed(123) from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 123 np.intersect1d( np.intersect1d(np.where(gx_list > 5e-2),np.where(1e-1 > gx_list)), np.intersect1d(np.where(gz_list > 5e-2),np.where(1e-1 > gz_list)) ) paramss =[ [459], # train on bottom left point [460], [509], [560] ] for i,params in enumerate(paramss): print(f"{i} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}") thetass = [None] * len(paramss) losss = [None] * len(paramss) costs = [None] * len(paramss) for i,params in enumerate(paramss): print(f"{i+1} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}") thetas, loss, accepted = optimize(params, max_iter=100, L=5) #, pick_optimizer="adam") thetass[i], losss[i] = thetas, loss plt.plot(loss) cost = run_inference(thetas) costs[i] = cost filename2 = "data/" + name + "_thetas-loss-cost_vary-training-states" np.savez(filename2, losss = losss, costs = costs, thetass = thetass) for i,params in enumerate(paramss): print(f"{i+1} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}") plot_result(np.load(filename2 + ".npz",allow_pickle=True)["costs"][i]) plt.show() for i,params in enumerate(paramss): print(f"{i+1} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}") thetas, loss, accepted = optimize(params, max_iter=100, L=5, pick_optimizer="cobyla") #, pick_optimizer="adam") thetass[i], losss[i] = thetas, loss cost = run_inference(thetas) costs[i] = cost filename2 = "data/" + name + "_thetas-loss-cost_vary-training-states_cobyla" np.savez(filename2, losss = losss, costs = costs, thetass = thetass) for i,params in enumerate(paramss): print(f"{i+1} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}") plot_result(np.load(filename2 + ".npz",allow_pickle=True)["costs"][i]) plt.show()
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Test circuits and reference outputs for conditional gates. """ import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Instruction def add_conditional_x(circuit, qreg, creg, val, conditional_type): """Add a conditional instruction to a circuit. Args: circuit (QuantumCircuit): circuit to add instruction to. qreg (QuantumRegister): qubit to apply conditional X to creg (ClassicalRegister): classical reg to condition on val (int): Classical reg value to condition on. conditional_type (string): instruction type to add conditional X as. Conditional type can be 'gate', 'unitary', 'kraus', 'superop' and will apply a conditional X-gate in that representation """ # X-gate matrix x_mat = np.array([[0, 1], [1, 0]], dtype=complex) x_superop = Instruction('superop', 1, 0, [np.kron(x_mat, x_mat)]) x_kraus = Instruction('kraus', 1, 0, [x_mat]) if conditional_type == 'unitary': circuit.unitary(x_mat, [qreg]).c_if(creg, val) elif conditional_type == 'kraus': circuit.append(x_kraus, [qreg]).c_if(creg, val) elif conditional_type == 'superop': circuit.append(x_superop, [qreg]).c_if(creg, val) else: circuit.x(qreg).c_if(creg, val) # ========================================================================== # Conditionals on 1-bit register # ========================================================================== def conditional_circuits_1bit(final_measure=True, conditional_type='gate'): """Conditional gates on single bit classical register.""" circuits = [] qr = QuantumRegister(1) cond = ClassicalRegister(1, 'cond') if final_measure: cr = ClassicalRegister(1, 'meas') regs = (qr, cr, cond) else: regs = (qr, cond) # Conditional on 0 (cond = 0) circuit = QuantumCircuit(*regs) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 0, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 0 (cond = 1) circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.measure(qr[0], cond[0]) circuit.x(qr) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 0, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 1 (cond = 0) circuit = QuantumCircuit(*regs) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 1, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 1 (cond = 1) circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.measure(qr[0], cond[0]) circuit.x(qr) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 1, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def conditional_counts_1bit(shots, hex_counts=True): """Conditional circuits reference counts.""" targets = [] if hex_counts: # Conditional on 0 (cond = 0), result "0 1" targets.append({'0x1': shots}) # Conditional on 0 (cond = 1), result "1 0" targets.append({'0x2': shots}) # Conditional on 1 (cond = 0), # result "0 0" targets.append({'0x0': shots}) # Conditional on 1 (cond = 1), # result "1 1" targets.append({'0x3': shots}) else: # Conditional on 0 (cond = 0), result "0 1" targets.append({'0 1': shots}) # Conditional on 0 (cond = 1), result "1 0" targets.append({'1 0': shots}) # Conditional on 1 (cond = 0), # result "0 0" targets.append({'0 0': shots}) # Conditional on 1 (cond = 1), # result "1 1" targets.append({'1 1': shots}) return targets def conditional_statevector_1bit(): """Conditional circuits reference statevector.""" targets = [] # Conditional on 0 (cond = 0) targets.append(np.array([0, 1])) # Conditional on 0 (cond = 1) targets.append(np.array([1, 0])) # Conditional on 1 (cond = 0) targets.append(np.array([1, 0])) # Conditional on 1 (cond = 1) targets.append(np.array([0, 1])) return targets # ========================================================================== # Conditionals on 2-bit register # ========================================================================== def conditional_circuits_2bit(final_measure=True, conditional_type='gate'): """Conditional test circuits on 2-bit classical register.""" circuits = [] qr = QuantumRegister(1) cond = ClassicalRegister(2, 'cond') if final_measure: cr = ClassicalRegister(1, 'meas') regs = (qr, cr, cond) else: regs = (qr, cond) # Conditional on 00 (cr = 00) circuit = QuantumCircuit(*regs) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 0, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 00 (cr = 01) circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.measure(qr[0], cond[0]) circuit.x(qr) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 0, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 00 (cr = 10) circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.measure(qr[0], cond[1]) circuit.x(qr) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 0, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 00 (cr = 11) circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.measure(qr[0], cond[0]) circuit.measure(qr[0], cond[1]) circuit.x(qr) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 0, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 01 (cr = 00) circuit = QuantumCircuit(*regs) add_conditional_x(circuit, qr[0], cond, 1, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 01 (cr = 01) circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.measure(qr[0], cond[0]) circuit.x(qr) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 1, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 01 (cr = 10) circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.measure(qr[0], cond[1]) circuit.x(qr) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 1, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 01 (cr = 11) circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.measure(qr[0], cond[0]) circuit.measure(qr[0], cond[1]) circuit.x(qr) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 1, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 10 (cr = 00) circuit = QuantumCircuit(*regs) circuit.x(qr).c_if(cond, 2) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 10 (cr = 01) circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.measure(qr[0], cond[0]) circuit.x(qr) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 2, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 10 (cr = 10) circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.measure(qr[0], cond[1]) circuit.x(qr) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 2, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 10 (cr = 11) circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.measure(qr[0], cond[0]) circuit.measure(qr[0], cond[1]) circuit.x(qr) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 2, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 11 (cr = 00) circuit = QuantumCircuit(*regs) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 3, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 11 (cr = 01) circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.measure(qr[0], cond[0]) circuit.x(qr) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 3, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 11 (cr = 10) circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.measure(qr[0], cond[1]) circuit.x(qr) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 3, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 11 (cr = 11) circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.measure(qr[0], cond[0]) circuit.measure(qr[0], cond[1]) circuit.x(qr) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 3, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def conditional_counts_2bit(shots, hex_counts=True): """2-bit conditional circuits reference counts.""" targets = [] if hex_counts: # Conditional on 00 (cr = 00), result "00 1" targets.append({'0x1': shots}) # Conditional on 00 (cr = 01), result "01 0" targets.append({'0x2': shots}) # Conditional on 00 (cr = 10), result "10 0" targets.append({'0x4': shots}) # Conditional on 00 (cr = 11), result "11 0" targets.append({'0x6': shots}) # Conditional on 01 (cr = 00), result "00 0" targets.append({'0x0': shots}) # Conditional on 01 (cr = 01), result "01 1" targets.append({'0x3': shots}) # Conditional on 01 (cr = 10), result "10 0" targets.append({'0x4': shots}) # Conditional on 01 (cr = 11), result "11 0" targets.append({'0x6': shots}) # Conditional on 10 (cr = 00), result "00 0" targets.append({'0x0': shots}) # Conditional on 10 (cr = 01), result "01 0" targets.append({'0x2': shots}) # Conditional on 10 (cr = 10), result "10 1" targets.append({'0x5': shots}) # Conditional on 10 (cr = 11), result "11 0" targets.append({'0x6': shots}) # Conditional on 11 (cr = 00), result "00 0" targets.append({'0x0': shots}) # Conditional on 11 (cr = 01), result "01 0" targets.append({'0x2': shots}) # Conditional on 11 (cr = 10), result "10 0" targets.append({'0x4': shots}) # Conditional on 11 (cr = 11), result "11 1" targets.append({'0x7': shots}) else: # Conditional on 00 (cr = 00), result "00 1" targets.append({'00 1': shots}) # Conditional on 00 (cr = 01), result "01 0" targets.append({'01 0': shots}) # Conditional on 00 (cr = 10), result "10 0" targets.append({'10 0': shots}) # Conditional on 00 (cr = 11), result "11 0" targets.append({'11 0': shots}) # Conditional on 01 (cr = 00), result "00 0" targets.append({'00 0': shots}) # Conditional on 01 (cr = 01), result "01 1" targets.append({'01 1': shots}) # Conditional on 01 (cr = 10), result "10 0" targets.append({'10 0': shots}) # Conditional on 01 (cr = 11), result "11 0" targets.append({'11 0': shots}) # Conditional on 10 (cr = 00), result "00 0" targets.append({'00 0': shots}) # Conditional on 10 (cr = 01), result "01 0" targets.append({'01 0': shots}) # Conditional on 10 (cr = 10), result "10 1" targets.append({'10 0': shots}) # Conditional on 10 (cr = 11), result "11 0" targets.append({'11 0': shots}) # Conditional on 11 (cr = 00), result "00 0" targets.append({'00 0': shots}) # Conditional on 11 (cr = 01), result "01 0" targets.append({'01 0': shots}) # Conditional on 11 (cr = 10), result "10 0" targets.append({'10 0': shots}) # Conditional on 11 (cr = 11), result "11 1" targets.append({'11 1': shots}) return targets def conditional_statevector_2bit(): """2-bit conditional circuits reference statevector.""" state_0 = np.array([1, 0]) state_1 = np.array([0, 1]) targets = [] # Conditional on 00 (cr = 00) targets.append(state_1) # Conditional on 00 (cr = 01) targets.append(state_0) # Conditional on 00 (cr = 10) targets.append(state_0) # Conditional on 00 (cr = 11) targets.append(state_0) # Conditional on 01 (cr = 00) targets.append(state_0) # Conditional on 01 (cr = 01) targets.append(state_1) # Conditional on 01 (cr = 10) targets.append(state_0) # Conditional on 01 (cr = 11) targets.append(state_0) # Conditional on 10 (cr = 00) targets.append(state_0) # Conditional on 10 (cr = 01) targets.append(state_0) # Conditional on 10 (cr = 10) targets.append(state_1) # Conditional on 10 (cr = 11) targets.append(state_0) # Conditional on 11 (cr = 00) targets.append(state_0) # Conditional on 11 (cr = 01) targets.append(state_0) # Conditional on 11 (cr = 10) targets.append(state_0) # Conditional on 11 (cr = 11) targets.append(state_1) return targets
https://github.com/DylanLi272/QiskitFinalProject
DylanLi272
from qiskit import BasicAer, Aer, IBMQ from qiskit.aqua import QuantumInstance, aqua_globals from qiskit.aqua.algorithms import VQE, ExactEigensolver, NumPyEigensolver from qiskit.aqua.components.initial_states import Zero from qiskit.aqua.components.optimizers import ADAM, AQGD, COBYLA, L_BFGS_B, SLSQP from qiskit.aqua.components.optimizers import SPSA, TNC, POWELL, P_BFGS from qiskit.aqua.components.optimizers import NFT, NELDER_MEAD, GSLS, CG from qiskit.aqua.components.variational_forms import RY, RYRZ, SwapRZ from qiskit.aqua.operators import WeightedPauliOperator, Z2Symmetries from qiskit.chemistry import FermionicOperator from qiskit.chemistry.drivers import PySCFDriver, UnitsType from qiskit.chemistry.components.variational_forms import UCCSD from qiskit.chemistry.components.initial_states import HartreeFock from qiskit.providers.aer import QasmSimulator from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors import QuantumError, ReadoutError from qiskit.providers.aer.noise.errors import pauli_error from qiskit.providers.aer.noise.errors import depolarizing_error from qiskit.providers.aer.noise.errors import thermal_relaxation_error from qiskit.providers.aer import noise from qiskit.tools.monitor import job_monitor from qiskit.providers.ibmq import least_busy import warnings IBMQ.load_account() provider = IBMQ.get_provider(group='open') backend = least_busy(provider.backends(simulator=False, operational=True)) import numpy as np import matplotlib.pyplot as plt from functools import partial distances = [] for inter_dist in range(5, 41): inter_dist /= 10.0 distances.append(inter_dist) map_type = 'parity' driver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0' + str(inter_dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') # please be aware that the idx here with respective to original idx freeze_list = [0] remove_list = [-3, -2] # negative number denotes the reverse order #Classically solve for the lowest eigenvalue def exact_solver(qubitOp): ee = ExactEigensolver(qubitOp) result = ee.run() ref = result['energy'] print('Reference value: {}'.format(ref)) return ref backend = BasicAer.get_backend('statevector_simulator') #Define our noise model based on the ibmq_essex chip chip_name = 'ibmq_essex' device = provider.get_backend(chip_name) coupling_map = device.configuration().coupling_map noise_model = noise.device.basic_device_noise_model(device.properties()) basis_gates = noise_model.basis_gates # Classically solve for the lowest eigenvalue # This is used just to compare how well you VQE approximation is performing def exact_solver(qubitOp): ee = ExactEigensolver(qubitOp) result = ee.run() ref = result['energy'] print('Reference value: {}'.format(ref)) return ref def reset_values(): counts = [] values = [] params = [] deviation = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) params.append(parameters) deviation.append(std) # Define your function for computing the qubit operations of LiH def compute_LiH_qubitOp(map_type, inter_dist, basis='sto3g'): # Specify details of our molecule driver = PySCFDriver(atom='Li 0 0 0; H 0 0 ' + str(inter_dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis=basis) # Compute relevant 1 and 2 body integrals. molecule = driver.run() h1 = molecule.one_body_integrals h2 = molecule.two_body_integrals num_particles = molecule.num_alpha + molecule.num_beta num_spin_orbitals = molecule.num_orbitals * 2 nuclear_repulsion_energy = molecule.nuclear_repulsion_energy print("# of electrons: {}".format(num_particles)) print("# of spin orbitals: {}".format(num_spin_orbitals)) # Please be aware that the idx here with respective to original idx freeze_list = [0,1,6,7] remove_list = [0,1,4,5] # negative number denotes the reverse order # Prepare full idx of freeze_list and remove_list # Convert all negative idx to positive num_spin_orbitals -= len(remove_list) # Prepare fermionic hamiltonian with orbital freezing and eliminating, and then map to qubit hamiltonian # and if PARITY mapping is selected, reduction qubits energy_shift = 0.0 qubit_reduction = True if map_type == 'parity' else False ferOp = FermionicOperator(h1=h1, h2=h2) if len(freeze_list) > 0: ferOp, energy_shift = ferOp.fermion_mode_freezing(freeze_list) num_spin_orbitals -= len(freeze_list) num_particles -= len(freeze_list)//2 if len(remove_list) > 0: ferOp = ferOp.fermion_mode_elimination(remove_list) qubitOp = ferOp.mapping(map_type) qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles) return qubitOp, num_spin_orbitals, num_particles, qubit_reduction, molecule, energy_shift, nuclear_repulsion_energy for inter_dist in distances: qubitOp, num_spin_orbitals, num_particles, qubit_reduction, molecule, energy_shift, nuclear_repulsion_energy = compute_LiH_qubitOp(map_type, inter_dist) # Classically solve for the exact solution and use that as your reference value ref = exact_solver(qubitOp) # Specify your initial state init_state = HartreeFock(num_spin_orbitals, num_particles, qubit_mapping=map_type) # Select a state preparation ansatz # Equivalently, choose a parameterization for our trial wave function. RY_var_form = RY(qubitOp.num_qubits, depth=2) # Choose where to run/simulate our circuit quantum_instance = backend max_eval = 1000 # Choose the classical optimizer POWELL_optimizer = POWELL(max_eval) warnings.filterwarnings("ignore") COBYLA_vqe = VQE(qubitOp, RY_var_form, SPSA_optimizer, callback=store_intermediate_result) COBYLA_vqe_eigenvalue = np.real(COBYLA_vqe.run(backend)['eigenvalue']) list_of_values.append(values) reset_values() COBYLA_vqe_result = np.real(energy_shift + COBYLA_vqe_eigenvalue) print("==================================================") print('Reference value: {}'.format(ref)) print("COBYLA VQE value: ", COBYLA_vqe_eigenvalue) print("HF energy: {}".format(molecule.hf_energy)) print("Reference Value Percent Error: " + str(abs((COBYLA_vqe_eigenvalue-ref)/ref)*100) + "%") print("Energy Value Percent Error: " + str(np.real(abs((COBYLA_vqe_result-molecule.hf_energy)/molecule.hf_energy))*100) + "%") print("==================================================") POWELL_vqe = VQE(qubitOp, RY_var_form, POWELL_optimizer) POWELL_vqe_eigenvalue = np.real(POWELL_vqe.run(backend)['eigenvalue']) list_of_values.append(values) reset_values() POWELL_vqe_result = np.real(energy_shift + POWELL_vqe_eigenvalue) print('Reference value: {}'.format(ref)) print("POWELL VQE value: ", POWELL_vqe_eigenvalue) print("HF energy: {}".format(molecule.hf_energy)) print("Reference Value Percent Error: " + str(abs((POWELL_vqe_eigenvalue-ref)/ref)*100) + "%") print("Energy Value Percent Error: " + str(np.real(abs((POWELL_vqe_result-molecule.hf_energy)/molecule.hf_energy))*100) + "%") print("==================================================") SPSA_vqe = VQE(qubitOp, RY_var_form, SPSA_optimizer, callback=store_intermediate_result) SPSA_vqe_eigenvalue = np.real(SPSA_vqe.run(backend)['eigenvalue']) list_of_values.append(values) reset_values() # Now compare the results of different compositions of your VQE algorithm! SPSA_vqe_result = np.real(energy_shift + SPSA_vqe_eigenvalue) print('Reference value: {}'.format(ref)) print("SPSA VQE energy: ", SPSA_vqe_eigenvalue) print("HF energy: {}".format(molecule.hf_energy)) print("SPSA Reference Value Percent Error: " + str(abs((SPSA_vqe_eigenvalue-ref)/ref)*100) + "%") print("SPSA Energy Value Percent Error: " + str(np.real(abs((SPSA_vqe_result-molecule.hf_energy)/molecule.hf_energy))*100) + "%") print("==================================================") TNC_vqe = VQE(qubitOp, RY_var_form, TNC_optimizer) TNC_vqe_eigenvalue = np.real(TNC_vqe.run(backend)['eigenvalue']) list_of_values.append(values) reset_values() TNC_vqe_result = np.real(energy_shift + TNC_vqe_eigenvalue) print('Reference value: {}'.format(ref)) print("TNC VQE energy: ", TNC_vqe_eigenvalue) print("HF energy: {}".format(molecule.hf_energy)) print("TNC Reference Value Percent Error: " + str(abs((TNC_vqe_eigenvalue-ref)/ref)*100) + "%") print("TNC Energy Value Percent Error: " + str(np.real(abs((TNC_vqe_result-molecule.hf_energy)/molecule.hf_energy))*100) + "%") print("==================================================") graph1 = plt.figure(figsize=(15,10)) names = ['COBYLA', 'POWELL', 'SPSA', 'TNC'] colors = ['r','g','b','y'] plt.xlabel('Evaluation Count') plt.ylabel('Logscale Error Difference from Reference Value') plt.title('Logscael Error of VQE Procedure: RY') plt.yscale('log') iterations = [] count = 0 for i in range(1000): iterations.append(i) COBYLA = [] SLSQP = [] SPSA = [] TNC = [] for i in iterations: COBYLA.append(((list_of_values[0][count] - ref)/ref)) count += 1 for i in iterations: SLSQP.append(((list_of_values[1][count]-ref)/ref)) count += 1 for i in iterations: SPSA.append(((list_of_values[2][count]-ref)/ref)) count += 1 for i in iterations: TNC.append(((list_of_values[3][count]-ref)/ref)) count += 1 plt.plot(iterations, COBYLA, 'r--', iterations, SLSQP, 'bs--', iterations, SPSA, 'g^--', iterations, TNC, 'y*--') plt.legend(names) graph2 = plt.figure(figsize=(15,10)) names = ['COBYLA', 'POWELL', 'SPSA', 'TNC'] colors = ['r','g','b','y'] plt.xlabel('Evaluation Count') plt.ylabel('Energy Minimization for Various Optimizers') plt.title('Energy Convergence VQE Procedure: RY') iterations = [] count = 0 for i in range(1000): iterations.append(i) COBYLA = [] SLSQP = [] SPSA = [] TNC = [] for i in iterations: COBYLA.append(energy_shift + list_of_values[0][count]) count += 1 for i in iterations: SLSQP.append(energy_shift + list_of_values[1][count]) count += 1 for i in iterations: SPSA.append(energy_shift + list_of_values[2][count]) count += 1 for i in iterations: TNC.append(energy_shift + list_of_values[3][count]) count += 1 plt.plot(iterations, COBYLA, 'r--', iterations, SLSQP, 'bs--', iterations, SPSA, 'g^--', iterations, TNC, 'y*--') plt.legend(names)
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
MonitSharma
# initialization import numpy as np # importing Qiskit from qiskit import QuantumCircuit, transpile from qiskit.primitives import Sampler, Estimator # import basic plot tools from qiskit.visualization import plot_histogram # set the length of the n-bit input string. n = 3 # set the length of the n-bit input string. n = 3 const_oracle = QuantumCircuit(n+1) output = np.random.randint(2) if output == 1: const_oracle.x(n) const_oracle.draw('mpl') balanced_oracle = QuantumCircuit(n+1) b_str = "101" balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) balanced_oracle.draw('mpl') balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() balanced_oracle.draw('mpl') balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Show oracle balanced_oracle.draw('mpl') dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) dj_circuit.draw('mpl') dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit = dj_circuit.compose(balanced_oracle) dj_circuit.draw('mpl') dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit = dj_circuit.compose(balanced_oracle) # Repeat H-gates for qubit in range(n): dj_circuit.h(qubit) dj_circuit.barrier() # Measure for i in range(n): dj_circuit.measure(i, i) # Display circuit dj_circuit.draw('mpl') # use local simulator sampler = Sampler() result = sampler.run(dj_circuit).result() answer = result.quasi_dists[0] plot_histogram(answer) def dj_oracle(case, n): # We need to make a QuantumCircuit object to return # This circuit has n+1 qubits: the size of the input, # plus one output qubit oracle_qc = QuantumCircuit(n+1) # First, let's deal with the case in which oracle is balanced if case == "balanced": # First generate a random number that tells us which CNOTs to # wrap in X-gates: b = np.random.randint(1,2**n) # Next, format 'b' as a binary string of length 'n', padded with zeros: b_str = format(b, '0'+str(n)+'b') # Next, we place the first X-gates. Each digit in our binary string # corresponds to a qubit, if the digit is 0, we do nothing, if it's 1 # we apply an X-gate to that qubit: for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Do the controlled-NOT gates for each qubit, using the output qubit # as the target: for qubit in range(n): oracle_qc.cx(qubit, n) # Next, place the final X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Case in which oracle is constant if case == "constant": # First decide what the fixed output of the oracle will be # (either always 0 or always 1) output = np.random.randint(2) if output == 1: oracle_qc.x(n) oracle_gate = oracle_qc.to_gate() oracle_gate.name = "Oracle" # To show when we display the circuit return oracle_gate def dj_algorithm(oracle, n): dj_circuit = QuantumCircuit(n+1, n) # Set up the output qubit: dj_circuit.x(n) dj_circuit.h(n) # And set up the input register: for qubit in range(n): dj_circuit.h(qubit) # Let's append the oracle gate to our circuit: dj_circuit.append(oracle, range(n+1)) # Finally, perform the H-gates again and measure: for qubit in range(n): dj_circuit.h(qubit) for i in range(n): dj_circuit.measure(i, i) return dj_circuit n = 4 oracle_gate = dj_oracle('balanced', n) dj_circuit = dj_algorithm(oracle_gate, n) dj_circuit.draw('mpl') result = sampler.run(dj_circuit).result() answer = result.quasi_dists[0] plot_histogram(answer) # from qiskit_ibm_runtime import QiskitRuntimeService # # Save an IBM Quantum account and set it as your default account. # QiskitRuntimeService.save_account(channel="ibm_quantum", token="<Enter Your Token Here>", overwrite=True) # # Load saved credentials # service = QiskitRuntimeService() from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService() service.backends() service = QiskitRuntimeService() backend = service.least_busy(operational=True,min_num_qubits=5) print(backend) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager pm = generate_preset_pass_manager(optimization_level=3, backend=backend,seed_transpiler=11) qc = pm.run(dj_circuit) qc.draw('mpl',idle_wires=False) # Get the results of the computation from qiskit.primitives import BackendSampler sampler = BackendSampler(backend) result = sampler.run(qc).result() answer = result.quasi_dists[0] plot_histogram(answer)
https://github.com/qBraid/qBraid
qBraid
# 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 transpiling ciruits with idle qubits """ import braket.circuits import cirq import pytest import qiskit from qbraid.interface.circuit_equality import assert_allclose_up_to_global_phase, circuits_allclose from qbraid.programs import load_program from qbraid.transpiler import transpile # pylint: disable=redefined-outer-name @pytest.fixture def braket_circuit() -> braket.circuits.Circuit: """Returns Braket bell circuit with idle qubits""" return braket.circuits.Circuit().h(4).cnot(4, 8) @pytest.fixture def cirq_circuit() -> cirq.Circuit: """Returns Cirq bell circuit with idle qubits""" q4, q8 = cirq.LineQubit(4), cirq.LineQubit(8) circuit = cirq.Circuit(cirq.ops.H(q4), cirq.ops.CNOT(q4, q8)) return circuit @pytest.fixture def qiskit_circuit() -> qiskit.QuantumCircuit: """Returns Qiskit bell circuit with idle qubits""" circuit = qiskit.QuantumCircuit(9) circuit.h(4) circuit.cx(4, 8) return circuit def test_braket_to_cirq(braket_circuit): """Tests Braket conversions""" cirq_test = transpile(braket_circuit, "cirq", require_native=True) assert circuits_allclose(cirq_test, braket_circuit) def test_braket_to_qiskit(braket_circuit): """Tests Braket conversions""" qiskit_test = transpile(braket_circuit, "qiskit", require_native=True) qprogram_qiskit = load_program(qiskit_test) qprogram_braket = load_program(braket_circuit) qprogram_braket.populate_idle_qubits() qiskit_u = qprogram_qiskit.unitary() braket_u = qprogram_braket.unitary() assert_allclose_up_to_global_phase(qiskit_u, braket_u, atol=1e-7) def test_cirq_to_braket(cirq_circuit): """Tests Cirq conversions""" braket_test = transpile(cirq_circuit, "braket", require_native=True) assert circuits_allclose(braket_test, cirq_circuit) def test_cirq_to_qiskit(cirq_circuit): """Tests Cirq conversions""" qiskit_test = transpile(cirq_circuit, "qiskit", require_native=True) assert circuits_allclose(qiskit_test, cirq_circuit) def test_qiskit_to_cirq(qiskit_circuit): """Tests Qiskit conversions""" cirq_test = transpile(qiskit_circuit, "cirq", require_native=True) qprogram_qiskit = load_program(qiskit_circuit) qprogram_cirq = load_program(cirq_test) qprogram_cirq.populate_idle_qubits() qiskit_u = qprogram_qiskit.unitary() cirq_u = qprogram_cirq.unitary() assert_allclose_up_to_global_phase(qiskit_u, cirq_u, atol=1e-7) def test_qiskit_to_braket(qiskit_circuit): """Tests Qiskit conversions""" braket_test = transpile(qiskit_circuit, "braket", require_native=True) qprogram_qiskit = load_program(qiskit_circuit) qprogram_braket = load_program(braket_test) qprogram_braket.populate_idle_qubits() qiskit_u = qprogram_qiskit.unitary() braket_u = qprogram_braket.unitary() assert_allclose_up_to_global_phase(qiskit_u, braket_u, atol=1e-7)