repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
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/esquivelgor/Quantum-Route-Minimizer
esquivelgor
# To clean enviroment variables %reset import numpy as np import pandas as pd import folium import matplotlib.pyplot as plt try: import cplex from cplex.exceptions import CplexError except: print("Warning: Cplex not found.") import math from qiskit.utils import algorithm_globals from qiskit_algorithms import SamplingVQE from qiskit_algorithms.optimizers import SPSA from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Sampler df = pd.read_csv("uscities.csv") columnsNeeded = ["city", "lat", "lng"] # Inicialization of variables locationsNumber = 15 # OJO que en local me crashea si sobrepaso 5 coordenatesDf = df[columnsNeeded].iloc[:locationsNumber] n = coordenatesDf.shape[0] # number of nodes + depot (n+1) K = 3 # number of vehicles print(coordenatesDf) # Initialize instance values by calculate the squared Euclidean distances between a set of coordinates # represented in the dataframe. def generate_instance(coordenatesDf): n = coordenatesDf.shape[0] xc = coordenatesDf["lat"] yc = coordenatesDf["lng"] loc = coordenatesDf["city"] instance = np.zeros([n, n]) for ii in range(0, n): for jj in range(ii + 1, n): instance[ii, jj] = (xc[ii] - xc[jj]) ** 2 + (yc[ii] - yc[jj]) ** 2 instance[jj, ii] = instance[ii, jj] return xc, yc, instance, loc # Initialize the problem by randomly generating the instance lat, lng, instance, loc = generate_instance(coordenatesDf) print(lat, lng, loc, instance) #print(instance) class ClassicalOptimizer: def __init__(self, instance, n, K): self.instance = instance self.n = n # number of nodes self.K = K # number of vehicles def compute_allowed_combinations(self): f = math.factorial return f(self.n) / f(self.K) / f(self.n - self.K) def cplex_solution(self): # refactoring instance = self.instance n = self.n K = self.K my_obj = list(instance.reshape(1, n**2)[0]) + [0.0 for x in range(0, n - 1)] my_ub = [1 for x in range(0, n**2 + n - 1)] my_lb = [0 for x in range(0, n**2)] + [0.1 for x in range(0, n - 1)] my_ctype = "".join(["I" for x in range(0, n**2)]) + "".join( ["C" for x in range(0, n - 1)] ) my_rhs = ( 2 * ([K] + [1 for x in range(0, n - 1)]) + [1 - 0.1 for x in range(0, (n - 1) ** 2 - (n - 1))] + [0 for x in range(0, n)] ) my_sense = ( "".join(["E" for x in range(0, 2 * n)]) + "".join(["L" for x in range(0, (n - 1) ** 2 - (n - 1))]) + "".join(["E" for x in range(0, n)]) ) try: my_prob = cplex.Cplex() self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs) my_prob.solve() except CplexError as exc: print(exc) return x = my_prob.solution.get_values() x = np.array(x) cost = my_prob.solution.get_objective_value() return x, cost def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs): n = self.n prob.objective.set_sense(prob.objective.sense.minimize) prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype) prob.set_log_stream(None) prob.set_error_stream(None) prob.set_warning_stream(None) prob.set_results_stream(None) rows = [] for ii in range(0, n): col = [x for x in range(0 + n * ii, n + n * ii)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [x for x in range(0 + ii, n**2, n)] coef = [1 for x in range(0, n)] rows.append([col, coef]) # Sub-tour elimination constraints: for ii in range(0, n): for jj in range(0, n): if (ii != jj) and (ii * jj > 0): col = [ii + (jj * n), n**2 + ii - 1, n**2 + jj - 1] coef = [1, 1, -1] rows.append([col, coef]) for ii in range(0, n): col = [(ii) * (n + 1)] coef = [1] rows.append([col, coef]) prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs) # Instantiate the classical optimizer class classical_optimizer = ClassicalOptimizer(instance, n, K) # Print number of feasible solutions print("Number of feasible solutions = " + str(classical_optimizer.compute_allowed_combinations())) # Solve the problem in a classical fashion via CPLEX x = None z = None try: x, classical_cost = classical_optimizer.cplex_solution() # Put the solution in the z variable z = [x[ii] for ii in range(n**2) if ii // n != ii % n] # Print the solution print(z) except: print("CPLEX may be missing.") m = folium.Map(location=[39.487660, -97.594333], zoom_start=0) marker_icon1 = folium.Icon(color = "red") for i in range(len(lat)): if (i == 0): folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}", icon=marker_icon1).add_to(m) else: folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}").add_to(m) for ii in range(0, n**2): if x[ii] > 0: ix = ii // n iy = ii % n folium.PolyLine([(lat[ix], lng[ix]), (lat[iy], lng[iy])], color="blue").add_to(m) m from qiskit_optimization import QuadraticProgram from qiskit_optimization.algorithms import MinimumEigenOptimizer from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver class QuantumOptimizer: def __init__(self, instance, n, K): self.instance = instance self.n = n self.K = K def binary_representation(self, x_sol=0): instance = self.instance n = self.n K = self.K A = np.max(instance) * 100 # A parameter of cost function # Determine the weights w instance_vec = instance.reshape(n**2) w_list = [instance_vec[x] for x in range(n**2) if instance_vec[x] > 0] w = np.zeros(n * (n - 1)) for ii in range(len(w_list)): w[ii] = w_list[ii] # Some variables I will use Id_n = np.eye(n) Im_n_1 = np.ones([n - 1, n - 1]) Iv_n_1 = np.ones(n) Iv_n_1[0] = 0 Iv_n = np.ones(n - 1) neg_Iv_n_1 = np.ones(n) - Iv_n_1 v = np.zeros([n, n * (n - 1)]) for ii in range(n): count = ii - 1 for jj in range(n * (n - 1)): if jj // (n - 1) == ii: count = ii if jj // (n - 1) != ii and jj % (n - 1) == count: v[ii][jj] = 1.0 vn = np.sum(v[1:], axis=0) # Q defines the interactions between variables Q = A * (np.kron(Id_n, Im_n_1) + np.dot(v.T, v)) # g defines the contribution from the individual variables g = ( w - 2 * A * (np.kron(Iv_n_1, Iv_n) + vn.T) - 2 * A * K * (np.kron(neg_Iv_n_1, Iv_n) + v[0].T) ) # c is the constant offset c = 2 * A * (n - 1) + 2 * A * (K**2) try: max(x_sol) # Evaluates the cost distance from a binary representation of a path fun = ( lambda x: np.dot(np.around(x), np.dot(Q, np.around(x))) + np.dot(g, np.around(x)) + c ) cost = fun(x_sol) except: cost = 0 return Q, g, c, cost def construct_problem(self, Q, g, c) -> QuadraticProgram: qp = QuadraticProgram() for i in range(n * (n - 1)): qp.binary_var(str(i)) qp.objective.quadratic = Q qp.objective.linear = g qp.objective.constant = c return qp def solve_problem(self, qp): algorithm_globals.random_seed = 10598 #vqe = SamplingVQE(sampler=Sampler(), optimizer=SPSA(), ansatz=RealAmplitudes()) #optimizer = MinimumEigenOptimizer(min_eigen_solver=vqe) meo = MinimumEigenOptimizer(min_eigen_solver=NumPyMinimumEigensolver()) result = meo.solve(qp) # compute cost of the obtained result _, _, _, level = self.binary_representation(x_sol=result.x) return result.x, level # Instantiate the quantum optimizer class with parameters: quantum_optimizer = QuantumOptimizer(instance, n, K) # Check if the binary representation is correct try: if z is not None: Q, g, c, binary_cost = quantum_optimizer.binary_representation(x_sol=z) print("Binary cost:", binary_cost, "classical cost:", classical_cost) if np.abs(binary_cost - classical_cost) < 0.01: print("Binary formulation is correct") else: print("Error in the binary formulation") else: print("Could not verify the correctness, due to CPLEX solution being unavailable.") Q, g, c, binary_cost = quantum_optimizer.binary_representation() print("Binary cost:", binary_cost) except NameError as e: print("Warning: Please run the cells above first.") print(e) qp = quantum_optimizer.construct_problem(Q, g, c) print(qp) #quantum_solution, quantum_cost = quantum_optimizer.solve_problem(qp) quantum_solution, quantum_cost = quantum_optimizer.solve_problem(qp) print(quantum_solution, quantum_cost) print(classical_cost) m = folium.Map(location=[39.487660, -97.594333], zoom_start=0) marker_icon1 = folium.Icon(color = "red") for i in range(len(lat)): if (i == 0): folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}", icon=marker_icon1).add_to(m) else: folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}").add_to(m) for ii in range(0, n**2): if x[ii] > 0: ix = ii // n iy = ii % n folium.PolyLine([(lat[ix], lng[ix]), (lat[iy], lng[iy])], color="blue").add_to(m) m print(quantum_cost) x_quantum = np.zeros(n**2) kk = 0 for ii in range(n**2): if ii // n != ii % n: x_quantum[ii] = quantum_solution[kk] kk += 1 m = folium.Map(location=[39.487660, -97.594333], zoom_start=0) marker_icon1 = folium.Icon(color = "red") for i in range(len(lat)): if (i == 0): folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}", icon=marker_icon1).add_to(m) else: folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}").add_to(m) for ii in range(0, n**2): if x_quantum[ii] > 0: ix = ii // n iy = ii % n folium.PolyLine([(lat[ix], lng[ix]), (lat[iy], lng[iy])], color="blue").add_to(m) m algorithms = ("Classic", "Quantum") data = { 'K = 1': (2249.2068134000006, 1706.2245994000696), 'k = 2': (2771.940853740001, 1845.127222779207), 'K = 3': (3981.1556002800016, 3981.155600280501), } x = np.arange(len(algorithms)) # the label locations width = 0.25 # the width of the bars multiplier = 0 fig, ax = plt.subplots(layout='constrained') for attribute, measurement in data.items(): offset = width * multiplier rects = ax.bar(x + offset, measurement, width, label=attribute) ax.bar_label(rects, padding=3) multiplier += 1 # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Length (mm)') ax.set_title('Comparision of Quantum and Classical Cost') ax.set_xticks(x + width, algorithms) ax.legend(loc='upper left', ncols=3) ax.set_ylim(0, 5000) plt.show()
https://github.com/xtophe388/QISKIT
xtophe388
import qiskit qiskit.__qiskit_version__ #initialization 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 the saved IBMQ accounts IBMQ.load_account() s = "010101" # the hidden bitstring assert 1 < len(s) < 20, "The length of s must be between 2 and 19" for c in s: assert c == "0" or c == "1", "s must be a bitstring of '0' and '1'" n = len(s) #the length of the bitstring # Step 1 # Creating registers # qubits for querying the oracle and recording its output qr = QuantumRegister(2*n) # for recording the measurement on the first register of qr cr = ClassicalRegister(n) circuitName = "Simon" simonCircuit = QuantumCircuit(qr, cr) # Step 2 # Apply Hadamard gates before querying the oracle for i in range(n): simonCircuit.h(qr[i]) # Apply barrier to mark the beginning of the blackbox function simonCircuit.barrier() # Step 3 query the blackbox function # copy the content of the first register to the second register for i in range(n): simonCircuit.cx(qr[i], qr[n+i]) # get the least index j such that s_j is "1" j = -1 for i, c in enumerate(s): if c == "1": j = i break # Creating 1-to-1 or 2-to-1 mapping with the j-th qubit of x as control to XOR the second register with s for i, c in enumerate(s): if c == "1" and j >= 0: simonCircuit.cx(qr[j], qr[n+i]) #the i-th qubit is flipped if s_i is 1 # get random permutation of n qubits perm = list(np.random.permutation(n)) #initial position init = list(range(n)) i = 0 while i < n: if init[i] != perm[i]: k = perm.index(init[i]) simonCircuit.swap(qr[n+i], qr[n+k]) #swap qubits init[i], init[k] = init[k], init[i] #marked swapped qubits else: i += 1 # randomly flip the qubit for i in range(n): if np.random.random() > 0.5: simonCircuit.x(qr[n+i]) # Apply the barrier to mark the end of the blackbox function simonCircuit.barrier() # Step 4 apply Hadamard gates to the first register for i in range(n): simonCircuit.h(qr[i]) # Step 5 perform measurement on the first register for i in range(n): simonCircuit.measure(qr[i], cr[i]) #draw the circuit simonCircuit.draw(output='mpl') # use local simulator backend = BasicAer.get_backend("qasm_simulator") # the number of shots is twice the length of the bitstring shots = 2*n job = execute(simonCircuit, backend=backend, shots=shots) answer = job.result().get_counts() plot_histogram(answer) # Post-processing step # Constructing the system of linear equations Y s = 0 # By k[::-1], we reverse the order of the bitstring lAnswer = [ (k[::-1],v) for k,v in answer.items() if k != "0"*n ] #excluding the trivial all-zero #Sort the basis by their probabilities lAnswer.sort(key = lambda x: x[1], reverse=True) Y = [] for k, v in lAnswer: Y.append( [ int(c) for c in k ] ) #import tools from sympy from sympy import Matrix, pprint, MatrixSymbol, expand, mod_inverse Y = Matrix(Y) #pprint(Y) #Perform Gaussian elimination on Y Y_transformed = Y.rref(iszerofunc=lambda x: x % 2==0) # linear algebra on GF(2) #to convert rational and negatives in rref of linear algebra on GF(2) def mod(x,modulus): numer, denom = x.as_numer_denom() return numer*mod_inverse(denom,modulus) % modulus Y_new = Y_transformed[0].applyfunc(lambda x: mod(x,2)) #must takecare of negatives and fractional values #pprint(Y_new) print("The hidden bistring s[ 0 ], s[ 1 ]....s[",n-1,"] is the one satisfying the following system of linear equations:") rows, cols = Y_new.shape for r in range(rows): Yr = [ "s[ "+str(i)+" ]" for i, v in enumerate(list(Y_new[r,:])) if v == 1 ] if len(Yr) > 0: tStr = " + ".join(Yr) print(tStr, "= 0") #Use one of the available backends backend = IBMQ.get_backend("ibmq_16_melbourne") # show the status of the backend print("Status of", backend, "is", backend.status()) shots = 10*n #run more experiments to be certain max_credits = 3 # Maximum number of credits to spend on executions. simonCompiled = transpile(simonCircuit, backend=backend, optimization_level=1) job_exp = execute(simonCompiled, backend=backend, shots=shots, max_credits=max_credits) job_monitor(job_exp) results = job_exp.result() answer = results.get_counts(simonCircuit) plot_histogram(answer) # Post-processing step # Constructing the system of linear equations Y s = 0 # By k[::-1], we reverse the order of the bitstring lAnswer = [ (k[::-1][:n],v) for k,v in answer.items() ] #excluding the qubits that are not part of the inputs #Sort the basis by their probabilities lAnswer.sort(key = lambda x: x[1], reverse=True) Y = [] for k, v in lAnswer: Y.append( [ int(c) for c in k ] ) Y = Matrix(Y) #Perform Gaussian elimination on Y Y_transformed = Y.rref(iszerofunc=lambda x: x % 2==0) # linear algebra on GF(2) Y_new = Y_transformed[0].applyfunc(lambda x: mod(x,2)) #must takecare of negatives and fractional values #pprint(Y_new) print("The hidden bistring s[ 0 ], s[ 1 ]....s[",n-1,"] is the one satisfying the following system of linear equations:") rows, cols = Y_new.shape for r in range(rows): Yr = [ "s[ "+str(i)+" ]" for i, v in enumerate(list(Y_new[r,:])) if v == 1 ] if len(Yr) > 0: tStr = " + ".join(Yr) print(tStr, "= 0")
https://github.com/qiskit-community/prototype-entanglement-forging
qiskit-community
import warnings warnings.filterwarnings("ignore") from matplotlib import pyplot as plt import numpy as np from qiskit.circuit.library import TwoLocal from qiskit_nature.drivers import Molecule from qiskit_nature.drivers.second_quantization import PySCFDriver from qiskit_nature.problems.second_quantization import ElectronicStructureProblem from qiskit_nature.mappers.second_quantization import JordanWignerMapper from qiskit_nature.converters.second_quantization import QubitConverter import sys sys.path.append("../../") from entanglement_forging import EntanglementForgedGroundStateSolver from entanglement_forging import EntanglementForgedConfig molecule = Molecule( geometry=[("H", [0.0, 0.0, 0.0]), ("H", [0.0, 0.0, 0.735])], charge=0, multiplicity=1, ) driver = PySCFDriver.from_molecule(molecule=molecule) problem = ElectronicStructureProblem(driver) problem.second_q_ops() converter = QubitConverter(JordanWignerMapper()) from qiskit_nature.algorithms.ground_state_solvers import ( GroundStateEigensolver, NumPyMinimumEigensolverFactory, ) solver = GroundStateEigensolver( converter, NumPyMinimumEigensolverFactory(use_default_filter_criterion=False) ) result = solver.solve(problem) print("Classical energy = ", result.total_energies[0]) bitstrings = [[1, 0], [0, 1]] ansatz = TwoLocal(2, [], "cry", [[0, 1], [1, 0]], reps=1) ansatz.draw() from qiskit import Aer backend = Aer.get_backend("statevector_simulator") config = EntanglementForgedConfig( backend=backend, maxiter=200, initial_params=[0, 0.5 * np.pi] ) calc = EntanglementForgedGroundStateSolver( qubit_converter=converter, ansatz=ansatz, bitstrings_u=bitstrings, config=config ) res = calc.solve(problem) res print("Energies (from only one paramset in each iteration):") plt.plot([e[0] for e in res.get_energies_history()]) plt.plot([e[1] for e in res.get_energies_history()[0:-1]]) plt.show() print("Schmidts (from only one paramset in each iteration):") plt.plot([s[0] for s in res.get_schmidts_history()]) plt.show() print("Parameters (from only one paramset in each iteration):") plt.plot([p[0] for p in res.get_parameters_history()]) plt.plot([p[1] for p in res.get_parameters_history()[0:-1]]) plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import sys, getpass try: sys.path.append("../../") # go to parent dir import Qconfig qx_config = { "APItoken": Qconfig.APItoken, "url": Qconfig.config['url']} print('Qconfig loaded from %s.' % Qconfig.__file__) except: APItoken = getpass.getpass('Please input your token and hit enter: ') qx_config = { "APItoken": APItoken, "url":"https://quantumexperience.ng.bluemix.net/api"} print('Qconfig.py not found in qiskit-tutorial directory; Qconfig loaded using user input.') import qiskit as qk import numpy as np from scipy.optimize import curve_fit from qiskit.tools.qcvv.fitters import exp_fit_fun, osc_fit_fun, plot_coherence # function for padding with QId gates def pad_QId(circuit,N,qr): # circuit to add to, N = number of QId gates to add, qr = qubit reg for ii in range(N): circuit.barrier(qr) circuit.iden(qr) return circuit qk.register(qx_config['APItoken'], qx_config['url']) # backend and token settings backend = qk.get_backend('ibmqx4') # the device to run on shots = 1024 # the number of shots in the experiment # Select qubit whose T1 is to be measured qubit=1 # Creating registers qr = qk.QuantumRegister(5) cr = qk.ClassicalRegister(5) # the delay times are all set in terms of single-qubit gates # so we need to calculate the time from these parameters params = backend.parameters['qubits'][qubit] pulse_length=params['gateTime']['value'] # single-qubit gate time buffer_length=params['buffer']['value'] # spacing between pulses unit = params['gateTime']['unit'] steps=10 gates_per_step=120 max_gates=(steps-1)*gates_per_step+1 tot_length=buffer_length+pulse_length time_per_step=gates_per_step*tot_length qc_dict={} for ii in range(steps): step_num='step_%s'%(str(ii)) qc_dict.update({step_num:qk.QuantumCircuit(qr, cr)}) qc_dict[step_num].x(qr[qubit]) qc_dict[step_num]=pad_QId(qc_dict[step_num],gates_per_step*ii,qr[qubit]) qc_dict[step_num].barrier(qr[qubit]) qc_dict[step_num].measure(qr[qubit], cr[qubit]) circuits=list(qc_dict.values()) # run the program status = backend.status if status['operational'] == False or status['pending_jobs'] > 10: print('Warning: the selected backend appears to be busy or unavailable at present; consider choosing a different one if possible') t1_job=qk.execute(circuits, backend, shots=shots) # arrange the data from the run result_t1 = t1_job.result() keys_0_1=list(result_t1.get_counts(qc_dict['step_0']).keys())# get the key of the excited state '00001' data=np.zeros(len(qc_dict.keys())) # numpy array for data sigma_data = np.zeros(len(qc_dict.keys())) # change unit from ns to microseconds plot_factor=1 if unit.find('ns')>-1: plot_factor=1000 punit='$\mu$s' xvals=time_per_step*np.linspace(0,len(qc_dict.keys()),len(qc_dict.keys()))/plot_factor # calculate the time steps in microseconds for ii,key in enumerate(qc_dict.keys()): # get the data in terms of counts for the excited state normalized to the total number of counts data[ii]=float(result_t1.get_counts(qc_dict[key])[keys_0_1[1]])/shots sigma_data[ii] = np.sqrt(data[ii]*(1-data[ii]))/np.sqrt(shots) # fit the data to an exponential fitT1, fcov = curve_fit(exp_fit_fun, xvals, data, bounds=([-1,2,0], [1., 500, 1])) ferr = np.sqrt(np.diag(fcov)) plot_coherence(xvals, data, sigma_data, fitT1, exp_fit_fun, punit, 'T$_1$ ', qubit) print("a: " + str(round(fitT1[0],2)) + u" \u00B1 " + str(round(ferr[0],2))) print("T1: " + str(round(fitT1[1],2))+ " µs" + u" \u00B1 " + str(round(ferr[1],2)) + ' µs') print("c: " + str(round(fitT1[2],2)) + u" \u00B1 " + str(round(ferr[2],2))) str(params['T1']['value']) +' ' + params['T1']['unit'] # Select qubit on which to measure T2* qubit=1 # Creating registers qr = qk.QuantumRegister(5) cr = qk.ClassicalRegister(5) params = backend.parameters['qubits'][qubit] pulse_length=params['gateTime']['value'] # single-qubit gate time buffer_length=params['buffer']['value'] # spacing between pulses unit = params['gateTime']['unit'] steps=35 gates_per_step=20 max_gates=(steps-1)*gates_per_step+2 num_osc=5 tot_length=buffer_length+pulse_length time_per_step=gates_per_step*tot_length qc_dict={} for ii in range(steps): step_num='step_%s'%(str(ii)) qc_dict.update({step_num:qk.QuantumCircuit(qr, cr)}) qc_dict[step_num].h(qr[qubit]) qc_dict[step_num]=pad_QId(qc_dict[step_num],gates_per_step*ii,qr[qubit]) qc_dict[step_num].u1(2*np.pi*num_osc*ii/(steps-1),qr[qubit]) qc_dict[step_num].h(qr[qubit]) qc_dict[step_num].barrier(qr[qubit]) qc_dict[step_num].measure(qr[qubit], cr[qubit]) circuits=list(qc_dict.values()) # run the program status = backend.status if status['operational'] == False or status['pending_jobs'] > 10: print('Warning: the selected backend appears to be busy or unavailable at present; consider choosing a different one if possible') t2star_job=qk.execute(circuits, backend, shots=shots) # arrange the data from the run result_t2star = t2star_job.result() keys_0_1=list(result_t2star.get_counts(qc_dict['step_0']).keys())# get the key of the excited state '00001' # change unit from ns to microseconds plot_factor=1 if unit.find('ns')>-1: plot_factor=1000 punit='$\mu$s' xvals=time_per_step*np.linspace(0,len(qc_dict.keys()),len(qc_dict.keys()))/plot_factor # calculate the time steps data=np.zeros(len(qc_dict.keys())) # numpy array for data sigma_data = np.zeros(len(qc_dict.keys())) for ii,key in enumerate(qc_dict.keys()): # get the data in terms of counts for the excited state normalized to the total number of counts data[ii]=float(result_t2star.get_counts(qc_dict[key])[keys_0_1[1]])/shots sigma_data[ii] = np.sqrt(data[ii]*(1-data[ii]))/np.sqrt(shots) fitT2s, fcov = curve_fit(osc_fit_fun, xvals, data, p0=[0.5, 100, 1/10, np.pi, 0], bounds=([0.3,0,0,0,0], [0.5, 200, 1/2,2*np.pi,1])) ferr = np.sqrt(np.diag(fcov)) plot_coherence(xvals, data, sigma_data, fitT2s, osc_fit_fun, punit, '$T_2^*$ ', qubit) print("a: " + str(round(fitT2s[0],2)) + u" \u00B1 " + str(round(ferr[0],2))) print("T2*: " + str(round(fitT2s[1],2))+ " µs"+ u" \u00B1 " + str(round(ferr[1],2)) + ' µs') print("f: " + str(round(10**3*fitT2s[2],3)) + 'kHz' + u" \u00B1 " + str(round(10**6*ferr[2],3)) + 'kHz') print("phi: " + str(round(fitT2s[3],2)) + u" \u00B1 " + str(round(ferr[3],2))) print("c: " + str(round(fitT2s[4],2)) + u" \u00B1 " + str(round(ferr[4],2))) # Select qubit to measure T2 echo on qubit=1 # Creating registers qr = qk.QuantumRegister(5) cr = qk.ClassicalRegister(5) params = backend.parameters['qubits'][qubit] pulse_length=params['gateTime']['value'] # single-qubit gate time buffer_length=params['buffer']['value'] # spacing between pulses unit = params['gateTime']['unit'] steps=18 gates_per_step=28 tot_length=buffer_length+pulse_length max_gates=(steps-1)*2*gates_per_step+3 time_per_step=(2*gates_per_step)*tot_length qc_dict={} for ii in range(steps): step_num='step_%s'%(str(ii)) qc_dict.update({step_num:qk.QuantumCircuit(qr, cr)}) qc_dict[step_num].h(qr[qubit]) qc_dict[step_num]=pad_QId(qc_dict[step_num],gates_per_step*ii,qr[qubit]) qc_dict[step_num].x(qr[qubit]) qc_dict[step_num]=pad_QId(qc_dict[step_num],gates_per_step*ii,qr[qubit]) qc_dict[step_num].h(qr[qubit]) qc_dict[step_num].barrier(qr[qubit]) qc_dict[step_num].measure(qr[qubit], cr[qubit]) circuits=list(qc_dict.values()) # run the program status = backend.status if status['operational'] == False or status['pending_jobs'] > 10: print('Warning: the selected backend appears to be busy or unavailable at present; consider choosing a different one if possible') t2echo_job=qk.execute(circuits, backend, shots=shots) # arrange the data from the run result_t2echo = t2echo_job.result() keys_0_1=list(result_t2echo.get_counts(qc_dict['step_0']).keys())# get the key of the excited state '00001' # change unit from ns to microseconds plot_factor=1 if unit.find('ns')>-1: plot_factor=1000 punit='$\mu$s' xvals=time_per_step*np.linspace(0,len(qc_dict.keys()),len(qc_dict.keys()))/plot_factor # calculate the time steps data=np.zeros(len(qc_dict.keys())) # numpy array for data sigma_data = np.zeros(len(qc_dict.keys())) for ii,key in enumerate(qc_dict.keys()): # get the data in terms of counts for the excited state normalized to the total number of counts data[ii]=float(result_t2echo.get_counts(qc_dict[key])[keys_0_1[1]])/shots sigma_data[ii] = np.sqrt(data[ii]*(1-data[ii]))/np.sqrt(shots) fitT2e, fcov = curve_fit(exp_fit_fun, xvals, data, bounds=([-1,10,0], [1, 150, 1])) ferr = np.sqrt(np.diag(fcov)) plot_coherence(xvals, data, sigma_data, fitT2e, exp_fit_fun, punit, '$T_{2echo}$ ', qubit) print("a: " + str(round(fitT2e[0],2)) + u" \u00B1 " + str(round(ferr[0],2))) print("T2: " + str(round(fitT2e[1],2))+ ' µs' + u" \u00B1 " + str(round(ferr[1],2)) + ' µs') print("c: " + str(round(fitT2e[2],2)) + u" \u00B1 " + str(round(ferr[2],2))) str(params['T2']['value']) +' ' + params['T2']['unit'] # Select qubit for CPMG measurement of T2 qubit=1 # Creating registers qr = qk.QuantumRegister(5) cr = qk.ClassicalRegister(5) params = backend.parameters['qubits'][qubit] pulse_length=params['gateTime']['value'] # single-qubit gate time buffer_length=params['buffer']['value'] # spacing between pulses unit = params['gateTime']['unit'] steps=10 gates_per_step=18 num_echo=5 # has to be odd number to end up in excited state at the end tot_length=buffer_length+pulse_length time_per_step=((num_echo+1)*gates_per_step+num_echo)*tot_length max_gates=num_echo*(steps-1)*gates_per_step+num_echo+2 qc_dict={} for ii in range(steps): step_num='step_%s'%(str(ii)) qc_dict.update({step_num:qk.QuantumCircuit(qr, cr)}) qc_dict[step_num].h(qr[qubit]) for iii in range(num_echo): qc_dict[step_num]=pad_QId(qc_dict[step_num], gates_per_step*ii, qr[qubit]) qc_dict[step_num].x(qr[qubit]) qc_dict[step_num]=pad_QId(qc_dict[step_num], gates_per_step*ii, qr[qubit]) qc_dict[step_num].h(qr[qubit]) qc_dict[step_num].barrier(qr[qubit]) qc_dict[step_num].measure(qr[qubit], cr[qubit]) circuits=list(qc_dict.values()) # run the program status = backend.status if status['operational'] == False or status['pending_jobs'] > 10: print('Warning: the selected backend appears to be busy or unavailable at present; consider choosing a different one if possible') t2cpmg_job=qk.execute(circuits, backend, shots=shots) # arrange the data from the run result_t2cpmg = t2cpmg_job.result() keys_0_1=list(result_t2cpmg.get_counts(qc_dict['step_0']).keys())# get the key of the excited state '00001' # change unit from ns to microseconds plot_factor=1 if unit.find('ns')>-1: plot_factor=1000 punit='$\mu$s' xvals=time_per_step*np.linspace(0,len(qc_dict.keys()),len(qc_dict.keys()))/plot_factor # calculate the time steps data=np.zeros(len(qc_dict.keys())) # numpy array for data sigma_data = np.zeros(len(qc_dict.keys())) for ii,key in enumerate(qc_dict.keys()): # get the data in terms of counts for the excited state normalized to the total number of counts data[ii]=float(result_t2cpmg.get_counts(qc_dict[key])[keys_0_1[1]])/shots sigma_data[ii] = np.sqrt(data[ii]*(1-data[ii]))/np.sqrt(shots) fitT2cpmg, fcov = curve_fit(exp_fit_fun, xvals, data, bounds=([-1,10,0], [1, 150, 1])) ferr = np.sqrt(np.diag(fcov)) plot_coherence(xvals, data, sigma_data, fitT2cpmg, exp_fit_fun, punit, '$T_{2cpmg}$ ', qubit) print("a: " + str(round(fitT2cpmg[0],2)) + u" \u00B1 " + str(round(ferr[0],2))) print("T2: " + str(round(fitT2cpmg[1],2))+ ' µs' + u" \u00B1 " + str(round(ferr[1],2)) + ' µs') print("c: " + str(round(fitT2cpmg[2],2)) + u" \u00B1 " + str(round(ferr[2],2)))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.mappers.second_quantization import LogarithmicMapper mapper = LogarithmicMapper(2) from qiskit_nature.second_q.mappers import LogarithmicMapper mapper = LogarithmicMapper(2) from qiskit_nature.second_q.mappers import LogarithmicMapper mapper = LogarithmicMapper(padding=2) from qiskit_nature.circuit.library import HartreeFock from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.mappers.second_quantization import JordanWignerMapper converter = QubitConverter(JordanWignerMapper()) init_state = HartreeFock(num_spin_orbitals=6, num_particles=(2, 1), qubit_converter=converter) print(init_state.draw()) from qiskit_nature.second_q.circuit.library import HartreeFock from qiskit_nature.second_q.mappers import JordanWignerMapper, QubitConverter converter = QubitConverter(JordanWignerMapper()) init_state = HartreeFock(num_spatial_orbitals=3, num_particles=(2, 1), qubit_converter=converter) print(init_state.draw()) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
#Once debugged, put this in Jupyter notebook from math import pi import numpy as np import scipy as sp # importing Qiskit from qiskit import Aer from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute from qiskit.tools.visualization import plot_histogram, matplotlib_circuit_drawer from scipy import linalg as las def xx_unitary(qcirc,theta, qa, qi, qj): # This is the circuit to do simulate an X_iX_j exponentiated Pauli operator where i < j qcirc.h(qi) qcirc.h( qj) qcirc.cx(qj, qi) qcirc.crz(2.0 *theta,qa,qi) qcirc.cx(qj, qi) qcirc.h(qi) qcirc.h( qj) def yy_unitary(qcirc,theta, qa, qi, qj): # This is the circuit to do simulate an Y_iY_j exponentiated Pauli operator where i < j qcirc.rx(pi/2.,qi) qcirc.rx(pi / 2., qj) qcirc.cx(qj, qi) qcirc.crz(2.0 * theta,qa,qi) qcirc.cx(qj, qi) qcirc.rx(-pi/2.,qi) qcirc.rx(-pi / 2., qj) def zz_unitary(qcirc,theta, qa, qi, qj): # This is the circuit to do simulate an Z_iZ_j exponentiated Pauli operator where i < j #I had to add a multiple of 2 for the CZ and now the eigenvalues match the unitaries in Miro's code qcirc.cx(qj, qi) qcirc.crz(2.0 * theta,qa,qi) qcirc.cx(qj, qi) def z_unitary(qcirc,theta, qa, qi): qcirc.crz(2.0 * theta, qa, qi) def unitary_specifiedtrotter(qcirc, h0, h1, h2, h3, h4, qa, q0, q1): z_unitary(qcirc, h0, qa, q0) z_unitary(qcirc, h1, qa, q1) xx_unitary(qcirc, h2, qa, q0, q1) yy_unitary(qcirc, h3, qa, q0, q1) # Expectation value of the following term can be computed classically with HF state. zz_unitary(qcirc, h4, qa, q0, q1) # print(qcirc) return 0 # Now begins main() backend = Aer.get_backend('qasm_simulator') # backend = Aer.get_backend('unitary_simulator') # qr = QuantumRegister(2,name='qr') # a = QuantumRegister(1, name='a') # cr = ClassicalRegister(1) # Circuit = QuantumCircuit(qr,cr) # Circuit.add_register(a) # Hamiltonian Values - Interestingly the entangling XX and YY terms are dominant when R is large - why? # R = 1.55 hI = -0.2265 h0 = 0.1843 h1 = -0.0549 h2 = 0.1165 h3 = 0.1165 h4 = 0.4386 #Strangly there is a t_0 being used for U(2^k t_0) = (e^i\theta Ht_0)^(2^k) #remember is trotter expansion dt = t_0 t_0 = 9.830 # Digit of precision bits = 8 # Circuit.h(a[0]) # Circuit.rz(0,a[0]) # This is identity, but will be needed in the circuit to get increased bits of precision # Circuit.x(qr[0]) # Initialize HF state for two qubit system # unitary_specifiedtrotter(Circuit,(2**bits)*h0*t_0, (2**bits)*h1*t_0, (2**bits)*h2*t_0, (2**bits)*h3*t_0,\ # (2**bits)*h4*t_0, a[0], qr[0], qr[1]) # # # Circuit.u1(t_0 * hI * (2 ** bits), qr[0]) # Circuit.h(a[0]) # Circuit.measure(a[0], cr[0]) # # # print('Circuit for least significant bit\n',Circuit) # #Circuit.draw(output='mpl') # # # alg = execute(Circuit, backend) # result = alg.result() # count = result.get_counts(Circuit) # print(count) # x = 1 if count['1'] > count['0'] else 0 # c1 = count['1']/1024 # c2 = count['0']/1024 # print('The distribution of measurements are {} with population percentage {}'.format(x, c1)) if count['1'] > count['0']\ # else print('The distribution of measurements are {} with population percentage {}'.format(x, c1)) # Execute unitary_sim # result = execute(Circuit, backend).result() # unitary = result.get_unitary(Circuit) # print("Circuit unitary:\n", unitary) # eval, evec = las.eigh(unitary) # print(eval[0]) binary_phase = [] x = 0 omega_coef = 0 for k in range(bits,0, -1): it_num = k-1 print('exponent: ', it_num) omega_coef /= 2.0 # omega_coef = 0 # for j in range(1,k-1): # print('j = ',j) # omega_coef += -pi*binary_phase[j-1]/(2**j) print(' {} is phase kickback'.format(omega_coef)) qr = QuantumRegister(2, name='qr') a = QuantumRegister(1, name='a') cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.add_register(a) qc.h(a[0]) qc.u1(-pi*2.*omega_coef,a[0]) qc.x(qr[0]) # Initialize HF state for two qubit system unitary_specifiedtrotter(qc,(2**it_num)*h0*t_0, (2**it_num)*h1*t_0, (2**it_num)*h2*t_0, (2**it_num)*h3*t_0,\ (2**it_num)*h4*t_0, a[0], qr[0], qr[1]) # qc.u1(t_0 * hI * (2 ** bits), a[0]) qc.h(a[0]) qc.measure(a[0], cr[0]) alg = execute(qc, backend) result = alg.result() count = result.get_counts(qc) x = 1 if count['1'] > count['0'] else 0 omega_coef = omega_coef + x / 2 print('phase is {} with a bit {} for k = {}'.format(omega_coef, x, k)) binary_phase.insert(0,x) E = (omega_coef-3*pi)/t_0 print(E+hI) print(binary_phase)
https://github.com/Fergus-Hayes/qiskit_tools
Fergus-Hayes
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ import qiskit_tools as qt import numpy as np import matplotlib.pyplot as plt import matplotlib digit = 2 a = 1 phase = False nint = qt.get_nint([digit,a]) npres = qt.get_npres([digit,a]) n = nint + npres if phase: n+=1 print(n, nint, npres) binary_x = qt.my_binary_repr(digit, n, nint=nint, phase=phase) binary_a = qt.my_binary_repr(a, n, nint=nint, phase=phase) print(binary_x,binary_a) print('It is',digit>=a,'that',str(digit)+' >= '+str(a)+'.') qx = QuantumRegister(n, 'x') qtarg = QuantumRegister(1, 'targ') qans = QuantumRegister(n-1, 'anc') out_reg = ClassicalRegister(1,'out_reg') circ = QuantumCircuit(qx, qtarg, qans, out_reg) x_gate = qt.input_bits_to_qubits(binary_x, circ, reg=qx, wrap=True) circ.append(x_gate, qx); intcomp_gate = qt.integer_compare(circ, qx, qtarg, qans, a, geq=True, wrap=True) circ.append(intcomp_gate, [*qx, *qtarg, *qans]); circ.measure(qtarg, out_reg); circ.draw('latex') circ.decompose(reps=1).draw('latex') shots=10 emulator = Aer.get_backend('qasm_simulator') job = execute(circ, emulator, shots=shots ) hist = job.result().get_counts() print('Target:') print(digit,'>=',a,'=',digit>=a) print('Result:') for label in hist.keys(): print(digit,'>=',a,'=',bool(qt.bin_to_dec(label, nint=nint, phase=False)),'->',label,'with probability',float(hist[label])/shots) digit = 1.5 a = 2.25 phase = False nint = qt.get_nint([digit,a]) npres = qt.get_npres([digit,a]) n = nint + npres if phase: n+=1 print(n, nint, npres) binary_x = qt.my_binary_repr(digit, n, nint=nint, phase=phase) binary_a = qt.my_binary_repr(a, n, nint=nint, phase=phase) int_x = qt.bin_to_dec(binary_x, nint=None, phase=False) int_a = qt.bin_to_dec(binary_a, nint=None, phase=False) print(digit,'->',binary_x,'->',int(int_x),',',a,'->',binary_a,'->',int(int_a)) print('It is',digit>=a,'that',str(digit)+' >= '+str(a)+', and it is',int_x>=int_a,'that',str(int_x)+' >= '+str(int_a)) qx = QuantumRegister(n, 'x') qtarg = QuantumRegister(1, 'targ') qans = QuantumRegister(n-1, 'anc') out_reg = ClassicalRegister(1,'out_reg') circ = QuantumCircuit(qx, qtarg, qans, out_reg) x_gate = qt.input_bits_to_qubits(binary_x, circ, reg=qx, wrap=True) circ.append(x_gate, qx); intcomp_gate = qt.integer_compare(circ, qx, qtarg, qans, int_a, geq=True, wrap=True) circ.append(intcomp_gate, [*qx, *qtarg, *qans]); circ.measure(qtarg, out_reg); shots=10 emulator = Aer.get_backend('qasm_simulator') job = execute(circ, emulator, shots=shots ) hist = job.result().get_counts() print('Target:') print(digit,'>=',a,'=',digit>=a) print('Result:') for label in hist.keys(): print(digit,'>=',a,'=',bool(qt.bin_to_dec(label, nint=nint, phase=False)),'->',label,'with probability',float(hist[label])/shots) digit = -1.5 a = 2.25 phase = True nint = qt.get_nint([digit,a]) npres = qt.get_npres([digit,a]) n = nint + npres if phase: n+=1 print(n, nint, npres) binary_x = qt.my_binary_repr(digit, n, nint=nint, phase=phase) binary_a = qt.my_binary_repr(a, n, nint=nint, phase=phase) binary_a_ = qt.my_binary_repr(a, n, nint=nint, phase=phase) if binary_a[0]=='0': binary_a_ = '1'+binary_a[1:] elif binary_a[0]=='1': binary_a_ = '0'+binary_a[1:] binary_x_ = qt.my_binary_repr(digit, n, nint=nint, phase=phase) if binary_x[0]=='0': binary_x_ = '1'+binary_x[1:] elif binary_x[0]=='1': binary_x_ = '0'+binary_x[1:] int_x = qt.bin_to_dec(binary_x_, nint=None, phase=False) int_a = qt.bin_to_dec(binary_a_, nint=None, phase=False) print(digit,'->',binary_x,'->',binary_x_,'->',int(int_x),',',a,'->',binary_a,'->',binary_a_,'->',int(int_a)) print('It is',digit>=a,'that',str(digit)+' >= '+str(a)+', and it is',int_x>=int_a,'that',str(int_x)+' >= '+str(int_a)) qx = QuantumRegister(n, 'x') qtarg = QuantumRegister(1, 'targ') qans = QuantumRegister(n-1, 'anc') out_reg = ClassicalRegister(1,'out_reg') circ = QuantumCircuit(qx, qtarg, qans, out_reg) x_gate = qt.input_bits_to_qubits(binary_x, circ, reg=qx, wrap=True) circ.append(x_gate, qx); circ.x(qx[-1]); intcomp_gate = qt.integer_compare(circ, qx, qtarg, qans, int_a, geq=True, wrap=True) circ.append(intcomp_gate, [*qx, *qtarg, *qans]); circ.x(qx[-1]); circ.measure(qtarg, out_reg); circ.draw('latex') shots=10 emulator = Aer.get_backend('qasm_simulator') job = execute(circ, emulator, shots=shots ) hist = job.result().get_counts() print('Target:') print(digit,'>=',a,'=',digit>=a) print('Result:') for label in hist.keys(): print(digit,'>=',a,'=',bool(qt.bin_to_dec(label, nint=nint, phase=False)),'->',label,'with probability',float(hist[label])/shots) digit = -1.5 a = 2.25 phase = True nint = qt.get_nint([digit,a]) npres = qt.get_npres([digit,a]) n = nint + npres if phase: n+=1 binary_x = qt.my_binary_repr(digit, n, nint=nint, phase=phase) binary_a = qt.my_binary_repr(a, n, nint=nint, phase=phase) binary_x_ = qt.my_binary_repr(digit, n, nint=nint, phase=phase) if binary_x[0]=='0': binary_x_ = '1'+binary_x[1:] elif binary_x[0]=='1': binary_x_ = '0'+binary_x[1:] binary_a_ = qt.my_binary_repr(a, n, nint=nint, phase=phase) if binary_a[0]=='0': binary_a_ = '1'+binary_a[1:] elif binary_a[0]=='1': binary_a_ = '0'+binary_a[1:] int_x = qt.bin_to_dec(binary_x_, nint=None, phase=False) int_a = qt.bin_to_dec(binary_a_, nint=None, phase=False) qx = QuantumRegister(n, 'x') qtarg = QuantumRegister(1, 'targ') qans = QuantumRegister(n-1, 'anc') out_reg = ClassicalRegister(1,'out_reg') circ = QuantumCircuit(qx, qtarg, qans, out_reg) x_gate = qt.input_bits_to_qubits(binary_x, circ, reg=qx, wrap=True) circ.append(x_gate, qx); circ.x(qx[-1]); intcomp_gate = qt.integer_compare(circ, qx, qtarg, qans, int_a, geq=False, wrap=True) circ.append(intcomp_gate, [*qx, *qtarg, *qans]); circ.x(qx[-1]); circ.measure(qtarg, out_reg); shots=10 emulator = Aer.get_backend('qasm_simulator') job = execute(circ, emulator, shots=shots ) hist = job.result().get_counts() print('Target:') print(digit,'<=',a,'=',digit<=a) print('Result:') for label in hist.keys(): print(digit,'<=',a,'=',bool(qt.bin_to_dec(label, nint=nint, phase=False)),'->',label,'with probability',float(hist[label])/shots) digit = 3.5 a = 2.25 phase = True nint = qt.get_nint([digit,a]) npres = qt.get_npres([digit,a]) n = nint + npres if phase: n+=1 binary_x = qt.my_binary_repr(digit, n, nint=nint, phase=phase) qx = QuantumRegister(n, 'x') qtarg = QuantumRegister(1, 'targ') qans = QuantumRegister(n-1, 'anc') out_reg = ClassicalRegister(1,'out_reg') circ = QuantumCircuit(qx, qtarg, qans, out_reg) x_gate = qt.input_bits_to_qubits(binary_x, circ, reg=qx, wrap=True) circ.append(x_gate, qx); comp_gate = qt.inequal_cond(circ, qx, qtarg, qans, a, nint=nint, phase=phase, geq=False, wrap=True) circ.append(comp_gate, [*qx, *qtarg, *qans]); circ.measure(qtarg, out_reg); shots=10 emulator = Aer.get_backend('qasm_simulator') job = execute(circ, emulator, shots=shots ) hist = job.result().get_counts() print('Target:') print(digit,'<=',a,'=',digit<=a) print('Result:') for label in hist.keys(): print(digit,'<=',a,'=',bool(qt.bin_to_dec(label, nint=nint, phase=False)),'->',label,'with probability',float(hist[label])/shots)
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) ### added x gate ### qc.x(qubit) return qc def decode_message(qc): qc.cx(1, 0) ### added z gate ### qc.z(1) qc.h(1) return qc
https://github.com/1chooo/Quantum-Oracle
1chooo
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit qrx = QuantumRegister(3, 'x') qry = QuantumRegister(1, 'y') cr = ClassicalRegister(3, 'c') qc = QuantumCircuit(qrx, qry, cr) qc.h(qrx) qc.x(qry) # qc.h(qry) 機率會不同 qc.h(qry) qc.barrier() qc.cx(qrx[0], qry) qc.barrier() qc.h(qrx) qc.h(qry) qc.measure(qrx, cr) qc.draw("mpl")
https://github.com/Dirac231/BCHamming
Dirac231
import numpy as np from qiskit import QuantumRegister, ClassicalRegister,QuantumCircuit, transpile, Aer from qiskit import IBMQ, Aer from qiskit.providers.aer import QasmSimulator from qiskit.providers.aer.noise import NoiseModel from Hamming import * import qiskit %matplotlib inline from random import randint # Create a hamming circuit N = 3 enc=HammingEncode(N) dec=HammingDecode(N,read=True) circuit = QuantumCircuit(dec.size,dec.size) # Create a input circuit.h(0) circuit.cx(0,1) circuit.x(1) circuit.cx(0,2) # Add the encoder to the circuit circuit.append(enc, range(enc.size)) # Add errors circuit.y(4) # Add the decoder to the circuit circuit.append(dec,range(dec.size)) # Measure the qubits circuit.measure(list(range(N)),list(range(N))) circuit.draw(output='mpl') # Simulate the circuit simulator = Aer.get_backend("qasm_simulator") result = qiskit.execute(circuit, backend = simulator, shots=1000).result() from qiskit.tools.visualization import plot_histogram plot_histogram(result.get_counts(circuit))
https://github.com/iqm-finland/qiskit-on-iqm
iqm-finland
# Copyright 2022-2023 Qiskit on IQM developers # # 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. """Testing IQM transpilation. """ import numpy as np import pytest from qiskit import QuantumCircuit, transpile from qiskit_aer import AerSimulator from iqm.qiskit_iqm.iqm_transpilation import optimize_single_qubit_gates from tests.utils import get_transpiled_circuit_json def test_optimize_single_qubit_gates_preserves_unitary(): """Test that single-qubit gate decomposition preserves the unitary of the circuit.""" circuit = QuantumCircuit(2, 2) circuit.t(0) circuit.rx(0.4, 0) circuit.cx(0, 1) circuit.ry(0.7, 1) circuit.h(1) circuit.r(0.2, 0.8, 0) circuit.h(0) transpiled_circuit = transpile(circuit, basis_gates=['r', 'cz']) optimized_circuit = optimize_single_qubit_gates(transpiled_circuit, drop_final_rz=False) transpiled_circuit.save_unitary() optimized_circuit.save_unitary() simulator = AerSimulator(method='unitary') transpiled_unitary = simulator.run(transpiled_circuit).result().get_unitary(transpiled_circuit) optimized_unitary = simulator.run(optimized_circuit).result().get_unitary(optimized_circuit) np.testing.assert_almost_equal(transpiled_unitary.data, optimized_unitary.data) def test_optimize_single_qubit_gates_drops_final_rz(): """Test that single-qubit gate decomposition drops the final rz gate if requested and there is no measurement.""" circuit = QuantumCircuit(2, 1) circuit.h(0) circuit.h(1) circuit.cz(0, 1) circuit.h(1) circuit.measure(1, 0) transpiled_circuit = transpile(circuit, basis_gates=['r', 'cz']) optimized_circuit_dropped_rz = optimize_single_qubit_gates(transpiled_circuit) optimized_circuit = optimize_single_qubit_gates(transpiled_circuit, drop_final_rz=False) simulator = AerSimulator(method='statevector') shots = 1000 transpiled_counts = simulator.run(transpiled_circuit, shots=shots).result().get_counts() optimized_counts = simulator.run(optimized_circuit, shots=shots).result().get_counts() optimized_dropped_rz_counts = simulator.run(optimized_circuit_dropped_rz, shots=shots).result().get_counts() for counts in [transpiled_counts, optimized_counts, optimized_dropped_rz_counts]: for key in counts: counts[key] = np.round(counts[key] / shots, 1) assert transpiled_counts == optimized_counts == optimized_dropped_rz_counts assert len(optimized_circuit_dropped_rz.get_instructions('r')) == 3 assert len(optimized_circuit.get_instructions('r')) == 5 def test_optimize_single_qubit_gates_reduces_gate_count(): """Test that single-qubit gate decomposition optimizes the number of single-qubit gates.""" circuit = QuantumCircuit(2, 2) circuit.h(0) circuit.cx(0, 1) circuit.measure_all() transpiled_circuit = transpile(circuit, basis_gates=['r', 'cz']) optimized_circuit = optimize_single_qubit_gates(transpiled_circuit) assert len(optimized_circuit.get_instructions('r')) == 3 def test_optimize_single_qubit_gates_raises_on_invalid_basis(): """Test that optimisation pass raises error if gates other than ``RZ`` and ``CZ`` are provided.""" circuit = QuantumCircuit(1, 1) circuit.h(0) with pytest.raises(ValueError, match="Invalid operation 'h' found "): optimize_single_qubit_gates(circuit) def test_submitted_circuit(adonis_architecture): """Test that a circuit submitted via IQM backend gets transpiled into proper JSON.""" circuit = QuantumCircuit(2, 2) circuit.h(0) circuit.cx(0, 1) circuit.measure_all() # This transpilation seed maps virtual qubit 0 to physical qubit 2, and virtual qubit 1 to physical qubit 4 # Other seeds will switch the mapping, and may also reorder the first phased_rx instructions submitted_circuit = get_transpiled_circuit_json(circuit, adonis_architecture, seed_transpiler=123) instr_names = [f"{instr.name}:{','.join(instr.qubits)}" for instr in submitted_circuit.instructions] assert instr_names == [ # Hadamard on 0 (= physical 0) 'prx:2', 'prx:2', # CX phase 1: Hadamard on target qubit 1 (= physical 4) 'prx:4', 'prx:4', # CX phase 2: CZ on 0,1 (= physical 2,4) 'cz:2,4', # Hadamard again on target qubit 1 (= physical 4) 'prx:4', 'prx:4', # Barrier before measurements 'barrier:2,4', # Measurement on both qubits 'measure:2', 'measure:4', ]
https://github.com/robinsonvs/tcc-information-systems
robinsonvs
import random import pycosat import numpy as np from qiskit import QuantumCircuit, transpile, QuantumRegister from qiskit_aer import AerSimulator from qiskit.visualization import plot_histogram import matplotlib.pyplot as plt import networkx as nx from qiskit import QuantumCircuit as qc from qiskit import QuantumRegister as qr from qiskit.result import Counts from heapq import nlargest from matplotlib.pyplot import show, subplots, xticks, yticks from matplotlib.backend_bases import MouseEvent N: int = 3 # Number of qubits SEARCH_VALUES: set[int] = { 0,1,3 } # Set of m nonnegative integers to search for using Grover's algorithm (i.e. TARGETS in base 10) SHOTS: int = 1024 # Amount of times the algorithm is simulated FONTSIZE: int = 10 # Histogram's font size TARGETS: set[str] = { f"{s:0{N}b}" for s in SEARCH_VALUES } # Set of m N-qubit binary strings representing target state(s) (i.e. SEARCH_VALUES in base 2) QUBITS: qr = qr(N, "qubit") def print_circuit(circuit: qc, name: str = ""): print(f"\n{name}:" if name else "") print(f"{circuit}") def outcome(winners: list[str], counts: Counts): print("WINNER(S):") print(f"Binary = {winners}\nDecimal = {[ int(key, 2) for key in winners ]}\n") print("TARGET(S):") print(f"Binary = {TARGETS}\nDecimal = {SEARCH_VALUES}\n") winners_frequency, total = 0, 0 for value, frequency in counts.items(): if value in winners: winners_frequency += frequency total += frequency print(f"Target(s) found with {winners_frequency / total:.2%} accuracy!") def display_results(results: Counts, combine_other_states: bool = True): # State(s) with highest count and their frequencies winners = { winner : results.get(winner) for winner in nlargest(len(TARGETS), results, key = results.get) } # Print outcome outcome(list(winners.keys()), results) # X-axis and y-axis value(s) for winners, respectively winners_x_axis = [ str(winner) for winner in [*winners] ] winners_y_axis = [ *winners.values() ] # All other states (i.e. non-winners) and their frequencies others = {state : frequency for state, frequency in results.items() if state not in winners} # X-axis and y-axis value(s) for all other states, respectively other_states_x_axis = "Others" if combine_other_states else [*others] other_states_y_axis = [ sum([*others.values()]) ] if combine_other_states else [ *others.values() ] # Create histogram for simulation results figure, axes = subplots(num = "Grover's Algorithm — Results", layout = "constrained") axes.bar(winners_x_axis, winners_y_axis, color = "green", label = "Target") axes.bar(other_states_x_axis, other_states_y_axis, color = "red", label = "Non-target") axes.legend(fontsize = FONTSIZE) axes.grid(axis = "y", ls = "dashed") axes.set_axisbelow(True) # Set histogram title, x-axis title, and y-axis title respectively axes.set_title(f"Outcome of {SHOTS} Simulations", fontsize = int(FONTSIZE * 1.45)) axes.set_xlabel("States (Qubits)", fontsize = int(FONTSIZE * 1.3)) axes.set_ylabel("Frequency", fontsize = int(FONTSIZE * 1.3)) # Set font properties for x-axis and y-axis labels respectively xticks(fontsize = FONTSIZE, family = "monospace", rotation = 0 if combine_other_states else 70) yticks(fontsize = FONTSIZE, family = "monospace") # Set properties for annotations displaying frequency above each bar annotation = axes.annotate("", xy = (0, 0), xytext = (5, 5), xycoords = "data", textcoords = "offset pixels", ha = "center", va = "bottom", family = "monospace", weight = "bold", fontsize = FONTSIZE, bbox = dict(facecolor = "white", alpha = 0.4, edgecolor = "None", pad = 0) ) def hover(event: MouseEvent): visibility = annotation.get_visible() if event.inaxes == axes: for bars in axes.containers: for bar in bars: cont, _ = bar.contains(event) if cont: x, y = bar.get_x() + bar.get_width() / 2, bar.get_y() + bar.get_height() annotation.xy = (x, y) annotation.set_text(y) annotation.set_visible(True) figure.canvas.draw_idle() return if visibility: annotation.set_visible(False) figure.canvas.draw_idle() # Display histogram id = figure.canvas.mpl_connect("motion_notify_event", hover) show() figure.canvas.mpl_disconnect(id) def generate_complete_graph(clique_size): graph = [[1 if i != j else 0 for j in range(clique_size)] for i in range(clique_size)] return remove_random_edges(graph, clique_size) def remove_random_edges(graph, clique_size): num_vertices = len(graph) max_edges = clique_size * (clique_size - 1) // 2 edges_to_remove = random.sample(range(max_edges, num_vertices * (num_vertices - 1) // 2), k=num_vertices * (num_vertices - 1) // 2 - max_edges) for edge in edges_to_remove: row = edge // num_vertices col = edge % num_vertices graph[row][col] = 0 graph[col][row] = 0 return graph def clique_max_sat(graph): num_vertices = len(graph) cnf_clauses = [] # Constraint 1: There is an ith vertex for i in range(num_vertices): clique_clause = [j + 1 for j in range(num_vertices) if j != i] cnf_clauses.append(clique_clause) # Constraint 2: The ith and jth vertices are different for i in range(num_vertices): for j in range(i + 1, num_vertices): if graph[i][j] == 0: cnf_clauses.append([-1 * (i + 1), -1 * (j + 1)]) return cnf_clauses def solve(number_of_vertices, cnf_clauses): solution = pycosat.solve(cnf_clauses) if solution != "UNSAT": return [i for i in range(1, number_of_vertices + 1) if i in solution] return None def amplify(num_of_qubits, num_sub_states): subsets = np.empty(num_sub_states, dtype=object) N = 2 ** num_of_qubits index = 0 sup_index = (N // num_sub_states) if (N % num_sub_states != 0): k = 0 for i in range(1, num_sub_states): sup = [0.] * N num_el = (N // num_sub_states) + 1 for j in range(index, sup_index + 1): sup[j] = np.sqrt((N / num_el) / N) subsets[k] = sup index = index + (N // num_sub_states) + 1 sup_index = sup_index + (N // num_sub_states) + 1 k = k + 1 sup = [0.] * N for j in range(len(sup)): sup[j] = np.sqrt((N / num_el) / N) subsets[num_sub_states - 1] = sup else: k = 0 for i in range(0, num_sub_states): sup = [0.] * N num_el = N / num_sub_states for j in range(index, sup_index): sup[j] = np.sqrt((N / num_el) / N) subsets[k] = sup index = index + (N // num_sub_states) sup_index = sup_index + (N // num_sub_states) k = k + 1 return subsets def oracle_circuit(sat, num_qubits, subsets, targets: set[str] = TARGETS, name: str = "Oracle", display_oracle: bool = True): # oracle = QuantumCircuit(num_qubits + 1, name=name) # for target in targets: # # Reverse target state since Qiskit uses little-endian for qubit ordering # target = target[::-1] # # Flip zero qubits in target # for i in range(num_qubits): # if target[i] == "0": # oracle.x(i) # Pauli-X gate # # Simulate (N - 1)-control Z gate # oracle.h(num_qubits - 1) # Hadamard gate # oracle.mcx(list(range(num_qubits - 1)), num_qubits - 1) # (N - 1)-control Toffoli gate # oracle.h(num_qubits - 1) # Hadamard gate # # Flip back to original state # for i in range(num_qubits): # if target[i] == "0": # oracle.x(i) # if display_oracle: print_circuit(oracle, "ORACLE") # return oracle for clause in sat: oracle = QuantumCircuit(num_qubits+1) for literal in clause: if literal > 0: #oracle.x(literal-1) oracle.h(num_qubits - 1) oracle.mcx(list(range(num_qubits - 1)), num_qubits - 1) for literal in clause: if literal > 0: #oracle.x(literal-1) oracle.h(num_qubits - 1) #oracle.append(oracle.to_gate().control(num_qubits+1), list(range(num_qubits+1))) if display_oracle: print_circuit(oracle, "ORACLE") return oracle #using subsets # qc = QuantumCircuit(num_qubits + 1) # for i, subset in enumerate(subsets): # for j, amplitude in enumerate(subset): # if j < num_qubits: # #qc.ry(2 * amplitude, j) # qc.h(num_qubits - 1) # #qc.mcp(2 * np.pi, list(range(num_qubits)), num_qubits) # qc.mcx(list(range(num_qubits - 1)), num_qubits - 1) # for j, amplitude in enumerate(subset): # if j < num_qubits: # #qc.ry(-2 * amplitude, j) # qc.h(num_qubits - 1) # return qc def diffusion_circuit(num_qubits, name: str = "Diffuser", display_diffuser: bool = True): qc = QuantumCircuit(num_qubits, name = name) for qubit in range(num_qubits): qc.h(qubit) for qubit in range(num_qubits): qc.x(qubit) qc.h(num_qubits - 1) qc.mcp(np.pi, list(range(num_qubits - 1)), num_qubits - 1) qc.h(num_qubits - 1) for qubit in range(num_qubits): qc.x(qubit) for qubit in range(num_qubits): qc.h(qubit) if display_diffuser: print_circuit(qc, "DIFFUSER") return qc def grover_algorithm(oracle, diffusion, num_iterations, name: str = "Grover Circuit", display_grover: bool = True): num_qubits = oracle.num_qubits - 1 qc = QuantumCircuit(num_qubits + 1, num_qubits, name = name) for qubit in range(num_qubits): qc.h(qubit) qc.x(num_qubits) qc.h(num_qubits) for _ in range(num_iterations): qc.append(oracle.to_gate(), range(num_qubits + 1)) qc.append(diffusion.to_gate(), range(num_qubits)) qc.measure(range(num_qubits), range(num_qubits)) if display_grover: print_circuit(qc, "GROVER CIRCUIT") return qc def map_solution(qubit_configurations, clique_size): # Mapeia as configurações dos qubits de volta para as soluções do problema original (clique máximo) solutions = [] for config in qubit_configurations: solution = [i for i, bit in enumerate(config) if bit == '1'] if len(solution) == clique_size: # Apenas considera as soluções que têm o tamanho correto da clique solutions.append(solution) return solutions if __name__ == '__main__': k = N graph = [ [0, 1, 0, 1], [1, 0, 1, 1], [0, 1, 0, 0], [1, 1, 0, 0] ] #print(graph) #graph = generate_complete_graph(k) #print(graph) # Plotar o grafo gerado G = nx.Graph() for i in range(len(graph)): for j in range(i + 1, len(graph)): if graph[i][j] == 1: G.add_edge(i, j) plt.figure(figsize=(6, 6)) nx.draw(G, with_labels=True, font_weight='bold') plt.title('Grafo Gerado') plt.show() cnf_clauses = clique_max_sat(graph) print("Fórmula SAT gerada:") for clause in cnf_clauses: print(clause) max_clique = solve(len(graph), cnf_clauses) print("Clique máximo encontrado pelo solve:", max_clique) if max_clique: print("Maximal-Clique problem found:", [x - 1 for x in max_clique]) else: print("It's not possible to find maximal-clique problem!") num_qubits = N # Número de qubits necessário para representar a fórmula SAT num_sub_states = 2 # Número de subestados para dividir o espaço SAT subsets = amplify(num_qubits, num_sub_states) # Aplicar amplify para otimização da busca oracle = oracle_circuit(cnf_clauses, num_qubits, subsets) diffusion = diffusion_circuit(num_qubits) grover_circuit = grover_algorithm(oracle, diffusion, SHOTS) backend = AerSimulator() new_circuit = transpile(grover_circuit, backend) result = backend.run(new_circuit).result() counts = result.get_counts(grover_circuit) print("Counts:", counts) solutions = map_solution(counts.keys(), len(max_clique)) print("Solutions found:", solutions) plot_histogram(counts) plt.show() display_results(counts, False)
https://github.com/AllenGabrielMarchen/HHL_implementation
AllenGabrielMarchen
#circuit_parts.py from qiskit.circuit.library.arithmetic.exact_reciprocal import ExactReciprocal from qiskit.circuit.library.arithmetic.piecewise_chebyshev import PiecewiseChebyshev from qiskit import QuantumCircuit, QuantumRegister,Aer import numpy as np def qft_dagger(n_l): # <qft를 구현하는 과정에 있어서 SWAP gate에 대한 참고사항> # SWAP 게이트를 걸어주는 목적은 qiskit은 qubit을 반대방향으로 읽기 때문임. # 하지만, SWAP 게이트를 위와 같은 이유로 걸어주게 된다고 하면, # HHL 알고리즘 상에서 Eigeninversion 단계에서 문제가 생기게 됨. # 즉, Eigeninversion에서는 SWAP이 된 상태를 인지하지 못하고 연산을 실시하여 잘못된 연산이 나오게 됨. """n-qubit QFTdagger the first n qubits in circ""" nl_rg = QuantumRegister(n_l, "l") qc = QuantumCircuit(nl_rg) # Don't forget the Swaps! #QFT의 역연산은 곧 QFT_dagger임을 기억하자. for j in reversed(range(n_l)): qc.h(j) for m in reversed(range(j)): qc.cp(-np.pi/float(2**(j-m)), m, j) qc.name = "QFT†" #display(qc.draw(output = 'mpl')) return qc def QPE(n_l,n_b,CU): #circuit initialization for HHL nl_rg = QuantumRegister(n_l, "l") nb_rg = QuantumRegister(n_b, "b") #QuantumRegister(size=None, name=None, bits=None) qc = QuantumCircuit(nl_rg,nb_rg) #display(qc.draw(output = 'mpl')) qc.h(nl_rg) qc.barrier(nl_rg[:]+nb_rg[:]) for l in range(n_l): for power in range(2**(l)): qc.append(CU, [nl_rg[l],nb_rg[0],nb_rg[1]]) #첫번째 큐비트는 2^0번, 이후 2^n꼴로 돌아가게 설계됨. #https://qiskit.org/documentation/stubs/qiskit.circuit.ControlledGate.html append의 예제. #즉, append의 첫번째 인자는 gate, 두번쨰 인자의 첫번째 요소는 control qubit, 이후 인자의 요소는 target qubit. qc.barrier(nl_rg[:]+nb_rg[:]) qc.append(qft_dagger(n_l),nl_rg[:]) qc.barrier(nl_rg[:]+nb_rg[:]) qc.name = "QPE" #display(qc.draw(output = 'mpl')) return qc def QPE_dagger(n_l,n_b,CU): qc = QPE(n_l,n_b,CU) qc = qc.inverse() #여기서 inverse함수는 모든 rotation 각도까지도 반대로 입력해줌을 확인하였음. #QPE dagger는 그저, QPE의 역과정이라고 생각하면 된다. 단, 각도는 반대방향이어야 함. #따라서 여기서 inverse함수를 이용하여 QPE의 역과정, 즉, QPE dagger를 실시하였음 qc.name = 'QPE†' return qc def Eigenvalue_inversion(n_l,delta,chevyshev = False): #Chevyshev 근사를 이용한 풀이방법. #Qiskit에서 제공한 HHL 알고리즘 상에서는 Chevyshev 근사를 이용한 부분이 있었다. #일단 Chevyshev 근사를 이용하는 경우, 기존 Taylor 근사보다 훨씬 빠르게 급수에 수렴한다는 장점이 있다. #참고 문헌 : https://freshrimpsushi.github.io/posts/chebyshev-expansion/ #여기서는 위의 표현한 cos(theta)에 대한 표현을 Chevyshev근사를 이용해 theta값을 알아내겠다는 접근방법이다. #하지만, 근사결과가 좋지 못하다는 점 때문에 Chevyshev 근사를 이용하는 대신에 직접 exact한 theta값을 알아내는 ExactReciprocal을 이용하였다. if chevyshev == True: print("Maybe using Chevyshev approximation is not accurate.") #Using Chebychev Approx. (not recommended!) nl_rg = QuantumRegister(n_l, "l") na_rg = QuantumRegister(n_l, "a") nf_rg = QuantumRegister(1, "f") qc = QuantumCircuit(nl_rg, na_rg, nf_rg) f_x, degree, breakpoints, num_state_qubits = lambda x: np.arcsin(1 / x), 2, [1,2,3,4], n_l #degree : 함수를 polynomial로 근사할 떄, 최고차항 정의 #breakpoints는 구간을 나누는 느낌. : 근사를 할 떄, 다항식을 어떤 구간에서 나눠서 사용할 지 #l : eigenvalue를 표현 #f : rotation #a : ancila pw_approximation = PiecewiseChebyshev(f_x, degree, breakpoints, num_state_qubits) pw_approximation._build() qc.append(pw_approximation,nl_rg[:]+[nf_rg[0]]+na_rg[:]) #range(nl*2+1)) qc.name = 'Chevyshev_inversion' return qc else: qc = ExactReciprocal(n_l, delta, neg_vals = True) qc.name = 'Reciprocal_inversion' return qc
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
import numpy as np from numpy import linalg as LA from scipy.linalg import expm, sinm, cosm import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import math from scipy import stats %matplotlib inline from IPython.display import Image, display, Math, Latex sns.set(color_codes=True) #number of vertices n = 4 #Define adjacency matrix A_Cn A = np.zeros((n, n)) for i in range(n): j1 = (i - 1)%n j2 = (i + 1)%n A[i][j1] = 1 A[i][j2] = 1 #Define our initial state Psi_a psi_a = np.zeros(n) psi_a[3] = 1 #Define the time t >= 0 t = math.pi/2 #Exponentiate or hamiltonian U_t = expm(1j*t*A) U_mt = expm(1j*(-t)*A) #Compute Psi_t psi_t = U_t @ psi_a #Compute the probabilities prob_t = abs(psi_t)**2 M_t = U_t*U_mt M_t = np.around(M_t, decimals = 3) M_t x = M_t[:, 0].real plt.bar(range(len(x)), x, tick_label=[0, 1, 2, 3]) plt.xlabel('Vertices') plt.ylabel('Probability')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import execute, pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.play(pulse.Constant(100, 1.0), d0) pulse_prog.draw()
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Hidden Shift Benchmark Program - QSim """ import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister sys.path[1:1] = [ "_common", "_common/qsim" ] sys.path[1:1] = [ "../../_common", "../../_common/qsim" ] import execute as ex import metrics as metrics from execute import BenchmarkResult # Benchmark Name benchmark_name = "Hidden Shift" np.random.seed(0) verbose = False # saved circuits for display QC_ = None Uf_ = None Ug_ = None ############### Circuit Definition # Uf oracle where Uf|x> = f(x)|x>, f(x) = {-1,1} def Uf_oracle(num_qubits, secret_int): # Initialize qubits qubits qr = QuantumRegister(num_qubits) qc = QuantumCircuit(qr, name=f"Uf") # Perform X on each qubit that matches a bit in secret string s = ('{0:0'+str(num_qubits)+'b}').format(secret_int) for i_qubit in range(num_qubits): if s[num_qubits-1-i_qubit]=='1': qc.x(qr[i_qubit]) for i_qubit in range(0,num_qubits-1,2): qc.cz(qr[i_qubit], qr[i_qubit+1]) # Perform X on each qubit that matches a bit in secret string s = ('{0:0'+str(num_qubits)+'b}').format(secret_int) for i_qubit in range(num_qubits): if s[num_qubits-1-i_qubit]=='1': qc.x(qr[i_qubit]) return qc # Generate Ug oracle where Ug|x> = g(x)|x>, g(x) = f(x+s) def Ug_oracle(num_qubits): # Initialize first n qubits qr = QuantumRegister(num_qubits) qc = QuantumCircuit(qr, name=f"Ug") for i_qubit in range(0,num_qubits-1,2): qc.cz(qr[i_qubit], qr[i_qubit+1]) return qc def HiddenShift (num_qubits, secret_int): # allocate qubits qr = QuantumRegister(num_qubits); cr = ClassicalRegister(num_qubits); qc = QuantumCircuit(qr, cr, name=f"hs-{num_qubits}-{secret_int}") # Start with Hadamard on all input qubits for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) qc.barrier() # Generate Uf oracle where Uf|x> = f(x)|x>, f(x) = {-1,1} Uf = Uf_oracle(num_qubits, secret_int) qc.append(Uf,qr) qc.barrier() # Again do Hadamard on all qubits for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) qc.barrier() # Generate Ug oracle where Ug|x> = g(x)|x>, g(x) = f(x+s) Ug = Ug_oracle(num_qubits) qc.append(Ug,qr) qc.barrier() # End with Hadamard on all qubits for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) qc.barrier() # measure all qubits qc.measure(qr, cr) # save smaller circuit example for display global QC_, Uf_, Ug_ if QC_ == None or num_qubits <= 6: if num_qubits < 9: QC_ = qc if Uf_ == None or num_qubits <= 6: if num_qubits < 9: Uf_ = Uf if Ug_ == None or num_qubits <= 6: if num_qubits < 9: Ug_ = Ug # return a handle on the circuit return qc ############### Circuit end # Analyze and print measured results # Expected result is always the secret_int, so fidelity calc is simple def analyze_and_print_result (qc, result, num_qubits, secret_int, num_shots): if result.backend_name == 'dm_simulator': benchmark_result = BenchmarkResult(result, num_shots) probs = benchmark_result.get_probs(num_shots) # get results as measured probability else: probs = result.get_counts(qc) # get results as measured counts if verbose: print(f"For secret int {secret_int} measured: {probs}") # create the key that is expected to have all the measurements (for this circuit) key = format(secret_int, f"0{num_qubits}b") # correct distribution is measuring the key 100% of the time correct_dist = {key: 1.0} # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(probs, correct_dist) return probs, fidelity ################ Benchmark Loop # Execute program with default parameters def run (min_qubits=2, max_qubits=6, skip_qubits=2, max_circuits=3, num_shots=100, backend_id='dm_simulator', provider_backend=None, # hub="ibm-q", group="open", project="main", exec_options=None, context=None): print(f"{benchmark_name} Benchmark Program - QSim") # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even skip_qubits = max(2, skip_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") # create context identifier if context is None: context = f"{benchmark_name} Benchmark" ########## # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler (qc, result, num_qubits, s_int, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots) metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, #hub=hub, group=group, project=project, exec_options=exec_options, context=context) ########## # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1, 2): # determine number of circuits to execute for this group num_circuits = min(2 ** (num_qubits), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # determine range of secret strings to loop over if 2**(num_qubits) <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(2**(num_qubits), num_circuits, False) # loop over limited # of secret strings for this for s_int in s_range: # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = HiddenShift(num_qubits, s_int).reverse_bits() #reverse_bits() is to change the endianness metrics.store_metric(num_qubits, s_int, 'create_time', time.time()-ts) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, s_int, shots=num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nQuantum Oracle 'Uf' ="); print(Uf_ if Uf_ != None else " ... too large!") print("\nQuantum Oracle 'Ug' ="); print(Ug_ if Ug_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - {benchmark_name} - QSim") # if main, execute method if __name__ == '__main__': ex.local_args() # calling local_args() needed while taking noise parameters through command line arguments (for individual benchmarks) run()
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
# Copyright 2019 Cambridge Quantum Computing # # 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. from qiskit import Aer from qiskit.compiler import assemble from qiskit.providers.aer.noise import NoiseModel from pytket.backends import Backend from pytket.qiskit import tk_to_qiskit from pytket.backends.ibm.ibm import _convert_bin_str from pytket._circuit import Circuit from pytket._transform import Transform from pytket._simulation import pauli_tensor_matrix, operator_matrix import numpy as np class AerBackend(Backend) : def __init__(self, noise_model:NoiseModel=None) : """Backend for running simulations on Qiskit Aer Qasm simulator. :param noise_model: Noise model to use in simulation, defaults to None. :type noise_model: NoiseModel, optional """ self._backend = Aer.get_backend('qasm_simulator') self.noise_model = noise_model def run(self, circuit:Circuit, shots:int, fit_to_constraints=True, seed:int=None) -> np.ndarray: """Run a circuit on Qiskit Aer Qasm simulator. :param circuit: The circuit to run :type circuit: Circuit :param shots: Number of shots (repeats) to run :type shots: int :param fit_to_constraints: Compile the circuit to meet the constraints of the backend, defaults to True :type fit_to_constraints: bool, optional :param seed: random seed to for simulator :type seed: int :return: Table of shot results, each row is a shot, columns are ordered by qubit ordering. Values are 0 or 1, corresponding to qubit basis states. :rtype: numpy.ndarray """ c = circuit.copy() if fit_to_constraints : Transform.RebaseToQiskit().apply(c) qc = tk_to_qiskit(c) qobj = assemble(qc, shots=shots, seed_simulator=seed, memory=True) job = self._backend.run(qobj, noise_model=self.noise_model) shot_list = job.result().get_memory(qc) return np.asarray([_convert_bin_str(shot) for shot in shot_list]) def get_counts(self, circuit, shots, fit_to_constraints=True, seed=None) : """ Run the circuit on the backend and accumulate the results into a summary of counts :param circuit: The circuit to run :param shots: Number of shots (repeats) to run :param fit_to_constraints: Compile the circuit to meet the constraints of the backend, defaults to True :param seed: Random seed to for simulator :return: Dictionary mapping bitvectors of results to number of times that result was observed (zero counts are omitted) """ c = circuit.copy() if fit_to_constraints : Transform.RebaseToQiskit().apply(c) qc = tk_to_qiskit(c) qobj = assemble(qc, shots=shots, seed_simulator=seed) job = self._backend.run(qobj, noise_model=self.noise_model) counts = job.result().get_counts(qc) return {tuple(_convert_bin_str(b)) : c for b, c in counts.items()} class AerStateBackend(Backend) : def __init__(self) : self._backend = Aer.get_backend('statevector_simulator') def get_state(self, circuit, fit_to_constraints=True) : """ Calculate the statevector for a circuit. :param circuit: circuit to calculate :return: complex numpy array of statevector """ c = circuit.copy() if fit_to_constraints : Transform.RebaseToQiskit().apply(c) qc = tk_to_qiskit(c) qobj = assemble(qc) job = self._backend.run(qobj) return np.asarray(job.result().get_statevector(qc, decimals=16)) def run(self, circuit, shots, fit_to_constraints=True) : raise Exception("Aer State Backend cannot currently generate shots. Use `get_state` instead.") def get_pauli_expectation_value(self, state_circuit, pauli, shots=1000) : state = self.get_state(state_circuit) pauli_op = pauli_tensor_matrix(pauli, state_circuit.n_qubits) return np.vdot(state, pauli_op.dot(state)) def get_operator_expectation_value(self, state_circuit, operator, shots=1000) : """ Calculates expectation value for an OpenFermion QubitOperator by summing over pauli expectations Note: This method is significantly faster using the ProjectQBackend than the AerStateBackend. """ state = self.get_state(state_circuit) n_qubits = state_circuit.n_qubits op_as_lists = [(list(p),c) for p,c in operator.terms.items()] op = operator_matrix(op_as_lists, n_qubits) return np.vdot(state, op.dot(state)) class AerUnitaryBackend(Backend) : def __init__(self) : self._backend = Aer.get_backend('unitary_simulator') def run(self, circuit, shots, fit_to_constraints=True) : raise Exception("Aer Unitary Backend cannot currently generate shots. Use `get_unitary` instead.") def get_unitary(self, circuit, fit_to_constraints=True) : """ Obtains the unitary for a given quantum circuit :param circuit: The circuit to inspect :type circuit: Circuit :param fit_to_constraints: Forces the circuit to be decomposed into the correct gate set, defaults to True :type fit_to_constraints: bool, optional :return: The unitary of the circuit. Qubits are ordered with qubit 0 as the least significant qubit """ c = circuit.copy() if fit_to_constraints : Transform.RebaseToQiskit().apply(c) qc = tk_to_qiskit(c) qobj = assemble(qc) job = self._backend.run(qobj) return job.result().get_unitary(qc)
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
import numpy as np from qiskit import pulse d0 = pulse.DriveChannel(0) x90 = pulse.Gaussian(10, 0.1, 3) x180 = pulse.Gaussian(10, 0.2, 3) def udd10_pos(j): return np.sin(np.pi*j/(2*10 + 2))**2 with pulse.build() as udd_sched: pulse.play(x90, d0) with pulse.align_func(duration=300, func=udd10_pos): for _ in range(10): pulse.play(x180, d0) pulse.play(x90, d0) udd_sched.draw()
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ QasmSimulator readout error NoiseModel integration tests """ from test.terra.utils.utils import list2dict from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Instruction from qiskit.providers.aer.noise import NoiseModel # ========================================================================== # Readout error # ========================================================================== # Error matrices used in tests ROERROR_1Q = [[0.9, 0.1], [0.3, 0.7]] ROERROR_2Q = [[0.3, 0, 0, 0.7], [0, 0.6, 0.4, 0], [0, 0, 1, 0], [0.1, 0, 0, 0.9]] def readout_error_circuits(): """Readout error test circuits""" circuits = [] # Test circuit: ideal bell state for 1-qubit readout errors qr = QuantumRegister(2, 'qr') cr = ClassicalRegister(2, 'cr') circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) # Ensure qubit 0 is measured before qubit 1 circuit.barrier(qr) circuit.measure(qr[0], cr[0]) circuit.barrier(qr) circuit.measure(qr[1], cr[1]) # Add three copies of circuit circuits += 3 * [circuit] # 2-qubit correlated readout error circuit measure2 = Instruction("measure", 2, 2, []) # 2-qubit measure qr = QuantumRegister(2, 'qr') cr = ClassicalRegister(2, 'cr') circuit = QuantumCircuit(qr, cr) circuit.h(qr) circuit.barrier(qr) circuit.append(measure2, [0, 1], [0, 1]) circuits.append(circuit) return circuits def readout_error_noise_models(): """Readout error test circuit noise models.""" noise_models = [] # 1-qubit readout error on qubit 0 noise_model = NoiseModel() noise_model.add_readout_error(ROERROR_1Q, [0]) noise_models.append(noise_model) # 1-qubit readout error on qubit 1 noise_model = NoiseModel() noise_model.add_readout_error(ROERROR_1Q, [1]) noise_models.append(noise_model) # 1-qubit readout error on qubit 1 noise_model = NoiseModel() noise_model.add_all_qubit_readout_error(ROERROR_1Q) noise_models.append(noise_model) # 2-qubit readout error on qubits 0,1 noise_model = NoiseModel() noise_model.add_readout_error(ROERROR_2Q, [0, 1]) noise_models.append(noise_model) return noise_models def readout_error_counts(shots, hex_counts=True): """Readout error test circuits reference counts.""" counts_lists = [] # 1-qubit readout error on qubit 0 counts = [ ROERROR_1Q[0][0] * shots / 2, ROERROR_1Q[0][1] * shots / 2, ROERROR_1Q[1][0] * shots / 2, ROERROR_1Q[1][1] * shots / 2 ] counts_lists.append(counts) # 1-qubit readout error on qubit 1 counts = [ ROERROR_1Q[0][0] * shots / 2, ROERROR_1Q[1][0] * shots / 2, ROERROR_1Q[0][1] * shots / 2, ROERROR_1Q[1][1] * shots / 2 ] counts_lists.append(counts) # 1-qubit readout error on qubit 1 p00 = 0.5 * (ROERROR_1Q[0][0]**2 + ROERROR_1Q[1][0]**2) p01 = 0.5 * ( ROERROR_1Q[0][0] * ROERROR_1Q[0][1] + ROERROR_1Q[1][0] * ROERROR_1Q[1][1]) p10 = 0.5 * ( ROERROR_1Q[0][0] * ROERROR_1Q[0][1] + ROERROR_1Q[1][0] * ROERROR_1Q[1][1]) p11 = 0.5 * (ROERROR_1Q[0][1]**2 + ROERROR_1Q[1][1]**2) counts = [p00 * shots, p01 * shots, p10 * shots, p11 * shots] counts_lists.append(counts) # 2-qubit readout error on qubits 0,1 probs_ideal = [0.25, 0.25, 0.25, 0.25] p00 = sum([ ideal * noise[0] for ideal, noise in zip(probs_ideal, ROERROR_2Q) ]) p01 = sum([ ideal * noise[1] for ideal, noise in zip(probs_ideal, ROERROR_2Q) ]) p10 = sum([ ideal * noise[2] for ideal, noise in zip(probs_ideal, ROERROR_2Q) ]) p11 = sum([ ideal * noise[3] for ideal, noise in zip(probs_ideal, ROERROR_2Q) ]) counts = [p00 * shots, p01 * shots, p10 * shots, p11 * shots] counts_lists.append(counts) return [list2dict(i, hex_counts) for i in counts_lists]
https://github.com/qiskit-community/qiskit-device-benchmarking
qiskit-community
import pandas as pd import numpy as np import scipy.stats as stats import matplotlib.pyplot as plt import rustworkx as rx from qiskit_ibm_runtime import QiskitRuntimeService import qiskit_device_benchmarking #preferred that the qiskit_device_benchmark package is installed as 'pip install .' but if not #uncomment the following #import sys #sys.path.append('../') #import paths_flatten,remove_permutations,path_to_edges,build_sys_graph,get_separated_sets import qiskit_device_benchmarking.utilities.graph_utils as gu #for testing from qiskit_aer import AerSimulator #import the qiskit experiment modules #uses Tphi experiment from qiskit_experiments.library import Tphi from qiskit_experiments.framework import ParallelExperiment, BatchExperiment #import the custom bell experiment from qiskit_device_benchmarking.bench_code.bell.bell_experiment import BellExperiment #enter your device hub/group/project here #and device hgp = 'ibm-q/open/main' service = QiskitRuntimeService() backend_real=service.backend('ibm_kyiv',instance=hgp) nq = backend_real.configuration().n_qubits coupling_map = backend_real.configuration().coupling_map #if you want to use the simulator #uncomment if (0): backend_sim = AerSimulator.from_backend(backend) backend = backend_sim else: backend = backend_real #build a set of gates G = gu.build_sys_graph(nq, coupling_map) #get all length 2 paths in the device paths = rx.all_pairs_all_simple_paths(G,2,2) #flatten those paths into a list from the rustwork x iterator paths = gu.paths_flatten(paths) #remove permutations paths = gu.remove_permutations(paths) #convert to the coupling map of the device paths = gu.path_to_edges(paths,coupling_map) #make into separate sets sep_sets = gu.get_separated_sets(G, paths, min_sep=2) qubits_nns = gu.get_iso_qubit_list(G) # Time intervals to wait before measurement for t1 and t2 delays_t1 = [0] + np.arange(1e-6, 100e-6, 10e-6).tolist() + np.arange(130e-6, 300e-6, 40e-6).tolist() delays_t2 = [0] + np.arange(1e-6, 100e-6, 10e-6).tolist() + np.arange(130e-6, 300e-6, 40e-6).tolist() num_periods = 5 max_T = delays_t2[-1] osc_freq = num_periods/(max_T) #Construct the experiments #First the Tphi exp_batches = [] for qubits in qubits_nns: coh_exps = ParallelExperiment([ Tphi((int(qubit),), delays_t1=delays_t1,delays_t2=delays_t2,t2type='hahn',osc_freq=osc_freq,backend=backend) for qubit in np.array(qubits).flatten()], flatten_results=False) exp_batches.append(coh_exps) #Bell bell_exp = BellExperiment(sep_sets,backend=backend) exp_batches.append(bell_exp) #Batch all together batch_exp = BatchExperiment(exp_batches,backend=backend,flatten_results=False) %%time #Run batch_exp.set_run_options(shots=300) batch_exp_data = batch_exp.run() batch_exp_data.status() plot_q = 0 #0 for the T1, 1 for the T2 plot_type = 0 plot_ind = [] for i in range(len(qubits_nns)): for j in range(len(qubits_nns[i])): if plot_q==qubits_nns[i][j]: plot_ind = [i,j] break print('Plotting Q%d'%plot_q) batch_exp_data.child_data()[i].child_data()[j].figure(plot_type) #generate a T1/T2 list q_list = [] t1_list = [] t2_list = [] for i in range(len(qubits_nns)): data1 = batch_exp_data.child_data()[i] for j in range(len(qubits_nns[i])): q_list.append(qubits_nns[i][j]) t1_list.append(data1.child_data()[j].analysis_results()[2].value.nominal_value) t2_list.append(data1.child_data()[j].analysis_results()[4].value.nominal_value) #plot the data ordered by Bell state fidelity (need to run the cell above first) plt.figure(dpi=150,figsize=[15,5]) argind = np.argsort(t1_list) plt.semilogy(range(len(q_list)),np.array(t1_list)[argind]/1e-6,label='T1', marker='.',color='blue') plt.semilogy(range(len(q_list)),np.array(t2_list)[argind]/1e-6,label='T2', marker='x',color='lightskyblue') plt.xticks(range(len(q_list)),np.array(q_list)[argind],rotation=90,fontsize=6); plt.ylabel('Time (us)') plt.ylim([10,1000]) plt.grid(True) plt.legend() plt.title('Device Coherence for %s, job %s'%(backend_real.name, batch_exp_data.job_ids[0])) #Quantile plot plt.figure(dpi=100) x1 = stats.probplot(t1_list) x2 = stats.probplot(t2_list) plt.semilogy(x1[0][0],x1[0][1]/1e-6,linestyle='None',marker='.',markersize=10,label='T1',color='blue') plt.semilogy(x2[0][0],x2[0][1]/1e-6,linestyle='None',marker='.',markersize=10,label='T2',color='lightskyblue') plt.grid(True,which='both') plt.legend(fontsize=16) plt.xlabel('Normal Quantile',fontsize=16) plt.ylabel('Coherence (us)',fontsize=16) plt.ylim([10,700]) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.title('Device Coherence for %s, job %s'%(backend_real.name, batch_exp_data.job_ids[0])) #Pull the data from the dataframe df = batch_exp_data.child_data()[2].analysis_results()[0].value bell_edge_list = [] bell_fid_list = [] for i in df.iterrows(): bell_edge_list.append(i[1]['connection']) bell_fid_list.append(i[1]['fidelity']) #plot the data ordered by Bell state fidelity (need to run the cell above first) plt.figure(dpi=150,figsize=[15,5]) argind = np.argsort(1-np.array(bell_fid_list)) plt.semilogy(range(len(bell_edge_list)),1-np.array(bell_fid_list)[argind],label='T1', color='blue', marker='.') plt.xticks(range(len(bell_edge_list)),np.array(bell_edge_list)[argind],rotation=90,fontsize=6); plt.ylabel('Bell Hellinger Error (1-Fid.)') plt.ylim([1e-3,1]) plt.grid(True) plt.legend() plt.title('Bell Edges for %s, job %s'%(backend_real.name, batch_exp_data.job_ids[0])) from IPython.display import HTML, display import datetime def qiskit_copyright(line="", cell=None): """IBM copyright""" now = datetime.datetime.now() html = "<div style='width: 100%; background-color:#d5d9e0;" html += "padding-left: 10px; padding-bottom: 10px; padding-right: 10px; padding-top: 5px'>" html += "<p>&copy; Copyright IBM 2017, %s.</p>" % now.year html += "<p>This code is licensed under the Apache License, Version 2.0. You may<br>" html += "obtain a copy of this license in the LICENSE.txt file in the root directory<br> " html += "of this source tree or at http://www.apache.org/licenses/LICENSE-2.0." html += "<p>Any modifications or derivative works of this code must retain this<br>" html += "copyright notice, and modified files need to carry a notice indicating<br>" html += "that they have been altered from the originals.</p>" html += "</div>" return display(HTML(html)) qiskit_copyright()
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) # with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) # with open(filename, "wb") as f: # pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) # with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump(backend.properties(), f) 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/matteoacrossi/oqs-jupyterbook
matteoacrossi
from IPython.display import IFrame IFrame(src='./gen_plots/channel_cap.html', width=450, height=500) from IPython.display import IFrame IFrame(src='./gen_plots/nonmark_witness.html', width=700, height=350) ####################################### # Amplitude damping channel # # with non-M. witness on IBMQ_VIGO # ####################################### from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit # Quantum and classical register q = QuantumRegister(5, name='q') c = ClassicalRegister(2, name='c') # Quantum circuit ad = QuantumCircuit(q, c) # Amplitude damping channel acting on system qubit # with non-Markovianity witness ## Qubit identification system = 1 environment = 2 ancilla = 3 # Define rotation angle theta = 0.0 # Construct circuit ## Bell state between system and ancilla ad.h(q[system]) ad.cx(q[system], q[ancilla]) ## Channel acting on system qubit ad.cu3(theta, 0.0, 0.0, q[system], q[environment]) ad.cx(q[environment], q[system]) ## Local measurement for the witness ### Choose observable observable = 'YY' ### Change to the corresponding basis if observable == 'XX': ad.h(q[system]) ad.h(q[ancilla]) elif observable == 'YY': ad.sdg(q[system]) ad.h(q[system]) ad.sdg(q[ancilla]) ad.h(q[ancilla]) ### Measure ad.measure(q[system], c[0]) ad.measure(q[ancilla], c[1]) # Draw circuit ad.draw(output='mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.problems import ElectronicBasis driver = PySCFDriver() driver.run_pyscf() ao_problem = driver.to_problem(basis=ElectronicBasis.AO) print(ao_problem.basis) ao_hamil = ao_problem.hamiltonian print(ao_hamil.electronic_integrals.alpha) from qiskit_nature.second_q.formats.qcschema_translator import get_ao_to_mo_from_qcschema qcschema = driver.to_qcschema() basis_transformer = get_ao_to_mo_from_qcschema(qcschema) print(basis_transformer.initial_basis) print(basis_transformer.final_basis) mo_problem = basis_transformer.transform(ao_problem) print(mo_problem.basis) mo_hamil = mo_problem.hamiltonian print(mo_hamil.electronic_integrals.alpha) import numpy as np from qiskit_nature.second_q.operators import ElectronicIntegrals from qiskit_nature.second_q.problems import ElectronicBasis from qiskit_nature.second_q.transformers import BasisTransformer ao2mo_alpha = np.random.random((2, 2)) ao2mo_beta = np.random.random((2, 2)) basis_transformer = BasisTransformer( ElectronicBasis.AO, ElectronicBasis.MO, ElectronicIntegrals.from_raw_integrals(ao2mo_alpha, h1_b=ao2mo_beta), ) from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver(atom="Li 0 0 0; H 0 0 1.5") full_problem = driver.run() print(full_problem.molecule) print(full_problem.num_particles) print(full_problem.num_spatial_orbitals) from qiskit_nature.second_q.transformers import FreezeCoreTransformer fc_transformer = FreezeCoreTransformer() fc_problem = fc_transformer.transform(full_problem) print(fc_problem.num_particles) print(fc_problem.num_spatial_orbitals) print(fc_problem.hamiltonian.constants) fc_transformer = FreezeCoreTransformer(remove_orbitals=[4, 5]) fc_problem = fc_transformer.transform(full_problem) print(fc_problem.num_particles) print(fc_problem.num_spatial_orbitals) from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver(atom="Li 0 0 0; H 0 0 1.5") full_problem = driver.run() print(full_problem.num_particles) print(full_problem.num_spatial_orbitals) from qiskit_nature.second_q.transformers import ActiveSpaceTransformer as_transformer = ActiveSpaceTransformer(2, 2) as_problem = as_transformer.transform(full_problem) print(as_problem.num_particles) print(as_problem.num_spatial_orbitals) print(as_problem.hamiltonian.electronic_integrals.alpha) as_transformer = ActiveSpaceTransformer(2, 2, active_orbitals=[0, 4]) as_problem = as_transformer.transform(full_problem) print(as_problem.num_particles) print(as_problem.num_spatial_orbitals) print(as_problem.hamiltonian.electronic_integrals.alpha) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# Necessary imports import numpy as np import matplotlib.pyplot as plt from torch import Tensor from torch.nn import Linear, CrossEntropyLoss, MSELoss from torch.optim import LBFGS from qiskit import QuantumCircuit from qiskit.utils import algorithm_globals from qiskit.circuit import Parameter from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap from qiskit_machine_learning.neural_networks import SamplerQNN, EstimatorQNN from qiskit_machine_learning.connectors import TorchConnector # Set seed for random generators algorithm_globals.random_seed = 42 # Generate random dataset # Select dataset dimension (num_inputs) and size (num_samples) num_inputs = 2 num_samples = 20 # Generate random input coordinates (X) and binary labels (y) X = 2 * algorithm_globals.random.random([num_samples, num_inputs]) - 1 y01 = 1 * (np.sum(X, axis=1) >= 0) # in { 0, 1}, y01 will be used for SamplerQNN example y = 2 * y01 - 1 # in {-1, +1}, y will be used for EstimatorQNN example # Convert to torch Tensors X_ = Tensor(X) y01_ = Tensor(y01).reshape(len(y)).long() y_ = Tensor(y).reshape(len(y), 1) # Plot dataset 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() # Set up a circuit feature_map = ZZFeatureMap(num_inputs) ansatz = RealAmplitudes(num_inputs) qc = QuantumCircuit(num_inputs) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) qc.draw("mpl") # Setup QNN qnn1 = EstimatorQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters ) # Set up PyTorch module # Note: If we don't explicitly declare the initial weights # they are chosen uniformly at random from [-1, 1]. initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn1.num_weights) - 1) model1 = TorchConnector(qnn1, initial_weights=initial_weights) print("Initial weights: ", initial_weights) # Test with a single input model1(X_[0, :]) # Define optimizer and loss optimizer = LBFGS(model1.parameters()) f_loss = MSELoss(reduction="sum") # Start training model1.train() # set model to training mode # Note from (https://pytorch.org/docs/stable/optim.html): # Some optimization algorithms such as LBFGS need to # reevaluate the function multiple times, so you have to # pass in a closure that allows them to recompute your model. # The closure should clear the gradients, compute the loss, # and return it. def closure(): optimizer.zero_grad() # Initialize/clear gradients loss = f_loss(model1(X_), y_) # Evaluate loss function loss.backward() # Backward pass print(loss.item()) # Print loss return loss # Run optimizer step4 optimizer.step(closure) # Evaluate model and compute accuracy y_predict = [] for x, y_target in zip(X, y): output = model1(Tensor(x)) y_predict += [np.sign(output.detach().numpy())[0]] print("Accuracy:", sum(y_predict == y) / len(y)) # 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() # Define feature map and ansatz feature_map = ZZFeatureMap(num_inputs) ansatz = RealAmplitudes(num_inputs, entanglement="linear", reps=1) # Define quantum circuit of num_qubits = input dim # Append feature map and ansatz qc = QuantumCircuit(num_inputs) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) # Define SamplerQNN and initial setup parity = lambda x: "{:b}".format(x).count("1") % 2 # optional interpret function output_shape = 2 # parity = 0, 1 qnn2 = SamplerQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, interpret=parity, output_shape=output_shape, ) # Set up PyTorch module # Reminder: If we don't explicitly declare the initial weights # they are chosen uniformly at random from [-1, 1]. initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn2.num_weights) - 1) print("Initial weights: ", initial_weights) model2 = TorchConnector(qnn2, initial_weights) # Define model, optimizer, and loss optimizer = LBFGS(model2.parameters()) f_loss = CrossEntropyLoss() # Our output will be in the [0,1] range # Start training model2.train() # Define LBFGS closure method (explained in previous section) def closure(): optimizer.zero_grad(set_to_none=True) # Initialize gradient loss = f_loss(model2(X_), y01_) # Calculate loss loss.backward() # Backward pass print(loss.item()) # Print loss return loss # Run optimizer (LBFGS requires closure) optimizer.step(closure); # Evaluate model and compute accuracy y_predict = [] for x in X: output = model2(Tensor(x)) y_predict += [np.argmax(output.detach().numpy())] print("Accuracy:", sum(y_predict == y01) / len(y01)) # plot results # red == wrongly classified for x, y_target, y_ 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_: plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2) plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() # Generate random dataset num_samples = 20 eps = 0.2 lb, ub = -np.pi, np.pi f = lambda x: np.sin(x) X = (ub - lb) * algorithm_globals.random.random([num_samples, 1]) + lb y = f(X) + eps * (2 * algorithm_globals.random.random([num_samples, 1]) - 1) plt.plot(np.linspace(lb, ub), f(np.linspace(lb, ub)), "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 feature map param_y = Parameter("y") ansatz = QuantumCircuit(1, name="vf") ansatz.ry(param_y, 0) qc = QuantumCircuit(1) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) # Construct QNN qnn3 = EstimatorQNN(circuit=qc, input_params=[param_x], weight_params=[param_y]) # Set up PyTorch module # Reminder: If we don't explicitly declare the initial weights # they are chosen uniformly at random from [-1, 1]. initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn3.num_weights) - 1) model3 = TorchConnector(qnn3, initial_weights) # Define optimizer and loss function optimizer = LBFGS(model3.parameters()) f_loss = MSELoss(reduction="sum") # Start training model3.train() # set model to training mode # Define objective function def closure(): optimizer.zero_grad(set_to_none=True) # Initialize gradient loss = f_loss(model3(Tensor(X)), Tensor(y)) # Compute batch loss loss.backward() # Backward pass print(loss.item()) # Print loss return loss # Run optimizer optimizer.step(closure) # Plot target function plt.plot(np.linspace(lb, ub), f(np.linspace(lb, ub)), "r--") # Plot data plt.plot(X, y, "bo") # Plot fitted line y_ = [] for x in np.linspace(lb, ub): output = model3(Tensor([x])) y_ += [output.detach().numpy()[0]] plt.plot(np.linspace(lb, ub), y_, "g-") plt.show() # Additional torch-related imports import torch from torch import cat, no_grad, manual_seed from torch.utils.data import DataLoader from torchvision import datasets, transforms import torch.optim as optim from torch.nn import ( Module, Conv2d, Linear, Dropout2d, NLLLoss, MaxPool2d, Flatten, Sequential, ReLU, ) import torch.nn.functional as F # Train Dataset # ------------- # Set train shuffle seed (for reproducibility) manual_seed(42) batch_size = 1 n_samples = 100 # We will concentrate on the first 100 samples # Use pre-defined torchvision function to load MNIST train data X_train = datasets.MNIST( root="./data", train=True, download=True, transform=transforms.Compose([transforms.ToTensor()]) ) # Filter out labels (originally 0-9), leaving only labels 0 and 1 idx = np.append( np.where(X_train.targets == 0)[0][:n_samples], np.where(X_train.targets == 1)[0][:n_samples] ) X_train.data = X_train.data[idx] X_train.targets = X_train.targets[idx] # Define torch dataloader with filtered data train_loader = DataLoader(X_train, batch_size=batch_size, shuffle=True) n_samples_show = 6 data_iter = iter(train_loader) fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) while n_samples_show > 0: images, targets = data_iter.__next__() axes[n_samples_show - 1].imshow(images[0, 0].numpy().squeeze(), cmap="gray") axes[n_samples_show - 1].set_xticks([]) axes[n_samples_show - 1].set_yticks([]) axes[n_samples_show - 1].set_title("Labeled: {}".format(targets[0].item())) n_samples_show -= 1 # Test Dataset # ------------- # Set test shuffle seed (for reproducibility) # manual_seed(5) n_samples = 50 # Use pre-defined torchvision function to load MNIST test data X_test = datasets.MNIST( root="./data", train=False, download=True, transform=transforms.Compose([transforms.ToTensor()]) ) # Filter out labels (originally 0-9), leaving only labels 0 and 1 idx = np.append( np.where(X_test.targets == 0)[0][:n_samples], np.where(X_test.targets == 1)[0][:n_samples] ) X_test.data = X_test.data[idx] X_test.targets = X_test.targets[idx] # Define torch dataloader with filtered data test_loader = DataLoader(X_test, batch_size=batch_size, shuffle=True) # Define and create QNN def create_qnn(): feature_map = ZZFeatureMap(2) ansatz = RealAmplitudes(2, reps=1) qc = QuantumCircuit(2) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) # REMEMBER TO SET input_gradients=True FOR ENABLING HYBRID GRADIENT BACKPROP qnn = EstimatorQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, input_gradients=True, ) return qnn qnn4 = create_qnn() # Define torch NN module class Net(Module): def __init__(self, qnn): super().__init__() self.conv1 = Conv2d(1, 2, kernel_size=5) self.conv2 = Conv2d(2, 16, kernel_size=5) self.dropout = Dropout2d() self.fc1 = Linear(256, 64) self.fc2 = Linear(64, 2) # 2-dimensional input to QNN self.qnn = TorchConnector(qnn) # Apply torch connector, weights chosen # uniformly at random from interval [-1,1]. self.fc3 = Linear(1, 1) # 1-dimensional output from QNN def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) x = x.view(x.shape[0], -1) x = F.relu(self.fc1(x)) x = self.fc2(x) x = self.qnn(x) # apply QNN x = self.fc3(x) return cat((x, 1 - x), -1) model4 = Net(qnn4) # Define model, optimizer, and loss function optimizer = optim.Adam(model4.parameters(), lr=0.001) loss_func = NLLLoss() # Start training epochs = 10 # Set number of epochs loss_list = [] # Store loss history model4.train() # Set model to training mode for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad(set_to_none=True) # Initialize gradient output = model4(data) # Forward pass loss = loss_func(output, target) # Calculate loss loss.backward() # Backward pass optimizer.step() # Optimize weights total_loss.append(loss.item()) # Store loss loss_list.append(sum(total_loss) / len(total_loss)) print("Training [{:.0f}%]\tLoss: {:.4f}".format(100.0 * (epoch + 1) / epochs, loss_list[-1])) # Plot loss convergence plt.plot(loss_list) plt.title("Hybrid NN Training Convergence") plt.xlabel("Training Iterations") plt.ylabel("Neg. Log Likelihood Loss") plt.show() torch.save(model4.state_dict(), "model4.pt") qnn5 = create_qnn() model5 = Net(qnn5) model5.load_state_dict(torch.load("model4.pt")) model5.eval() # set model to evaluation mode with no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model5(data) if len(output.shape) == 1: output = output.reshape(1, *output.shape) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print( "Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%".format( sum(total_loss) / len(total_loss), correct / len(test_loader) / batch_size * 100 ) ) # Plot predicted labels n_samples_show = 6 count = 0 fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) model5.eval() with no_grad(): for batch_idx, (data, target) in enumerate(test_loader): if count == n_samples_show: break output = model5(data[0:1]) if len(output.shape) == 1: output = output.reshape(1, *output.shape) pred = output.argmax(dim=1, keepdim=True) axes[count].imshow(data[0].numpy().squeeze(), cmap="gray") axes[count].set_xticks([]) axes[count].set_yticks([]) axes[count].set_title("Predicted {}".format(pred.item())) count += 1 import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=bad-docstring-quotes,invalid-name """Quantum circuit object.""" from __future__ import annotations import collections.abc import copy import itertools import multiprocessing as mp import string import re import warnings import typing from collections import OrderedDict, defaultdict, namedtuple from typing import ( Union, Optional, Tuple, Type, TypeVar, Sequence, Callable, Mapping, Iterable, Any, DefaultDict, Literal, overload, ) import numpy as np from qiskit.exceptions import QiskitError from qiskit.utils.multiprocessing import is_main_process from qiskit.circuit.instruction import Instruction from qiskit.circuit.gate import Gate from qiskit.circuit.parameter import Parameter from qiskit.circuit.exceptions import CircuitError from qiskit.utils import optionals as _optionals from . import _classical_resource_map from ._utils import sort_parameters from .classical import expr from .parameterexpression import ParameterExpression, ParameterValueType from .quantumregister import QuantumRegister, Qubit, AncillaRegister, AncillaQubit from .classicalregister import ClassicalRegister, Clbit from .parametertable import ParameterReferences, ParameterTable, ParameterView from .parametervector import ParameterVector from .instructionset import InstructionSet from .operation import Operation from .register import Register from .bit import Bit from .quantumcircuitdata import QuantumCircuitData, CircuitInstruction from .delay import Delay from .measure import Measure from .reset import Reset from .tools import pi_check if typing.TYPE_CHECKING: import qiskit # pylint: disable=cyclic-import from qiskit.transpiler.layout import TranspileLayout # pylint: disable=cyclic-import BitLocations = namedtuple("BitLocations", ("index", "registers")) # The following types are not marked private to avoid leaking this "private/public" abstraction out # into the documentation. They are not imported by circuit.__init__, nor are they meant to be. # Arbitrary type variables for marking up generics. S = TypeVar("S") T = TypeVar("T") # Types that can be coerced to a valid Qubit specifier in a circuit. QubitSpecifier = Union[ Qubit, QuantumRegister, int, slice, Sequence[Union[Qubit, int]], ] # Types that can be coerced to a valid Clbit specifier in a circuit. ClbitSpecifier = Union[ Clbit, ClassicalRegister, int, slice, Sequence[Union[Clbit, int]], ] # Generic type which is either :obj:`~Qubit` or :obj:`~Clbit`, used to specify types of functions # which operate on either type of bit, but not both at the same time. BitType = TypeVar("BitType", Qubit, Clbit) # Regex pattern to match valid OpenQASM identifiers VALID_QASM2_IDENTIFIER = re.compile("[a-z][a-zA-Z_0-9]*") QASM2_RESERVED = { "OPENQASM", "qreg", "creg", "include", "gate", "opaque", "U", "CX", "measure", "reset", "if", "barrier", } class QuantumCircuit: """Create a new circuit. A circuit is a list of instructions bound to some registers. Args: regs (list(:class:`~.Register`) or list(``int``) or list(list(:class:`~.Bit`))): The registers to be included in the circuit. * If a list of :class:`~.Register` objects, represents the :class:`.QuantumRegister` and/or :class:`.ClassicalRegister` objects to include in the circuit. For example: * ``QuantumCircuit(QuantumRegister(4))`` * ``QuantumCircuit(QuantumRegister(4), ClassicalRegister(3))`` * ``QuantumCircuit(QuantumRegister(4, 'qr0'), QuantumRegister(2, 'qr1'))`` * If a list of ``int``, the amount of qubits and/or classical bits to include in the circuit. It can either be a single int for just the number of quantum bits, or 2 ints for the number of quantum bits and classical bits, respectively. For example: * ``QuantumCircuit(4) # A QuantumCircuit with 4 qubits`` * ``QuantumCircuit(4, 3) # A QuantumCircuit with 4 qubits and 3 classical bits`` * If a list of python lists containing :class:`.Bit` objects, a collection of :class:`.Bit` s to be added to the circuit. name (str): the name of the quantum circuit. If not set, an automatically generated string will be assigned. global_phase (float or ParameterExpression): The global phase of the circuit in radians. metadata (dict): Arbitrary key value metadata to associate with the circuit. This gets stored as free-form data in a dict in the :attr:`~qiskit.circuit.QuantumCircuit.metadata` attribute. It will not be directly used in the circuit. Raises: CircuitError: if the circuit name, if given, is not valid. Examples: Construct a simple Bell state circuit. .. plot:: :include-source: from qiskit import QuantumCircuit qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) qc.draw('mpl') Construct a 5-qubit GHZ circuit. .. code-block:: from qiskit import QuantumCircuit qc = QuantumCircuit(5) qc.h(0) qc.cx(0, range(1, 5)) qc.measure_all() Construct a 4-qubit Bernstein-Vazirani circuit using registers. .. plot:: :include-source: from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(3, 'q') anc = QuantumRegister(1, 'ancilla') cr = ClassicalRegister(3, 'c') qc = QuantumCircuit(qr, anc, cr) qc.x(anc[0]) qc.h(anc[0]) qc.h(qr[0:3]) qc.cx(qr[0:3], anc[0]) qc.h(qr[0:3]) qc.barrier(qr) qc.measure(qr, cr) qc.draw('mpl') """ instances = 0 prefix = "circuit" # Class variable OPENQASM header header = "OPENQASM 2.0;" extension_lib = 'include "qelib1.inc";' def __init__( self, *regs: Register | int | Sequence[Bit], name: str | None = None, global_phase: ParameterValueType = 0, metadata: dict | None = None, ): if any(not isinstance(reg, (list, QuantumRegister, ClassicalRegister)) for reg in regs): # check if inputs are integers, but also allow e.g. 2.0 try: valid_reg_size = all(reg == int(reg) for reg in regs) except (ValueError, TypeError): valid_reg_size = False if not valid_reg_size: raise CircuitError( "Circuit args must be Registers or integers. (%s '%s' was " "provided)" % ([type(reg).__name__ for reg in regs], regs) ) regs = tuple(int(reg) for reg in regs) # cast to int self._base_name = None if name is None: self._base_name = self.cls_prefix() self._name_update() elif not isinstance(name, str): raise CircuitError( "The circuit name should be a string (or None to auto-generate a name)." ) else: self._base_name = name self.name = name self._increment_instances() # Data contains a list of instructions and their contexts, # in the order they were applied. self._data: list[CircuitInstruction] = [] self._op_start_times = None # A stack to hold the instruction sets that are being built up during for-, if- and # while-block construction. These are stored as a stripped down sequence of instructions, # and sets of qubits and clbits, rather than a full QuantumCircuit instance because the # builder interfaces need to wait until they are completed before they can fill in things # like `break` and `continue`. This is because these instructions need to "operate" on the # full width of bits, but the builder interface won't know what bits are used until the end. self._control_flow_scopes: list[ "qiskit.circuit.controlflow.builder.ControlFlowBuilderBlock" ] = [] self.qregs: list[QuantumRegister] = [] self.cregs: list[ClassicalRegister] = [] self._qubits: list[Qubit] = [] self._clbits: list[Clbit] = [] # Dict mapping Qubit or Clbit instances to tuple comprised of 0) the # corresponding index in circuit.{qubits,clbits} and 1) a list of # Register-int pairs for each Register containing the Bit and its index # within that register. self._qubit_indices: dict[Qubit, BitLocations] = {} self._clbit_indices: dict[Clbit, BitLocations] = {} self._ancillas: list[AncillaQubit] = [] self._calibrations: DefaultDict[str, dict[tuple, Any]] = defaultdict(dict) self.add_register(*regs) # Parameter table tracks instructions with variable parameters. self._parameter_table = ParameterTable() # Cache to avoid re-sorting parameters self._parameters = None self._layout = None self._global_phase: ParameterValueType = 0 self.global_phase = global_phase self.duration = None self.unit = "dt" self.metadata = {} if metadata is None else metadata @staticmethod def from_instructions( instructions: Iterable[ CircuitInstruction | tuple[qiskit.circuit.Instruction] | tuple[qiskit.circuit.Instruction, Iterable[Qubit]] | tuple[qiskit.circuit.Instruction, Iterable[Qubit], Iterable[Clbit]] ], *, qubits: Iterable[Qubit] = (), clbits: Iterable[Clbit] = (), name: str | None = None, global_phase: ParameterValueType = 0, metadata: dict | None = None, ) -> "QuantumCircuit": """Construct a circuit from an iterable of CircuitInstructions. Args: instructions: The instructions to add to the circuit. qubits: Any qubits to add to the circuit. This argument can be used, for example, to enforce a particular ordering of qubits. clbits: Any classical bits to add to the circuit. This argument can be used, for example, to enforce a particular ordering of classical bits. name: The name of the circuit. global_phase: The global phase of the circuit in radians. metadata: Arbitrary key value metadata to associate with the circuit. Returns: The quantum circuit. """ circuit = QuantumCircuit(name=name, global_phase=global_phase, metadata=metadata) added_qubits = set() added_clbits = set() if qubits: qubits = list(qubits) circuit.add_bits(qubits) added_qubits.update(qubits) if clbits: clbits = list(clbits) circuit.add_bits(clbits) added_clbits.update(clbits) for instruction in instructions: if not isinstance(instruction, CircuitInstruction): instruction = CircuitInstruction(*instruction) qubits = [qubit for qubit in instruction.qubits if qubit not in added_qubits] clbits = [clbit for clbit in instruction.clbits if clbit not in added_clbits] circuit.add_bits(qubits) circuit.add_bits(clbits) added_qubits.update(qubits) added_clbits.update(clbits) circuit._append(instruction) return circuit @property def layout(self) -> Optional[TranspileLayout]: r"""Return any associated layout information about the circuit This attribute contains an optional :class:`~.TranspileLayout` object. This is typically set on the output from :func:`~.transpile` or :meth:`.PassManager.run` to retain information about the permutations caused on the input circuit by transpilation. There are two types of permutations caused by the :func:`~.transpile` function, an initial layout which permutes the qubits based on the selected physical qubits on the :class:`~.Target`, and a final layout which is an output permutation caused by :class:`~.SwapGate`\s inserted during routing. """ return self._layout @property def data(self) -> QuantumCircuitData: """Return the circuit data (instructions and context). Returns: QuantumCircuitData: a list-like object containing the :class:`.CircuitInstruction`\\ s for each instruction. """ return QuantumCircuitData(self) @data.setter def data(self, data_input: Iterable): """Sets the circuit data from a list of instructions and context. Args: data_input (Iterable): A sequence of instructions with their execution contexts. The elements must either be instances of :class:`.CircuitInstruction` (preferred), or a 3-tuple of ``(instruction, qargs, cargs)`` (legacy). In the legacy format, ``instruction`` must be an :class:`~.circuit.Instruction`, while ``qargs`` and ``cargs`` must be iterables of :class:`.Qubit` or :class:`.Clbit` specifiers (similar to the allowed forms in calls to :meth:`append`). """ # If data_input is QuantumCircuitData(self), clearing self._data # below will also empty data_input, so make a shallow copy first. data_input = list(data_input) self._data = [] self._parameter_table = ParameterTable() if not data_input: return if isinstance(data_input[0], CircuitInstruction): for instruction in data_input: self.append(instruction) else: for instruction, qargs, cargs in data_input: self.append(instruction, qargs, cargs) @property def op_start_times(self) -> list[int]: """Return a list of operation start times. This attribute is enabled once one of scheduling analysis passes runs on the quantum circuit. Returns: List of integers representing instruction start times. The index corresponds to the index of instruction in :attr:`QuantumCircuit.data`. Raises: AttributeError: When circuit is not scheduled. """ if self._op_start_times is None: raise AttributeError( "This circuit is not scheduled. " "To schedule it run the circuit through one of the transpiler scheduling passes." ) return self._op_start_times @property def calibrations(self) -> dict: """Return calibration dictionary. The custom pulse definition of a given gate is of the form ``{'gate_name': {(qubits, params): schedule}}`` """ return dict(self._calibrations) @calibrations.setter def calibrations(self, calibrations: dict): """Set the circuit calibration data from a dictionary of calibration definition. Args: calibrations (dict): A dictionary of input in the format ``{'gate_name': {(qubits, gate_params): schedule}}`` """ self._calibrations = defaultdict(dict, calibrations) def has_calibration_for(self, instruction: CircuitInstruction | tuple): """Return True if the circuit has a calibration defined for the instruction context. In this case, the operation does not need to be translated to the device basis. """ if isinstance(instruction, CircuitInstruction): operation = instruction.operation qubits = instruction.qubits else: operation, qubits, _ = instruction if not self.calibrations or operation.name not in self.calibrations: return False qubits = tuple(self.qubits.index(qubit) for qubit in qubits) params = [] for p in operation.params: if isinstance(p, ParameterExpression) and not p.parameters: params.append(float(p)) else: params.append(p) params = tuple(params) return (qubits, params) in self.calibrations[operation.name] @property def metadata(self) -> dict: """The user provided metadata associated with the circuit. The metadata for the circuit is a user provided ``dict`` of metadata for the circuit. It will not be used to influence the execution or operation of the circuit, but it is expected to be passed between all transforms of the circuit (ie transpilation) and that providers will associate any circuit metadata with the results it returns from execution of that circuit. """ return self._metadata @metadata.setter def metadata(self, metadata: dict | None): """Update the circuit metadata""" if metadata is None: metadata = {} warnings.warn( "Setting metadata to None was deprecated in Terra 0.24.0 and this ability will be " "removed in a future release. Instead, set metadata to an empty dictionary.", DeprecationWarning, stacklevel=2, ) elif not isinstance(metadata, dict): raise TypeError("Only a dictionary is accepted for circuit metadata") self._metadata = metadata def __str__(self) -> str: return str(self.draw(output="text")) def __eq__(self, other) -> bool: if not isinstance(other, QuantumCircuit): return False # TODO: remove the DAG from this function from qiskit.converters import circuit_to_dag return circuit_to_dag(self, copy_operations=False) == circuit_to_dag( other, copy_operations=False ) @classmethod def _increment_instances(cls): cls.instances += 1 @classmethod def cls_instances(cls) -> int: """Return the current number of instances of this class, useful for auto naming.""" return cls.instances @classmethod def cls_prefix(cls) -> str: """Return the prefix to use for auto naming.""" return cls.prefix def _name_update(self) -> None: """update name of instance using instance number""" if not is_main_process(): pid_name = f"-{mp.current_process().pid}" else: pid_name = "" self.name = f"{self._base_name}-{self.cls_instances()}{pid_name}" def has_register(self, register: Register) -> bool: """ Test if this circuit has the register r. Args: register (Register): a quantum or classical register. Returns: bool: True if the register is contained in this circuit. """ has_reg = False if isinstance(register, QuantumRegister) and register in self.qregs: has_reg = True elif isinstance(register, ClassicalRegister) and register in self.cregs: has_reg = True return has_reg def reverse_ops(self) -> "QuantumCircuit": """Reverse the circuit by reversing the order of instructions. This is done by recursively reversing all instructions. It does not invert (adjoint) any gate. Returns: QuantumCircuit: the reversed circuit. Examples: input: .. parsed-literal:: ┌───┐ q_0: ┤ H ├─────■────── └───┘┌────┴─────┐ q_1: ─────┤ RX(1.57) ├ └──────────┘ output: .. parsed-literal:: ┌───┐ q_0: ─────■──────┤ H ├ ┌────┴─────┐└───┘ q_1: ┤ RX(1.57) ├───── └──────────┘ """ reverse_circ = QuantumCircuit( self.qubits, self.clbits, *self.qregs, *self.cregs, name=self.name + "_reverse" ) for instruction in reversed(self.data): reverse_circ._append(instruction.replace(operation=instruction.operation.reverse_ops())) reverse_circ.duration = self.duration reverse_circ.unit = self.unit return reverse_circ def reverse_bits(self) -> "QuantumCircuit": """Return a circuit with the opposite order of wires. The circuit is "vertically" flipped. If a circuit is defined over multiple registers, the resulting circuit will have the same registers but with their order flipped. This method is useful for converting a circuit written in little-endian convention to the big-endian equivalent, and vice versa. Returns: QuantumCircuit: the circuit with reversed bit order. Examples: input: .. parsed-literal:: ┌───┐ a_0: ┤ H ├──■───────────────── └───┘┌─┴─┐ a_1: ─────┤ X ├──■──────────── └───┘┌─┴─┐ a_2: ──────────┤ X ├──■─────── └───┘┌─┴─┐ b_0: ───────────────┤ X ├──■── └───┘┌─┴─┐ b_1: ────────────────────┤ X ├ └───┘ output: .. parsed-literal:: ┌───┐ b_0: ────────────────────┤ X ├ ┌───┐└─┬─┘ b_1: ───────────────┤ X ├──■── ┌───┐└─┬─┘ a_0: ──────────┤ X ├──■─────── ┌───┐└─┬─┘ a_1: ─────┤ X ├──■──────────── ┌───┐└─┬─┘ a_2: ┤ H ├──■───────────────── └───┘ """ circ = QuantumCircuit( list(reversed(self.qubits)), list(reversed(self.clbits)), name=self.name, global_phase=self.global_phase, ) new_qubit_map = circ.qubits[::-1] new_clbit_map = circ.clbits[::-1] for reg in reversed(self.qregs): bits = [new_qubit_map[self.find_bit(qubit).index] for qubit in reversed(reg)] circ.add_register(QuantumRegister(bits=bits, name=reg.name)) for reg in reversed(self.cregs): bits = [new_clbit_map[self.find_bit(clbit).index] for clbit in reversed(reg)] circ.add_register(ClassicalRegister(bits=bits, name=reg.name)) for instruction in self.data: qubits = [new_qubit_map[self.find_bit(qubit).index] for qubit in instruction.qubits] clbits = [new_clbit_map[self.find_bit(clbit).index] for clbit in instruction.clbits] circ._append(instruction.replace(qubits=qubits, clbits=clbits)) return circ def inverse(self) -> "QuantumCircuit": """Invert (take adjoint of) this circuit. This is done by recursively inverting all gates. Returns: QuantumCircuit: the inverted circuit Raises: CircuitError: if the circuit cannot be inverted. Examples: input: .. parsed-literal:: ┌───┐ q_0: ┤ H ├─────■────── └───┘┌────┴─────┐ q_1: ─────┤ RX(1.57) ├ └──────────┘ output: .. parsed-literal:: ┌───┐ q_0: ──────■──────┤ H ├ ┌─────┴─────┐└───┘ q_1: ┤ RX(-1.57) ├───── └───────────┘ """ inverse_circ = QuantumCircuit( self.qubits, self.clbits, *self.qregs, *self.cregs, name=self.name + "_dg", global_phase=-self.global_phase, ) for instruction in reversed(self._data): inverse_circ._append(instruction.replace(operation=instruction.operation.inverse())) return inverse_circ def repeat(self, reps: int) -> "QuantumCircuit": """Repeat this circuit ``reps`` times. Args: reps (int): How often this circuit should be repeated. Returns: QuantumCircuit: A circuit containing ``reps`` repetitions of this circuit. """ repeated_circ = QuantumCircuit( self.qubits, self.clbits, *self.qregs, *self.cregs, name=self.name + f"**{reps}" ) # benefit of appending instructions: decomposing shows the subparts, i.e. the power # is actually `reps` times this circuit, and it is currently much faster than `compose`. if reps > 0: try: # try to append as gate if possible to not disallow to_gate inst: Instruction = self.to_gate() except QiskitError: inst = self.to_instruction() for _ in range(reps): repeated_circ._append(inst, self.qubits, self.clbits) return repeated_circ def power(self, power: float, matrix_power: bool = False) -> "QuantumCircuit": """Raise this circuit to the power of ``power``. If ``power`` is a positive integer and ``matrix_power`` is ``False``, this implementation defaults to calling ``repeat``. Otherwise, if the circuit is unitary, the matrix is computed to calculate the matrix power. Args: power (float): The power to raise this circuit to. matrix_power (bool): If True, the circuit is converted to a matrix and then the matrix power is computed. If False, and ``power`` is a positive integer, the implementation defaults to ``repeat``. Raises: CircuitError: If the circuit needs to be converted to a gate but it is not unitary. Returns: QuantumCircuit: A circuit implementing this circuit raised to the power of ``power``. """ if power >= 0 and isinstance(power, (int, np.integer)) and not matrix_power: return self.repeat(power) # attempt conversion to gate if self.num_parameters > 0: raise CircuitError( "Cannot raise a parameterized circuit to a non-positive power " "or matrix-power, please bind the free parameters: " "{}".format(self.parameters) ) try: gate = self.to_gate() except QiskitError as ex: raise CircuitError( "The circuit contains non-unitary operations and cannot be " "controlled. Note that no qiskit.circuit.Instruction objects may " "be in the circuit for this operation." ) from ex power_circuit = QuantumCircuit(self.qubits, self.clbits, *self.qregs, *self.cregs) power_circuit.append(gate.power(power), list(range(gate.num_qubits))) return power_circuit def control( self, num_ctrl_qubits: int = 1, label: str | None = None, ctrl_state: str | int | None = None, ) -> "QuantumCircuit": """Control this circuit on ``num_ctrl_qubits`` qubits. Args: num_ctrl_qubits (int): The number of control qubits. label (str): An optional label to give the controlled operation for visualization. ctrl_state (str or int): The control state in decimal or as a bitstring (e.g. '111'). If None, use ``2**num_ctrl_qubits - 1``. Returns: QuantumCircuit: The controlled version of this circuit. Raises: CircuitError: If the circuit contains a non-unitary operation and cannot be controlled. """ try: gate = self.to_gate() except QiskitError as ex: raise CircuitError( "The circuit contains non-unitary operations and cannot be " "controlled. Note that no qiskit.circuit.Instruction objects may " "be in the circuit for this operation." ) from ex controlled_gate = gate.control(num_ctrl_qubits, label, ctrl_state) control_qreg = QuantumRegister(num_ctrl_qubits) controlled_circ = QuantumCircuit( control_qreg, self.qubits, *self.qregs, name=f"c_{self.name}" ) controlled_circ.append(controlled_gate, controlled_circ.qubits) return controlled_circ def compose( self, other: Union["QuantumCircuit", Instruction], qubits: QubitSpecifier | Sequence[QubitSpecifier] | None = None, clbits: ClbitSpecifier | Sequence[ClbitSpecifier] | None = None, front: bool = False, inplace: bool = False, wrap: bool = False, ) -> Optional["QuantumCircuit"]: """Compose circuit with ``other`` circuit or instruction, optionally permuting wires. ``other`` can be narrower or of equal width to ``self``. Args: other (qiskit.circuit.Instruction or QuantumCircuit): (sub)circuit or instruction to compose onto self. If not a :obj:`.QuantumCircuit`, this can be anything that :obj:`.append` will accept. qubits (list[Qubit|int]): qubits of self to compose onto. clbits (list[Clbit|int]): clbits of self to compose onto. front (bool): If True, front composition will be performed. This is not possible within control-flow builder context managers. inplace (bool): If True, modify the object. Otherwise return composed circuit. wrap (bool): If True, wraps the other circuit into a gate (or instruction, depending on whether it contains only unitary instructions) before composing it onto self. Returns: QuantumCircuit: the composed circuit (returns None if inplace==True). Raises: CircuitError: if no correct wire mapping can be made between the two circuits, such as if ``other`` is wider than ``self``. CircuitError: if trying to emit a new circuit while ``self`` has a partially built control-flow context active, such as the context-manager forms of :meth:`if_test`, :meth:`for_loop` and :meth:`while_loop`. CircuitError: if trying to compose to the front of a circuit when a control-flow builder block is active; there is no clear meaning to this action. Examples: .. code-block:: python >>> lhs.compose(rhs, qubits=[3, 2], inplace=True) .. parsed-literal:: ┌───┐ ┌─────┐ ┌───┐ lqr_1_0: ───┤ H ├─── rqr_0: ──■──┤ Tdg ├ lqr_1_0: ───┤ H ├─────────────── ├───┤ ┌─┴─┐└─────┘ ├───┤ lqr_1_1: ───┤ X ├─── rqr_1: ┤ X ├─────── lqr_1_1: ───┤ X ├─────────────── ┌──┴───┴──┐ └───┘ ┌──┴───┴──┐┌───┐ lqr_1_2: ┤ U1(0.1) ├ + = lqr_1_2: ┤ U1(0.1) ├┤ X ├─────── └─────────┘ └─────────┘└─┬─┘┌─────┐ lqr_2_0: ─────■───── lqr_2_0: ─────■───────■──┤ Tdg ├ ┌─┴─┐ ┌─┴─┐ └─────┘ lqr_2_1: ───┤ X ├─── lqr_2_1: ───┤ X ├─────────────── └───┘ └───┘ lcr_0: 0 ═══════════ lcr_0: 0 ═══════════════════════ lcr_1: 0 ═══════════ lcr_1: 0 ═══════════════════════ """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.switch_case import SwitchCaseOp if inplace and front and self._control_flow_scopes: # If we're composing onto ourselves while in a stateful control-flow builder context, # there's no clear meaning to composition to the "front" of the circuit. raise CircuitError( "Cannot compose to the front of a circuit while a control-flow context is active." ) if not inplace and self._control_flow_scopes: # If we're inside a stateful control-flow builder scope, even if we successfully cloned # the partial builder scope (not simple), the scope wouldn't be controlled by an active # `with` statement, so the output circuit would be permanently broken. raise CircuitError( "Cannot emit a new composed circuit while a control-flow context is active." ) dest = self if inplace else self.copy() # As a special case, allow composing some clbits onto no clbits - normally the destination # has to be strictly larger. This allows composing final measurements onto unitary circuits. if isinstance(other, QuantumCircuit): if not self.clbits and other.clbits: dest.add_bits(other.clbits) for reg in other.cregs: dest.add_register(reg) if wrap and isinstance(other, QuantumCircuit): other = ( other.to_gate() if all(isinstance(ins.operation, Gate) for ins in other.data) else other.to_instruction() ) if not isinstance(other, QuantumCircuit): if qubits is None: qubits = self.qubits[: other.num_qubits] if clbits is None: clbits = self.clbits[: other.num_clbits] if front: # Need to keep a reference to the data for use after we've emptied it. old_data = list(dest.data) dest.clear() dest.append(other, qubits, clbits) for instruction in old_data: dest._append(instruction) else: dest.append(other, qargs=qubits, cargs=clbits) if inplace: return None return dest if other.num_qubits > dest.num_qubits or other.num_clbits > dest.num_clbits: raise CircuitError( "Trying to compose with another QuantumCircuit which has more 'in' edges." ) # number of qubits and clbits must match number in circuit or None edge_map: dict[Qubit | Clbit, Qubit | Clbit] = {} if qubits is None: edge_map.update(zip(other.qubits, dest.qubits)) else: mapped_qubits = dest.qbit_argument_conversion(qubits) if len(mapped_qubits) != len(other.qubits): raise CircuitError( f"Number of items in qubits parameter ({len(mapped_qubits)}) does not" f" match number of qubits in the circuit ({len(other.qubits)})." ) edge_map.update(zip(other.qubits, mapped_qubits)) if clbits is None: edge_map.update(zip(other.clbits, dest.clbits)) else: mapped_clbits = dest.cbit_argument_conversion(clbits) if len(mapped_clbits) != len(other.clbits): raise CircuitError( f"Number of items in clbits parameter ({len(mapped_clbits)}) does not" f" match number of clbits in the circuit ({len(other.clbits)})." ) edge_map.update(zip(other.clbits, dest.cbit_argument_conversion(clbits))) variable_mapper = _classical_resource_map.VariableMapper( dest.cregs, edge_map, dest.add_register ) mapped_instrs: list[CircuitInstruction] = [] for instr in other.data: n_qargs: list[Qubit] = [edge_map[qarg] for qarg in instr.qubits] n_cargs: list[Clbit] = [edge_map[carg] for carg in instr.clbits] n_op = instr.operation.copy() if (condition := getattr(n_op, "condition", None)) is not None: n_op.condition = variable_mapper.map_condition(condition) if isinstance(n_op, SwitchCaseOp): n_op.target = variable_mapper.map_target(n_op.target) mapped_instrs.append(CircuitInstruction(n_op, n_qargs, n_cargs)) if front: # adjust new instrs before original ones and update all parameters mapped_instrs += dest.data dest.clear() append = dest._control_flow_scopes[-1].append if dest._control_flow_scopes else dest._append for instr in mapped_instrs: append(instr) for gate, cals in other.calibrations.items(): dest._calibrations[gate].update(cals) dest.global_phase += other.global_phase if inplace: return None return dest def tensor(self, other: "QuantumCircuit", inplace: bool = False) -> Optional["QuantumCircuit"]: """Tensor ``self`` with ``other``. Remember that in the little-endian convention the leftmost operation will be at the bottom of the circuit. See also `the docs <qiskit.org/documentation/tutorials/circuits/3_summary_of_quantum_operations.html>`__ for more information. .. parsed-literal:: ┌────────┐ ┌─────┐ ┌─────┐ q_0: ┤ bottom ├ ⊗ q_0: ┤ top ├ = q_0: ─┤ top ├── └────────┘ └─────┘ ┌┴─────┴─┐ q_1: ┤ bottom ├ └────────┘ Args: other (QuantumCircuit): The other circuit to tensor this circuit with. inplace (bool): If True, modify the object. Otherwise return composed circuit. Examples: .. plot:: :include-source: 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') Returns: QuantumCircuit: The tensored circuit (returns None if inplace==True). """ num_qubits = self.num_qubits + other.num_qubits num_clbits = self.num_clbits + other.num_clbits # If a user defined both circuits with via register sizes and not with named registers # (e.g. QuantumCircuit(2, 2)) then we have a naming collision, as the registers are by # default called "q" resp. "c". To still allow tensoring we define new registers of the # correct sizes. if ( len(self.qregs) == len(other.qregs) == 1 and self.qregs[0].name == other.qregs[0].name == "q" ): # check if classical registers are in the circuit if num_clbits > 0: dest = QuantumCircuit(num_qubits, num_clbits) else: dest = QuantumCircuit(num_qubits) # handle case if ``measure_all`` was called on both circuits, in which case the # registers are both named "meas" elif ( len(self.cregs) == len(other.cregs) == 1 and self.cregs[0].name == other.cregs[0].name == "meas" ): cr = ClassicalRegister(self.num_clbits + other.num_clbits, "meas") dest = QuantumCircuit(*other.qregs, *self.qregs, cr) # Now we don't have to handle any more cases arising from special implicit naming else: dest = QuantumCircuit( other.qubits, self.qubits, other.clbits, self.clbits, *other.qregs, *self.qregs, *other.cregs, *self.cregs, ) # compose self onto the output, and then other dest.compose(other, range(other.num_qubits), range(other.num_clbits), inplace=True) dest.compose( self, range(other.num_qubits, num_qubits), range(other.num_clbits, num_clbits), inplace=True, ) # Replace information from tensored circuit into self when inplace = True if inplace: self.__dict__.update(dest.__dict__) return None return dest @property def qubits(self) -> list[Qubit]: """ Returns a list of quantum bits in the order that the registers were added. """ return self._qubits @property def clbits(self) -> list[Clbit]: """ Returns a list of classical bits in the order that the registers were added. """ return self._clbits @property def ancillas(self) -> list[AncillaQubit]: """ Returns a list of ancilla bits in the order that the registers were added. """ return self._ancillas def __and__(self, rhs: "QuantumCircuit") -> "QuantumCircuit": """Overload & to implement self.compose.""" return self.compose(rhs) def __iand__(self, rhs: "QuantumCircuit") -> "QuantumCircuit": """Overload &= to implement self.compose in place.""" self.compose(rhs, inplace=True) return self def __xor__(self, top: "QuantumCircuit") -> "QuantumCircuit": """Overload ^ to implement self.tensor.""" return self.tensor(top) def __ixor__(self, top: "QuantumCircuit") -> "QuantumCircuit": """Overload ^= to implement self.tensor in place.""" self.tensor(top, inplace=True) return self def __len__(self) -> int: """Return number of operations in circuit.""" return len(self._data) @typing.overload def __getitem__(self, item: int) -> CircuitInstruction: ... @typing.overload def __getitem__(self, item: slice) -> list[CircuitInstruction]: ... def __getitem__(self, item): """Return indexed operation.""" return self._data[item] @staticmethod def cast(value: S, type_: Callable[..., T]) -> Union[S, T]: """Best effort to cast value to type. Otherwise, returns the value.""" try: return type_(value) except (ValueError, TypeError): return value def qbit_argument_conversion(self, qubit_representation: QubitSpecifier) -> list[Qubit]: """ Converts several qubit representations (such as indexes, range, etc.) into a list of qubits. Args: qubit_representation (Object): representation to expand Returns: List(Qubit): the resolved instances of the qubits. """ return _bit_argument_conversion( qubit_representation, self.qubits, self._qubit_indices, Qubit ) def cbit_argument_conversion(self, clbit_representation: ClbitSpecifier) -> list[Clbit]: """ Converts several classical bit representations (such as indexes, range, etc.) into a list of classical bits. Args: clbit_representation (Object): representation to expand Returns: List(tuple): Where each tuple is a classical bit. """ return _bit_argument_conversion( clbit_representation, self.clbits, self._clbit_indices, Clbit ) def _resolve_classical_resource(self, specifier): """Resolve a single classical resource specifier into a concrete resource, raising an error if the specifier is invalid. This is slightly different to :meth:`.cbit_argument_conversion`, because it should not unwrap :obj:`.ClassicalRegister` instances into lists, and in general it should not allow iterables or broadcasting. It is expected to be used as a callback for things like :meth:`.InstructionSet.c_if` to check the validity of their arguments. Args: specifier (Union[Clbit, ClassicalRegister, int]): a specifier of a classical resource present in this circuit. An ``int`` will be resolved into a :obj:`.Clbit` using the same conventions as measurement operations on this circuit use. Returns: Union[Clbit, ClassicalRegister]: the resolved resource. Raises: CircuitError: if the resource is not present in this circuit, or if the integer index passed is out-of-bounds. """ if isinstance(specifier, Clbit): if specifier not in self._clbit_indices: raise CircuitError(f"Clbit {specifier} is not present in this circuit.") return specifier if isinstance(specifier, ClassicalRegister): # This is linear complexity for something that should be constant, but QuantumCircuit # does not currently keep a hashmap of registers, and requires non-trivial changes to # how it exposes its registers publically before such a map can be safely stored so it # doesn't miss updates. (Jake, 2021-11-10). if specifier not in self.cregs: raise CircuitError(f"Register {specifier} is not present in this circuit.") return specifier if isinstance(specifier, int): try: return self._clbits[specifier] except IndexError: raise CircuitError(f"Classical bit index {specifier} is out-of-range.") from None raise CircuitError(f"Unknown classical resource specifier: '{specifier}'.") def _validate_expr(self, node: expr.Expr) -> expr.Expr: for var in expr.iter_vars(node): if isinstance(var.var, Clbit): if var.var not in self._clbit_indices: raise CircuitError(f"Clbit {var.var} is not present in this circuit.") elif isinstance(var.var, ClassicalRegister): if var.var not in self.cregs: raise CircuitError(f"Register {var.var} is not present in this circuit.") return node def append( self, instruction: Operation | CircuitInstruction, qargs: Sequence[QubitSpecifier] | None = None, cargs: Sequence[ClbitSpecifier] | None = None, ) -> InstructionSet: """Append one or more instructions to the end of the circuit, modifying the circuit in place. The ``qargs`` and ``cargs`` will be expanded and broadcast according to the rules of the given :class:`~.circuit.Instruction`, and any non-:class:`.Bit` specifiers (such as integer indices) will be resolved into the relevant instances. If a :class:`.CircuitInstruction` is given, it will be unwrapped, verified in the context of this circuit, and a new object will be appended to the circuit. In this case, you may not pass ``qargs`` or ``cargs`` separately. Args: instruction: :class:`~.circuit.Instruction` instance to append, or a :class:`.CircuitInstruction` with all its context. qargs: specifiers of the :class:`.Qubit`\\ s to attach instruction to. cargs: specifiers of the :class:`.Clbit`\\ s to attach instruction to. Returns: qiskit.circuit.InstructionSet: a handle to the :class:`.CircuitInstruction`\\ s that were actually added to the circuit. Raises: CircuitError: if the operation passed is not an instance of :class:`~.circuit.Instruction` . """ if isinstance(instruction, CircuitInstruction): operation = instruction.operation qargs = instruction.qubits cargs = instruction.clbits else: operation = instruction # Convert input to instruction if not isinstance(operation, Operation): if hasattr(operation, "to_instruction"): operation = operation.to_instruction() if not isinstance(operation, Operation): raise CircuitError("operation.to_instruction() is not an Operation.") else: if issubclass(operation, Operation): raise CircuitError( "Object is a subclass of Operation, please add () to " "pass an instance of this object." ) raise CircuitError( "Object to append must be an Operation or have a to_instruction() method." ) # Make copy of parameterized gate instances if hasattr(operation, "params"): is_parameter = any(isinstance(param, Parameter) for param in operation.params) if is_parameter: operation = copy.deepcopy(operation) expanded_qargs = [self.qbit_argument_conversion(qarg) for qarg in qargs or []] expanded_cargs = [self.cbit_argument_conversion(carg) for carg in cargs or []] if self._control_flow_scopes: appender = self._control_flow_scopes[-1].append requester = self._control_flow_scopes[-1].request_classical_resource else: appender = self._append requester = self._resolve_classical_resource instructions = InstructionSet(resource_requester=requester) if isinstance(operation, Instruction): for qarg, carg in operation.broadcast_arguments(expanded_qargs, expanded_cargs): self._check_dups(qarg) instruction = CircuitInstruction(operation, qarg, carg) appender(instruction) instructions.add(instruction) else: # For Operations that are non-Instructions, we use the Instruction's default method for qarg, carg in Instruction.broadcast_arguments( operation, expanded_qargs, expanded_cargs ): self._check_dups(qarg) instruction = CircuitInstruction(operation, qarg, carg) appender(instruction) instructions.add(instruction) return instructions # Preferred new style. @typing.overload def _append( self, instruction: CircuitInstruction, _qargs: None = None, _cargs: None = None ) -> CircuitInstruction: ... # To-be-deprecated old style. @typing.overload def _append( self, operation: Operation, qargs: Sequence[Qubit], cargs: Sequence[Clbit], ) -> Operation: ... def _append( self, instruction: CircuitInstruction | Instruction, qargs: Sequence[Qubit] | None = None, cargs: Sequence[Clbit] | None = None, ): """Append an instruction to the end of the circuit, modifying the circuit in place. .. warning:: This is an internal fast-path function, and it is the responsibility of the caller to ensure that all the arguments are valid; there is no error checking here. In particular, all the qubits and clbits must already exist in the circuit and there can be no duplicates in the list. .. note:: This function may be used by callers other than :obj:`.QuantumCircuit` when the caller is sure that all error-checking, broadcasting and scoping has already been performed, and the only reference to the circuit the instructions are being appended to is within that same function. In particular, it is not safe to call :meth:`QuantumCircuit._append` on a circuit that is received by a function argument. This is because :meth:`.QuantumCircuit._append` will not recognise the scoping constructs of the control-flow builder interface. Args: instruction: Operation instance to append qargs: Qubits to attach the instruction to. cargs: Clbits to attach the instruction to. Returns: Operation: a handle to the instruction that was just added :meta public: """ old_style = not isinstance(instruction, CircuitInstruction) if old_style: instruction = CircuitInstruction(instruction, qargs, cargs) self._data.append(instruction) if isinstance(instruction.operation, Instruction): self._update_parameter_table(instruction) # mark as normal circuit if a new instruction is added self.duration = None self.unit = "dt" return instruction.operation if old_style else instruction def _update_parameter_table(self, instruction: CircuitInstruction): for param_index, param in enumerate(instruction.operation.params): if isinstance(param, (ParameterExpression, QuantumCircuit)): # Scoped constructs like the control-flow ops use QuantumCircuit as a parameter. atomic_parameters = set(param.parameters) else: atomic_parameters = set() for parameter in atomic_parameters: if parameter in self._parameter_table: self._parameter_table[parameter].add((instruction.operation, param_index)) else: if parameter.name in self._parameter_table.get_names(): raise CircuitError(f"Name conflict on adding parameter: {parameter.name}") self._parameter_table[parameter] = ParameterReferences( ((instruction.operation, param_index),) ) # clear cache if new parameter is added self._parameters = None def add_register(self, *regs: Register | int | Sequence[Bit]) -> None: """Add registers.""" if not regs: return if any(isinstance(reg, int) for reg in regs): # QuantumCircuit defined without registers if len(regs) == 1 and isinstance(regs[0], int): # QuantumCircuit with anonymous quantum wires e.g. QuantumCircuit(2) if regs[0] == 0: regs = () else: regs = (QuantumRegister(regs[0], "q"),) elif len(regs) == 2 and all(isinstance(reg, int) for reg in regs): # QuantumCircuit with anonymous wires e.g. QuantumCircuit(2, 3) if regs[0] == 0: qregs: tuple[QuantumRegister, ...] = () else: qregs = (QuantumRegister(regs[0], "q"),) if regs[1] == 0: cregs: tuple[ClassicalRegister, ...] = () else: cregs = (ClassicalRegister(regs[1], "c"),) regs = qregs + cregs else: raise CircuitError( "QuantumCircuit parameters can be Registers or Integers." " If Integers, up to 2 arguments. QuantumCircuit was called" " with %s." % (regs,) ) for register in regs: if isinstance(register, Register) and any( register.name == reg.name for reg in self.qregs + self.cregs ): raise CircuitError('register name "%s" already exists' % register.name) if isinstance(register, AncillaRegister): for bit in register: if bit not in self._qubit_indices: self._ancillas.append(bit) if isinstance(register, QuantumRegister): self.qregs.append(register) for idx, bit in enumerate(register): if bit in self._qubit_indices: self._qubit_indices[bit].registers.append((register, idx)) else: self._qubits.append(bit) self._qubit_indices[bit] = BitLocations( len(self._qubits) - 1, [(register, idx)] ) elif isinstance(register, ClassicalRegister): self.cregs.append(register) for idx, bit in enumerate(register): if bit in self._clbit_indices: self._clbit_indices[bit].registers.append((register, idx)) else: self._clbits.append(bit) self._clbit_indices[bit] = BitLocations( len(self._clbits) - 1, [(register, idx)] ) elif isinstance(register, list): self.add_bits(register) else: raise CircuitError("expected a register") def add_bits(self, bits: Iterable[Bit]) -> None: """Add Bits to the circuit.""" duplicate_bits = set(self._qubit_indices).union(self._clbit_indices).intersection(bits) if duplicate_bits: raise CircuitError(f"Attempted to add bits found already in circuit: {duplicate_bits}") for bit in bits: if isinstance(bit, AncillaQubit): self._ancillas.append(bit) if isinstance(bit, Qubit): self._qubits.append(bit) self._qubit_indices[bit] = BitLocations(len(self._qubits) - 1, []) elif isinstance(bit, Clbit): self._clbits.append(bit) self._clbit_indices[bit] = BitLocations(len(self._clbits) - 1, []) else: raise CircuitError( "Expected an instance of Qubit, Clbit, or " "AncillaQubit, but was passed {}".format(bit) ) def find_bit(self, bit: Bit) -> BitLocations: """Find locations in the circuit which can be used to reference a given :obj:`~Bit`. Args: bit (Bit): The bit to locate. Returns: namedtuple(int, List[Tuple(Register, int)]): A 2-tuple. The first element (``index``) contains the index at which the ``Bit`` can be found (in either :obj:`~QuantumCircuit.qubits`, :obj:`~QuantumCircuit.clbits`, depending on its type). The second element (``registers``) is a list of ``(register, index)`` pairs with an entry for each :obj:`~Register` in the circuit which contains the :obj:`~Bit` (and the index in the :obj:`~Register` at which it can be found). Notes: The circuit index of an :obj:`~AncillaQubit` will be its index in :obj:`~QuantumCircuit.qubits`, not :obj:`~QuantumCircuit.ancillas`. Raises: CircuitError: If the supplied :obj:`~Bit` was of an unknown type. CircuitError: If the supplied :obj:`~Bit` could not be found on the circuit. """ try: if isinstance(bit, Qubit): return self._qubit_indices[bit] elif isinstance(bit, Clbit): return self._clbit_indices[bit] else: raise CircuitError(f"Could not locate bit of unknown type: {type(bit)}") except KeyError as err: raise CircuitError( f"Could not locate provided bit: {bit}. Has it been added to the QuantumCircuit?" ) from err def _check_dups(self, qubits: Sequence[Qubit]) -> None: """Raise exception if list of qubits contains duplicates.""" squbits = set(qubits) if len(squbits) != len(qubits): raise CircuitError("duplicate qubit arguments") def to_instruction( self, parameter_map: dict[Parameter, ParameterValueType] | None = None, label: str | None = None, ) -> Instruction: """Create an Instruction out of this circuit. Args: parameter_map(dict): For parameterized circuits, a mapping from parameters in the circuit to parameters to be used in the instruction. If None, existing circuit parameters will also parameterize the instruction. label (str): Optional gate label. Returns: qiskit.circuit.Instruction: a composite instruction encapsulating this circuit (can be decomposed back) """ from qiskit.converters.circuit_to_instruction import circuit_to_instruction return circuit_to_instruction(self, parameter_map, label=label) def to_gate( self, parameter_map: dict[Parameter, ParameterValueType] | None = None, label: str | None = None, ) -> Gate: """Create a Gate out of this circuit. Args: parameter_map(dict): For parameterized circuits, a mapping from parameters in the circuit to parameters to be used in the gate. If None, existing circuit parameters will also parameterize the gate. label (str): Optional gate label. Returns: Gate: a composite gate encapsulating this circuit (can be decomposed back) """ from qiskit.converters.circuit_to_gate import circuit_to_gate return circuit_to_gate(self, parameter_map, label=label) def decompose( self, gates_to_decompose: Type[Gate] | Sequence[Type[Gate]] | Sequence[str] | str | None = None, reps: int = 1, ) -> "QuantumCircuit": """Call a decomposition pass on this circuit, to decompose one level (shallow decompose). Args: gates_to_decompose (type or str or list(type, str)): Optional subset of gates to decompose. Can be a gate type, such as ``HGate``, or a gate name, such as 'h', or a gate label, such as 'My H Gate', or a list of any combination of these. If a gate name is entered, it will decompose all gates with that name, whether the gates have labels or not. Defaults to all gates in circuit. reps (int): Optional number of times the circuit should be decomposed. For instance, ``reps=2`` equals calling ``circuit.decompose().decompose()``. can decompose specific gates specific time Returns: QuantumCircuit: a circuit one level decomposed """ # pylint: disable=cyclic-import from qiskit.transpiler.passes.basis.decompose import Decompose from qiskit.transpiler.passes.synthesis import HighLevelSynthesis from qiskit.converters.circuit_to_dag import circuit_to_dag from qiskit.converters.dag_to_circuit import dag_to_circuit dag = circuit_to_dag(self) dag = HighLevelSynthesis().run(dag) pass_ = Decompose(gates_to_decompose) for _ in range(reps): dag = pass_.run(dag) return dag_to_circuit(dag) def qasm( self, formatted: bool = False, filename: str | None = None, encoding: str | None = None, ) -> str | None: """Return OpenQASM string. Args: formatted (bool): Return formatted Qasm string. filename (str): Save Qasm to file with name 'filename'. encoding (str): Optionally specify the encoding to use for the output file if ``filename`` is specified. By default this is set to the system's default encoding (ie whatever ``locale.getpreferredencoding()`` returns) and can be set to any valid codec or alias from stdlib's `codec module <https://docs.python.org/3/library/codecs.html#standard-encodings>`__ Returns: str: If formatted=False. Raises: MissingOptionalLibraryError: If pygments is not installed and ``formatted`` is ``True``. QASM2ExportError: If circuit has free parameters. QASM2ExportError: If an operation that has no OpenQASM 2 representation is encountered. """ from qiskit.qasm2 import QASM2ExportError # pylint: disable=cyclic-import if self.num_parameters > 0: raise QASM2ExportError( "Cannot represent circuits with unbound parameters in OpenQASM 2." ) existing_gate_names = { "barrier", "measure", "reset", "u3", "u2", "u1", "cx", "id", "u0", "u", "p", "x", "y", "z", "h", "s", "sdg", "t", "tdg", "rx", "ry", "rz", "sx", "sxdg", "cz", "cy", "swap", "ch", "ccx", "cswap", "crx", "cry", "crz", "cu1", "cp", "cu3", "csx", "cu", "rxx", "rzz", "rccx", "rc3x", "c3x", "c3sx", # This is the Qiskit gate name, but the qelib1.inc name is 'c3sqrtx'. "c4x", } # Mapping of instruction name to a pair of the source for a definition, and an OQ2 string # that includes the `gate` or `opaque` statement that defines the gate. gates_to_define: OrderedDict[str, tuple[Instruction, str]] = OrderedDict() regless_qubits = [bit for bit in self.qubits if not self.find_bit(bit).registers] regless_clbits = [bit for bit in self.clbits if not self.find_bit(bit).registers] dummy_registers: list[QuantumRegister | ClassicalRegister] = [] if regless_qubits: dummy_registers.append(QuantumRegister(name="qregless", bits=regless_qubits)) if regless_clbits: dummy_registers.append(ClassicalRegister(name="cregless", bits=regless_clbits)) register_escaped_names: dict[str, QuantumRegister | ClassicalRegister] = {} for regs in (self.qregs, self.cregs, dummy_registers): for reg in regs: register_escaped_names[ _make_unique(_qasm_escape_name(reg.name, "reg_"), register_escaped_names) ] = reg bit_labels: dict[Qubit | Clbit, str] = { bit: "%s[%d]" % (name, idx) for name, register in register_escaped_names.items() for (idx, bit) in enumerate(register) } register_definitions_qasm = "".join( f"{'qreg' if isinstance(reg, QuantumRegister) else 'creg'} {name}[{reg.size}];\n" for name, reg in register_escaped_names.items() ) instruction_calls = [] for instruction in self._data: operation = instruction.operation if operation.name == "measure": qubit = instruction.qubits[0] clbit = instruction.clbits[0] instruction_qasm = f"measure {bit_labels[qubit]} -> {bit_labels[clbit]};" elif operation.name == "reset": instruction_qasm = f"reset {bit_labels[instruction.qubits[0]]};" elif operation.name == "barrier": if not instruction.qubits: # Barriers with no operands are invalid in (strict) OQ2, and the statement # would have no meaning anyway. continue qargs = ",".join(bit_labels[q] for q in instruction.qubits) instruction_qasm = "barrier;" if not qargs else f"barrier {qargs};" else: instruction_qasm = _qasm2_custom_operation_statement( instruction, existing_gate_names, gates_to_define, bit_labels ) instruction_calls.append(instruction_qasm) instructions_qasm = "".join(f"{call}\n" for call in instruction_calls) gate_definitions_qasm = "".join(f"{qasm}\n" for _, qasm in gates_to_define.values()) out = "".join( ( self.header, "\n", self.extension_lib, "\n", gate_definitions_qasm, register_definitions_qasm, instructions_qasm, ) ) if filename: with open(filename, "w+", encoding=encoding) as file: file.write(out) if formatted: _optionals.HAS_PYGMENTS.require_now("formatted OpenQASM 2 output") import pygments from pygments.formatters import ( # pylint: disable=no-name-in-module Terminal256Formatter, ) from qiskit.qasm.pygments import OpenQASMLexer from qiskit.qasm.pygments import QasmTerminalStyle code = pygments.highlight( out, OpenQASMLexer(), Terminal256Formatter(style=QasmTerminalStyle) ) print(code) return None return out def draw( self, output: str | None = None, scale: float | None = None, filename: str | None = None, style: dict | str | None = None, interactive: bool = False, plot_barriers: bool = True, reverse_bits: bool = None, justify: str | None = None, vertical_compression: str | None = "medium", idle_wires: bool = True, with_layout: bool = True, fold: int | None = None, # The type of ax is matplotlib.axes.Axes, but this is not a fixed dependency, so cannot be # safely forward-referenced. ax: Any | None = None, initial_state: bool = False, cregbundle: bool = None, wire_order: list = None, ): """Draw the quantum circuit. Use the output parameter to choose the drawing format: **text**: ASCII art TextDrawing that can be printed in the console. **mpl**: images with color rendered purely in Python using matplotlib. **latex**: high-quality images compiled via latex. **latex_source**: raw uncompiled latex output. .. warning:: Support for :class:`~.expr.Expr` nodes in conditions and :attr:`.SwitchCaseOp.target` fields is preliminary and incomplete. The ``text`` and ``mpl`` drawers will make a best-effort attempt to show data dependencies, but the LaTeX-based drawers will skip these completely. Args: output (str): select the output method to use for drawing the circuit. Valid choices are ``text``, ``mpl``, ``latex``, ``latex_source``. By default the `text` drawer is used unless the user config file (usually ``~/.qiskit/settings.conf``) has an alternative backend set as the default. For example, ``circuit_drawer = latex``. If the output kwarg is set, that backend will always be used over the default in the user config file. scale (float): scale of image to draw (shrink if < 1.0). Only used by the `mpl`, `latex` and `latex_source` outputs. Defaults to 1.0. filename (str): file path to save image to. Defaults to None. style (dict or str): dictionary of style or file name of style json file. This option is only used by the `mpl` or `latex` output type. If `style` is a str, it is used as the path to a json file which contains a style dict. The file will be opened, parsed, and then any style elements in the dict will replace the default values in the input dict. A file to be loaded must end in ``.json``, but the name entered here can omit ``.json``. For example, ``style='iqx.json'`` or ``style='iqx'``. If `style` is a dict and the ``'name'`` key is set, that name will be used to load a json file, followed by loading the other items in the style dict. For example, ``style={'name': 'iqx'}``. If `style` is not a str and `name` is not a key in the style dict, then the default value from the user config file (usually ``~/.qiskit/settings.conf``) will be used, for example, ``circuit_mpl_style = iqx``. If none of these are set, the `default` style will be used. The search path for style json files can be specified in the user config, for example, ``circuit_mpl_style_path = /home/user/styles:/home/user``. See: :class:`~qiskit.visualization.qcstyle.DefaultStyle` for more information on the contents. interactive (bool): when set to true, show the circuit in a new window (for `mpl` this depends on the matplotlib backend being used supporting this). Note when used with either the `text` or the `latex_source` output type this has no effect and will be silently ignored. Defaults to False. reverse_bits (bool): when set to True, reverse the bit order inside registers for the output visualization. Defaults to False unless the user config file (usually ``~/.qiskit/settings.conf``) has an alternative value set. For example, ``circuit_reverse_bits = True``. plot_barriers (bool): enable/disable drawing barriers in the output circuit. Defaults to True. justify (string): options are ``left``, ``right`` or ``none``. If anything else is supplied, it defaults to left justified. It refers to where gates should be placed in the output circuit if there is an option. ``none`` results in each gate being placed in its own column. vertical_compression (string): ``high``, ``medium`` or ``low``. It merges the lines generated by the `text` output so the drawing will take less vertical room. Default is ``medium``. Only used by the `text` output, will be silently ignored otherwise. idle_wires (bool): include idle wires (wires with no circuit elements) in output visualization. Default is True. with_layout (bool): include layout information, with labels on the physical layout. Default is True. fold (int): sets pagination. It can be disabled using -1. In `text`, sets the length of the lines. This is useful when the drawing does not fit in the console. If None (default), it will try to guess the console width using ``shutil.get_terminal_size()``. However, if running in jupyter, the default line length is set to 80 characters. In `mpl`, it is the number of (visual) layers before folding. Default is 25. ax (matplotlib.axes.Axes): Only used by the `mpl` backend. An optional Axes object to be used for the visualization output. If none is specified, a new matplotlib Figure will be created and used. Additionally, if specified there will be no returned Figure since it is redundant. initial_state (bool): Optional. Adds ``|0>`` in the beginning of the wire. Default is False. cregbundle (bool): Optional. If set True, bundle classical registers. Default is True, except for when ``output`` is set to ``"text"``. wire_order (list): Optional. A list of integers used to reorder the display of the bits. The list must have an entry for every bit with the bits in the range 0 to (``num_qubits`` + ``num_clbits``). Returns: :class:`.TextDrawing` or :class:`matplotlib.figure` or :class:`PIL.Image` or :class:`str`: * `TextDrawing` (output='text') A drawing that can be printed as ascii art. * `matplotlib.figure.Figure` (output='mpl') A matplotlib figure object for the circuit diagram. * `PIL.Image` (output='latex') An in-memory representation of the image of the circuit diagram. * `str` (output='latex_source') The LaTeX source code for visualizing the circuit diagram. Raises: VisualizationError: when an invalid output method is selected ImportError: when the output methods requires non-installed libraries. Example: .. plot:: :include-source: 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'}) """ # pylint: disable=cyclic-import from qiskit.visualization import circuit_drawer return circuit_drawer( self, scale=scale, filename=filename, style=style, output=output, interactive=interactive, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify, vertical_compression=vertical_compression, idle_wires=idle_wires, with_layout=with_layout, fold=fold, ax=ax, initial_state=initial_state, cregbundle=cregbundle, wire_order=wire_order, ) def size( self, filter_function: Callable[..., int] = lambda x: not getattr( x.operation, "_directive", False ), ) -> int: """Returns total number of instructions in circuit. Args: filter_function (callable): a function to filter out some instructions. Should take as input a tuple of (Instruction, list(Qubit), list(Clbit)). By default filters out "directives", such as barrier or snapshot. Returns: int: Total number of gate operations. """ return sum(map(filter_function, self._data)) def depth( self, filter_function: Callable[..., int] = lambda x: not getattr( x.operation, "_directive", False ), ) -> int: """Return circuit depth (i.e., length of critical path). Args: filter_function (callable): A function to filter instructions. Should take as input a tuple of (Instruction, list(Qubit), list(Clbit)). Instructions for which the function returns False are ignored in the computation of the circuit depth. By default filters out "directives", such as barrier or snapshot. Returns: int: Depth of circuit. Notes: The circuit depth and the DAG depth need not be the same. """ # Assign each bit in the circuit a unique integer # to index into op_stack. bit_indices: dict[Qubit | Clbit, int] = { bit: idx for idx, bit in enumerate(self.qubits + self.clbits) } # If no bits, return 0 if not bit_indices: return 0 # A list that holds the height of each qubit # and classical bit. op_stack = [0] * len(bit_indices) # Here we are playing a modified version of # Tetris where we stack gates, but multi-qubit # gates, or measurements have a block for each # qubit or cbit that are connected by a virtual # line so that they all stacked at the same depth. # Conditional gates act on all cbits in the register # they are conditioned on. # The max stack height is the circuit depth. for instruction in self._data: levels = [] reg_ints = [] for ind, reg in enumerate(instruction.qubits + instruction.clbits): # Add to the stacks of the qubits and # cbits used in the gate. reg_ints.append(bit_indices[reg]) if filter_function(instruction): levels.append(op_stack[reg_ints[ind]] + 1) else: levels.append(op_stack[reg_ints[ind]]) # Assuming here that there is no conditional # snapshots or barriers ever. if getattr(instruction.operation, "condition", None): # Controls operate over all bits of a classical register # or over a single bit if isinstance(instruction.operation.condition[0], Clbit): condition_bits = [instruction.operation.condition[0]] else: condition_bits = instruction.operation.condition[0] for cbit in condition_bits: idx = bit_indices[cbit] if idx not in reg_ints: reg_ints.append(idx) levels.append(op_stack[idx] + 1) max_level = max(levels) for ind in reg_ints: op_stack[ind] = max_level return max(op_stack) def width(self) -> int: """Return number of qubits plus clbits in circuit. Returns: int: Width of circuit. """ return len(self.qubits) + len(self.clbits) @property def num_qubits(self) -> int: """Return number of qubits.""" return len(self.qubits) @property def num_ancillas(self) -> int: """Return the number of ancilla qubits.""" return len(self.ancillas) @property def num_clbits(self) -> int: """Return number of classical bits.""" return len(self.clbits) # The stringified return type is because OrderedDict can't be subscripted before Python 3.9, and # typing.OrderedDict wasn't added until 3.7.2. It can be turned into a proper type once 3.6 # support is dropped. def count_ops(self) -> "OrderedDict[Instruction, int]": """Count each operation kind in the circuit. Returns: OrderedDict: a breakdown of how many operations of each kind, sorted by amount. """ count_ops: dict[Instruction, int] = {} for instruction in self._data: count_ops[instruction.operation.name] = count_ops.get(instruction.operation.name, 0) + 1 return OrderedDict(sorted(count_ops.items(), key=lambda kv: kv[1], reverse=True)) def num_nonlocal_gates(self) -> int: """Return number of non-local gates (i.e. involving 2+ qubits). Conditional nonlocal gates are also included. """ multi_qubit_gates = 0 for instruction in self._data: if instruction.operation.num_qubits > 1 and not getattr( instruction.operation, "_directive", False ): multi_qubit_gates += 1 return multi_qubit_gates def get_instructions(self, name: str) -> list[CircuitInstruction]: """Get instructions matching name. Args: name (str): The name of instruction to. Returns: list(tuple): list of (instruction, qargs, cargs). """ return [match for match in self._data if match.operation.name == name] def num_connected_components(self, unitary_only: bool = False) -> int: """How many non-entangled subcircuits can the circuit be factored to. Args: unitary_only (bool): Compute only unitary part of graph. Returns: int: Number of connected components in circuit. """ # Convert registers to ints (as done in depth). bits = self.qubits if unitary_only else (self.qubits + self.clbits) bit_indices: dict[Qubit | Clbit, int] = {bit: idx for idx, bit in enumerate(bits)} # Start with each qubit or cbit being its own subgraph. sub_graphs = [[bit] for bit in range(len(bit_indices))] num_sub_graphs = len(sub_graphs) # Here we are traversing the gates and looking to see # which of the sub_graphs the gate joins together. for instruction in self._data: if unitary_only: args = instruction.qubits num_qargs = len(args) else: args = instruction.qubits + instruction.clbits num_qargs = len(args) + ( 1 if getattr(instruction.operation, "condition", None) else 0 ) if num_qargs >= 2 and not getattr(instruction.operation, "_directive", False): graphs_touched = [] num_touched = 0 # Controls necessarily join all the cbits in the # register that they use. if not unitary_only: for bit in instruction.operation.condition_bits: idx = bit_indices[bit] for k in range(num_sub_graphs): if idx in sub_graphs[k]: graphs_touched.append(k) break for item in args: reg_int = bit_indices[item] for k in range(num_sub_graphs): if reg_int in sub_graphs[k]: if k not in graphs_touched: graphs_touched.append(k) break graphs_touched = list(set(graphs_touched)) num_touched = len(graphs_touched) # If the gate touches more than one subgraph # join those graphs together and return # reduced number of subgraphs if num_touched > 1: connections = [] for idx in graphs_touched: connections.extend(sub_graphs[idx]) _sub_graphs = [] for idx in range(num_sub_graphs): if idx not in graphs_touched: _sub_graphs.append(sub_graphs[idx]) _sub_graphs.append(connections) sub_graphs = _sub_graphs num_sub_graphs -= num_touched - 1 # Cannot go lower than one so break if num_sub_graphs == 1: break return num_sub_graphs def num_unitary_factors(self) -> int: """Computes the number of tensor factors in the unitary (quantum) part of the circuit only. """ return self.num_connected_components(unitary_only=True) def num_tensor_factors(self) -> int: """Computes the number of tensor factors in the unitary (quantum) part of the circuit only. Notes: This is here for backwards compatibility, and will be removed in a future release of Qiskit. You should call `num_unitary_factors` instead. """ return self.num_unitary_factors() def copy(self, name: str | None = None) -> "QuantumCircuit": """Copy the circuit. Args: name (str): name to be given to the copied circuit. If None, then the name stays the same. Returns: QuantumCircuit: a deepcopy of the current circuit, with the specified name """ cpy = self.copy_empty_like(name) operation_copies = { id(instruction.operation): instruction.operation.copy() for instruction in self._data } cpy._parameter_table = ParameterTable( { param: ParameterReferences( (operation_copies[id(operation)], param_index) for operation, param_index in self._parameter_table[param] ) for param in self._parameter_table } ) cpy._data = [ instruction.replace(operation=operation_copies[id(instruction.operation)]) for instruction in self._data ] return cpy def copy_empty_like(self, name: str | None = None) -> "QuantumCircuit": """Return a copy of self with the same structure but empty. That structure includes: * name, calibrations and other metadata * global phase * all the qubits and clbits, including the registers Args: name (str): Name for the copied circuit. If None, then the name stays the same. Returns: QuantumCircuit: An empty copy of self. """ if not (name is None or isinstance(name, str)): raise TypeError( f"invalid name for a circuit: '{name}'. The name must be a string or 'None'." ) cpy = copy.copy(self) # copy registers correctly, in copy.copy they are only copied via reference cpy.qregs = self.qregs.copy() cpy.cregs = self.cregs.copy() cpy._qubits = self._qubits.copy() cpy._ancillas = self._ancillas.copy() cpy._clbits = self._clbits.copy() cpy._qubit_indices = self._qubit_indices.copy() cpy._clbit_indices = self._clbit_indices.copy() cpy._parameter_table = ParameterTable() cpy._data = [] cpy._calibrations = copy.deepcopy(self._calibrations) cpy._metadata = copy.deepcopy(self._metadata) if name: cpy.name = name return cpy def clear(self) -> None: """Clear all instructions in self. Clearing the circuits will keep the metadata and calibrations. """ self._data.clear() self._parameter_table.clear() def _create_creg(self, length: int, name: str) -> ClassicalRegister: """Creates a creg, checking if ClassicalRegister with same name exists""" if name in [creg.name for creg in self.cregs]: save_prefix = ClassicalRegister.prefix ClassicalRegister.prefix = name new_creg = ClassicalRegister(length) ClassicalRegister.prefix = save_prefix else: new_creg = ClassicalRegister(length, name) return new_creg def _create_qreg(self, length: int, name: str) -> QuantumRegister: """Creates a qreg, checking if QuantumRegister with same name exists""" if name in [qreg.name for qreg in self.qregs]: save_prefix = QuantumRegister.prefix QuantumRegister.prefix = name new_qreg = QuantumRegister(length) QuantumRegister.prefix = save_prefix else: new_qreg = QuantumRegister(length, name) return new_qreg def reset(self, qubit: QubitSpecifier) -> InstructionSet: """Reset the quantum bit(s) to their default state. Args: qubit: qubit(s) to reset. Returns: qiskit.circuit.InstructionSet: handle to the added instruction. """ return self.append(Reset(), [qubit], []) def measure(self, qubit: QubitSpecifier, cbit: ClbitSpecifier) -> InstructionSet: r"""Measure a quantum bit (``qubit``) in the Z basis into a classical bit (``cbit``). When a quantum state is measured, a qubit is projected in the computational (Pauli Z) basis to either :math:`\lvert 0 \rangle` or :math:`\lvert 1 \rangle`. The classical bit ``cbit`` indicates the result of that projection as a ``0`` or a ``1`` respectively. This operation is non-reversible. Args: qubit: qubit(s) to measure. cbit: classical bit(s) to place the measurement result(s) in. Returns: qiskit.circuit.InstructionSet: handle to the added instructions. Raises: CircuitError: if arguments have bad format. Examples: In this example, a qubit is measured and the result of that measurement is stored in the classical bit (usually expressed in diagrams as a double line): .. code-block:: from qiskit import QuantumCircuit circuit = QuantumCircuit(1, 1) circuit.h(0) circuit.measure(0, 0) circuit.draw() .. parsed-literal:: ┌───┐┌─┐ q: ┤ H ├┤M├ └───┘└╥┘ c: 1/══════╩═ 0 It is possible to call ``measure`` with lists of ``qubits`` and ``cbits`` as a shortcut for one-to-one measurement. These two forms produce identical results: .. code-block:: circuit = QuantumCircuit(2, 2) circuit.measure([0,1], [0,1]) .. code-block:: circuit = QuantumCircuit(2, 2) circuit.measure(0, 0) circuit.measure(1, 1) Instead of lists, you can use :class:`~qiskit.circuit.QuantumRegister` and :class:`~qiskit.circuit.ClassicalRegister` under the same logic. .. code-block:: from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister qreg = QuantumRegister(2, "qreg") creg = ClassicalRegister(2, "creg") circuit = QuantumCircuit(qreg, creg) circuit.measure(qreg, creg) This is equivalent to: .. code-block:: circuit = QuantumCircuit(qreg, creg) circuit.measure(qreg[0], creg[0]) circuit.measure(qreg[1], creg[1]) """ return self.append(Measure(), [qubit], [cbit]) def measure_active(self, inplace: bool = True) -> Optional["QuantumCircuit"]: """Adds measurement to all non-idle qubits. Creates a new ClassicalRegister with a size equal to the number of non-idle qubits being measured. Returns a new circuit with measurements if `inplace=False`. Args: inplace (bool): All measurements inplace or return new circuit. Returns: QuantumCircuit: Returns circuit with measurements when `inplace = False`. """ from qiskit.converters.circuit_to_dag import circuit_to_dag if inplace: circ = self else: circ = self.copy() dag = circuit_to_dag(circ) qubits_to_measure = [qubit for qubit in circ.qubits if qubit not in dag.idle_wires()] new_creg = circ._create_creg(len(qubits_to_measure), "measure") circ.add_register(new_creg) circ.barrier() circ.measure(qubits_to_measure, new_creg) if not inplace: return circ else: return None def measure_all( self, inplace: bool = True, add_bits: bool = True ) -> Optional["QuantumCircuit"]: """Adds measurement to all qubits. By default, adds new classical bits in a :obj:`.ClassicalRegister` to store these measurements. If ``add_bits=False``, the results of the measurements will instead be stored in the already existing classical bits, with qubit ``n`` being measured into classical bit ``n``. Returns a new circuit with measurements if ``inplace=False``. Args: inplace (bool): All measurements inplace or return new circuit. add_bits (bool): Whether to add new bits to store the results. Returns: QuantumCircuit: Returns circuit with measurements when ``inplace=False``. Raises: CircuitError: if ``add_bits=False`` but there are not enough classical bits. """ if inplace: circ = self else: circ = self.copy() if add_bits: new_creg = circ._create_creg(len(circ.qubits), "meas") circ.add_register(new_creg) circ.barrier() circ.measure(circ.qubits, new_creg) else: if len(circ.clbits) < len(circ.qubits): raise CircuitError( "The number of classical bits must be equal or greater than " "the number of qubits." ) circ.barrier() circ.measure(circ.qubits, circ.clbits[0 : len(circ.qubits)]) if not inplace: return circ else: return None def remove_final_measurements(self, inplace: bool = True) -> Optional["QuantumCircuit"]: """Removes final measurements and barriers on all qubits if they are present. Deletes the classical registers that were used to store the values from these measurements that become idle as a result of this operation, and deletes classical bits that are referenced only by removed registers, or that aren't referenced at all but have become idle as a result of this operation. Measurements and barriers are considered final if they are followed by no other operations (aside from other measurements or barriers.) Args: inplace (bool): All measurements removed inplace or return new circuit. Returns: QuantumCircuit: Returns the resulting circuit when ``inplace=False``, else None. """ # pylint: disable=cyclic-import from qiskit.transpiler.passes import RemoveFinalMeasurements from qiskit.converters import circuit_to_dag if inplace: circ = self else: circ = self.copy() dag = circuit_to_dag(circ) remove_final_meas = RemoveFinalMeasurements() new_dag = remove_final_meas.run(dag) kept_cregs = set(new_dag.cregs.values()) kept_clbits = set(new_dag.clbits) # Filter only cregs/clbits still in new DAG, preserving original circuit order cregs_to_add = [creg for creg in circ.cregs if creg in kept_cregs] clbits_to_add = [clbit for clbit in circ._clbits if clbit in kept_clbits] # Clear cregs and clbits circ.cregs = [] circ._clbits = [] circ._clbit_indices = {} # We must add the clbits first to preserve the original circuit # order. This way, add_register never adds clbits and just # creates registers that point to them. circ.add_bits(clbits_to_add) for creg in cregs_to_add: circ.add_register(creg) # Clear instruction info circ.data.clear() circ._parameter_table.clear() # Set circ instructions to match the new DAG for node in new_dag.topological_op_nodes(): # Get arguments for classical condition (if any) inst = node.op.copy() circ.append(inst, node.qargs, node.cargs) if not inplace: return circ else: return None @staticmethod def from_qasm_file(path: str) -> "QuantumCircuit": """Take in a QASM file and generate a QuantumCircuit object. Args: path (str): Path to the file for a QASM program Return: QuantumCircuit: The QuantumCircuit object for the input QASM See also: :func:`.qasm2.load`: the complete interface to the OpenQASM 2 importer. """ # pylint: disable=cyclic-import from qiskit import qasm2 return qasm2.load( path, include_path=qasm2.LEGACY_INCLUDE_PATH, custom_instructions=qasm2.LEGACY_CUSTOM_INSTRUCTIONS, custom_classical=qasm2.LEGACY_CUSTOM_CLASSICAL, strict=False, ) @staticmethod def from_qasm_str(qasm_str: str) -> "QuantumCircuit": """Take in a QASM string and generate a QuantumCircuit object. Args: qasm_str (str): A QASM program string Return: QuantumCircuit: The QuantumCircuit object for the input QASM See also: :func:`.qasm2.loads`: the complete interface to the OpenQASM 2 importer. """ # pylint: disable=cyclic-import from qiskit import qasm2 return qasm2.loads( qasm_str, include_path=qasm2.LEGACY_INCLUDE_PATH, custom_instructions=qasm2.LEGACY_CUSTOM_INSTRUCTIONS, custom_classical=qasm2.LEGACY_CUSTOM_CLASSICAL, strict=False, ) @property def global_phase(self) -> ParameterValueType: """Return the global phase of the circuit in radians.""" return self._global_phase @global_phase.setter def global_phase(self, angle: ParameterValueType): """Set the phase of the circuit. Args: angle (float, ParameterExpression): radians """ if isinstance(angle, ParameterExpression) and angle.parameters: self._global_phase = angle else: # Set the phase to the [0, 2π) interval angle = float(angle) if not angle: self._global_phase = 0 else: self._global_phase = angle % (2 * np.pi) @property def parameters(self) -> ParameterView: """The parameters defined in the circuit. This attribute returns the :class:`.Parameter` objects in the circuit sorted alphabetically. Note that parameters instantiated with a :class:`.ParameterVector` are still sorted numerically. Examples: The snippet below shows that insertion order of parameters does not matter. .. code-block:: python >>> from qiskit.circuit import QuantumCircuit, Parameter >>> a, b, elephant = Parameter("a"), Parameter("b"), Parameter("elephant") >>> circuit = QuantumCircuit(1) >>> circuit.rx(b, 0) >>> circuit.rz(elephant, 0) >>> circuit.ry(a, 0) >>> circuit.parameters # sorted alphabetically! ParameterView([Parameter(a), Parameter(b), Parameter(elephant)]) Bear in mind that alphabetical sorting might be unintuitive when it comes to numbers. The literal "10" comes before "2" in strict alphabetical sorting. .. code-block:: python >>> from qiskit.circuit import QuantumCircuit, Parameter >>> angles = [Parameter("angle_1"), Parameter("angle_2"), Parameter("angle_10")] >>> circuit = QuantumCircuit(1) >>> circuit.u(*angles, 0) >>> circuit.draw() ┌─────────────────────────────┐ q: ┤ U(angle_1,angle_2,angle_10) ├ └─────────────────────────────┘ >>> circuit.parameters ParameterView([Parameter(angle_1), Parameter(angle_10), Parameter(angle_2)]) To respect numerical sorting, a :class:`.ParameterVector` can be used. .. code-block:: python >>> from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector >>> x = ParameterVector("x", 12) >>> circuit = QuantumCircuit(1) >>> for x_i in x: ... circuit.rx(x_i, 0) >>> circuit.parameters ParameterView([ ParameterVectorElement(x[0]), ParameterVectorElement(x[1]), ParameterVectorElement(x[2]), ParameterVectorElement(x[3]), ..., ParameterVectorElement(x[11]) ]) Returns: The sorted :class:`.Parameter` objects in the circuit. """ # parameters from gates if self._parameters is None: self._parameters = sort_parameters(self._unsorted_parameters()) # return as parameter view, which implements the set and list interface return ParameterView(self._parameters) @property def num_parameters(self) -> int: """The number of parameter objects in the circuit.""" return len(self._unsorted_parameters()) def _unsorted_parameters(self) -> set[Parameter]: """Efficiently get all parameters in the circuit, without any sorting overhead.""" parameters = set(self._parameter_table) if isinstance(self.global_phase, ParameterExpression): parameters.update(self.global_phase.parameters) return parameters @overload def assign_parameters( self, parameters: Union[Mapping[Parameter, ParameterValueType], Sequence[ParameterValueType]], inplace: Literal[False] = ..., *, flat_input: bool = ..., strict: bool = ..., ) -> "QuantumCircuit": ... @overload def assign_parameters( self, parameters: Union[Mapping[Parameter, ParameterValueType], Sequence[ParameterValueType]], inplace: Literal[True] = ..., *, flat_input: bool = ..., strict: bool = ..., ) -> None: ... def assign_parameters( # pylint: disable=missing-raises-doc self, parameters: Union[Mapping[Parameter, ParameterValueType], Sequence[ParameterValueType]], inplace: bool = False, *, flat_input: bool = False, strict: bool = True, ) -> Optional["QuantumCircuit"]: """Assign parameters to new parameters or values. If ``parameters`` is passed as a dictionary, the keys must be :class:`.Parameter` instances in the current circuit. The values of the dictionary can either be numeric values or new parameter objects. If ``parameters`` is passed as a list or array, the elements are assigned to the current parameters in the order of :attr:`parameters` which is sorted alphabetically (while respecting the ordering in :class:`.ParameterVector` objects). The values can be assigned to the current circuit object or to a copy of it. Args: parameters: Either a dictionary or iterable specifying the new parameter values. inplace: If False, a copy of the circuit with the bound parameters is returned. If True the circuit instance itself is modified. flat_input: If ``True`` and ``parameters`` is a mapping type, it is assumed to be exactly a mapping of ``{parameter: value}``. By default (``False``), the mapping may also contain :class:`.ParameterVector` keys that point to a corresponding sequence of values, and these will be unrolled during the mapping. strict: If ``False``, any parameters given in the mapping that are not used in the circuit will be ignored. If ``True`` (the default), an error will be raised indicating a logic error. Raises: CircuitError: If parameters is a dict and contains parameters not present in the circuit. ValueError: If parameters is a list/array and the length mismatches the number of free parameters in the circuit. Returns: A copy of the circuit with bound parameters if ``inplace`` is False, otherwise None. Examples: Create a parameterized circuit and assign the parameters in-place. .. plot:: :include-source: from qiskit.circuit import QuantumCircuit, Parameter circuit = QuantumCircuit(2) params = [Parameter('A'), Parameter('B'), Parameter('C')] circuit.ry(params[0], 0) circuit.crx(params[1], 0, 1) circuit.draw('mpl') circuit.assign_parameters({params[0]: params[2]}, inplace=True) circuit.draw('mpl') Bind the values out-of-place by list and get a copy of the original circuit. .. plot:: :include-source: from qiskit.circuit import QuantumCircuit, ParameterVector circuit = QuantumCircuit(2) params = ParameterVector('P', 2) circuit.ry(params[0], 0) circuit.crx(params[1], 0, 1) bound_circuit = circuit.assign_parameters([1, 2]) bound_circuit.draw('mpl') circuit.draw('mpl') """ if inplace: target = self else: target = self.copy() target._increment_instances() target._name_update() # Normalise the inputs into simple abstract interfaces, so we've dispatched the "iteration" # logic in one place at the start of the function. This lets us do things like calculate # and cache expensive properties for (e.g.) the sequence format only if they're used; for # many large, close-to-hardware circuits, we won't need the extra handling for # `global_phase` or recursive definition binding. # # During normalisation, be sure to reference 'parameters' and related things from 'self' not # 'target' so we can take advantage of any caching we might be doing. if isinstance(parameters, dict): raw_mapping = parameters if flat_input else self._unroll_param_dict(parameters) our_parameters = self._unsorted_parameters() if strict and (extras := raw_mapping.keys() - our_parameters): raise CircuitError( f"Cannot bind parameters ({', '.join(str(x) for x in extras)}) not present in" " the circuit." ) parameter_binds = _ParameterBindsDict(raw_mapping, our_parameters) else: our_parameters = self.parameters if len(parameters) != len(our_parameters): raise ValueError( "Mismatching number of values and parameters. For partial binding " "please pass a dictionary of {parameter: value} pairs." ) parameter_binds = _ParameterBindsSequence(our_parameters, parameters) # Clear out the parameter table for the relevant entries, since we'll be binding those. # Any new references to parameters are reinserted as part of the bind. target._parameters = None # This is deliberately eager, because we want the side effect of clearing the table. all_references = [ (parameter, value, target._parameter_table.pop(parameter, ())) for parameter, value in parameter_binds.items() ] seen_operations = {} # The meat of the actual binding for regular operations. for to_bind, bound_value, references in all_references: update_parameters = ( tuple(bound_value.parameters) if isinstance(bound_value, ParameterExpression) else () ) for operation, index in references: seen_operations[id(operation)] = operation assignee = operation.params[index] if isinstance(assignee, ParameterExpression): new_parameter = assignee.assign(to_bind, bound_value) for parameter in update_parameters: if parameter not in target._parameter_table: target._parameter_table[parameter] = ParameterReferences(()) target._parameter_table[parameter].add((operation, index)) if not new_parameter.parameters: if new_parameter.is_real(): new_parameter = ( int(new_parameter) if new_parameter._symbol_expr.is_integer else float(new_parameter) ) else: new_parameter = complex(new_parameter) new_parameter = operation.validate_parameter(new_parameter) elif isinstance(assignee, QuantumCircuit): new_parameter = assignee.assign_parameters( {to_bind: bound_value}, inplace=False, flat_input=True ) else: raise RuntimeError( # pragma: no cover f"Saw an unknown type during symbolic binding: {assignee}." " This may indicate an internal logic error in symbol tracking." ) operation.params[index] = new_parameter # After we've been through everything at the top level, make a single visit to each # operation we've seen, rebinding its definition if necessary. for operation in seen_operations.values(): if ( definition := getattr(operation, "_definition", None) ) is not None and definition.num_parameters: definition.assign_parameters( parameter_binds.mapping, inplace=True, flat_input=True, strict=False ) if isinstance(target.global_phase, ParameterExpression): new_phase = target.global_phase for parameter in new_phase.parameters & parameter_binds.mapping.keys(): new_phase = new_phase.assign(parameter, parameter_binds.mapping[parameter]) target.global_phase = new_phase # Finally, assign the parameters inside any of the calibrations. We don't track these in # the `ParameterTable`, so we manually reconstruct things. def map_calibration(qubits, parameters, schedule): modified = False new_parameters = list(parameters) for i, parameter in enumerate(new_parameters): if not isinstance(parameter, ParameterExpression): continue if not (contained := parameter.parameters & parameter_binds.mapping.keys()): continue for to_bind in contained: parameter = parameter.assign(to_bind, parameter_binds.mapping[to_bind]) if not parameter.parameters: parameter = ( int(parameter) if parameter._symbol_expr.is_integer else float(parameter) ) new_parameters[i] = parameter modified = True if modified: schedule.assign_parameters(parameter_binds.mapping) return (qubits, tuple(new_parameters)), schedule target._calibrations = defaultdict( dict, ( ( gate, dict( map_calibration(qubits, parameters, schedule) for (qubits, parameters), schedule in calibrations.items() ), ) for gate, calibrations in target._calibrations.items() ), ) return None if inplace else target @staticmethod def _unroll_param_dict( parameter_binds: Mapping[Parameter, ParameterValueType] ) -> Mapping[Parameter, ParameterValueType]: out = {} for parameter, value in parameter_binds.items(): if isinstance(parameter, ParameterVector): if len(parameter) != len(value): raise CircuitError( f"Parameter vector '{parameter.name}' has length {len(parameter)}," f" but was assigned to {len(value)} values." ) out.update(zip(parameter, value)) else: out[parameter] = value return out def bind_parameters( self, values: Union[Mapping[Parameter, float], Sequence[float]] ) -> "QuantumCircuit": """Assign numeric parameters to values yielding a new circuit. If the values are given as list or array they are bound to the circuit in the order of :attr:`parameters` (see the docstring for more details). To assign new Parameter objects or bind the values in-place, without yielding a new circuit, use the :meth:`assign_parameters` method. Args: values: ``{parameter: value, ...}`` or ``[value1, value2, ...]`` Raises: CircuitError: If values is a dict and contains parameters not present in the circuit. TypeError: If values contains a ParameterExpression. Returns: Copy of self with assignment substitution. """ if isinstance(values, dict): if any(isinstance(value, ParameterExpression) for value in values.values()): raise TypeError( "Found ParameterExpression in values; use assign_parameters() instead." ) return self.assign_parameters(values) else: if any(isinstance(value, ParameterExpression) for value in values): raise TypeError( "Found ParameterExpression in values; use assign_parameters() instead." ) return self.assign_parameters(values) def barrier(self, *qargs: QubitSpecifier, label=None) -> InstructionSet: """Apply :class:`~.library.Barrier`. If ``qargs`` is empty, applies to all qubits in the circuit. Args: qargs (QubitSpecifier): Specification for one or more qubit arguments. label (str): The string label of the barrier. Returns: qiskit.circuit.InstructionSet: handle to the added instructions. """ from .barrier import Barrier qubits: list[QubitSpecifier] = [] if not qargs: # None qubits.extend(self.qubits) for qarg in qargs: if isinstance(qarg, QuantumRegister): qubits.extend([qarg[j] for j in range(qarg.size)]) elif isinstance(qarg, list): qubits.extend(qarg) elif isinstance(qarg, range): qubits.extend(list(qarg)) elif isinstance(qarg, slice): qubits.extend(self.qubits[qarg]) else: qubits.append(qarg) return self.append(Barrier(len(qubits), label=label), qubits, []) def delay( self, duration: ParameterValueType, qarg: QubitSpecifier | None = None, unit: str = "dt", ) -> InstructionSet: """Apply :class:`~.circuit.Delay`. If qarg is ``None``, applies to all qubits. When applying to multiple qubits, delays with the same duration will be created. Args: duration (int or float or ParameterExpression): duration of the delay. qarg (Object): qubit argument to apply this delay. unit (str): unit of the duration. Supported units: ``'s'``, ``'ms'``, ``'us'``, ``'ns'``, ``'ps'``, and ``'dt'``. Default is ``'dt'``, i.e. integer time unit depending on the target backend. Returns: qiskit.circuit.InstructionSet: handle to the added instructions. Raises: CircuitError: if arguments have bad format. """ qubits: list[QubitSpecifier] = [] if qarg is None: # -> apply delays to all qubits for q in self.qubits: qubits.append(q) else: if isinstance(qarg, QuantumRegister): qubits.extend([qarg[j] for j in range(qarg.size)]) elif isinstance(qarg, list): qubits.extend(qarg) elif isinstance(qarg, (range, tuple)): qubits.extend(list(qarg)) elif isinstance(qarg, slice): qubits.extend(self.qubits[qarg]) else: qubits.append(qarg) instructions = InstructionSet(resource_requester=self._resolve_classical_resource) for q in qubits: inst: tuple[ Instruction, Sequence[QubitSpecifier] | None, Sequence[ClbitSpecifier] | None ] = (Delay(duration, unit), [q], []) self.append(*inst) instructions.add(*inst) return instructions def h(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.HGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.h import HGate return self.append(HGate(), [qubit], []) def ch( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CHGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.h import CHGate return self.append( CHGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def i(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.IGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.i import IGate return self.append(IGate(), [qubit], []) def id(self, qubit: QubitSpecifier) -> InstructionSet: # pylint: disable=invalid-name """Apply :class:`~qiskit.circuit.library.IGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. See Also: QuantumCircuit.i: the same function. """ return self.i(qubit) def ms(self, theta: ParameterValueType, qubits: Sequence[QubitSpecifier]) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.MSGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. qubits: The qubits to apply the gate to. Returns: A handle to the instructions created. """ # pylint: disable=cyclic-import from .library.generalized_gates.gms import MSGate return self.append(MSGate(len(qubits), theta), qubits) def p(self, theta: ParameterValueType, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.PhaseGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: THe angle of the rotation. qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.p import PhaseGate return self.append(PhaseGate(theta), [qubit], []) def cp( self, theta: ParameterValueType, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CPhaseGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.p import CPhaseGate return self.append( CPhaseGate(theta, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def mcp( self, lam: ParameterValueType, control_qubits: Sequence[QubitSpecifier], target_qubit: QubitSpecifier, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.MCPhaseGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: lam: The angle of the rotation. control_qubits: The qubits used as the controls. target_qubit: The qubit(s) targeted by the gate. Returns: A handle to the instructions created. """ from .library.standard_gates.p import MCPhaseGate num_ctrl_qubits = len(control_qubits) return self.append( MCPhaseGate(lam, num_ctrl_qubits), control_qubits[:] + [target_qubit], [] ) def r( self, theta: ParameterValueType, phi: ParameterValueType, qubit: QubitSpecifier ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. phi: The angle of the axis of rotation in the x-y plane. qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.r import RGate return self.append(RGate(theta, phi), [qubit], []) def rv( self, vx: ParameterValueType, vy: ParameterValueType, vz: ParameterValueType, qubit: QubitSpecifier, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RVGate`. For the full matrix form of this gate, see the underlying gate documentation. Rotation around an arbitrary rotation axis :math:`v`, where :math:`|v|` is the angle of rotation in radians. Args: vx: x-component of the rotation axis. vy: y-component of the rotation axis. vz: z-component of the rotation axis. qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.generalized_gates.rv import RVGate return self.append(RVGate(vx, vy, vz), [qubit], []) def rccx( self, control_qubit1: QubitSpecifier, control_qubit2: QubitSpecifier, target_qubit: QubitSpecifier, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RCCXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit1: The qubit(s) used as the first control. control_qubit2: The qubit(s) used as the second control. target_qubit: The qubit(s) targeted by the gate. Returns: A handle to the instructions created. """ from .library.standard_gates.x import RCCXGate return self.append(RCCXGate(), [control_qubit1, control_qubit2, target_qubit], []) def rcccx( self, control_qubit1: QubitSpecifier, control_qubit2: QubitSpecifier, control_qubit3: QubitSpecifier, target_qubit: QubitSpecifier, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RC3XGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit1: The qubit(s) used as the first control. control_qubit2: The qubit(s) used as the second control. control_qubit3: The qubit(s) used as the third control. target_qubit: The qubit(s) targeted by the gate. Returns: A handle to the instructions created. """ from .library.standard_gates.x import RC3XGate return self.append( RC3XGate(), [control_qubit1, control_qubit2, control_qubit3, target_qubit], [] ) def rx( self, theta: ParameterValueType, qubit: QubitSpecifier, label: str | None = None ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The rotation angle of the gate. qubit: The qubit(s) to apply the gate to. label: The string label of the gate in the circuit. Returns: A handle to the instructions created. """ from .library.standard_gates.rx import RXGate return self.append(RXGate(theta, label=label), [qubit], []) def crx( self, theta: ParameterValueType, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CRXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.rx import CRXGate return self.append( CRXGate(theta, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def rxx( self, theta: ParameterValueType, qubit1: QubitSpecifier, qubit2: QubitSpecifier ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RXXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. qubit1: The qubit(s) to apply the gate to. qubit2: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.rxx import RXXGate return self.append(RXXGate(theta), [qubit1, qubit2], []) def ry( self, theta: ParameterValueType, qubit: QubitSpecifier, label: str | None = None ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RYGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The rotation angle of the gate. qubit: The qubit(s) to apply the gate to. label: The string label of the gate in the circuit. Returns: A handle to the instructions created. """ from .library.standard_gates.ry import RYGate return self.append(RYGate(theta, label=label), [qubit], []) def cry( self, theta: ParameterValueType, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CRYGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.ry import CRYGate return self.append( CRYGate(theta, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def ryy( self, theta: ParameterValueType, qubit1: QubitSpecifier, qubit2: QubitSpecifier ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RYYGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The rotation angle of the gate. qubit1: The qubit(s) to apply the gate to. qubit2: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.ryy import RYYGate return self.append(RYYGate(theta), [qubit1, qubit2], []) def rz(self, phi: ParameterValueType, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: phi: The rotation angle of the gate. qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.rz import RZGate return self.append(RZGate(phi), [qubit], []) def crz( self, theta: ParameterValueType, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CRZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.rz import CRZGate return self.append( CRZGate(theta, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def rzx( self, theta: ParameterValueType, qubit1: QubitSpecifier, qubit2: QubitSpecifier ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RZXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The rotation angle of the gate. qubit1: The qubit(s) to apply the gate to. qubit2: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.rzx import RZXGate return self.append(RZXGate(theta), [qubit1, qubit2], []) def rzz( self, theta: ParameterValueType, qubit1: QubitSpecifier, qubit2: QubitSpecifier ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RZZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The rotation angle of the gate. qubit1: The qubit(s) to apply the gate to. qubit2: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.rzz import RZZGate return self.append(RZZGate(theta), [qubit1, qubit2], []) def ecr(self, qubit1: QubitSpecifier, qubit2: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.ECRGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit1, qubit2: The qubits to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.ecr import ECRGate return self.append(ECRGate(), [qubit1, qubit2], []) def s(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.s import SGate return self.append(SGate(), [qubit], []) def sdg(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SdgGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.s import SdgGate return self.append(SdgGate(), [qubit], []) def cs( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CSGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.s import CSGate return self.append( CSGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], ) def csdg( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CSdgGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.s import CSdgGate return self.append( CSdgGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], ) def swap(self, qubit1: QubitSpecifier, qubit2: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SwapGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit1, qubit2: The qubits to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.swap import SwapGate return self.append(SwapGate(), [qubit1, qubit2], []) def iswap(self, qubit1: QubitSpecifier, qubit2: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.iSwapGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit1, qubit2: The qubits to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.iswap import iSwapGate return self.append(iSwapGate(), [qubit1, qubit2], []) def cswap( self, control_qubit: QubitSpecifier, target_qubit1: QubitSpecifier, target_qubit2: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CSwapGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit1: The qubit(s) targeted by the gate. target_qubit2: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. ``'1'``). Defaults to controlling on the ``'1'`` state. Returns: A handle to the instructions created. """ from .library.standard_gates.swap import CSwapGate return self.append( CSwapGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit1, target_qubit2], [], ) def fredkin( self, control_qubit: QubitSpecifier, target_qubit1: QubitSpecifier, target_qubit2: QubitSpecifier, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CSwapGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit1: The qubit(s) targeted by the gate. target_qubit2: The qubit(s) targeted by the gate. Returns: A handle to the instructions created. See Also: QuantumCircuit.cswap: the same function with a different name. """ return self.cswap(control_qubit, target_qubit1, target_qubit2) def sx(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.sx import SXGate return self.append(SXGate(), [qubit], []) def sxdg(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SXdgGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.sx import SXdgGate return self.append(SXdgGate(), [qubit], []) def csx( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CSXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.sx import CSXGate return self.append( CSXGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], ) def t(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.TGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.t import TGate return self.append(TGate(), [qubit], []) def tdg(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.TdgGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.t import TdgGate return self.append(TdgGate(), [qubit], []) def u( self, theta: ParameterValueType, phi: ParameterValueType, lam: ParameterValueType, qubit: QubitSpecifier, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.UGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The :math:`\theta` rotation angle of the gate. phi: The :math:`\phi` rotation angle of the gate. lam: The :math:`\lambda` rotation angle of the gate. qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.u import UGate return self.append(UGate(theta, phi, lam), [qubit], []) def cu( self, theta: ParameterValueType, phi: ParameterValueType, lam: ParameterValueType, gamma: ParameterValueType, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CUGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The :math:`\theta` rotation angle of the gate. phi: The :math:`\phi` rotation angle of the gate. lam: The :math:`\lambda` rotation angle of the gate. gamma: The global phase applied of the U gate, if applied. control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.u import CUGate return self.append( CUGate(theta, phi, lam, gamma, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], ) def x(self, qubit: QubitSpecifier, label: str | None = None) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.XGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. label: The string label of the gate in the circuit. Returns: A handle to the instructions created. """ from .library.standard_gates.x import XGate return self.append(XGate(label=label), [qubit], []) def cx( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.x import CXGate return self.append( CXGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def cnot( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. See Also: QuantumCircuit.cx: the same function with a different name. """ return self.cx(control_qubit, target_qubit, label, ctrl_state) def dcx(self, qubit1: QubitSpecifier, qubit2: QubitSpecifier) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.DCXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit1: The qubit(s) to apply the gate to. qubit2: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.dcx import DCXGate return self.append(DCXGate(), [qubit1, qubit2], []) def ccx( self, control_qubit1: QubitSpecifier, control_qubit2: QubitSpecifier, target_qubit: QubitSpecifier, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CCXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit1: The qubit(s) used as the first control. control_qubit2: The qubit(s) used as the second control. target_qubit: The qubit(s) targeted by the gate. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.x import CCXGate return self.append( CCXGate(ctrl_state=ctrl_state), [control_qubit1, control_qubit2, target_qubit], [], ) def toffoli( self, control_qubit1: QubitSpecifier, control_qubit2: QubitSpecifier, target_qubit: QubitSpecifier, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CCXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit1: The qubit(s) used as the first control. control_qubit2: The qubit(s) used as the second control. target_qubit: The qubit(s) targeted by the gate. Returns: A handle to the instructions created. See Also: QuantumCircuit.ccx: the same gate with a different name. """ return self.ccx(control_qubit1, control_qubit2, target_qubit) def mcx( self, control_qubits: Sequence[QubitSpecifier], target_qubit: QubitSpecifier, ancilla_qubits: QubitSpecifier | Sequence[QubitSpecifier] | None = None, mode: str = "noancilla", ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.MCXGate`. The multi-cX gate can be implemented using different techniques, which use different numbers of ancilla qubits and have varying circuit depth. These modes are: - ``'noancilla'``: Requires 0 ancilla qubits. - ``'recursion'``: Requires 1 ancilla qubit if more than 4 controls are used, otherwise 0. - ``'v-chain'``: Requires 2 less ancillas than the number of control qubits. - ``'v-chain-dirty'``: Same as for the clean ancillas (but the circuit will be longer). For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubits: The qubits used as the controls. target_qubit: The qubit(s) targeted by the gate. ancilla_qubits: The qubits used as the ancillae, if the mode requires them. mode: The choice of mode, explained further above. Returns: A handle to the instructions created. Raises: ValueError: if the given mode is not known, or if too few ancilla qubits are passed. AttributeError: if no ancilla qubits are passed, but some are needed. """ from .library.standard_gates.x import MCXGrayCode, MCXRecursive, MCXVChain num_ctrl_qubits = len(control_qubits) available_implementations = { "noancilla": MCXGrayCode(num_ctrl_qubits), "recursion": MCXRecursive(num_ctrl_qubits), "v-chain": MCXVChain(num_ctrl_qubits, False), "v-chain-dirty": MCXVChain(num_ctrl_qubits, dirty_ancillas=True), # outdated, previous names "advanced": MCXRecursive(num_ctrl_qubits), "basic": MCXVChain(num_ctrl_qubits, dirty_ancillas=False), "basic-dirty-ancilla": MCXVChain(num_ctrl_qubits, dirty_ancillas=True), } # check ancilla input if ancilla_qubits: _ = self.qbit_argument_conversion(ancilla_qubits) try: gate = available_implementations[mode] except KeyError as ex: all_modes = list(available_implementations.keys()) raise ValueError( f"Unsupported mode ({mode}) selected, choose one of {all_modes}" ) from ex if hasattr(gate, "num_ancilla_qubits") and gate.num_ancilla_qubits > 0: required = gate.num_ancilla_qubits if ancilla_qubits is None: raise AttributeError(f"No ancillas provided, but {required} are needed!") # convert ancilla qubits to a list if they were passed as int or qubit if not hasattr(ancilla_qubits, "__len__"): ancilla_qubits = [ancilla_qubits] if len(ancilla_qubits) < required: actually = len(ancilla_qubits) raise ValueError(f"At least {required} ancillas required, but {actually} given.") # size down if too many ancillas were provided ancilla_qubits = ancilla_qubits[:required] else: ancilla_qubits = [] return self.append(gate, control_qubits[:] + [target_qubit] + ancilla_qubits[:], []) def mct( self, control_qubits: Sequence[QubitSpecifier], target_qubit: QubitSpecifier, ancilla_qubits: QubitSpecifier | Sequence[QubitSpecifier] | None = None, mode: str = "noancilla", ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.MCXGate`. The multi-cX gate can be implemented using different techniques, which use different numbers of ancilla qubits and have varying circuit depth. These modes are: - ``'noancilla'``: Requires 0 ancilla qubits. - ``'recursion'``: Requires 1 ancilla qubit if more than 4 controls are used, otherwise 0. - ``'v-chain'``: Requires 2 less ancillas than the number of control qubits. - ``'v-chain-dirty'``: Same as for the clean ancillas (but the circuit will be longer). For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubits: The qubits used as the controls. target_qubit: The qubit(s) targeted by the gate. ancilla_qubits: The qubits used as the ancillae, if the mode requires them. mode: The choice of mode, explained further above. Returns: A handle to the instructions created. Raises: ValueError: if the given mode is not known, or if too few ancilla qubits are passed. AttributeError: if no ancilla qubits are passed, but some are needed. See Also: QuantumCircuit.mcx: the same gate with a different name. """ return self.mcx(control_qubits, target_qubit, ancilla_qubits, mode) def y(self, qubit: QubitSpecifier) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.YGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.y import YGate return self.append(YGate(), [qubit], []) def cy( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CYGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the controls. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.y import CYGate return self.append( CYGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def z(self, qubit: QubitSpecifier) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.ZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.z import ZGate return self.append(ZGate(), [qubit], []) def cz( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the controls. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.z import CZGate return self.append( CZGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def ccz( self, control_qubit1: QubitSpecifier, control_qubit2: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CCZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit1: The qubit(s) used as the first control. control_qubit2: The qubit(s) used as the second control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '10'). Defaults to controlling on the '11' state. Returns: A handle to the instructions created. """ from .library.standard_gates.z import CCZGate return self.append( CCZGate(label=label, ctrl_state=ctrl_state), [control_qubit1, control_qubit2, target_qubit], [], ) def pauli( self, pauli_string: str, qubits: Sequence[QubitSpecifier], ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.PauliGate`. Args: pauli_string: A string representing the Pauli operator to apply, e.g. 'XX'. qubits: The qubits to apply this gate to. Returns: A handle to the instructions created. """ from qiskit.circuit.library.generalized_gates.pauli import PauliGate return self.append(PauliGate(pauli_string), qubits, []) def _push_scope( self, qubits: Iterable[Qubit] = (), clbits: Iterable[Clbit] = (), registers: Iterable[Register] = (), allow_jumps: bool = True, forbidden_message: Optional[str] = None, ): """Add a scope for collecting instructions into this circuit. This should only be done by the control-flow context managers, which will handle cleaning up after themselves at the end as well. Args: qubits: Any qubits that this scope should automatically use. clbits: Any clbits that this scope should automatically use. allow_jumps: Whether this scope allows jumps to be used within it. forbidden_message: If given, all attempts to add instructions to this scope will raise a :exc:`.CircuitError` with this message. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.builder import ControlFlowBuilderBlock # Chain resource requests so things like registers added to inner scopes via conditions are # requested in the outer scope as well. if self._control_flow_scopes: resource_requester = self._control_flow_scopes[-1].request_classical_resource else: resource_requester = self._resolve_classical_resource self._control_flow_scopes.append( ControlFlowBuilderBlock( qubits, clbits, resource_requester=resource_requester, registers=registers, allow_jumps=allow_jumps, forbidden_message=forbidden_message, ) ) def _pop_scope(self) -> "qiskit.circuit.controlflow.builder.ControlFlowBuilderBlock": """Finish a scope used in the control-flow builder interface, and return it to the caller. This should only be done by the control-flow context managers, since they naturally synchronise the creation and deletion of stack elements.""" return self._control_flow_scopes.pop() def _peek_previous_instruction_in_scope(self) -> CircuitInstruction: """Return the instruction 3-tuple of the most recent instruction in the current scope, even if that scope is currently under construction. This function is only intended for use by the control-flow ``if``-statement builders, which may need to modify a previous instruction.""" if self._control_flow_scopes: return self._control_flow_scopes[-1].peek() if not self._data: raise CircuitError("This circuit contains no instructions.") return self._data[-1] def _pop_previous_instruction_in_scope(self) -> CircuitInstruction: """Return the instruction 3-tuple of the most recent instruction in the current scope, even if that scope is currently under construction, and remove it from that scope. This function is only intended for use by the control-flow ``if``-statement builders, which may need to replace a previous instruction with another. """ if self._control_flow_scopes: return self._control_flow_scopes[-1].pop() if not self._data: raise CircuitError("This circuit contains no instructions.") instruction = self._data.pop() if isinstance(instruction.operation, Instruction): self._update_parameter_table_on_instruction_removal(instruction) return instruction def _update_parameter_table_on_instruction_removal(self, instruction: CircuitInstruction): """Update the :obj:`.ParameterTable` of this circuit given that an instance of the given ``instruction`` has just been removed from the circuit. .. note:: This does not account for the possibility for the same instruction instance being added more than once to the circuit. At the time of writing (2021-11-17, main commit 271a82f) there is a defensive ``deepcopy`` of parameterised instructions inside :meth:`.QuantumCircuit.append`, so this should be safe. Trying to account for it would involve adding a potentially quadratic-scaling loop to check each entry in ``data``. """ atomic_parameters: list[tuple[Parameter, int]] = [] for index, parameter in enumerate(instruction.operation.params): if isinstance(parameter, (ParameterExpression, QuantumCircuit)): atomic_parameters.extend((p, index) for p in parameter.parameters) for atomic_parameter, index in atomic_parameters: new_entries = self._parameter_table[atomic_parameter].copy() new_entries.discard((instruction.operation, index)) if not new_entries: del self._parameter_table[atomic_parameter] # Invalidate cache. self._parameters = None else: self._parameter_table[atomic_parameter] = new_entries @typing.overload def while_loop( self, condition: tuple[ClassicalRegister | Clbit, int] | expr.Expr, body: None, qubits: None, clbits: None, *, label: str | None, ) -> "qiskit.circuit.controlflow.while_loop.WhileLoopContext": ... @typing.overload def while_loop( self, condition: tuple[ClassicalRegister | Clbit, int] | expr.Expr, body: "QuantumCircuit", qubits: Sequence[QubitSpecifier], clbits: Sequence[ClbitSpecifier], *, label: str | None, ) -> InstructionSet: ... def while_loop(self, condition, body=None, qubits=None, clbits=None, *, label=None): """Create a ``while`` loop on this circuit. There are two forms for calling this function. If called with all its arguments (with the possible exception of ``label``), it will create a :obj:`~qiskit.circuit.controlflow.WhileLoopOp` with the given ``body``. If ``body`` (and ``qubits`` and ``clbits``) are *not* passed, then this acts as a context manager, which will automatically build a :obj:`~qiskit.circuit.controlflow.WhileLoopOp` when the scope finishes. In this form, you do not need to keep track of the qubits or clbits you are using, because the scope will handle it for you. Example usage:: from qiskit.circuit import QuantumCircuit, Clbit, Qubit bits = [Qubit(), Qubit(), Clbit()] qc = QuantumCircuit(bits) with qc.while_loop((bits[2], 0)): qc.h(0) qc.cx(0, 1) qc.measure(0, 0) Args: condition (Tuple[Union[ClassicalRegister, Clbit], int]): An equality condition to be checked prior to executing ``body``. The left-hand side of the condition must be a :obj:`~ClassicalRegister` or a :obj:`~Clbit`, and the right-hand side must be an integer or boolean. body (Optional[QuantumCircuit]): The loop body to be repeatedly executed. Omit this to use the context-manager mode. qubits (Optional[Sequence[Qubit]]): The circuit qubits over which the loop body should be run. Omit this to use the context-manager mode. clbits (Optional[Sequence[Clbit]]): The circuit clbits over which the loop body should be run. Omit this to use the context-manager mode. label (Optional[str]): The string label of the instruction in the circuit. Returns: InstructionSet or WhileLoopContext: If used in context-manager mode, then this should be used as a ``with`` resource, which will infer the block content and operands on exit. If the full form is used, then this returns a handle to the instructions created. Raises: CircuitError: if an incorrect calling convention is used. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.while_loop import WhileLoopOp, WhileLoopContext if isinstance(condition, expr.Expr): condition = self._validate_expr(condition) else: condition = (self._resolve_classical_resource(condition[0]), condition[1]) if body is None: if qubits is not None or clbits is not None: raise CircuitError( "When using 'while_loop' as a context manager," " you cannot pass qubits or clbits." ) return WhileLoopContext(self, condition, label=label) elif qubits is None or clbits is None: raise CircuitError( "When using 'while_loop' with a body, you must pass qubits and clbits." ) return self.append(WhileLoopOp(condition, body, label), qubits, clbits) @typing.overload def for_loop( self, indexset: Iterable[int], loop_parameter: Parameter | None, body: None, qubits: None, clbits: None, *, label: str | None, ) -> "qiskit.circuit.controlflow.for_loop.ForLoopContext": ... @typing.overload def for_loop( self, indexset: Iterable[int], loop_parameter: Union[Parameter, None], body: "QuantumCircuit", qubits: Sequence[QubitSpecifier], clbits: Sequence[ClbitSpecifier], *, label: str | None, ) -> InstructionSet: ... def for_loop( self, indexset, loop_parameter=None, body=None, qubits=None, clbits=None, *, label=None ): """Create a ``for`` loop on this circuit. There are two forms for calling this function. If called with all its arguments (with the possible exception of ``label``), it will create a :class:`~qiskit.circuit.ForLoopOp` with the given ``body``. If ``body`` (and ``qubits`` and ``clbits``) are *not* passed, then this acts as a context manager, which, when entered, provides a loop variable (unless one is given, in which case it will be reused) and will automatically build a :class:`~qiskit.circuit.ForLoopOp` when the scope finishes. In this form, you do not need to keep track of the qubits or clbits you are using, because the scope will handle it for you. For example:: from qiskit import QuantumCircuit qc = QuantumCircuit(2, 1) with qc.for_loop(range(5)) as i: qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qc.break_loop().c_if(0, True) Args: indexset (Iterable[int]): A collection of integers to loop over. Always necessary. loop_parameter (Optional[Parameter]): The parameter used within ``body`` to which the values from ``indexset`` will be assigned. In the context-manager form, if this argument is not supplied, then a loop parameter will be allocated for you and returned as the value of the ``with`` statement. This will only be bound into the circuit if it is used within the body. If this argument is ``None`` in the manual form of this method, ``body`` will be repeated once for each of the items in ``indexset`` but their values will be ignored. body (Optional[QuantumCircuit]): The loop body to be repeatedly executed. Omit this to use the context-manager mode. qubits (Optional[Sequence[QubitSpecifier]]): The circuit qubits over which the loop body should be run. Omit this to use the context-manager mode. clbits (Optional[Sequence[ClbitSpecifier]]): The circuit clbits over which the loop body should be run. Omit this to use the context-manager mode. label (Optional[str]): The string label of the instruction in the circuit. Returns: InstructionSet or ForLoopContext: depending on the call signature, either a context manager for creating the for loop (it will automatically be added to the circuit at the end of the block), or an :obj:`~InstructionSet` handle to the appended loop operation. Raises: CircuitError: if an incorrect calling convention is used. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.for_loop import ForLoopOp, ForLoopContext if body is None: if qubits is not None or clbits is not None: raise CircuitError( "When using 'for_loop' as a context manager, you cannot pass qubits or clbits." ) return ForLoopContext(self, indexset, loop_parameter, label=label) elif qubits is None or clbits is None: raise CircuitError( "When using 'for_loop' with a body, you must pass qubits and clbits." ) return self.append(ForLoopOp(indexset, loop_parameter, body, label), qubits, clbits) @typing.overload def if_test( self, condition: tuple[ClassicalRegister | Clbit, int], true_body: None, qubits: None, clbits: None, *, label: str | None, ) -> "qiskit.circuit.controlflow.if_else.IfContext": ... @typing.overload def if_test( self, condition: tuple[ClassicalRegister | Clbit, int], true_body: "QuantumCircuit", qubits: Sequence[QubitSpecifier], clbits: Sequence[ClbitSpecifier], *, label: str | None = None, ) -> InstructionSet: ... def if_test( self, condition, true_body=None, qubits=None, clbits=None, *, label=None, ): """Create an ``if`` statement on this circuit. There are two forms for calling this function. If called with all its arguments (with the possible exception of ``label``), it will create a :obj:`~qiskit.circuit.IfElseOp` with the given ``true_body``, and there will be no branch for the ``false`` condition (see also the :meth:`.if_else` method). However, if ``true_body`` (and ``qubits`` and ``clbits``) are *not* passed, then this acts as a context manager, which can be used to build ``if`` statements. The return value of the ``with`` statement is a chainable context manager, which can be used to create subsequent ``else`` blocks. In this form, you do not need to keep track of the qubits or clbits you are using, because the scope will handle it for you. For example:: from qiskit.circuit import QuantumCircuit, Qubit, Clbit bits = [Qubit(), Qubit(), Qubit(), Clbit(), Clbit()] qc = QuantumCircuit(bits) qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qc.h(0) qc.cx(0, 1) qc.measure(0, 1) with qc.if_test((bits[3], 0)) as else_: qc.x(2) with else_: qc.h(2) qc.z(2) Args: condition (Tuple[Union[ClassicalRegister, Clbit], int]): A condition to be evaluated at circuit runtime which, if true, will trigger the evaluation of ``true_body``. Can be specified as either a tuple of a ``ClassicalRegister`` to be tested for equality with a given ``int``, or as a tuple of a ``Clbit`` to be compared to either a ``bool`` or an ``int``. true_body (Optional[QuantumCircuit]): The circuit body to be run if ``condition`` is true. qubits (Optional[Sequence[QubitSpecifier]]): The circuit qubits over which the if/else should be run. clbits (Optional[Sequence[ClbitSpecifier]]): The circuit clbits over which the if/else should be run. label (Optional[str]): The string label of the instruction in the circuit. Returns: InstructionSet or IfContext: depending on the call signature, either a context manager for creating the ``if`` block (it will automatically be added to the circuit at the end of the block), or an :obj:`~InstructionSet` handle to the appended conditional operation. Raises: CircuitError: If the provided condition references Clbits outside the enclosing circuit. CircuitError: if an incorrect calling convention is used. Returns: A handle to the instruction created. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.if_else import IfElseOp, IfContext if isinstance(condition, expr.Expr): condition = self._validate_expr(condition) else: condition = (self._resolve_classical_resource(condition[0]), condition[1]) if true_body is None: if qubits is not None or clbits is not None: raise CircuitError( "When using 'if_test' as a context manager, you cannot pass qubits or clbits." ) # We can only allow jumps if we're in a loop block, but the default path (no scopes) # also allows adding jumps to support the more verbose internal mode. in_loop = bool(self._control_flow_scopes and self._control_flow_scopes[-1].allow_jumps) return IfContext(self, condition, in_loop=in_loop, label=label) elif qubits is None or clbits is None: raise CircuitError("When using 'if_test' with a body, you must pass qubits and clbits.") return self.append(IfElseOp(condition, true_body, None, label), qubits, clbits) def if_else( self, condition: tuple[ClassicalRegister, int] | tuple[Clbit, int] | tuple[Clbit, bool], true_body: "QuantumCircuit", false_body: "QuantumCircuit", qubits: Sequence[QubitSpecifier], clbits: Sequence[ClbitSpecifier], label: str | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.IfElseOp`. .. note:: This method does not have an associated context-manager form, because it is already handled by the :meth:`.if_test` method. You can use the ``else`` part of that with something such as:: from qiskit.circuit import QuantumCircuit, Qubit, Clbit bits = [Qubit(), Qubit(), Clbit()] qc = QuantumCircuit(bits) qc.h(0) qc.cx(0, 1) qc.measure(0, 0) with qc.if_test((bits[2], 0)) as else_: qc.h(0) with else_: qc.x(0) Args: condition: A condition to be evaluated at circuit runtime which, if true, will trigger the evaluation of ``true_body``. Can be specified as either a tuple of a ``ClassicalRegister`` to be tested for equality with a given ``int``, or as a tuple of a ``Clbit`` to be compared to either a ``bool`` or an ``int``. true_body: The circuit body to be run if ``condition`` is true. false_body: The circuit to be run if ``condition`` is false. qubits: The circuit qubits over which the if/else should be run. clbits: The circuit clbits over which the if/else should be run. label: The string label of the instruction in the circuit. Raises: CircuitError: If the provided condition references Clbits outside the enclosing circuit. Returns: A handle to the instruction created. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.if_else import IfElseOp if isinstance(condition, expr.Expr): condition = self._validate_expr(condition) else: condition = (self._resolve_classical_resource(condition[0]), condition[1]) return self.append(IfElseOp(condition, true_body, false_body, label), qubits, clbits) @typing.overload def switch( self, target: Union[ClbitSpecifier, ClassicalRegister], cases: None, qubits: None, clbits: None, *, label: Optional[str], ) -> "qiskit.circuit.controlflow.switch_case.SwitchContext": ... @typing.overload def switch( self, target: Union[ClbitSpecifier, ClassicalRegister], cases: Iterable[Tuple[typing.Any, QuantumCircuit]], qubits: Sequence[QubitSpecifier], clbits: Sequence[ClbitSpecifier], *, label: Optional[str], ) -> InstructionSet: ... def switch(self, target, cases=None, qubits=None, clbits=None, *, label=None): """Create a ``switch``/``case`` structure on this circuit. There are two forms for calling this function. If called with all its arguments (with the possible exception of ``label``), it will create a :class:`.SwitchCaseOp` with the given case structure. If ``cases`` (and ``qubits`` and ``clbits``) are *not* passed, then this acts as a context manager, which will automatically build a :class:`.SwitchCaseOp` when the scope finishes. In this form, you do not need to keep track of the qubits or clbits you are using, because the scope will handle it for you. Example usage:: from qiskit.circuit import QuantumCircuit, ClassicalRegister, QuantumRegister qreg = QuantumRegister(3) creg = ClassicalRegister(3) qc = QuantumCircuit(qreg, creg) qc.h([0, 1, 2]) qc.measure([0, 1, 2], [0, 1, 2]) with qc.switch(creg) as case: with case(0): qc.x(0) with case(1, 2): qc.z(1) with case(case.DEFAULT): qc.cx(0, 1) Args: target (Union[ClassicalRegister, Clbit]): The classical value to switch one. This must be integer-like. cases (Iterable[Tuple[typing.Any, QuantumCircuit]]): A sequence of case specifiers. Each tuple defines one case body (the second item). The first item of the tuple can be either a single integer value, the special value :data:`.CASE_DEFAULT`, or a tuple of several integer values. Each of the integer values will be tried in turn; control will then pass to the body corresponding to the first match. :data:`.CASE_DEFAULT` matches all possible values. Omit in context-manager form. qubits (Sequence[Qubit]): The circuit qubits over which all case bodies execute. Omit in context-manager form. clbits (Sequence[Clbit]): The circuit clbits over which all case bodies execute. Omit in context-manager form. label (Optional[str]): The string label of the instruction in the circuit. Returns: InstructionSet or SwitchCaseContext: If used in context-manager mode, then this should be used as a ``with`` resource, which will return an object that can be repeatedly entered to produce cases for the switch statement. If the full form is used, then this returns a handle to the instructions created. Raises: CircuitError: if an incorrect calling convention is used. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.switch_case import SwitchCaseOp, SwitchContext if isinstance(target, expr.Expr): target = self._validate_expr(target) else: target = self._resolve_classical_resource(target) if cases is None: if qubits is not None or clbits is not None: raise CircuitError( "When using 'switch' as a context manager, you cannot pass qubits or clbits." ) in_loop = bool(self._control_flow_scopes and self._control_flow_scopes[-1].allow_jumps) return SwitchContext(self, target, in_loop=in_loop, label=label) if qubits is None or clbits is None: raise CircuitError("When using 'switch' with cases, you must pass qubits and clbits.") return self.append(SwitchCaseOp(target, cases, label=label), qubits, clbits) def break_loop(self) -> InstructionSet: """Apply :class:`~qiskit.circuit.BreakLoopOp`. .. warning:: If you are using the context-manager "builder" forms of :meth:`.if_test`, :meth:`.for_loop` or :meth:`.while_loop`, you can only call this method if you are within a loop context, because otherwise the "resource width" of the operation cannot be determined. This would quickly lead to invalid circuits, and so if you are trying to construct a reusable loop body (without the context managers), you must also use the non-context-manager form of :meth:`.if_test` and :meth:`.if_else`. Take care that the :obj:`.BreakLoopOp` instruction must span all the resources of its containing loop, not just the immediate scope. Returns: A handle to the instruction created. Raises: CircuitError: if this method was called within a builder context, but not contained within a loop. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.break_loop import BreakLoopOp, BreakLoopPlaceholder if self._control_flow_scopes: operation = BreakLoopPlaceholder() resources = operation.placeholder_resources() return self.append(operation, resources.qubits, resources.clbits) return self.append(BreakLoopOp(self.num_qubits, self.num_clbits), self.qubits, self.clbits) def continue_loop(self) -> InstructionSet: """Apply :class:`~qiskit.circuit.ContinueLoopOp`. .. warning:: If you are using the context-manager "builder" forms of :meth:`.if_test`, :meth:`.for_loop` or :meth:`.while_loop`, you can only call this method if you are within a loop context, because otherwise the "resource width" of the operation cannot be determined. This would quickly lead to invalid circuits, and so if you are trying to construct a reusable loop body (without the context managers), you must also use the non-context-manager form of :meth:`.if_test` and :meth:`.if_else`. Take care that the :class:`~qiskit.circuit.ContinueLoopOp` instruction must span all the resources of its containing loop, not just the immediate scope. Returns: A handle to the instruction created. Raises: CircuitError: if this method was called within a builder context, but not contained within a loop. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.continue_loop import ContinueLoopOp, ContinueLoopPlaceholder if self._control_flow_scopes: operation = ContinueLoopPlaceholder() resources = operation.placeholder_resources() return self.append(operation, resources.qubits, resources.clbits) return self.append( ContinueLoopOp(self.num_qubits, self.num_clbits), self.qubits, self.clbits ) def add_calibration( self, gate: Union[Gate, str], qubits: Sequence[int], # Schedule has the type `qiskit.pulse.Schedule`, but `qiskit.pulse` cannot be imported # while this module is, and so Sphinx will not accept a forward reference to it. Sphinx # needs the types available at runtime, whereas mypy will accept it, because it handles the # type checking by static analysis. schedule, params: Sequence[ParameterValueType] | None = None, ) -> None: """Register a low-level, custom pulse definition for the given gate. Args: gate (Union[Gate, str]): Gate information. qubits (Union[int, Tuple[int]]): List of qubits to be measured. schedule (Schedule): Schedule information. params (Optional[List[Union[float, Parameter]]]): A list of parameters. Raises: Exception: if the gate is of type string and params is None. """ def _format(operand): try: # Using float/complex value as a dict key is not good idea. # This makes the mapping quite sensitive to the rounding error. # However, the mechanism is already tied to the execution model (i.e. pulse gate) # and we cannot easily update this rule. # The same logic exists in DAGCircuit.add_calibration. evaluated = complex(operand) if np.isreal(evaluated): evaluated = float(evaluated.real) if evaluated.is_integer(): evaluated = int(evaluated) return evaluated except TypeError: # Unassigned parameter return operand if isinstance(gate, Gate): params = gate.params gate = gate.name if params is not None: params = tuple(map(_format, params)) else: params = () self._calibrations[gate][(tuple(qubits), params)] = schedule # Functions only for scheduled circuits def qubit_duration(self, *qubits: Union[Qubit, int]) -> float: """Return the duration between the start and stop time of the first and last instructions, excluding delays, over the supplied qubits. Its time unit is ``self.unit``. Args: *qubits: Qubits within ``self`` to include. Returns: Return the duration between the first start and last stop time of non-delay instructions """ return self.qubit_stop_time(*qubits) - self.qubit_start_time(*qubits) def qubit_start_time(self, *qubits: Union[Qubit, int]) -> float: """Return the start time of the first instruction, excluding delays, over the supplied qubits. Its time unit is ``self.unit``. Return 0 if there are no instructions over qubits Args: *qubits: Qubits within ``self`` to include. Integers are allowed for qubits, indicating indices of ``self.qubits``. Returns: Return the start time of the first instruction, excluding delays, over the qubits Raises: CircuitError: if ``self`` is a not-yet scheduled circuit. """ if self.duration is None: # circuit has only delays, this is kind of scheduled for instruction in self._data: if not isinstance(instruction.operation, Delay): raise CircuitError( "qubit_start_time undefined. Circuit must be scheduled first." ) return 0 qubits = [self.qubits[q] if isinstance(q, int) else q for q in qubits] starts = {q: 0 for q in qubits} dones = {q: False for q in qubits} for instruction in self._data: for q in qubits: if q in instruction.qubits: if isinstance(instruction.operation, Delay): if not dones[q]: starts[q] += instruction.operation.duration else: dones[q] = True if len(qubits) == len([done for done in dones.values() if done]): # all done return min(start for start in starts.values()) return 0 # If there are no instructions over bits def qubit_stop_time(self, *qubits: Union[Qubit, int]) -> float: """Return the stop time of the last instruction, excluding delays, over the supplied qubits. Its time unit is ``self.unit``. Return 0 if there are no instructions over qubits Args: *qubits: Qubits within ``self`` to include. Integers are allowed for qubits, indicating indices of ``self.qubits``. Returns: Return the stop time of the last instruction, excluding delays, over the qubits Raises: CircuitError: if ``self`` is a not-yet scheduled circuit. """ if self.duration is None: # circuit has only delays, this is kind of scheduled for instruction in self._data: if not isinstance(instruction.operation, Delay): raise CircuitError( "qubit_stop_time undefined. Circuit must be scheduled first." ) return 0 qubits = [self.qubits[q] if isinstance(q, int) else q for q in qubits] stops = {q: self.duration for q in qubits} dones = {q: False for q in qubits} for instruction in reversed(self._data): for q in qubits: if q in instruction.qubits: if isinstance(instruction.operation, Delay): if not dones[q]: stops[q] -= instruction.operation.duration else: dones[q] = True if len(qubits) == len([done for done in dones.values() if done]): # all done return max(stop for stop in stops.values()) return 0 # If there are no instructions over bits class _ParameterBindsDict: __slots__ = ("mapping", "allowed_keys") def __init__(self, mapping, allowed_keys): self.mapping = mapping self.allowed_keys = allowed_keys def items(self): """Iterator through all the keys in the mapping that we care about. Wrapping the main mapping allows us to avoid reconstructing a new 'dict', but just use the given 'mapping' without any copy / reconstruction.""" for parameter, value in self.mapping.items(): if parameter in self.allowed_keys: yield parameter, value class _ParameterBindsSequence: __slots__ = ("parameters", "values", "mapping_cache") def __init__(self, parameters, values): self.parameters = parameters self.values = values self.mapping_cache = None def items(self): """Iterator through all the keys in the mapping that we care about.""" return zip(self.parameters, self.values) @property def mapping(self): """Cached version of a mapping. This is only generated on demand.""" if self.mapping_cache is None: self.mapping_cache = dict(zip(self.parameters, self.values)) return self.mapping_cache # Used by the OQ2 exporter. Just needs to have enough parameters to support the largest standard # (non-controlled) gate in our standard library. We have to use the same `Parameter` instances each # time so the equality comparisons will work. _QASM2_FIXED_PARAMETERS = [Parameter("param0"), Parameter("param1"), Parameter("param2")] def _qasm2_custom_operation_statement( instruction, existing_gate_names, gates_to_define, bit_labels ): operation = _qasm2_define_custom_operation( instruction.operation, existing_gate_names, gates_to_define ) # Insert qasm representation of the original instruction if instruction.clbits: bits = itertools.chain(instruction.qubits, instruction.clbits) else: bits = instruction.qubits bits_qasm = ",".join(bit_labels[j] for j in bits) instruction_qasm = f"{_instruction_qasm2(operation)} {bits_qasm};" return instruction_qasm def _qasm2_define_custom_operation(operation, existing_gate_names, gates_to_define): """Extract a custom definition from the given operation, and append any necessary additional subcomponents' definitions to the ``gates_to_define`` ordered dictionary. Returns a potentially new :class:`.Instruction`, which should be used for the :meth:`~.Instruction.qasm` call (it may have been renamed).""" # pylint: disable=cyclic-import from qiskit.circuit import library as lib from qiskit.qasm2 import QASM2ExportError if operation.name in existing_gate_names: return operation # Check instructions names or label are valid escaped = _qasm_escape_name(operation.name, "gate_") if escaped != operation.name: operation = operation.copy(name=escaped) # These are built-in gates that are known to be safe to construct by passing the correct number # of `Parameter` instances positionally, and have no other information. We can't guarantee that # if they've been subclassed, though. This is a total hack; ideally we'd be able to inspect the # "calling" signatures of Qiskit `Gate` objects to know whether they're safe to re-parameterise. known_good_parameterized = { lib.PhaseGate, lib.RGate, lib.RXGate, lib.RXXGate, lib.RYGate, lib.RYYGate, lib.RZGate, lib.RZXGate, lib.RZZGate, lib.XXMinusYYGate, lib.XXPlusYYGate, lib.UGate, lib.U1Gate, lib.U2Gate, lib.U3Gate, } # In known-good situations we want to use a manually parametrised object as the source of the # definition, but still continue to return the given object as the call-site object. if type(operation) in known_good_parameterized: parameterized_operation = type(operation)(*_QASM2_FIXED_PARAMETERS[: len(operation.params)]) elif hasattr(operation, "_qasm2_decomposition"): new_op = operation._qasm2_decomposition() parameterized_operation = operation = new_op.copy( name=_qasm_escape_name(new_op.name, "gate_") ) else: parameterized_operation = operation # If there's an _equal_ operation in the existing circuits to be defined, then our job is done. previous_definition_source, _ = gates_to_define.get(operation.name, (None, None)) if parameterized_operation == previous_definition_source: return operation # Otherwise, if there's a naming clash, we need a unique name. if operation.name in gates_to_define: operation = _rename_operation(operation) new_name = operation.name if parameterized_operation.params: parameters_qasm = ( "(" + ",".join(f"param{i}" for i in range(len(parameterized_operation.params))) + ")" ) else: parameters_qasm = "" if operation.num_qubits == 0: raise QASM2ExportError( f"OpenQASM 2 cannot represent '{operation.name}, which acts on zero qubits." ) if operation.num_clbits != 0: raise QASM2ExportError( f"OpenQASM 2 cannot represent '{operation.name}', which acts on {operation.num_clbits}" " classical bits." ) qubits_qasm = ",".join(f"q{i}" for i in range(parameterized_operation.num_qubits)) parameterized_definition = getattr(parameterized_operation, "definition", None) if parameterized_definition is None: gates_to_define[new_name] = ( parameterized_operation, f"opaque {new_name}{parameters_qasm} {qubits_qasm};", ) else: qubit_labels = {bit: f"q{i}" for i, bit in enumerate(parameterized_definition.qubits)} body_qasm = " ".join( _qasm2_custom_operation_statement( instruction, existing_gate_names, gates_to_define, qubit_labels ) for instruction in parameterized_definition.data ) # if an inner operation has the same name as the actual operation, it needs to be renamed if operation.name in gates_to_define: operation = _rename_operation(operation) new_name = operation.name definition_qasm = f"gate {new_name}{parameters_qasm} {qubits_qasm} {{ {body_qasm} }}" gates_to_define[new_name] = (parameterized_operation, definition_qasm) return operation def _rename_operation(operation): """Returns the operation with a new name following this pattern: {operation name}_{operation id}""" new_name = f"{operation.name}_{id(operation)}" updated_operation = operation.copy(name=new_name) return updated_operation def _qasm_escape_name(name: str, prefix: str) -> str: """Returns a valid OpenQASM identifier, using `prefix` as a prefix if necessary. `prefix` must itself be a valid identifier.""" # Replace all non-ASCII-word characters (letters, digits, underscore) with the underscore. escaped_name = re.sub(r"\W", "_", name, flags=re.ASCII) if ( not escaped_name or escaped_name[0] not in string.ascii_lowercase or escaped_name in QASM2_RESERVED ): escaped_name = prefix + escaped_name return escaped_name def _instruction_qasm2(operation): """Return an OpenQASM 2 string for the instruction.""" from qiskit.qasm2 import QASM2ExportError # pylint: disable=cyclic-import if operation.name == "c3sx": qasm2_call = "c3sqrtx" else: qasm2_call = operation.name if operation.params: qasm2_call = "{}({})".format( qasm2_call, ",".join([pi_check(i, output="qasm", eps=1e-12) for i in operation.params]), ) if operation.condition is not None: if not isinstance(operation.condition[0], ClassicalRegister): raise QASM2ExportError( "OpenQASM 2 can only condition on registers, but got '{operation.condition[0]}'" ) qasm2_call = ( "if(%s==%d) " % (operation.condition[0].name, operation.condition[1]) + qasm2_call ) return qasm2_call def _make_unique(name: str, already_defined: collections.abc.Set[str]) -> str: """Generate a name by suffixing the given stem that is unique within the defined set.""" if name not in already_defined: return name used = {in_use[len(name) :] for in_use in already_defined if in_use.startswith(name)} characters = (string.digits + string.ascii_letters) if name else string.ascii_letters for parts in itertools.chain.from_iterable( itertools.product(characters, repeat=n) for n in itertools.count(1) ): suffix = "".join(parts) if suffix not in used: return name + suffix # This isn't actually reachable because the above loop is infinite. return name def _bit_argument_conversion(specifier, bit_sequence, bit_set, type_) -> list[Bit]: """Get the list of bits referred to by the specifier ``specifier``. Valid types for ``specifier`` are integers, bits of the correct type (as given in ``type_``), or iterables of one of those two scalar types. Integers are interpreted as indices into the sequence ``bit_sequence``. All allowed bits must be in ``bit_set`` (which should implement fast lookup), which is assumed to contain the same bits as ``bit_sequence``. Returns: List[Bit]: a list of the specified bits from ``bits``. Raises: CircuitError: if an incorrect type or index is encountered, if the same bit is specified more than once, or if the specifier is to a bit not in the ``bit_set``. """ # The duplication between this function and `_bit_argument_conversion_scalar` is so that fast # paths return as quickly as possible, and all valid specifiers will resolve without needing to # try/catch exceptions (which is too slow for inner-loop code). if isinstance(specifier, type_): if specifier in bit_set: return [specifier] raise CircuitError(f"Bit '{specifier}' is not in the circuit.") if isinstance(specifier, (int, np.integer)): try: return [bit_sequence[specifier]] except IndexError as ex: raise CircuitError( f"Index {specifier} out of range for size {len(bit_sequence)}." ) from ex # Slices can't raise IndexError - they just return an empty list. if isinstance(specifier, slice): return bit_sequence[specifier] try: return [ _bit_argument_conversion_scalar(index, bit_sequence, bit_set, type_) for index in specifier ] except TypeError as ex: message = ( f"Incorrect bit type: expected '{type_.__name__}' but got '{type(specifier).__name__}'" if isinstance(specifier, Bit) else f"Invalid bit index: '{specifier}' of type '{type(specifier)}'" ) raise CircuitError(message) from ex def _bit_argument_conversion_scalar(specifier, bit_sequence, bit_set, type_): if isinstance(specifier, type_): if specifier in bit_set: return specifier raise CircuitError(f"Bit '{specifier}' is not in the circuit.") if isinstance(specifier, (int, np.integer)): try: return bit_sequence[specifier] except IndexError as ex: raise CircuitError( f"Index {specifier} out of range for size {len(bit_sequence)}." ) from ex message = ( f"Incorrect bit type: expected '{type_.__name__}' but got '{type(specifier).__name__}'" if isinstance(specifier, Bit) else f"Invalid bit index: '{specifier}' of type '{type(specifier)}'" ) raise CircuitError(message)
https://github.com/Spintronic6889/Introduction-of-Quantum-walk-its-application-on-search-and-decision-making
Spintronic6889
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer,assemble, transpile from qiskit import BasicAer from random import randrange from qiskit.tools.visualization import plot_histogram, plot_state_city import numpy as np from qiskit.quantum_info.operators import Operator, Pauli from qiskit.quantum_info import Operator, Statevector q = QuantumRegister(6) # "Qubits q[0] and q[1] for coin 1 and 2", "q[2] and q[3] for player 1" and q[4] and q[5] for player 2" c = ClassicalRegister(6) Q = QuantumCircuit(q,c) #Coin Operators # Apply u gate as Hadamard gate to each coin Q.u(np.pi/2,0,np.pi,q[0]) Q.u(np.pi/2,0,np.pi,q[1]) #S operator Q.x(q[0]) Q.x(q[1]) Q.mct([q[0],q[1]],q[3]) Q.mct([q[0],q[1]],q[5]) Q.x(q[0]) Q.x(q[1]) Q.barrier() Q.x(q[0]) Q.mct([q[0],q[1]],q[2]) Q.mct([q[0],q[1]],q[3]) Q.x(q[0]) Q.barrier() Q.x(q[1]) Q.mct([q[0],q[1]],q[4]) Q.mct([q[0],q[1]],q[5]) Q.x(q[1]) Q.barrier() Q.mct([q[0],q[1]],q[2]) Q.mct([q[0],q[1]],q[4]) Q.measure_all() Q.draw(output='mpl') # Execute the circuit on the qasm simulator # Use Aer's qasm_simulator backend_sim = Aer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator. # We've set the number of repeats of the circuit # to be 1024, which is the default. job_sim = execute(Q, backend_sim, shots=1000) # Grab the results from the job. result_sim = job_sim.result() counts = result_sim.get_counts(Q) print(counts) plot_histogram(counts, color='midnightblue', title="Decision Histogram") q_o = QuantumRegister(6) # "Qubits q[0] and q[1] for coin 1 and 2", "q[2] and q[3] for player 1" and q[4] and q[5] for player 2" c_o = ClassicalRegister(6) Q_o = QuantumCircuit(q,c) #Coin Operators # Apply u gate as Hadamard gate to each coin Q_o.u(2*np.pi/3,0,np.pi,q[0]) Q_o.u(np.pi/2,0,np.pi,q[1]) #S operator Q_o.x(q[0]) Q_o.x(q[1]) Q_o.mct([q[0],q[1]],q[3]) Q_o.mct([q[0],q[1]],q[5]) Q_o.x(q[0]) Q_o.x(q[1]) Q_o.barrier() Q_o.x(q[0]) Q_o.mct([q[0],q[1]],q[2]) Q_o.mct([q[0],q[1]],q[3]) Q_o.x(q[0]) Q_o.barrier() Q_o.x(q[1]) Q_o.mct([q[0],q[1]],q[4]) Q_o.mct([q[0],q[1]],q[5]) Q_o.x(q[1]) Q_o.barrier() Q_o.mct([q[0],q[1]],q[2]) Q_o.mct([q[0],q[1]],q[4]) Q_o.measure_all() # Execute the circuit on the qasm simulator # Use Aer's qasm_simulator backend_sim_o = Aer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator. # We've set the number of repeats of the circuit # to be 1024, which is the default. job_sim_o = execute(Q_o, backend_sim, shots=1000) # Grab the results from the job. result_sim_o = job_sim_o.result() counts_o = result_sim_o.get_counts(Q_o) print(counts_o) plot_histogram(counts_o, color='midnightblue', title="Decision Histogram")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import QuantumCircuit from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits to represent the uncertainty num_uncertainty_qubits = 3 # parameters for considered random distribution S = 2.0 # initial spot price vol = 0.4 # volatility of 40% r = 0.05 # annual interest rate of 4% T = 40 / 365 # 40 days to maturity # resulting parameters for log-normal distribution mu = (r - 0.5 * vol**2) * T + np.log(S) sigma = vol * np.sqrt(T) mean = np.exp(mu + sigma**2 / 2) variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2) stddev = np.sqrt(variance) # lowest and highest value considered for the spot price; in between, an equidistant discretization is considered. low = np.maximum(0, mean - 3 * stddev) high = mean + 3 * stddev # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, high) ) # plot probability distribution x = uncertainty_model.values y = uncertainty_model.probabilities plt.bar(x, y, width=0.2) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.grid() plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15) plt.ylabel("Probability ($\%$)", size=15) plt.show() # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 1.896 # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [0, 1] offsets = [0, 0] f_min = 0 f_max = high - strike_price european_call_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=c_approx, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective num_qubits = european_call_objective.num_qubits european_call = QuantumCircuit(num_qubits) european_call.append(uncertainty_model, range(num_uncertainty_qubits)) european_call.append(european_call_objective, range(num_qubits)) # draw the circuit european_call.draw() # plot exact payoff function (evaluated on the grid of the uncertainty model) x = uncertainty_model.values y = np.maximum(0, x - strike_price) plt.plot(x, y, "ro-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Spot Price", size=15) plt.ylabel("Payoff", size=15) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.show() # evaluate exact expected value (normalized to the [0, 1] interval) exact_value = np.dot(uncertainty_model.probabilities, y) exact_delta = sum(uncertainty_model.probabilities[x >= strike_price]) print("exact expected value:\t%.4f" % exact_value) print("exact delta value: \t%.4f" % exact_delta) european_call.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_call, objective_qubits=[3], post_processing=european_call_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) from qiskit_finance.applications.estimation import EuropeanCallPricing european_call_pricing = EuropeanCallPricing( num_state_qubits=num_uncertainty_qubits, strike_price=strike_price, rescaling_factor=c_approx, bounds=(low, high), uncertainty_model=uncertainty_model, ) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_pricing.to_estimation_problem() # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (european_call_pricing.interpret(result))) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) from qiskit_finance.applications.estimation import EuropeanCallDelta european_call_delta = EuropeanCallDelta( num_state_qubits=num_uncertainty_qubits, strike_price=strike_price, bounds=(low, high), uncertainty_model=uncertainty_model, ) european_call_delta._objective.decompose().draw() european_call_delta_circ = QuantumCircuit(european_call_delta._objective.num_qubits) european_call_delta_circ.append(uncertainty_model, range(num_uncertainty_qubits)) european_call_delta_circ.append( european_call_delta._objective, range(european_call_delta._objective.num_qubits) ) european_call_delta_circ.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_delta.to_estimation_problem() # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) conf_int = np.array(result_delta.confidence_interval_processed) print("Exact delta: \t%.4f" % exact_delta) print("Esimated value: \t%.4f" % european_call_delta.interpret(result_delta)) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/usamisaori/quantum-expressibility-entangling-capability
usamisaori
import numpy as np import matplotlib.pyplot as plt import matplotlib.mlab as mlab from mpl_toolkits.mplot3d import Axes3D plt.rc('font',family='Microsoft YaHei') plt.rcParams['axes.unicode_minus'] = False palettes = [ "#999999", "#FFEE00", "#FF9900", "#FF3636", "#99CC33", "#66CCCC", "#3399CC", "#9966CC" ] plt.scatter(0.1, 0.1, color=palettes[0]) plt.scatter(0.2, 0.2, color=palettes[1]) plt.scatter(0.3, 0.3, color=palettes[2]) plt.scatter(0.4, 0.4, color=palettes[3]) plt.scatter(0.5, 0.5, color=palettes[4]) plt.scatter(0.6, 0.6, color=palettes[5]) plt.scatter(0.7, 0.7, color=palettes[6]) plt.scatter(0.8, 0.8, color=palettes[7]) # Expressibility Entanglement plt.figure(figsize=(8, 5)) c1 = "#FF6666" c2 = "#FF9900" c3 = "#66CCFF" # layer 1 # layer 1 qubit 3 plt.grid() plt.xticks([1, 2, 3, 4, 5, 6]) plt.ylim(0.13, 0.7) plt.title("角度编码方案与表达能力", fontsize=14) plt.xlabel("Qubit数", fontsize=13) plt.ylabel("Expr", fontsize=13) plt.scatter(3, 0.1974, color=c1, label="Rx(θ)(·)") plt.scatter(3, 0.1997, color=c2, label="Ry(θ)H(·)") plt.scatter(3, 0.1918, color=c3, label="Rz(θ)H(·)") plt.scatter(4, 0.1462, color=c1) plt.scatter(4, 0.1442, color=c2) plt.scatter(4, 0.1331, color=c3) plt.scatter(5, 0.1711, color=c1) plt.scatter(5, 0.1824, color=c2) plt.scatter(5, 0.1741, color=c3) plt.scatter(1, 0.6515, color=c1) plt.scatter(1, 0.6613, color=c2) plt.scatter(1, 0.6260, color=c3) plt.scatter(2, 0.3435, color=c1) plt.scatter(2, 0.3355, color=c2) plt.scatter(2, 0.3304, color=c3) plt.scatter(6, 0.2582, color=c1) plt.scatter(6, 0.2748, color=c2) plt.scatter(6, 0.2644, color=c3) plt.legend(loc='upper center') plt.figure(figsize=(15, 3.8)) # layer 1 # layer 1 qubit 3 ax = plt.subplot(1,3,1) plt.grid() plt.ylim(0.3, 0.8) plt.xlim(0.4, 2.4) plt.title("Quibts: 3, Layers: 1") plt.xlabel("Expr", fontsize=13) plt.ylabel("Ent", fontsize=13) plt.scatter(1.189, 0.625, color=palettes[0], label="C1") plt.scatter(0.704, 0.377, color=palettes[1], label="C2") plt.scatter(2.175, 0.702, color=palettes[2], label="C3") plt.scatter(2.352, 0.540, color=palettes[3], label="C4") plt.scatter(1.799, 0.542, color=palettes[4], label="C5") plt.scatter(2.287, 0.720, color=palettes[5], label="C6") plt.scatter(1.546, 0.338, color=palettes[6], label="C7") plt.scatter(1.905, 0.456, color=palettes[7], label="C8") ax.legend(loc='upper left', ncol=3, bbox_to_anchor=(0, 1.01)) plt.axvline(2.352, linestyle="--", color="#FF363666") plt.axvline(2.175, linestyle="--", color="#FF990066") plt.axhline(0.540, linestyle="--", color="#FF363666") plt.axhline(0.702, linestyle="--", color="#FF990066") # # layer 1 qubit 4 plt.subplot(1,3,2) plt.grid() plt.ylim(0.3, 0.8) plt.xlim(0.4, 2.4) plt.title("Quibts: 4, Layers: 1") plt.xlabel("Expr", fontsize=13) plt.scatter(1.724, 0.625, color=palettes[0]) plt.scatter(0.503, 0.375, color=palettes[1]) plt.scatter(1.881, 0.704, color=palettes[2]) plt.scatter(1.982, 0.537, color=palettes[3]) plt.scatter(1.837, 0.545, color=palettes[4]) plt.scatter(2.115, 0.721, color=palettes[5]) plt.scatter(1.219, 0.337, color=palettes[6]) plt.scatter(1.390, 0.457, color=palettes[7]) plt.axvline(1.982, linestyle="--", color="#FF363666") plt.axvline(1.881, linestyle="--", color="#FF990066") plt.axhline(0.537, linestyle="--", color="#FF363666") plt.axhline(0.704, linestyle="--", color="#FF990066") # # layer 1 qubit 5 plt.subplot(1,3,3) plt.grid() plt.ylim(0.3, 0.8) plt.xlim(0.4, 2.4) plt.title("Quibts: 5, Layers: 1") plt.xlabel("Expr", fontsize=13) plt.scatter(1.376, 0.625, color=palettes[0]) plt.scatter(0.456, 0.377, color=palettes[1]) plt.scatter(1.465, 0.703, color=palettes[2]) plt.scatter(1.557, 0.536, color=palettes[3]) plt.scatter(1.424, 0.547, color=palettes[4]) plt.scatter(2.113, 0.722, color=palettes[5]) plt.scatter(0.942, 0.339, color=palettes[6]) plt.scatter(1.152, 0.456, color=palettes[7]) plt.axvline(1.557, linestyle="--", color="#FF363666") plt.axvline(1.465, linestyle="--", color="#FF990066") plt.axhline(0.536, linestyle="--", color="#FF363666") plt.axhline(0.703, linestyle="--", color="#FF990066") def depth(circuit_type, n, L): if circuit_type == 1: return (2 * n + 1) * L elif circuit_type >= 2 and circuit_type <= 4: return (n + 1) * L + 1 elif circuit_type == 5: return (2 + n + n // np.gcd(n, 3)) * L elif circuit_type == 6: return (n ** 2 - n + 4) * L elif circuit_type == 7: return 6 * L elif circuit_type == 8: return (n + 2) * L colors2 = ['#FFCC33', '#FF9900', '#FF9966', '#FF6666', '#CC3333'] colors = ['#99CCFF', '#66CCFF', '#0088CC', '#6666FF', '#0000FF'] types = ['o', '^', ',', 'p', 'X'] plt.grid() plt.title("线路深度同量子比特数量关系") plt.xlabel("线路类型", fontsize=13) plt.ylabel("线路深度", fontsize=13) for n in range(2, 7): for ct in range(1, 9): if ct == 1: plt.scatter(ct, depth(ct, n, 1), color=colors[n - 2], marker=types[n - 2], label=f"n={n}, L=1") else: plt.scatter(ct, depth(ct, n, 1), color=colors[n - 2], marker=types[n - 2]) for n in range(2, 7): for ct in range(1, 9): if ct == 1: plt.scatter(ct, depth(ct, n, 3), color=colors2[n - 2], marker=types[n - 2], label=f"n={n}, L=3") else: plt.scatter(ct, depth(ct, n, 3), color=colors2[n - 2], marker=types[n - 2]) plt.axhline(22, 0, 8, linestyle="--", color="#CC6666") plt.legend() plt.figure(figsize=(7, 5)) # layer 1 # layer 1 qubit 3 plt.grid() plt.ylim(0.4, 0.6) plt.xlim(1, 1.7) plt.title("原始线路与丢弃处理后线路的可表达性与纠缠能力", fontsize=13) plt.xlabel("Expr", fontsize=13) plt.ylabel("Ent", fontsize=13) plt.scatter(1.6105, 0.5622, color="#FF9966", label="原始线路") plt.scatter(1.4415, 0.5158, color="#FF6666", label="纠缠丢弃") plt.scatter(1.1185, 0.4283, color="#3399CC", label="旋转丢弃") plt.legend(loc='upper left')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import * from qiskit.visualization import plot_histogram # quantum circuit to make a Bell state bell = QuantumCircuit(2, 2) bell.h(0) bell.cx(0, 1) meas = QuantumCircuit(2, 2) meas.measure([0,1], [0,1]) # execute the quantum circuit backend = BasicAer.get_backend('qasm_simulator') # the device to run on circ = bell.compose(meas) result = backend.run(transpile(circ, backend), shots=1000).result() counts = result.get_counts(circ) print(counts) plot_histogram(counts) # Execute 2-qubit Bell state again second_result = backend.run(transpile(circ, backend), shots=1000).result() second_counts = second_result.get_counts(circ) # Plot results with legend legend = ['First execution', 'Second execution'] plot_histogram([counts, second_counts], legend=legend) plot_histogram([counts, second_counts], legend=legend, sort='desc', figsize=(15,12), color=['orange', 'black'], bar_labels=False) from qiskit.visualization import plot_state_city, plot_bloch_multivector from qiskit.visualization import plot_state_paulivec, plot_state_hinton from qiskit.visualization import plot_state_qsphere # execute the quantum circuit backend = BasicAer.get_backend('statevector_simulator') # the device to run on result = backend.run(transpile(bell, backend)).result() psi = result.get_statevector(bell) plot_state_city(psi) plot_state_hinton(psi) plot_state_qsphere(psi) plot_state_paulivec(psi) plot_bloch_multivector(psi) plot_state_city(psi, title="My City", color=['black', 'orange']) plot_state_hinton(psi, title="My Hinton") plot_state_paulivec(psi, title="My Paulivec", color=['purple', 'orange', 'green']) plot_bloch_multivector(psi, title="My Bloch Spheres") from qiskit.visualization import plot_bloch_vector plot_bloch_vector([0,1,0]) plot_bloch_vector([0,1,0], title='My Bloch Sphere') import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Tojarieh97/VQE
Tojarieh97
%load_ext autoreload %autoreload 2 from qiskit.circuit.library.standard_gates import RXGate, RZGate, CXGate, CZGate from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister def get_thetas_circuit(thetas, D2): qr = QuantumRegister(4, name="qubit") qc = QuantumCircuit(qr) for d in range(D2): qc.append(RXGate(thetas[0]), [qr[0]]) qc.append(RXGate(thetas[1]), [qr[1]]) qc.append(RXGate(thetas[2]), [qr[2]]) qc.append(RXGate(thetas[3]), [qr[3]]) qc.append(RZGate(thetas[4]), [qr[0]]) qc.append(RZGate(thetas[5]), [qr[1]]) qc.append(RZGate(thetas[6]), [qr[2]]) qc.append(RZGate(thetas[7]), [qr[3]]) qc.append(CZGate(), [qr[0], qr[1]]) qc.append(CZGate(), [qr[1], qr[2]]) qc.append(CZGate(), [qr[2], qr[3]]) qc.barrier(qr) qc.append(RXGate(thetas[0]), [qr[0]]) qc.append(RXGate(thetas[1]), [qr[1]]) qc.append(RXGate(thetas[2]), [qr[2]]) qc.append(RXGate(thetas[3]), [qr[3]]) qc.append(RZGate(thetas[4]), [qr[0]]) qc.append(RZGate(thetas[5]), [qr[1]]) qc.append(RZGate(thetas[6]), [qr[2]]) qc.append(RZGate(thetas[7]), [qr[3]]) return qc def get_phis_circuit(phis, D1, input_state): qr = QuantumRegister(4, name="qubit") qc = QuantumCircuit(qr) qc.initialize(input_state) for d in range(D1): qc.append(RXGate(phis[0]), [qr[2]]) qc.append(RXGate(phis[1]), [qr[3]]) qc.append(RZGate(phis[2]), [qr[2]]) qc.append(RZGate(phis[3]), [qr[3]]) qc.append(CZGate(), [qr[2], qr[3]]) qc.barrier(qr) return qc def get_full_variational_quantum_circuit(thetas, phis, D1, D2, input_state): thetas_quantum_circuit = get_thetas_circuit(thetas, D2) phis_quantum_circuit = get_phis_circuit(phis, D1, input_state) variational_quantum_circuit = phis_quantum_circuit.compose(thetas_quantum_circuit) return variational_quantum_circuit
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# External imports from pylab import cm from sklearn import metrics import numpy as np import matplotlib.pyplot as plt # Qiskit imports from qiskit import QuantumCircuit from qiskit.circuit import ParameterVector from qiskit.visualization import circuit_drawer from qiskit.algorithms.optimizers import SPSA from qiskit.circuit.library import ZZFeatureMap from qiskit_machine_learning.kernels import TrainableFidelityQuantumKernel from qiskit_machine_learning.kernels.algorithms import QuantumKernelTrainer from qiskit_machine_learning.algorithms import QSVC from qiskit_machine_learning.datasets import ad_hoc_data class QKTCallback: """Callback wrapper class.""" def __init__(self) -> None: self._data = [[] for i in range(5)] def callback(self, x0, x1=None, x2=None, x3=None, x4=None): """ Args: x0: number of function evaluations x1: the parameters x2: the function value x3: the stepsize x4: whether the step was accepted """ self._data[0].append(x0) self._data[1].append(x1) self._data[2].append(x2) self._data[3].append(x3) self._data[4].append(x4) def get_callback_data(self): return self._data def clear_callback_data(self): self._data = [[] for i in range(5)] adhoc_dimension = 2 X_train, y_train, X_test, y_test, adhoc_total = ad_hoc_data( training_size=20, test_size=5, n=adhoc_dimension, gap=0.3, plot_data=False, one_hot=False, include_sample_total=True, ) plt.figure(figsize=(5, 5)) plt.ylim(0, 2 * np.pi) plt.xlim(0, 2 * np.pi) plt.imshow( np.asmatrix(adhoc_total).T, interpolation="nearest", origin="lower", cmap="RdBu", extent=[0, 2 * np.pi, 0, 2 * np.pi], ) plt.scatter( X_train[np.where(y_train[:] == 0), 0], X_train[np.where(y_train[:] == 0), 1], marker="s", facecolors="w", edgecolors="b", label="A train", ) plt.scatter( X_train[np.where(y_train[:] == 1), 0], X_train[np.where(y_train[:] == 1), 1], marker="o", facecolors="w", edgecolors="r", label="B train", ) plt.scatter( X_test[np.where(y_test[:] == 0), 0], X_test[np.where(y_test[:] == 0), 1], marker="s", facecolors="b", edgecolors="w", label="A test", ) plt.scatter( X_test[np.where(y_test[:] == 1), 0], X_test[np.where(y_test[:] == 1), 1], marker="o", facecolors="r", edgecolors="w", label="B test", ) plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0) plt.title("Ad hoc dataset for classification") plt.show() # Create a rotational layer to train. We will rotate each qubit the same amount. training_params = ParameterVector("θ", 1) fm0 = QuantumCircuit(2) fm0.ry(training_params[0], 0) fm0.ry(training_params[0], 1) # Use ZZFeatureMap to represent input data fm1 = ZZFeatureMap(2) # Create the feature map, composed of our two circuits fm = fm0.compose(fm1) print(circuit_drawer(fm)) print(f"Trainable parameters: {training_params}") # Instantiate quantum kernel quant_kernel = TrainableFidelityQuantumKernel(feature_map=fm, training_parameters=training_params) # Set up the optimizer cb_qkt = QKTCallback() spsa_opt = SPSA(maxiter=10, callback=cb_qkt.callback, learning_rate=0.05, perturbation=0.05) # Instantiate a quantum kernel trainer. qkt = QuantumKernelTrainer( quantum_kernel=quant_kernel, loss="svc_loss", optimizer=spsa_opt, initial_point=[np.pi / 2] ) # Train the kernel using QKT directly qka_results = qkt.fit(X_train, y_train) optimized_kernel = qka_results.quantum_kernel print(qka_results) # Use QSVC for classification qsvc = QSVC(quantum_kernel=optimized_kernel) # Fit the QSVC qsvc.fit(X_train, y_train) # Predict the labels labels_test = qsvc.predict(X_test) # Evalaute the test accuracy accuracy_test = metrics.balanced_accuracy_score(y_true=y_test, y_pred=labels_test) print(f"accuracy test: {accuracy_test}") plot_data = cb_qkt.get_callback_data() # callback data K = optimized_kernel.evaluate(X_train) # kernel matrix evaluated on the training samples plt.rcParams["font.size"] = 20 fig, ax = plt.subplots(1, 2, figsize=(14, 5)) ax[0].plot([i + 1 for i in range(len(plot_data[0]))], np.array(plot_data[2]), c="k", marker="o") ax[0].set_xlabel("Iterations") ax[0].set_ylabel("Loss") ax[1].imshow(K, cmap=cm.get_cmap("bwr", 20)) fig.tight_layout() plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/PayalSolanki2906/Quantum_algorithms_using_Qiskit
PayalSolanki2906
from qiskit import QuantumCircuit qc=QuantumCircuit() from qiskit import QuantumRegister qr = QuantumRegister(2,'a') qc.add_register(qr) qc.qregs ## qc.qregs is for displaying qc.draw() qc.h(qr[0]) ## applying Hadamard gate on the first qubit qc.draw() #qc.x(qr[0]) ## applying Hadamard gate on the first qubit #qc.draw() qc.cx(qr[1], qr[0]) qc.draw() from qiskit import Aer sv_sim = Aer.get_backend('aer_simulator') ##it is simulator for showing output for backend in Aer.backends(): print(backend) from qiskit import assemble qc.save_statevector() ## this converts output in to state vector qobj = assemble(qc) ## this assembles quantum circuit job = sv_sim.run(qobj) ## this is for running the job ket = job.result().get_statevector() for amplitude in ket: print(amplitude) new_qc = QuantumCircuit(qr) new_qc.initialize(ket, qr) new_qc.x(qr[0]) from qiskit import assemble new_qc.save_statevector() ## this converts output in to state vector qobj = assemble(new_qc) ## this assembles quantum circuit job = sv_sim.run(qobj) ket = job.result().get_statevector() for amplitude in ket: print(amplitude) from qiskit import ClassicalRegister cr = ClassicalRegister(2,'creg') qc.add_register(cr) qc.measure(qr[0],cr[0]) ##measuring first quibit on first classical register qc.measure(qr[1],cr[1]) ##measuring second quibit on second classical register qc.draw() aer_sim = Aer.get_backend('aer_simulator') qobj = assemble(qc, shots=100) ##shots is the number of experiments job = aer_sim.run(qobj, memory=True) ##.run is for running the experiments hist = job.result().get_counts() print(hist) from qiskit.visualization import plot_histogram plot_histogram(hist) samples = job.result().get_memory() #to get result of each experiment as a result print(samples) qubit = QuantumRegister(8) bit = ClassicalRegister(8) qc_2 = QuantumCircuit(qubit,bit) qc_2.x(qubit[7]) qc_2.measure(qubit,bit) # this is a way to do all the qc.measure(qr8[j],cr8[j]) at once qobj = assemble(qc_2, shots=8192) aer_sim.run(qobj).result().get_counts() qc = QuantumCircuit(2,1) ## where first arguments is corresponding to number of quantum regsiter and second ##argument is corresponding to the number of classical register. qc.h(0) qc.cx(0,1) qc.measure(1,0) qc.draw() sub_circuit = QuantumCircuit(3, name='toggle_cx') sub_circuit.cx(0,1) sub_circuit.cx(1,2) sub_circuit.cx(0,1) sub_circuit.cx(1,2) sub_circuit.draw() toggle_cx = sub_circuit.to_instruction() ##we convert this circuit to the custom gate qr = QuantumRegister(4) new_qc = QuantumCircuit(qr) new_qc.append(toggle_cx, [qr[1],qr[2],qr[3] ]) new_qc.draw()
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/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as drive_sched: d0 = pulse.drive_channel(0) a0 = pulse.acquire_channel(0) pulse.play(pulse.library.Constant(10, 1.0), d0) pulse.delay(20, d0) pulse.shift_phase(3.14/2, d0) pulse.set_phase(3.14, d0) pulse.shift_frequency(1e7, d0) pulse.set_frequency(5e9, d0) with pulse.build() as temp_sched: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), d0) pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), d0) pulse.call(temp_sched) pulse.acquire(30, a0, pulse.MemorySlot(0)) drive_sched.draw()
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/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit, transpile from qiskit.quantum_info import Kraus, SuperOp from qiskit_aer import AerSimulator from qiskit.tools.visualization import plot_histogram # Import from Qiskit Aer noise module from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError, pauli_error, depolarizing_error, thermal_relaxation_error) # Construct a 1-qubit bit-flip and phase-flip errors p_error = 0.05 bit_flip = pauli_error([('X', p_error), ('I', 1 - p_error)]) phase_flip = pauli_error([('Z', p_error), ('I', 1 - p_error)]) print(bit_flip) print(phase_flip) # Compose two bit-flip and phase-flip errors bitphase_flip = bit_flip.compose(phase_flip) print(bitphase_flip) # Tensor product two bit-flip and phase-flip errors with # bit-flip on qubit-0, phase-flip on qubit-1 error2 = phase_flip.tensor(bit_flip) print(error2) # Convert to Kraus operator bit_flip_kraus = Kraus(bit_flip) print(bit_flip_kraus) # Convert to Superoperator phase_flip_sop = SuperOp(phase_flip) print(phase_flip_sop) # Convert back to a quantum error print(QuantumError(bit_flip_kraus)) # Check conversion is equivalent to original error QuantumError(bit_flip_kraus) == bit_flip # Measurement miss-assignement probabilities p0given1 = 0.1 p1given0 = 0.05 ReadoutError([[1 - p1given0, p1given0], [p0given1, 1 - p0given1]]) # Create an empty noise model noise_model = NoiseModel() # Add depolarizing error to all single qubit u1, u2, u3 gates error = depolarizing_error(0.05, 1) noise_model.add_all_qubit_quantum_error(error, ['u1', 'u2', 'u3']) # Print noise model info print(noise_model) # Create an empty noise model noise_model = NoiseModel() # Add depolarizing error to all single qubit u1, u2, u3 gates on qubit 0 only error = depolarizing_error(0.05, 1) noise_model.add_quantum_error(error, ['u1', 'u2', 'u3'], [0]) # Print noise model info print(noise_model) # System Specification n_qubits = 4 circ = QuantumCircuit(n_qubits) # Test Circuit circ.h(0) for qubit in range(n_qubits - 1): circ.cx(qubit, qubit + 1) circ.measure_all() print(circ) # Ideal simulator and execution sim_ideal = AerSimulator() result_ideal = sim_ideal.run(circ).result() plot_histogram(result_ideal.get_counts(0)) # Example error probabilities p_reset = 0.03 p_meas = 0.1 p_gate1 = 0.05 # QuantumError objects error_reset = pauli_error([('X', p_reset), ('I', 1 - p_reset)]) error_meas = pauli_error([('X',p_meas), ('I', 1 - p_meas)]) error_gate1 = pauli_error([('X',p_gate1), ('I', 1 - p_gate1)]) error_gate2 = error_gate1.tensor(error_gate1) # Add errors to noise model noise_bit_flip = NoiseModel() noise_bit_flip.add_all_qubit_quantum_error(error_reset, "reset") noise_bit_flip.add_all_qubit_quantum_error(error_meas, "measure") noise_bit_flip.add_all_qubit_quantum_error(error_gate1, ["u1", "u2", "u3"]) noise_bit_flip.add_all_qubit_quantum_error(error_gate2, ["cx"]) print(noise_bit_flip) # Create noisy simulator backend sim_noise = AerSimulator(noise_model=noise_bit_flip) # Transpile circuit for noisy basis gates circ_tnoise = transpile(circ, sim_noise) # Run and get counts result_bit_flip = sim_noise.run(circ_tnoise).result() counts_bit_flip = result_bit_flip.get_counts(0) # Plot noisy output plot_histogram(counts_bit_flip) # T1 and T2 values for qubits 0-3 T1s = np.random.normal(50e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec T2s = np.random.normal(70e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec # Truncate random T2s <= T1s T2s = np.array([min(T2s[j], 2 * T1s[j]) for j in range(4)]) # Instruction times (in nanoseconds) time_u1 = 0 # virtual gate time_u2 = 50 # (single X90 pulse) time_u3 = 100 # (two X90 pulses) time_cx = 300 time_reset = 1000 # 1 microsecond time_measure = 1000 # 1 microsecond # QuantumError objects errors_reset = [thermal_relaxation_error(t1, t2, time_reset) for t1, t2 in zip(T1s, T2s)] errors_measure = [thermal_relaxation_error(t1, t2, time_measure) for t1, t2 in zip(T1s, T2s)] errors_u1 = [thermal_relaxation_error(t1, t2, time_u1) for t1, t2 in zip(T1s, T2s)] errors_u2 = [thermal_relaxation_error(t1, t2, time_u2) for t1, t2 in zip(T1s, T2s)] errors_u3 = [thermal_relaxation_error(t1, t2, time_u3) for t1, t2 in zip(T1s, T2s)] errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand( thermal_relaxation_error(t1b, t2b, time_cx)) for t1a, t2a in zip(T1s, T2s)] for t1b, t2b in zip(T1s, T2s)] # Add errors to noise model noise_thermal = NoiseModel() for j in range(4): noise_thermal.add_quantum_error(errors_reset[j], "reset", [j]) noise_thermal.add_quantum_error(errors_measure[j], "measure", [j]) noise_thermal.add_quantum_error(errors_u1[j], "u1", [j]) noise_thermal.add_quantum_error(errors_u2[j], "u2", [j]) noise_thermal.add_quantum_error(errors_u3[j], "u3", [j]) for k in range(4): noise_thermal.add_quantum_error(errors_cx[j][k], "cx", [j, k]) print(noise_thermal) # Run the noisy simulation sim_thermal = AerSimulator(noise_model=noise_thermal) # Transpile circuit for noisy basis gates circ_tthermal = transpile(circ, sim_thermal) # Run and get counts result_thermal = sim_thermal.run(circ_tthermal).result() counts_thermal = result_thermal.get_counts(0) # Plot noisy output plot_histogram(counts_thermal) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Qiskit's gates in QASM2.""" import unittest from math import pi import re from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.test import QiskitTestCase from qiskit.circuit import Parameter, Qubit, Clbit, Gate from qiskit.circuit.library import C3SXGate, CCZGate, CSGate, CSdgGate, PermutationGate from qiskit.qasm.exceptions import QasmError # Regex pattern to match valid OpenQASM identifiers VALID_QASM2_IDENTIFIER = re.compile("[a-z][a-zA-Z_0-9]*") class TestCircuitQasm(QiskitTestCase): """QuantumCircuit QASM2 tests.""" def test_circuit_qasm(self): """Test circuit qasm() method.""" qr1 = QuantumRegister(1, "qr1") qr2 = QuantumRegister(2, "qr2") cr = ClassicalRegister(3, "cr") qc = QuantumCircuit(qr1, qr2, cr) qc.p(0.3, qr1[0]) qc.u(0.3, 0.2, 0.1, qr2[1]) qc.s(qr2[1]) qc.sdg(qr2[1]) qc.cx(qr1[0], qr2[1]) qc.barrier(qr2) qc.cx(qr2[1], qr1[0]) qc.h(qr2[1]) qc.x(qr2[1]).c_if(cr, 0) qc.y(qr1[0]).c_if(cr, 1) qc.z(qr1[0]).c_if(cr, 2) qc.barrier(qr1, qr2) qc.measure(qr1[0], cr[0]) qc.measure(qr2[0], cr[1]) qc.measure(qr2[1], cr[2]) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; qreg qr1[1]; qreg qr2[2]; creg cr[3]; p(0.3) qr1[0]; u(0.3,0.2,0.1) qr2[1]; s qr2[1]; sdg qr2[1]; cx qr1[0],qr2[1]; barrier qr2[0],qr2[1]; cx qr2[1],qr1[0]; h qr2[1]; if(cr==0) x qr2[1]; if(cr==1) y qr1[0]; if(cr==2) z qr1[0]; barrier qr1[0],qr2[0],qr2[1]; measure qr1[0] -> cr[0]; measure qr2[0] -> cr[1]; measure qr2[1] -> cr[2];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_composite_circuit(self): """Test circuit qasm() method when a composite circuit instruction is included within circuit. """ composite_circ_qreg = QuantumRegister(2) composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ") composite_circ.h(0) composite_circ.x(1) composite_circ.cx(0, 1) composite_circ_instr = composite_circ.to_instruction() qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0, 1) qc.barrier() qc.append(composite_circ_instr, [0, 1]) qc.measure([0, 1], [0, 1]) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate composite_circ q0,q1 { h q0; x q1; cx q0,q1; } qreg qr[2]; creg cr[2]; h qr[0]; cx qr[0],qr[1]; barrier qr[0],qr[1]; composite_circ qr[0],qr[1]; measure qr[0] -> cr[0]; measure qr[1] -> cr[1];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_multiple_same_composite_circuits(self): """Test circuit qasm() method when a composite circuit is added to the circuit multiple times """ composite_circ_qreg = QuantumRegister(2) composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ") composite_circ.h(0) composite_circ.x(1) composite_circ.cx(0, 1) composite_circ_instr = composite_circ.to_instruction() qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0, 1) qc.barrier() qc.append(composite_circ_instr, [0, 1]) qc.append(composite_circ_instr, [0, 1]) qc.measure([0, 1], [0, 1]) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate composite_circ q0,q1 { h q0; x q1; cx q0,q1; } qreg qr[2]; creg cr[2]; h qr[0]; cx qr[0],qr[1]; barrier qr[0],qr[1]; composite_circ qr[0],qr[1]; composite_circ qr[0],qr[1]; measure qr[0] -> cr[0]; measure qr[1] -> cr[1];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_multiple_composite_circuits_with_same_name(self): """Test circuit qasm() method when multiple composite circuit instructions with the same circuit name are added to the circuit """ my_gate = QuantumCircuit(1, name="my_gate") my_gate.h(0) my_gate_inst1 = my_gate.to_instruction() my_gate = QuantumCircuit(1, name="my_gate") my_gate.x(0) my_gate_inst2 = my_gate.to_instruction() my_gate = QuantumCircuit(1, name="my_gate") my_gate.x(0) my_gate_inst3 = my_gate.to_instruction() qr = QuantumRegister(1, name="qr") circuit = QuantumCircuit(qr, name="circuit") circuit.append(my_gate_inst1, [qr[0]]) circuit.append(my_gate_inst2, [qr[0]]) my_gate_inst2_id = id(circuit.data[-1].operation) circuit.append(my_gate_inst3, [qr[0]]) my_gate_inst3_id = id(circuit.data[-1].operation) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate my_gate q0 {{ h q0; }} gate my_gate_{1} q0 {{ x q0; }} gate my_gate_{0} q0 {{ x q0; }} qreg qr[1]; my_gate qr[0]; my_gate_{1} qr[0]; my_gate_{0} qr[0];\n""".format( my_gate_inst3_id, my_gate_inst2_id ) self.assertEqual(circuit.qasm(), expected_qasm) def test_circuit_qasm_with_composite_circuit_with_children_composite_circuit(self): """Test circuit qasm() method when composite circuits with children composite circuits in the definitions are added to the circuit""" child_circ = QuantumCircuit(2, name="child_circ") child_circ.h(0) child_circ.cx(0, 1) parent_circ = QuantumCircuit(3, name="parent_circ") parent_circ.append(child_circ, range(2)) parent_circ.h(2) grandparent_circ = QuantumCircuit(4, name="grandparent_circ") grandparent_circ.append(parent_circ, range(3)) grandparent_circ.x(3) qc = QuantumCircuit(4) qc.append(grandparent_circ, range(4)) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate child_circ q0,q1 { h q0; cx q0,q1; } gate parent_circ q0,q1,q2 { child_circ q0,q1; h q2; } gate grandparent_circ q0,q1,q2,q3 { parent_circ q0,q1,q2; x q3; } qreg q[4]; grandparent_circ q[0],q[1],q[2],q[3];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_pi(self): """Test circuit qasm() method with pi params.""" circuit = QuantumCircuit(2) circuit.cz(0, 1) circuit.u(2 * pi, 3 * pi, -5 * pi, 0) qasm_str = circuit.qasm() circuit2 = QuantumCircuit.from_qasm_str(qasm_str) self.assertEqual(circuit, circuit2) def test_circuit_qasm_with_composite_circuit_with_one_param(self): """Test circuit qasm() method when a composite circuit instruction has one param """ original_str = """OPENQASM 2.0; include "qelib1.inc"; gate nG0(param0) q0 { h q0; } qreg q[3]; creg c[3]; nG0(pi) q[0];\n""" qc = QuantumCircuit.from_qasm_str(original_str) self.assertEqual(original_str, qc.qasm()) def test_circuit_qasm_with_composite_circuit_with_many_params_and_qubits(self): """Test circuit qasm() method when a composite circuit instruction has many params and qubits """ original_str = """OPENQASM 2.0; include "qelib1.inc"; gate nG0(param0,param1) q0,q1 { h q0; h q1; } qreg q[3]; qreg r[3]; creg c[3]; creg d[3]; nG0(pi,pi/2) q[0],r[0];\n""" qc = QuantumCircuit.from_qasm_str(original_str) self.assertEqual(original_str, qc.qasm()) def test_c3sxgate_roundtrips(self): """Test that C3SXGate correctly round trips. Qiskit gives this gate a different name ('c3sx') to the name in Qiskit's version of qelib1.inc ('c3sqrtx') gate, which can lead to resolution issues.""" qc = QuantumCircuit(4) qc.append(C3SXGate(), qc.qubits, []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; qreg q[4]; c3sqrtx q[0],q[1],q[2],q[3]; """ self.assertEqual(qasm, expected) parsed = QuantumCircuit.from_qasm_str(qasm) self.assertIsInstance(parsed.data[0].operation, C3SXGate) def test_c3sxgate_qasm_deprecation_warning(self): """Test deprecation warning for C3SXGate.""" with self.assertWarnsRegex(DeprecationWarning, r"Correct exporting to OpenQASM 2"): C3SXGate().qasm() def test_cczgate_qasm(self): """Test that CCZ dumps definition as a non-qelib1 gate.""" qc = QuantumCircuit(3) qc.append(CCZGate(), qc.qubits, []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate ccz q0,q1,q2 { h q2; ccx q0,q1,q2; h q2; } qreg q[3]; ccz q[0],q[1],q[2]; """ self.assertEqual(qasm, expected) def test_csgate_qasm(self): """Test that CS dumps definition as a non-qelib1 gate.""" qc = QuantumCircuit(2) qc.append(CSGate(), qc.qubits, []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate cs q0,q1 { p(pi/4) q0; cx q0,q1; p(-pi/4) q1; cx q0,q1; p(pi/4) q1; } qreg q[2]; cs q[0],q[1]; """ self.assertEqual(qasm, expected) def test_csdggate_qasm(self): """Test that CSdg dumps definition as a non-qelib1 gate.""" qc = QuantumCircuit(2) qc.append(CSdgGate(), qc.qubits, []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate csdg q0,q1 { p(-pi/4) q0; cx q0,q1; p(pi/4) q1; cx q0,q1; p(-pi/4) q1; } qreg q[2]; csdg q[0],q[1]; """ self.assertEqual(qasm, expected) def test_rzxgate_qasm(self): """Test that RZX dumps definition as a non-qelib1 gate.""" qc = QuantumCircuit(2) qc.rzx(0, 0, 1) qc.rzx(pi / 2, 1, 0) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate rzx(param0) q0,q1 { h q1; cx q0,q1; rz(param0) q1; cx q0,q1; h q1; } qreg q[2]; rzx(0) q[0],q[1]; rzx(pi/2) q[1],q[0]; """ self.assertEqual(qasm, expected) def test_ecrgate_qasm(self): """Test that ECR dumps its definition as a non-qelib1 gate.""" qc = QuantumCircuit(2) qc.ecr(0, 1) qc.ecr(1, 0) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate rzx(param0) q0,q1 { h q1; cx q0,q1; rz(param0) q1; cx q0,q1; h q1; } gate ecr q0,q1 { rzx(pi/4) q0,q1; x q0; rzx(-pi/4) q0,q1; } qreg q[2]; ecr q[0],q[1]; ecr q[1],q[0]; """ self.assertEqual(qasm, expected) def test_unitary_qasm(self): """Test that UnitaryGate can be dumped to OQ2 correctly.""" qc = QuantumCircuit(1) qc.unitary([[1, 0], [0, 1]], 0) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate unitary q0 { u(0,0,0) q0; } qreg q[1]; unitary q[0]; """ self.assertEqual(qasm, expected) def test_multiple_unitary_qasm(self): """Test that multiple UnitaryGate instances can all dump successfully.""" custom = QuantumCircuit(1, name="custom") custom.unitary([[1, 0], [0, -1]], 0) qc = QuantumCircuit(2) qc.unitary([[1, 0], [0, 1]], 0) qc.unitary([[0, 1], [1, 0]], 1) qc.append(custom.to_gate(), [0], []) qasm = qc.qasm() expected = re.compile( r"""OPENQASM 2.0; include "qelib1.inc"; gate unitary q0 { u\(0,0,0\) q0; } gate (?P<u1>unitary_[0-9]*) q0 { u\(pi,-pi/2,pi/2\) q0; } gate (?P<u2>unitary_[0-9]*) q0 { u\(0,pi/2,pi/2\) q0; } gate custom q0 { (?P=u2) q0; } qreg q\[2\]; unitary q\[0\]; (?P=u1) q\[1\]; custom q\[0\]; """, re.MULTILINE, ) self.assertRegex(qasm, expected) def test_unbound_circuit_raises(self): """Test circuits with unbound parameters raises.""" qc = QuantumCircuit(1) theta = Parameter("θ") qc.rz(theta, 0) with self.assertRaises(QasmError): qc.qasm() def test_gate_qasm_with_ctrl_state(self): """Test gate qasm() with controlled gate that has ctrl_state setting.""" from qiskit.quantum_info import Operator qc = QuantumCircuit(2) qc.ch(0, 1, ctrl_state=0) qasm_str = qc.qasm() self.assertEqual(Operator(qc), Operator(QuantumCircuit.from_qasm_str(qasm_str))) def test_circuit_qasm_with_mcx_gate(self): """Test circuit qasm() method with MCXGate See https://github.com/Qiskit/qiskit-terra/issues/4943 """ qc = QuantumCircuit(4) qc.mcx([0, 1, 2], 3) # qasm output doesn't support parameterized gate yet. # param0 for "gate mcuq(param0) is not used inside the definition expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate mcx q0,q1,q2,q3 { h q3; p(pi/8) q0; p(pi/8) q1; p(pi/8) q2; p(pi/8) q3; cx q0,q1; p(-pi/8) q1; cx q0,q1; cx q1,q2; p(-pi/8) q2; cx q0,q2; p(pi/8) q2; cx q1,q2; p(-pi/8) q2; cx q0,q2; cx q2,q3; p(-pi/8) q3; cx q1,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q0,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q1,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q0,q3; h q3; } qreg q[4]; mcx q[0],q[1],q[2],q[3];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_mcx_gate_variants(self): """Test circuit qasm() method with MCXGrayCode, MCXRecursive, MCXVChain""" import qiskit.circuit.library as cl n = 5 qc = QuantumCircuit(2 * n - 1) qc.append(cl.MCXGrayCode(n), range(n + 1)) qc.append(cl.MCXRecursive(n), range(n + 2)) qc.append(cl.MCXVChain(n), range(2 * n - 1)) # qasm output doesn't support parameterized gate yet. # param0 for "gate mcuq(param0) is not used inside the definition expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate mcu1(param0) q0,q1,q2,q3,q4,q5 { cu1(pi/16) q4,q5; cx q4,q3; cu1(-pi/16) q3,q5; cx q4,q3; cu1(pi/16) q3,q5; cx q3,q2; cu1(-pi/16) q2,q5; cx q4,q2; cu1(pi/16) q2,q5; cx q3,q2; cu1(-pi/16) q2,q5; cx q4,q2; cu1(pi/16) q2,q5; cx q2,q1; cu1(-pi/16) q1,q5; cx q4,q1; cu1(pi/16) q1,q5; cx q3,q1; cu1(-pi/16) q1,q5; cx q4,q1; cu1(pi/16) q1,q5; cx q2,q1; cu1(-pi/16) q1,q5; cx q4,q1; cu1(pi/16) q1,q5; cx q3,q1; cu1(-pi/16) q1,q5; cx q4,q1; cu1(pi/16) q1,q5; cx q1,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q3,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q2,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q3,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q1,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q3,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q2,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q3,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; } gate mcx_gray q0,q1,q2,q3,q4,q5 { h q5; mcu1(pi) q0,q1,q2,q3,q4,q5; h q5; } gate mcx q0,q1,q2,q3 { h q3; p(pi/8) q0; p(pi/8) q1; p(pi/8) q2; p(pi/8) q3; cx q0,q1; p(-pi/8) q1; cx q0,q1; cx q1,q2; p(-pi/8) q2; cx q0,q2; p(pi/8) q2; cx q1,q2; p(-pi/8) q2; cx q0,q2; cx q2,q3; p(-pi/8) q3; cx q1,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q0,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q1,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q0,q3; h q3; } gate mcx_recursive q0,q1,q2,q3,q4,q5,q6 { mcx q0,q1,q2,q6; mcx q3,q4,q6,q5; mcx q0,q1,q2,q6; mcx q3,q4,q6,q5; } gate mcx_vchain q0,q1,q2,q3,q4,q5,q6,q7,q8 { rccx q0,q1,q6; rccx q2,q6,q7; rccx q3,q7,q8; ccx q4,q8,q5; rccx q3,q7,q8; rccx q2,q6,q7; rccx q0,q1,q6; } qreg q[9]; mcx_gray q[0],q[1],q[2],q[3],q[4],q[5]; mcx_recursive q[0],q[1],q[2],q[3],q[4],q[5],q[6]; mcx_vchain q[0],q[1],q[2],q[3],q[4],q[5],q[6],q[7],q[8];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_registerless_bits(self): """Test that registerless bits do not have naming collisions in their registers.""" initial_registers = [QuantumRegister(2), ClassicalRegister(2)] qc = QuantumCircuit(*initial_registers, [Qubit(), Clbit()]) # Match a 'qreg identifier[3];'-like QASM register declaration. register_regex = re.compile(r"\s*[cq]reg\s+(\w+)\s*\[\d+\]\s*", re.M) qasm_register_names = set() for statement in qc.qasm().split(";"): match = register_regex.match(statement) if match: qasm_register_names.add(match.group(1)) self.assertEqual(len(qasm_register_names), 4) # Check that no additional registers were added to the circuit. self.assertEqual(len(qc.qregs), 1) self.assertEqual(len(qc.cregs), 1) # Check that the registerless-register names are recalculated after adding more registers, # to avoid naming clashes in this case. generated_names = qasm_register_names - {register.name for register in initial_registers} for generated_name in generated_names: qc.add_register(QuantumRegister(1, name=generated_name)) qasm_register_names = set() for statement in qc.qasm().split(";"): match = register_regex.match(statement) if match: qasm_register_names.add(match.group(1)) self.assertEqual(len(qasm_register_names), 6) def test_circuit_qasm_with_repeated_instruction_names(self): """Test that qasm() doesn't change the name of the instructions that live in circuit.data, but a copy of them when there are repeated names.""" qc = QuantumCircuit(2) qc.h(0) qc.x(1) # Create some random custom gate and name it "custom" custom = QuantumCircuit(1) custom.h(0) custom.y(0) gate = custom.to_gate() gate.name = "custom" # Another random custom gate named "custom" as well custom2 = QuantumCircuit(2) custom2.x(0) custom2.z(1) gate2 = custom2.to_gate() gate2.name = "custom" # Append custom gates with same name to original circuit qc.append(gate, [0]) qc.append(gate2, [1, 0]) # Expected qasm string will append the id to the second gate with repeated name expected_qasm = f"""OPENQASM 2.0; include "qelib1.inc"; gate custom q0 {{ h q0; y q0; }} gate custom_{id(gate2)} q0,q1 {{ x q0; z q1; }} qreg q[2]; h q[0]; x q[1]; custom q[0]; custom_{id(gate2)} q[1],q[0];\n""" # Check qasm() produced the correct string self.assertEqual(expected_qasm, qc.qasm()) # Check instruction names were not changed by qasm() names = ["h", "x", "custom", "custom"] for idx, instruction in enumerate(qc._data): self.assertEqual(instruction.operation.name, names[idx]) def test_circuit_qasm_with_invalid_identifiers(self): """Test that qasm() detects and corrects invalid OpenQASM gate identifiers, while not changing the instructions on the original circuit""" qc = QuantumCircuit(2) # Create some gate and give it an invalid name custom = QuantumCircuit(1) custom.x(0) custom.u(0, 0, pi, 0) gate = custom.to_gate() gate.name = "A[$]" # Another gate also with invalid name custom2 = QuantumCircuit(2) custom2.x(0) custom2.append(gate, [1]) gate2 = custom2.to_gate() gate2.name = "invalid[name]" # Append gates qc.append(gate, [0]) qc.append(gate2, [1, 0]) # Expected qasm with valid identifiers expected_qasm = "\n".join( [ "OPENQASM 2.0;", 'include "qelib1.inc";', "gate gate_A___ q0 { x q0; u(0,0,pi) q0; }", "gate invalid_name_ q0,q1 { x q0; gate_A___ q1; }", "qreg q[2];", "gate_A___ q[0];", "invalid_name_ q[1],q[0];", "", ] ) # Check qasm() produces the correct string self.assertEqual(expected_qasm, qc.qasm()) # Check instruction names were not changed by qasm() names = ["A[$]", "invalid[name]"] for idx, instruction in enumerate(qc._data): self.assertEqual(instruction.operation.name, names[idx]) def test_circuit_qasm_with_duplicate_invalid_identifiers(self): """Test that qasm() corrects invalid identifiers and the de-duplication code runs correctly, without altering original instructions""" base = QuantumCircuit(1) # First gate with invalid name, escapes to "invalid__" clash1 = QuantumCircuit(1, name="invalid??") clash1.x(0) base.append(clash1, [0]) # Second gate with invalid name that also escapes to "invalid__" clash2 = QuantumCircuit(1, name="invalid[]") clash2.z(0) base.append(clash2, [0]) # Check qasm is correctly produced names = set() for match in re.findall(r"gate (\S+)", base.qasm()): self.assertTrue(VALID_QASM2_IDENTIFIER.fullmatch(match)) names.add(match) self.assertEqual(len(names), 2) # Check instruction names were not changed by qasm() names = ["invalid??", "invalid[]"] for idx, instruction in enumerate(base._data): self.assertEqual(instruction.operation.name, names[idx]) def test_circuit_qasm_escapes_register_names(self): """Test that registers that have invalid OpenQASM 2 names get correctly escaped, even when they would escape to the same value.""" qc = QuantumCircuit(QuantumRegister(2, "?invalid"), QuantumRegister(2, "!invalid")) qc.cx(0, 1) qc.cx(2, 3) qasm = qc.qasm() match = re.fullmatch( rf"""OPENQASM 2.0; include "qelib1.inc"; qreg ({VALID_QASM2_IDENTIFIER.pattern})\[2\]; qreg ({VALID_QASM2_IDENTIFIER.pattern})\[2\]; cx \1\[0\],\1\[1\]; cx \2\[0\],\2\[1\]; """, qasm, ) self.assertTrue(match) self.assertNotEqual(match.group(1), match.group(2)) def test_circuit_qasm_escapes_reserved(self): """Test that the OpenQASM 2 exporter won't export reserved names.""" qc = QuantumCircuit(QuantumRegister(1, "qreg")) gate = Gate("gate", 1, []) gate.definition = QuantumCircuit(1) qc.append(gate, [qc.qubits[0]]) qasm = qc.qasm() match = re.fullmatch( rf"""OPENQASM 2.0; include "qelib1.inc"; gate ({VALID_QASM2_IDENTIFIER.pattern}) q0 {{ }} qreg ({VALID_QASM2_IDENTIFIER.pattern})\[1\]; \1 \2\[0\]; """, qasm, ) self.assertTrue(match) self.assertNotEqual(match.group(1), "gate") self.assertNotEqual(match.group(1), "qreg") def test_circuit_qasm_with_double_precision_rotation_angle(self): """Test that qasm() emits high precision rotation angles per default.""" from qiskit.circuit.tools.pi_check import MAX_FRAC qc = QuantumCircuit(1) qc.p(0.123456789, 0) qc.p(pi * pi, 0) qc.p(MAX_FRAC * pi + 1, 0) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; p(0.123456789) q[0]; p(9.869604401089358) q[0]; p(51.26548245743669) q[0];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_rotation_angles_close_to_pi(self): """Test that qasm() properly rounds values closer than 1e-12 to pi.""" qc = QuantumCircuit(1) qc.p(pi + 1e-11, 0) qc.p(pi + 1e-12, 0) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; p(3.141592653599793) q[0]; p(pi) q[0];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_raises_on_single_bit_condition(self): """OpenQASM 2 can't represent single-bit conditions, so test that a suitable error is printed if this is attempted.""" qc = QuantumCircuit(1, 1) qc.x(0).c_if(0, True) with self.assertRaisesRegex(QasmError, "OpenQASM 2 can only condition on registers"): qc.qasm() def test_circuit_raises_invalid_custom_gate_no_qubits(self): """OpenQASM 2 exporter of custom gates with no qubits. See: https://github.com/Qiskit/qiskit-terra/issues/10435""" legit_circuit = QuantumCircuit(5, name="legit_circuit") empty_circuit = QuantumCircuit(name="empty_circuit") legit_circuit.append(empty_circuit) with self.assertRaisesRegex(QasmError, "acts on zero qubits"): legit_circuit.qasm() def test_circuit_raises_invalid_custom_gate_clbits(self): """OpenQASM 2 exporter of custom instruction. See: https://github.com/Qiskit/qiskit-terra/issues/7351""" instruction = QuantumCircuit(2, 2, name="inst") instruction.cx(0, 1) instruction.measure([0, 1], [0, 1]) custom_instruction = instruction.to_instruction() qc = QuantumCircuit(2, 2) qc.append(custom_instruction, [0, 1], [0, 1]) with self.assertRaisesRegex(QasmError, "acts on 2 classical bits"): qc.qasm() def test_circuit_qasm_with_permutations(self): """Test circuit qasm() method with Permutation gates.""" qc = QuantumCircuit(4) qc.append(PermutationGate([2, 1, 0]), [0, 1, 2]) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate permutation__2_1_0_ q0,q1,q2 { swap q0,q2; } qreg q[4]; permutation__2_1_0_ q[0],q[1],q[2];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_multiple_permutation(self): """Test that multiple PermutationGates can be added to a circuit.""" custom = QuantumCircuit(3, name="custom") custom.append(PermutationGate([2, 1, 0]), [0, 1, 2]) custom.append(PermutationGate([0, 1, 2]), [0, 1, 2]) qc = QuantumCircuit(4) qc.append(PermutationGate([2, 1, 0]), [0, 1, 2], []) qc.append(PermutationGate([1, 2, 0]), [0, 1, 2], []) qc.append(custom.to_gate(), [1, 3, 2], []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate permutation__2_1_0_ q0,q1,q2 { swap q0,q2; } gate permutation__1_2_0_ q0,q1,q2 { swap q1,q2; swap q0,q2; } gate permutation__0_1_2_ q0,q1,q2 { } gate custom q0,q1,q2 { permutation__2_1_0_ q0,q1,q2; permutation__0_1_2_ q0,q1,q2; } qreg q[4]; permutation__2_1_0_ q[0],q[1],q[2]; permutation__1_2_0_ q[0],q[1],q[2]; custom q[1],q[3],q[2]; """ self.assertEqual(qasm, expected) def test_circuit_qasm_with_reset(self): """Test circuit qasm() method with Reset.""" qc = QuantumCircuit(2) qc.reset([0, 1]) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; qreg q[2]; reset q[0]; reset q[1];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_nested_gate_naming_clashes(self): """Test that gates that have naming clashes but only appear in the body of another gate still get exported correctly.""" # pylint: disable=missing-class-docstring class Inner(Gate): def __init__(self, param): super().__init__("inner", 1, [param]) def _define(self): self._definition = QuantumCircuit(1) self._definition.rx(self.params[0], 0) class Outer(Gate): def __init__(self, param): super().__init__("outer", 1, [param]) def _define(self): self._definition = QuantumCircuit(1) self._definition.append(Inner(self.params[0]), [0], []) qc = QuantumCircuit(1) qc.append(Outer(1.0), [0], []) qc.append(Outer(2.0), [0], []) qasm = qc.qasm() expected = re.compile( r"""OPENQASM 2\.0; include "qelib1\.inc"; gate inner\(param0\) q0 { rx\(1\.0\) q0; } gate outer\(param0\) q0 { inner\(1\.0\) q0; } gate (?P<inner1>inner_[0-9]*)\(param0\) q0 { rx\(2\.0\) q0; } gate (?P<outer1>outer_[0-9]*)\(param0\) q0 { (?P=inner1)\(2\.0\) q0; } qreg q\[1\]; outer\(1\.0\) q\[0\]; (?P=outer1)\(2\.0\) q\[0\]; """, re.MULTILINE, ) self.assertRegex(qasm, expected) def test_opaque_output(self): """Test that gates with no definition are exported as `opaque`.""" custom = QuantumCircuit(1, name="custom") custom.append(Gate("my_c", 1, []), [0]) qc = QuantumCircuit(2) qc.append(Gate("my_a", 1, []), [0]) qc.append(Gate("my_a", 1, []), [1]) qc.append(Gate("my_b", 2, [1.0]), [1, 0]) qc.append(custom.to_gate(), [0], []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; opaque my_a q0; opaque my_b(param0) q0,q1; opaque my_c q0; gate custom q0 { my_c q0; } qreg q[2]; my_a q[0]; my_a q[1]; my_b(1.0) q[1],q[0]; custom q[0]; """ self.assertEqual(qasm, expected) def test_sequencial_inner_gates_with_same_name(self): """Test if inner gates sequentially added with the same name result in the correct qasm""" qubits_range = range(3) gate_a = QuantumCircuit(3, name="a") gate_a.h(qubits_range) gate_a = gate_a.to_instruction() gate_b = QuantumCircuit(3, name="a") gate_b.append(gate_a, qubits_range) gate_b.x(qubits_range) gate_b = gate_b.to_instruction() qc = QuantumCircuit(3) qc.append(gate_b, qubits_range) qc.z(qubits_range) gate_a_id = id(qc.data[0].operation) expected_output = f"""OPENQASM 2.0; include "qelib1.inc"; gate a q0,q1,q2 {{ h q0; h q1; h q2; }} gate a_{gate_a_id} q0,q1,q2 {{ a q0,q1,q2; x q0; x q1; x q2; }} qreg q[3]; a_{gate_a_id} q[0],q[1],q[2]; z q[0]; z q[1]; z q[2]; """ self.assertEqual(qc.qasm(), expected_output) def test_empty_barrier(self): """Test that a blank barrier statement in _Qiskit_ acts over all qubits, while an explicitly no-op barrier (assuming Qiskit continues to allow this) is not output to OQ2 at all, since the statement requires an argument in the spec.""" qc = QuantumCircuit(QuantumRegister(2, "qr1"), QuantumRegister(3, "qr2")) qc.barrier() # In Qiskit land, this affects _all_ qubits. qc.barrier([]) # This explicitly affects _no_ qubits (so is totally meaningless). expected = """\ OPENQASM 2.0; include "qelib1.inc"; qreg qr1[2]; qreg qr2[3]; barrier qr1[0],qr1[1],qr2[0],qr2[1],qr2[2]; """ self.assertEqual(qc.qasm(), expected) def test_small_angle_valid(self): """Test that small angles do not get converted to invalid OQ2 floating-point values.""" # OQ2 _technically_ requires a decimal point in all floating-point values, even ones that # are followed by an exponent. qc = QuantumCircuit(1) qc.rx(0.000001, 0) expected = """\ OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; rx(1.e-06) q[0]; """ self.assertEqual(qc.qasm(), expected) if __name__ == "__main__": unittest.main()
https://github.com/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/hritiksauw199/Qiskit-textbook-solutions
hritiksauw199
from qiskit_textbook.widgets import bv_widget bv_widget(4, "1011", hide_oracle=False) from qiskit_textbook.widgets import bv_widget bv_widget(8, "11101101", hide_oracle=False)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=missing-docstring,invalid-name,no-member # pylint: disable=attribute-defined-outside-init # pylint: disable=unused-argument from qiskit import QuantumRegister, QuantumCircuit from qiskit.compiler import transpile from qiskit.quantum_info.random import random_unitary class IsometryTranspileBench: params = ([0, 1, 2, 3], [3, 4, 5, 6]) param_names = ["number of input qubits", "number of output qubits"] def setup(self, m, n): q = QuantumRegister(n) qc = QuantumCircuit(q) if not hasattr(qc, "iso"): raise NotImplementedError iso = random_unitary(2**n, seed=0).data[:, 0 : 2**m] if len(iso.shape) == 1: iso = iso.reshape((len(iso), 1)) qc.iso(iso, q[:m], q[m:]) self.circuit = qc def track_cnot_counts_after_mapping_to_ibmq_16_melbourne(self, *unused): coupling = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] circuit = transpile( self.circuit, basis_gates=["u1", "u3", "u2", "cx"], coupling_map=coupling, seed_transpiler=0, ) counts = circuit.count_ops() cnot_count = counts.get("cx", 0) return cnot_count
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.circuit import Parameter from qiskit import QuantumCircuit theta = Parameter('$\\theta$') chsh_circuits_no_meas = QuantumCircuit(2) chsh_circuits_no_meas.h(0) chsh_circuits_no_meas.cx(0, 1) chsh_circuits_no_meas.ry(theta, 0) chsh_circuits_no_meas.draw('mpl') import numpy as np number_of_phases = 21 phases = np.linspace(0, 2*np.pi, number_of_phases) # Phases need to be expressed as list of lists in order to work individual_phases = [[ph] for ph in phases] from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService() backend = "ibmq_qasm_simulator" # use the simulator from qiskit_ibm_runtime import Estimator, Session from qiskit.quantum_info import SparsePauliOp ZZ = SparsePauliOp.from_list([("ZZ", 1)]) ZX = SparsePauliOp.from_list([("ZX", 1)]) XZ = SparsePauliOp.from_list([("XZ", 1)]) XX = SparsePauliOp.from_list([("XX", 1)]) ops = [ZZ, ZX, XZ, XX] chsh_est_sim = [] # Simulator with Session(service=service, backend=backend): estimator = Estimator() for op in ops: job = estimator.run( circuits=[chsh_circuits_no_meas]*len(individual_phases), observables=[op]*len(individual_phases), parameter_values=individual_phases) est_result = job.result() chsh_est_sim.append(est_result) # <CHSH1> = <AB> - <Ab> + <aB> + <ab> chsh1_est_sim = chsh_est_sim[0].values - chsh_est_sim[1].values + chsh_est_sim[2].values + chsh_est_sim[3].values # <CHSH2> = <AB> + <Ab> - <aB> + <ab> chsh2_est_sim = chsh_est_sim[0].values + chsh_est_sim[1].values - chsh_est_sim[2].values + chsh_est_sim[3].values import matplotlib.pyplot as plt import matplotlib.ticker as tck fig, ax = plt.subplots(figsize=(10, 6)) # results from a simulator ax.plot(phases/np.pi, chsh1_est_sim, 'o-', label='CHSH1 Simulation') ax.plot(phases/np.pi, chsh2_est_sim, 'o-', label='CHSH2 Simulation') # classical bound +-2 ax.axhline(y=2, color='r', linestyle='--') ax.axhline(y=-2, color='r', linestyle='--') # quantum bound, +-2√2 ax.axhline(y=np.sqrt(2)*2, color='b', linestyle='-.') ax.axhline(y=-np.sqrt(2)*2, color='b', linestyle='-.') # set x tick labels to the unit of pi ax.xaxis.set_major_formatter(tck.FormatStrFormatter('%g $\pi$')) ax.xaxis.set_major_locator(tck.MultipleLocator(base=0.5)) # set title, labels, and legend plt.title('Violation of CHSH Inequality') plt.xlabel('Theta') plt.ylabel('CHSH witness') plt.legend() import qiskit_ibm_runtime qiskit_ibm_runtime.version.get_version_info() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# Import requisite modules import math import datetime import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Import Qiskit packages from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit_aer.primitives import Sampler from qiskit_optimization.algorithms import MinimumEigenOptimizer # The data providers of stock-market data from qiskit_finance.data_providers import RandomDataProvider from qiskit_finance.applications.optimization import PortfolioDiversification # Generate a pairwise time-series similarity matrix seed = 123 stocks = ["TICKER1", "TICKER2"] n = len(stocks) data = RandomDataProvider( tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=seed, ) data.run() rho = data.get_similarity_matrix() q = 1 # q less or equal than n class ClassicalOptimizer: def __init__(self, rho, n, q): self.rho = rho self.n = n # number of inner variables self.q = q # number of required selection def compute_allowed_combinations(self): f = math.factorial return int(f(self.n) / f(self.q) / f(self.n - self.q)) def cplex_solution(self): # refactoring rho = self.rho n = self.n q = self.q my_obj = list(rho.reshape(1, n**2)[0]) + [0.0 for x in range(0, n)] my_ub = [1 for x in range(0, n**2 + n)] my_lb = [0 for x in range(0, n**2 + n)] my_ctype = "".join(["I" for x in range(0, n**2 + n)]) my_rhs = ( [q] + [1 for x in range(0, n)] + [0 for x in range(0, n)] + [0.1 for x in range(0, n**2)] ) my_sense = ( "".join(["E" for x in range(0, 1 + n)]) + "".join(["E" for x in range(0, n)]) + "".join(["L" for x in range(0, n**2)]) ) try: my_prob = cplex.Cplex() self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs) my_prob.solve() except CplexError as exc: print(exc) return x = my_prob.solution.get_values() x = np.array(x) cost = my_prob.solution.get_objective_value() return x, cost def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs): n = self.n prob.objective.set_sense(prob.objective.sense.minimize) prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype) prob.set_log_stream(None) prob.set_error_stream(None) prob.set_warning_stream(None) prob.set_results_stream(None) rows = [] col = [x for x in range(n**2, n**2 + n)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [x for x in range(0 + n * ii, n + n * ii)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [ii * n + ii, n**2 + ii] coef = [1, -1] rows.append([col, coef]) for ii in range(0, n): for jj in range(0, n): col = [ii * n + jj, n**2 + jj] coef = [1, -1] rows.append([col, coef]) prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs) # Instantiate the classical optimizer class classical_optimizer = ClassicalOptimizer(rho, n, q) # Compute the number of feasible solutions: print("Number of feasible combinations= " + str(classical_optimizer.compute_allowed_combinations())) # Compute the total number of possible combinations (feasible + unfeasible) print("Total number of combinations= " + str(2 ** (n * (n + 1)))) # Visualize the solution def visualize_solution(xc, yc, x, C, n, K, title_str): plt.figure() plt.scatter(xc, yc, s=200) for i in range(len(xc)): plt.annotate(i, (xc[i] + 0.015, yc[i]), size=16, color="r") plt.grid() for ii in range(n**2, n**2 + n): if x[ii] > 0: plt.plot(xc[ii - n**2], yc[ii - n**2], "r*", ms=20) for ii in range(0, n**2): if x[ii] > 0: iy = ii // n ix = ii % n plt.plot([xc[ix], xc[iy]], [yc[ix], yc[iy]], "C2") plt.title(title_str + " cost = " + str(int(C * 100) / 100.0)) plt.show() from qiskit.utils import algorithm_globals class QuantumOptimizer: def __init__(self, rho, n, q): self.rho = rho self.n = n self.q = q self.pdf = PortfolioDiversification(similarity_matrix=rho, num_assets=n, num_clusters=q) self.qp = self.pdf.to_quadratic_program() # Obtains the least eigenvalue of the Hamiltonian classically def exact_solution(self): exact_mes = NumPyMinimumEigensolver() exact_eigensolver = MinimumEigenOptimizer(exact_mes) result = exact_eigensolver.solve(self.qp) return self.decode_result(result) def vqe_solution(self): algorithm_globals.random_seed = 100 cobyla = COBYLA() cobyla.set_options(maxiter=250) ry = TwoLocal(n, "ry", "cz", reps=5, entanglement="full") vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla) vqe = MinimumEigenOptimizer(vqe_mes) result = vqe.solve(self.qp) return self.decode_result(result) def qaoa_solution(self): algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=250) qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3) qaoa = MinimumEigenOptimizer(qaoa_mes) result = qaoa.solve(self.qp) return self.decode_result(result) def decode_result(self, result, offset=0): quantum_solution = 1 - (result.x) ground_level = self.qp.objective.evaluate(result.x) return quantum_solution, ground_level # Instantiate the quantum optimizer class with parameters: quantum_optimizer = QuantumOptimizer(rho, n, q) # Check if the binary representation is correct. This requires CPLEX try: import cplex # warnings.filterwarnings('ignore') quantum_solution, quantum_cost = quantum_optimizer.exact_solution() print(quantum_solution, quantum_cost) classical_solution, classical_cost = classical_optimizer.cplex_solution() print(classical_solution, classical_cost) if np.abs(quantum_cost - classical_cost) < 0.01: print("Binary formulation is correct") else: print("Error in the formulation of the Hamiltonian") except Exception as ex: print(ex) ground_state, ground_level = quantum_optimizer.exact_solution() print(ground_state) classical_cost = 1.000779571614484 # obtained from the CPLEX solution try: if np.abs(ground_level - classical_cost) < 0.01: print("Ising Hamiltonian in Z basis is correct") else: print("Error in the Ising Hamiltonian formulation") except Exception as ex: print(ex) vqe_state, vqe_level = quantum_optimizer.vqe_solution() print(vqe_state, vqe_level) try: if np.linalg.norm(ground_state - vqe_state) < 0.01: print("SamplingVQE produces the same solution as the exact eigensolver.") else: print( "SamplingVQE does not produce the same solution as the exact eigensolver, but that is to be expected." ) except Exception as ex: print(ex) xc, yc = data.get_coordinates() visualize_solution(xc, yc, ground_state, ground_level, n, q, "Classical") visualize_solution(xc, yc, vqe_state, vqe_level, n, q, "VQE") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/abhilash1910/EuroPython-21-QuantumDeepLearning
abhilash1910
!pip install pennylane !pip install qiskit import pennylane as qml from pennylane import numpy as np import tensorflow as tf import matplotlib.pyplot as plt device=qml.device("default.qubit",wires=2) @qml.qnode(device,interface='tf') def create_circuit(inputs): qml.RX(inputs[0],wires=0) qml.RY(inputs[1],wires=1) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0)) # return qml.expval(qml.PauliZ(0)@qml.PauliZ(1)) @tf.function def cost_function(x,step): val=-(-1)**(step//100) #delta=tf.abs(tf.square(create_circuit(x)-val)) delta= tf.reduce_mean(tf.square(create_circuit(x)-val)) return delta def initialize_tensor(angle_1,angle_2): tensors=[] phi=tf.Variable(angle_1) theta=tf.Variable(angle_2) tensors.append(phi) tensors.append(theta) return tensors def optimize_circuit(tensors,steps): g0,g1,g2,g3=[],[],[],[] opt = tf.keras.optimizers.SGD(learning_rate=0.1) for i in range(steps): with tf.GradientTape() as tape: loss=cost_function(tensors,i) grads=tape.gradient(loss,tensors) opt.apply_gradients(zip(grads, tensors)) g0.append(grads[0].numpy()[0]) g1.append(grads[0].numpy()[1]) g2.append(grads[1].numpy()[0]) g3.append(grads[1].numpy()[1]) if (i+1)%5==0: print(f"Gradients after {i} iterations:") print(f"Gradient 1:{grads[0]} ,Gradient 2:{grads[1]} For the provided input tensor") plt.plot(g0) #plt.plot(g1) plt.plot(g2) #plt.plot(g3) plt.show() return g0,g1,g2,g3 phi=[0.05,0.87] theta=[0.43,0.034] tf_tensors=initialize_tensor(phi,theta) conj_angles=[phi,theta] #create_circuit(conj_angles) steps=200 g0,g1,g2,g3=optimize_circuit(tf_tensors,steps) from qiskit.visualization import plot_bloch_vector %matplotlib inline final_anglex=g0[-1] final_angley=g1[-1] final_anglex1=g2[-1] final_angley1=g3[-1] rot_1=[final_anglex,final_angley,0] rot_2=[final_anglex1,final_angley1,0] plot_bloch_vector([rot_1], title="Bloch Sphere")
https://github.com/chaurasiyag/minor-project-quantum-computing
chaurasiyag
from qiskit import * qr=QuantumRegister(1) qc=ClassicalRegister(1) cir=QuantumCircuit(qr,qc) cir.draw() cir.x(qr[0]) cir.draw() cir.measure(qr,qc) cir.draw() simulator=BasicAer.get_backend("qasm_simulator") res=execute(cir,backend=simulator).result() print(res) from qiskit.tools.visualization import plot_histogram plot_histogram(res.get_counts(cir)) IBMQ.save_account('7cd5664973bf6ce405272fc6fa2bd7684625b387b768de3dd459fa38dd3cdc417387fa4c306562485e0bb6ddb46fd20fcd24da495248304d90d155b52011fd6f') IBMQ.load_account() provider=IBMQ.get_provider('ibm-q') qcomp=provider.get_backend('ibmq_quito') job=execute(cir,backend=qcomp) from qiskit.tools.monitor import job_monitor job_monitor(job) res=job.result() plot_histogram(res.get_counts(cir)) from qiskit import * from math import pi qr=QuantumRegister(1) cr=ClassicalRegister(1) qc=QuantumCircuit(qr,cr) qc.draw() qc.u3(pi,0,0,qr[0]) qc.measure(qr,cr) qc.draw() simulator=BasicAer.get_backend("qasm_simulator") job=execute(qc,backend=simulator) from qiskit.tools.visualization import plot_histogram plot_histogram(job.result().get_counts()) plot_histogram(job.result().get_counts(qc)) qrr=QuantumRegister(1) crr=ClassicalRegister(1) qcc=QuantumCircuit(qrr,crr) qcc.x(qrr[0]) qcc.z(qrr[0]) qcc.draw() qcc.measure(qrr,crr) simu=BasicAer.get_backend("qasm_simulator") result=execute(qcc,backend=simu).result() plot_histogram(result.get_counts(qcc)) qr2=QuantumRegister(2) cr2=ClassicalRegister(2) qc=QuantumCircuit(qr2,cr2) qc.h(qr2[0]) qc.cx(qr2[0],qr2[1]) qc.draw() qc.measure(qr2,cr2) simu=BasicAer.get_backend("qasm_simulator") result=execute(qc,backend=simu).result() from qiskit.tools.visualization import plot_histogram plot_histogram(result.get_counts(qc)) IBMQ.save_account('7cd5664973bf6ce405272fc6fa2bd7684625b387b768de3dd459fa38dd3cdc417387fa4c306562485e0bb6ddb46fd20fcd24da495248304d90d155b52011fd6f',overwrite=True) IBMQ.load_account() pr=IBMQ.get_provider('ibm-q') qcomp=pr.get_backend("ibmq_quito") job=execute(qc,backend=qcomp) from qiskit.tools.monitor import job_monitor job_monitor(job) res=job.result() plot_histogram(res.get_counts(qc)) qiskit.tools from qiskit import * from qiskit.tools.monitor import job_monitor from qiskit.visualization import plot_histogram qr=QuantumRegister(2) cr=ClassicalRegister(2) qc=QuantumCircuit(qr,cr) qc.x(qr[0]) qc.draw() qc.h(qr[0]) qc.cx(qr[0],qr[1]) qc.draw() qc.measure(qr,cr) simu=BasicAer.get_backend("qasm_simulator") result=execute(qc,backend=simu).result() plot_histogram(result.get_counts(qc)) IBMQ.save_account('c10fa12997ad898683c72c5496c720b9657d7b96ce93b3f443366854e87973466f32f0bd9d807b4c147a63ac230eb03987972bdf400193154e11bdd834503a58',overwrite=True) IBMQ.load_account() pr=IBMQ.get_provider("ibm-q") qcomp=pr.get_backend("ibmq_manila") job=execute(qc,backend=qcomp) job_monitor(job) result=job.result() plot_histogram(result.get_counts(qc)) qr1=QuantumRegister(2) cr1=ClassicalRegister(2) qc1=QuantumCircuit(qr1,cr1) qc1.h(qr1[0]) qc1.x(qr1[1]) qc1.cx(qr1[0],qr1[1]) qc1.measure(qr1,cr1) simu=BasicAer.get_backend("qasm_simulator") job=execute(qc1,backend=simu).result() print(job.get_counts()) plot_histogram(job.get_counts(qc1)) qcomp1=pr.get_backend("ibmq_manila") job1=execute(qc1,backend=qcomp1) job_monitor(job1) plot_histogram(job1.result().get_counts(q)) print(job1.result().get_counts()) from qiskit import * from qiskit.visualization import plot_histogram from qiskit.tools.monitor import job_monitor qr2=QuantumRegister(2) cr2=ClassicalRegister(2) qc2=QuantumCircuit(qr2,cr2) qc2.x(qr2[0]) qc2.x(qr2[1]) qc2.h(qr2[0]) qc2.cx(qr2[0],qr2[1]) qc2.draw() simu=BasicAer.get_backend("qasm_simulator") qc2.measure(qr2,cr2) job3=execute(qc2,backend=simu) print(job3.result().get_counts()) plot_histogram(job3.result().get_counts()) IBMQ.load_account() pr=IBMQ.get_provider("ibm-q") qcomp2=pr.get_backend("ibmq_manila") job4=execute(qc2,backend=qcomp2) job_monitor(job4) print(job4.result().get_counts()) plot_histogram(job4.result().get_counts()) from qiskit import * bell=QuantumCircuit(2,2) bell.h(0) bell.cx(0,1) meas=QuantumCircuit(2,2) meas.measure([0,1],[0,1]) backend=BasicAer.get_backend('qasm_simulator') circ=bell.compose(meas) result=backend.run(transpile(circ,backend)).result() count=result.get_counts(circ) print(count) from qiskit.visualization import plot_bloch_multivector,plot_state_qsphere,plot_histogram,plot_bloch_vector # bell=QuantumCircuit(1,1) bell.h(0) bell.y(0) backend=BasicAer.get_backend('statevector_simulator') result=backend.run(transpile(bell,backend)).result() ps1=result.get_statevector(bell) plot_bloch_multivector(ps1) !pip install seaborn # plot_state_qsphere(ps1) # plot_bloch_vector(['00','11']) q=QuantumCircuit(1,1) q.y(0) plot_bloch_multivector(q) from qiskit_textbook.widgets import bloch_calc !pip install qiskit_textbook from qiskit_textbook.widgets import binary_widget binary_widget(nbits=5) print("Just adding for update automatically on github repo using shell script cronjob") print("Added Second Line to Check Automatic Update") print("third") print($$$) print(000) print("Last") print("Automatic Updates Successfully") from qiskit import * import numpy as np pi=np.pi def qft(no_of_qbit): qc=QuantumCircuit(no_of_qbit) for qbit in range(no_of_qbit): qc.h(qbit) for other_qbit in range(qbit+1,no_of_qbit): qc.cu1(pi/(2**(other_qbit-qbit)),other_qbit,qbit) return qc display(qft(5).draw()) display(qft(4).draw()) display(qft(3).draw()) print(90)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute from qiskit import Aer import numpy as np import sys N=int(sys.argv[1]) filename = sys.argv[2] backend = Aer.get_backend('unitary_simulator') def GHZ(n): if n<=0: return None circ = QuantumCircuit(n) # Put your code below # ---------------------------- circ.h(0) for x in range(1,n): circ.cx(x-1,x) # ---------------------------- return circ circuit = GHZ(N) job = execute(circuit, backend, shots=8192) result = job.result() array = result.get_unitary(circuit,3) np.savetxt(filename, array, delimiter=",", fmt = "%0.3f")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag from qiskit.circuit.library.standard_gates import CHGate, U2Gate, CXGate from qiskit.converters import dag_to_circuit q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') circ = QuantumCircuit(q, c) circ.h(q[0]) circ.cx(q[0], q[1]) circ.measure(q[0], c[0]) circ.rz(0.5, q[1]).c_if(c, 2) dag = circuit_to_dag(circ) circuit = dag_to_circuit(dag) circuit.draw('mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# Import requisite modules import math import datetime import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Import Qiskit packages from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit_aer.primitives import Sampler from qiskit_optimization.algorithms import MinimumEigenOptimizer # The data providers of stock-market data from qiskit_finance.data_providers import RandomDataProvider from qiskit_finance.applications.optimization import PortfolioDiversification # Generate a pairwise time-series similarity matrix seed = 123 stocks = ["TICKER1", "TICKER2"] n = len(stocks) data = RandomDataProvider( tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=seed, ) data.run() rho = data.get_similarity_matrix() q = 1 # q less or equal than n class ClassicalOptimizer: def __init__(self, rho, n, q): self.rho = rho self.n = n # number of inner variables self.q = q # number of required selection def compute_allowed_combinations(self): f = math.factorial return int(f(self.n) / f(self.q) / f(self.n - self.q)) def cplex_solution(self): # refactoring rho = self.rho n = self.n q = self.q my_obj = list(rho.reshape(1, n**2)[0]) + [0.0 for x in range(0, n)] my_ub = [1 for x in range(0, n**2 + n)] my_lb = [0 for x in range(0, n**2 + n)] my_ctype = "".join(["I" for x in range(0, n**2 + n)]) my_rhs = ( [q] + [1 for x in range(0, n)] + [0 for x in range(0, n)] + [0.1 for x in range(0, n**2)] ) my_sense = ( "".join(["E" for x in range(0, 1 + n)]) + "".join(["E" for x in range(0, n)]) + "".join(["L" for x in range(0, n**2)]) ) try: my_prob = cplex.Cplex() self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs) my_prob.solve() except CplexError as exc: print(exc) return x = my_prob.solution.get_values() x = np.array(x) cost = my_prob.solution.get_objective_value() return x, cost def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs): n = self.n prob.objective.set_sense(prob.objective.sense.minimize) prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype) prob.set_log_stream(None) prob.set_error_stream(None) prob.set_warning_stream(None) prob.set_results_stream(None) rows = [] col = [x for x in range(n**2, n**2 + n)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [x for x in range(0 + n * ii, n + n * ii)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [ii * n + ii, n**2 + ii] coef = [1, -1] rows.append([col, coef]) for ii in range(0, n): for jj in range(0, n): col = [ii * n + jj, n**2 + jj] coef = [1, -1] rows.append([col, coef]) prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs) # Instantiate the classical optimizer class classical_optimizer = ClassicalOptimizer(rho, n, q) # Compute the number of feasible solutions: print("Number of feasible combinations= " + str(classical_optimizer.compute_allowed_combinations())) # Compute the total number of possible combinations (feasible + unfeasible) print("Total number of combinations= " + str(2 ** (n * (n + 1)))) # Visualize the solution def visualize_solution(xc, yc, x, C, n, K, title_str): plt.figure() plt.scatter(xc, yc, s=200) for i in range(len(xc)): plt.annotate(i, (xc[i] + 0.015, yc[i]), size=16, color="r") plt.grid() for ii in range(n**2, n**2 + n): if x[ii] > 0: plt.plot(xc[ii - n**2], yc[ii - n**2], "r*", ms=20) for ii in range(0, n**2): if x[ii] > 0: iy = ii // n ix = ii % n plt.plot([xc[ix], xc[iy]], [yc[ix], yc[iy]], "C2") plt.title(title_str + " cost = " + str(int(C * 100) / 100.0)) plt.show() from qiskit.utils import algorithm_globals class QuantumOptimizer: def __init__(self, rho, n, q): self.rho = rho self.n = n self.q = q self.pdf = PortfolioDiversification(similarity_matrix=rho, num_assets=n, num_clusters=q) self.qp = self.pdf.to_quadratic_program() # Obtains the least eigenvalue of the Hamiltonian classically def exact_solution(self): exact_mes = NumPyMinimumEigensolver() exact_eigensolver = MinimumEigenOptimizer(exact_mes) result = exact_eigensolver.solve(self.qp) return self.decode_result(result) def vqe_solution(self): algorithm_globals.random_seed = 100 cobyla = COBYLA() cobyla.set_options(maxiter=250) ry = TwoLocal(n, "ry", "cz", reps=5, entanglement="full") vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla) vqe = MinimumEigenOptimizer(vqe_mes) result = vqe.solve(self.qp) return self.decode_result(result) def qaoa_solution(self): algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=250) qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3) qaoa = MinimumEigenOptimizer(qaoa_mes) result = qaoa.solve(self.qp) return self.decode_result(result) def decode_result(self, result, offset=0): quantum_solution = 1 - (result.x) ground_level = self.qp.objective.evaluate(result.x) return quantum_solution, ground_level # Instantiate the quantum optimizer class with parameters: quantum_optimizer = QuantumOptimizer(rho, n, q) # Check if the binary representation is correct. This requires CPLEX try: import cplex # warnings.filterwarnings('ignore') quantum_solution, quantum_cost = quantum_optimizer.exact_solution() print(quantum_solution, quantum_cost) classical_solution, classical_cost = classical_optimizer.cplex_solution() print(classical_solution, classical_cost) if np.abs(quantum_cost - classical_cost) < 0.01: print("Binary formulation is correct") else: print("Error in the formulation of the Hamiltonian") except Exception as ex: print(ex) ground_state, ground_level = quantum_optimizer.exact_solution() print(ground_state) classical_cost = 1.000779571614484 # obtained from the CPLEX solution try: if np.abs(ground_level - classical_cost) < 0.01: print("Ising Hamiltonian in Z basis is correct") else: print("Error in the Ising Hamiltonian formulation") except Exception as ex: print(ex) vqe_state, vqe_level = quantum_optimizer.vqe_solution() print(vqe_state, vqe_level) try: if np.linalg.norm(ground_state - vqe_state) < 0.01: print("SamplingVQE produces the same solution as the exact eigensolver.") else: print( "SamplingVQE does not produce the same solution as the exact eigensolver, but that is to be expected." ) except Exception as ex: print(ex) xc, yc = data.get_coordinates() visualize_solution(xc, yc, ground_state, ground_level, n, q, "Classical") visualize_solution(xc, yc, vqe_state, vqe_level, n, q, "VQE") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Keerthiraj-Nagaraj/IBM-quantum-challenge-2020
Keerthiraj-Nagaraj
import json import logging import numpy as np import warnings from functools import wraps from typing import Any, Callable, Optional, Tuple, Union from qiskit import IBMQ, QuantumCircuit, assemble from qiskit.circuit import Barrier, Gate, Instruction, Measure from qiskit.circuit.library import UGate, U3Gate, CXGate from qiskit.providers.ibmq import AccountProvider, IBMQProviderError from qiskit.providers.ibmq.job import IBMQJob def get_provider() -> AccountProvider: with warnings.catch_warnings(): warnings.simplefilter('ignore') ibmq_logger = logging.getLogger('qiskit.providers.ibmq') current_level = ibmq_logger.level ibmq_logger.setLevel(logging.ERROR) # get provider try: provider = IBMQ.get_provider() except IBMQProviderError: provider = IBMQ.load_account() ibmq_logger.setLevel(current_level) return provider def get_job(job_id: str) -> Optional[IBMQJob]: try: job = get_provider().backends.retrieve_job(job_id) return job except Exception: pass return None def circuit_to_json(qc: QuantumCircuit) -> str: class _QobjEncoder(json.encoder.JSONEncoder): def default(self, obj: Any) -> Any: if isinstance(obj, np.ndarray): return obj.tolist() if isinstance(obj, complex): return (obj.real, obj.imag) return json.JSONEncoder.default(self, obj) return json.dumps(circuit_to_dict(qc), cls=_QobjEncoder) def circuit_to_dict(qc: QuantumCircuit) -> dict: qobj = assemble(qc) return qobj.to_dict() def get_job_urls(job: Union[str, IBMQJob]) -> Tuple[bool, Optional[str], Optional[str]]: try: job_id = job.job_id() if isinstance(job, IBMQJob) else job download_url = get_provider()._api_client.account_api.job(job_id).download_url()['url'] result_url = get_provider()._api_client.account_api.job(job_id).result_url()['url'] return download_url, result_url except Exception: return None, None def cached(key_function: Callable) -> Callable: def _decorator(f: Any) -> Callable: f.__cache = {} @wraps(f) def _decorated(*args: Any, **kwargs: Any) -> int: key = key_function(*args, **kwargs) if key not in f.__cache: f.__cache[key] = f(*args, **kwargs) return f.__cache[key] return _decorated return _decorator def gate_key(gate: Gate) -> Tuple[str, int]: return gate.name, gate.num_qubits @cached(gate_key) def gate_cost(gate: Gate) -> int: if isinstance(gate, (UGate, U3Gate)): return 1 elif isinstance(gate, CXGate): return 10 elif isinstance(gate, (Measure, Barrier)): return 0 return sum(map(gate_cost, (g for g, _, _ in gate.definition.data))) def compute_cost(circuit: Union[Instruction, QuantumCircuit]) -> int: print('Computing cost...') circuit_data = None if isinstance(circuit, QuantumCircuit): circuit_data = circuit.data elif isinstance(circuit, Instruction): circuit_data = circuit.definition.data else: raise Exception(f'Unable to obtain circuit data from {type(circuit)}') return sum(map(gate_cost, (g for g, _, _ in circuit_data))) def uses_multiqubit_gate(circuit: QuantumCircuit) -> bool: circuit_data = None if isinstance(circuit, QuantumCircuit): circuit_data = circuit.data elif isinstance(circuit, Instruction) and circuit.definition is not None: circuit_data = circuit.definition.data else: raise Exception(f'Unable to obtain circuit data from {type(circuit)}') for g, _, _ in circuit_data: if isinstance(g, (Barrier, Measure)): continue elif isinstance(g, Gate): if g.num_qubits > 1: return True elif isinstance(g, (QuantumCircuit, Instruction)) and uses_multiqubit_gate(g): return True return False
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/abbarreto/qiskit2
abbarreto
%run init.ipynb
https://github.com/asierarranz/QiskitUnityAsset
asierarranz
#!/usr/bin/env python3 from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, Aer, execute def run_qasm(qasm, backend_to_run="qasm_simulator"): qc = QuantumCircuit.from_qasm_str(qasm) backend = Aer.get_backend(backend_to_run) job_sim = execute(qc, backend) sim_result = job_sim.result() return sim_result.get_counts(qc)
https://github.com/anirban-m/qiskit-superstaq
anirban-m
import qiskit import qiskit_superstaq def test_circuit_serialization() -> None: circuits = [qiskit.QuantumCircuit(3), qiskit.QuantumCircuit(2)] circuits[0].cx(2, 1) circuits[0].cz(0, 1) circuits[1].swap(0, 1) serialized_circuits = qiskit_superstaq.serialization.serialize_circuits(circuits) assert isinstance(serialized_circuits, str) assert qiskit_superstaq.serialization.deserialize_circuits(serialized_circuits) == circuits
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
import numpy as np from qiskit import transpile, QuantumCircuit def version_check(): import qiskit if qiskit.version.VERSION == '1.0.2': return print("You have the right version! Enjoy the challenge!") else: return print("please install right version by copy/paste and execute - !pip install 'qiskit[visualization]' == 1.0.2'") def transpile_scoring(circ, layout, backend): """ A custom cost function that includes T1 and T2 computed during idle periods Parameters: circ (QuantumCircuit): circuit of interest layouts (list of lists): List of specified layouts backend (IBMQBackend): An IBM Quantum backend instance Returns: list: Tuples of layout and cost """ fid = 1 touched = set() dt = backend.dt num_qubits = backend.num_qubits error=0 t1s = [backend.qubit_properties(qq).t1 for qq in range(num_qubits)] t2s = [backend.qubit_properties(qq).t2 for qq in range(num_qubits)] for item in circ._data: for gate in backend.operation_names: if item[0].name == gate: if (item[0].name == 'cz') or (item[0].name == 'ecr'): q0 = circ.find_bit(item[1][0]).index q1 = circ.find_bit(item[1][1]).index fid *= 1 - backend.target[item[0].name][(q0, q1)].error touched.add(q0) touched.add(q1) elif item[0].name == 'measure': q0 = circ.find_bit(item[1][0]).index fid *= 1 - backend.target[item[0].name][(q0, )].error touched.add(q0) elif item[0].name == 'delay': q0 = circ.find_bit(item[1][0]).index # Ignore delays that occur before gates # This assumes you are in ground state and errors # do not occur. if q0 in touched: time = item[0].duration * dt fid *= 1-qubit_error(time, t1s[q0], t2s[q0]) else: q0 = circ.find_bit(item[1][0]).index fid *= 1 - backend.target[item[0].name][(q0, )].error touched.add(q0) return fid def qubit_error(time, t1, t2): """Compute the approx. idle error from T1 and T2 Parameters: time (float): Delay time in sec t1 (float): T1 time in sec t2 (float): T2 time in sec Returns: float: Idle error """ t2 = min(t1, t2) rate1 = 1/t1 rate2 = 1/t2 p_reset = 1-np.exp(-time*rate1) p_z = (1-p_reset)*(1-np.exp(-time*(rate2-rate1)))/2 return p_z + p_reset
https://github.com/Pitt-JonesLab/mirror-gates
Pitt-JonesLab
"""CNS Transformations for mirror gates.""" import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import Instruction from qiskit.circuit.library import SwapGate from qiskit.dagcircuit import DAGCircuit, DAGOpNode from qiskit.extensions import UnitaryGate from mirror_gates.fast_unitary import FastConsolidateBlocks, NoCheckUnitary # Global CNS Transformations # cx -> iswap cx_replace = QuantumCircuit(2, 0, name="iswap_prime") cx_replace.h(1) cx_replace.rz(-np.pi / 2, 0) cx_replace.rz(-np.pi / 2, 1) cx_replace.iswap(0, 1) # cx_replace.append(SiSwapGate(), [0, 1]) # cx_replace.append(SiSwapGate(), [0, 1]) cx_replace.h(0) # iswap -> cx iswap_replace = QuantumCircuit(2, 0, name="cx_prime") iswap_replace.rz(np.pi / 2, 0) iswap_replace.rz(np.pi / 2, 1) iswap_replace.h(1) iswap_replace.cx(0, 1) iswap_replace.h(1) def _get_node_cns(node: DAGOpNode, use_fast_settings: bool = True) -> Instruction: """Get the CNS transformation for a given node.""" if len(node.qargs) != 2: raise ValueError("Only supports 2Q gates") # NOTE, the UnitaryGate() constructor is a bit expensive if use_fast_settings: new_op = SwapGate().to_matrix() @ node.op.to_matrix() new_unitary = NoCheckUnitary(new_op, label="u+swap") # TODO: calculate mirror coordinate directly # from monodromy.coordinates import mirror_monodromy_coordinate # _monodromy_coord = mirror_monodromy_coordinate(node.op._monodromy_coord) new_unitary._monodromy_coord = FastConsolidateBlocks.unitary_to_coordinate( new_unitary ) else: new_op = SwapGate().to_matrix() @ node.op.to_matrix() new_unitary = UnitaryGate(new_op, label="u+swap") return DAGOpNode(op=new_unitary, qargs=node.qargs) def cns_transform(dag: DAGCircuit, *h_nodes, preserve_layout=False) -> DAGCircuit: """Transform DAG by applying CNS transformations on multiple nodes. Args: dag (DAGCircuit): DAG to be transformed (will not be modified) h_nodes (DAGOpNode): Nodes to be transformed. preserve_layout (bool): If True, the layout of the original DAG is preserved. Use this option if testing equivalence of original and transformed circuits. """ new_dag = dag.copy_empty_like() if preserve_layout: # convert so can be modified h_nodes = list(h_nodes) # Initialize layout for each node layout = {qarg: qarg for node in dag.topological_op_nodes() for qarg in node.qargs} for node in dag.topological_op_nodes(): qargs = [layout.get(qarg, qarg) for qarg in node.qargs] # check if node is in list of nodes to be transformed # FIXME, this is true multiple times, # semantic_eq checks if is a CX but not if the exact same CX if any(node == h_node for h_node in h_nodes): # if any(DAGNode.semantic_eq(node, h_node) for h_node in h_nodes): try: # checks if has a defined CNS transformation node_prime = _get_node_cns(node) new_dag.apply_operation_back(node_prime.op, qargs) # swap values in layout layout[node.qargs[0]], layout[node.qargs[1]] = qargs[1], qargs[0] except ValueError: new_dag.apply_operation_back(node.op, qargs) h_nodes.remove(node) else: new_dag.apply_operation_back(node.op, qargs) if preserve_layout: for h_node in reversed(h_nodes): new_dag.apply_operation_back(SwapGate(), h_node.qargs) return new_dag # legacy code, only works for a single node # def cns_transform(dag: DAGCircuit, h_node, preserve_layout=False): # """Alternative implementation, adds nodes into blank copy of dag.""" # new_dag = dag.copy_empty_like() # flip_flag = False # swap_wires = { # qarg1: qarg2 for qarg1, qarg2 in zip(h_node.qargs, h_node.qargs[::-1]) # } # for node in dag.topological_op_nodes(): # # if node == h_node: # if DAGNode.semantic_eq(node, h_node): # # here we add the cns transformation, and use the flip flag # # flip_flag tells us from this gate onwards, qargs will reverse # # effectively, we are adding the virtual swap here # new_dag.apply_operation_back(_get_node_cns(node).op, node.qargs) # flip_flag = True # else: # if flip_flag: # new_dag.apply_operation_back( # node.op, [swap_wires.get(qarg, qarg) for qarg in node.qargs] # ) # else: # new_dag.apply_operation_back(node.op, node.qargs) # # fix with a swap # # if preserve_layout: # # new_dag.apply_operation_back(SwapGate(), h_node.qargs) # return new_dag
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import execute, pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.play(pulse.Constant(100, 1.0), d0) pulse_prog.draw()
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. """Test the Solovay Kitaev transpilation pass.""" import unittest import math import numpy as np import scipy from ddt import ddt, data from qiskit.test import QiskitTestCase from qiskit import transpile from qiskit.circuit import QuantumCircuit from qiskit.circuit.library import TGate, TdgGate, HGate, SGate, SdgGate, IGate, QFT from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit.quantum_info import Operator from qiskit.synthesis.discrete_basis.generate_basis_approximations import ( generate_basic_approximations, ) from qiskit.synthesis.discrete_basis.commutator_decompose import commutator_decompose from qiskit.synthesis.discrete_basis.gate_sequence import GateSequence from qiskit.transpiler import PassManager from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.passes import UnitarySynthesis, Collect1qRuns, ConsolidateBlocks from qiskit.transpiler.passes.synthesis import SolovayKitaev, SolovayKitaevSynthesis def _trace_distance(circuit1, circuit2): """Return the trace distance of the two input circuits.""" op1, op2 = Operator(circuit1), Operator(circuit2) return 0.5 * np.trace(scipy.linalg.sqrtm(np.conj(op1 - op2).T.dot(op1 - op2))).real def _generate_x_rotation(angle: float) -> np.ndarray: return np.array( [[1, 0, 0], [0, math.cos(angle), -math.sin(angle)], [0, math.sin(angle), math.cos(angle)]] ) def _generate_y_rotation(angle: float) -> np.ndarray: return np.array( [[math.cos(angle), 0, math.sin(angle)], [0, 1, 0], [-math.sin(angle), 0, math.cos(angle)]] ) def _generate_z_rotation(angle: float) -> np.ndarray: return np.array( [[math.cos(angle), -math.sin(angle), 0], [math.sin(angle), math.cos(angle), 0], [0, 0, 1]] ) def is_so3_matrix(array: np.ndarray) -> bool: """Check if the input array is a SO(3) matrix.""" if array.shape != (3, 3): return False if abs(np.linalg.det(array) - 1.0) > 1e-10: return False if False in np.isreal(array): return False return True @ddt class TestSolovayKitaev(QiskitTestCase): """Test the Solovay Kitaev algorithm and transformation pass.""" def setUp(self): super().setUp() self.basic_approx = generate_basic_approximations([HGate(), TGate(), TdgGate()], 3) def test_unitary_synthesis(self): """Test the unitary synthesis transpiler pass with Solovay-Kitaev.""" circuit = QuantumCircuit(2) circuit.rx(0.8, 0) circuit.cx(0, 1) circuit.x(1) _1q = Collect1qRuns() _cons = ConsolidateBlocks() _synth = UnitarySynthesis(["h", "s"], method="sk") passes = PassManager([_1q, _cons, _synth]) compiled = passes.run(circuit) diff = np.linalg.norm(Operator(compiled) - Operator(circuit)) self.assertLess(diff, 1) self.assertEqual(set(compiled.count_ops().keys()), {"h", "s", "cx"}) def test_plugin(self): """Test calling the plugin directly.""" circuit = QuantumCircuit(1) circuit.rx(0.8, 0) unitary = Operator(circuit).data plugin = SolovayKitaevSynthesis() out = plugin.run(unitary, basis_gates=["h", "s"]) reference = QuantumCircuit(1, global_phase=3 * np.pi / 4) reference.h(0) reference.s(0) reference.h(0) self.assertEqual(dag_to_circuit(out), reference) def test_generating_default_approximation(self): """Test the approximation set is generated by default.""" skd = SolovayKitaev() circuit = QuantumCircuit(1) dummy = skd(circuit) self.assertIsNotNone(skd._sk.basic_approximations) def test_i_returns_empty_circuit(self): """Test that ``SolovayKitaev`` returns an empty circuit when it approximates the I-gate.""" circuit = QuantumCircuit(1) circuit.i(0) skd = SolovayKitaev(3, self.basic_approx) decomposed_circuit = skd(circuit) self.assertEqual(QuantumCircuit(1), decomposed_circuit) def test_exact_decomposition_acts_trivially(self): """Test that the a circuit that can be represented exactly is represented exactly.""" circuit = QuantumCircuit(1) circuit.t(0) circuit.h(0) circuit.tdg(0) synth = SolovayKitaev(3, self.basic_approx) dag = circuit_to_dag(circuit) decomposed_dag = synth.run(dag) decomposed_circuit = dag_to_circuit(decomposed_dag) self.assertEqual(circuit, decomposed_circuit) def test_fails_with_no_to_matrix(self): """Test failer if gate does not have to_matrix.""" circuit = QuantumCircuit(1) circuit.initialize("0") synth = SolovayKitaev(3, self.basic_approx) dag = circuit_to_dag(circuit) with self.assertRaises(TranspilerError) as cm: _ = synth.run(dag) self.assertEqual( "SolovayKitaev does not support gate without to_matrix method: initialize", cm.exception.message, ) def test_str_basis_gates(self): """Test specifying the basis gates by string works.""" circuit = QuantumCircuit(1) circuit.rx(0.8, 0) basic_approx = generate_basic_approximations(["h", "t", "s"], 3) synth = SolovayKitaev(2, basic_approx) dag = circuit_to_dag(circuit) discretized = dag_to_circuit(synth.run(dag)) reference = QuantumCircuit(1, global_phase=7 * np.pi / 8) reference.h(0) reference.t(0) reference.h(0) self.assertEqual(discretized, reference) def test_approximation_on_qft(self): """Test the Solovay-Kitaev decomposition on the QFT circuit.""" qft = QFT(3) transpiled = transpile(qft, basis_gates=["u", "cx"], optimization_level=1) skd = SolovayKitaev(1) with self.subTest("1 recursion"): discretized = skd(transpiled) self.assertLess(_trace_distance(transpiled, discretized), 15) skd.recursion_degree = 2 with self.subTest("2 recursions"): discretized = skd(transpiled) self.assertLess(_trace_distance(transpiled, discretized), 7) def test_u_gates_work(self): """Test SK works on Qiskit's UGate. Regression test of Qiskit/qiskit-terra#9437. """ circuit = QuantumCircuit(1) circuit.u(np.pi / 2, -np.pi, -np.pi, 0) circuit.u(np.pi / 2, np.pi / 2, -np.pi, 0) circuit.u(-np.pi / 4, 0, -np.pi / 2, 0) circuit.u(np.pi / 4, -np.pi / 16, 0, 0) circuit.u(0, 0, np.pi / 16, 0) circuit.u(0, np.pi / 4, np.pi / 4, 0) circuit.u(np.pi / 2, 0, -15 * np.pi / 16, 0) circuit.p(-np.pi / 4, 0) circuit.p(np.pi / 4, 0) circuit.u(np.pi / 2, 0, -3 * np.pi / 4, 0) circuit.u(0, 0, -np.pi / 16, 0) circuit.u(np.pi / 2, 0, 15 * np.pi / 16, 0) depth = 4 basis_gates = ["h", "t", "tdg", "s", "z"] gate_approx_library = generate_basic_approximations(basis_gates=basis_gates, depth=depth) skd = SolovayKitaev(recursion_degree=2, basic_approximations=gate_approx_library) discretized = skd(circuit) included_gates = set(discretized.count_ops().keys()) self.assertEqual(set(basis_gates), included_gates) @ddt class TestGateSequence(QiskitTestCase): """Test the ``GateSequence`` class.""" def test_append(self): """Test append.""" seq = GateSequence([IGate()]) seq.append(HGate()) ref = GateSequence([IGate(), HGate()]) self.assertEqual(seq, ref) def test_eq(self): """Test equality.""" base = GateSequence([HGate(), HGate()]) seq1 = GateSequence([HGate(), HGate()]) seq2 = GateSequence([IGate()]) seq3 = GateSequence([HGate(), HGate()]) seq3.global_phase = 0.12 seq4 = GateSequence([IGate(), HGate()]) with self.subTest("equal"): self.assertEqual(base, seq1) with self.subTest("same product, but different repr (-> false)"): self.assertNotEqual(base, seq2) with self.subTest("differing global phase (-> false)"): self.assertNotEqual(base, seq3) with self.subTest("same num gates, but different gates (-> false)"): self.assertNotEqual(base, seq4) def test_to_circuit(self): """Test converting a gate sequence to a circuit.""" seq = GateSequence([HGate(), HGate(), TGate(), SGate(), SdgGate()]) ref = QuantumCircuit(1) ref.h(0) ref.h(0) ref.t(0) ref.s(0) ref.sdg(0) # a GateSequence is SU(2), so add the right phase z = 1 / np.sqrt(np.linalg.det(Operator(ref))) ref.global_phase = np.arctan2(np.imag(z), np.real(z)) self.assertEqual(seq.to_circuit(), ref) def test_adjoint(self): """Test adjoint.""" seq = GateSequence([TGate(), SGate(), HGate(), IGate()]) inv = GateSequence([IGate(), HGate(), SdgGate(), TdgGate()]) self.assertEqual(seq.adjoint(), inv) def test_copy(self): """Test copy.""" seq = GateSequence([IGate()]) copied = seq.copy() seq.gates.append(HGate()) self.assertEqual(len(seq.gates), 2) self.assertEqual(len(copied.gates), 1) @data(0, 1, 10) def test_len(self, n): """Test __len__.""" seq = GateSequence([IGate()] * n) self.assertEqual(len(seq), n) def test_getitem(self): """Test __getitem__.""" seq = GateSequence([IGate(), HGate(), IGate()]) self.assertEqual(seq[0], IGate()) self.assertEqual(seq[1], HGate()) self.assertEqual(seq[2], IGate()) self.assertEqual(seq[-2], HGate()) def test_from_su2_matrix(self): """Test from_matrix with an SU2 matrix.""" matrix = np.array([[1, 1], [1, -1]], dtype=complex) / np.sqrt(2) matrix /= np.sqrt(np.linalg.det(matrix)) seq = GateSequence.from_matrix(matrix) ref = GateSequence([HGate()]) self.assertEqual(seq.gates, []) self.assertTrue(np.allclose(seq.product, ref.product)) self.assertEqual(seq.global_phase, 0) def test_from_so3_matrix(self): """Test from_matrix with an SO3 matrix.""" matrix = np.array([[0, 0, -1], [0, -1, 0], [-1, 0, 0]]) seq = GateSequence.from_matrix(matrix) ref = GateSequence([HGate()]) self.assertEqual(seq.gates, []) self.assertTrue(np.allclose(seq.product, ref.product)) self.assertEqual(seq.global_phase, 0) def test_from_invalid_matrix(self): """Test from_matrix with invalid matrices.""" with self.subTest("2x2 but not SU2"): matrix = np.array([[1, 1], [1, -1]], dtype=complex) / np.sqrt(2) with self.assertRaises(ValueError): _ = GateSequence.from_matrix(matrix) with self.subTest("not 2x2 or 3x3"): with self.assertRaises(ValueError): _ = GateSequence.from_matrix(np.array([[1]])) def test_dot(self): """Test dot.""" seq1 = GateSequence([HGate()]) seq2 = GateSequence([TGate(), SGate()]) composed = seq1.dot(seq2) ref = GateSequence([TGate(), SGate(), HGate()]) # check the product matches self.assertTrue(np.allclose(ref.product, composed.product)) # check the circuit & phases are equivalent self.assertTrue(Operator(ref.to_circuit()).equiv(composed.to_circuit())) @ddt class TestSolovayKitaevUtils(QiskitTestCase): """Test the public functions in the Solovay Kitaev utils.""" @data( _generate_x_rotation(0.1), _generate_y_rotation(0.2), _generate_z_rotation(0.3), np.dot(_generate_z_rotation(0.5), _generate_y_rotation(0.4)), np.dot(_generate_y_rotation(0.5), _generate_x_rotation(0.4)), ) def test_commutator_decompose_return_type(self, u_so3: np.ndarray): """Test that ``commutator_decompose`` returns two SO(3) gate sequences.""" v, w = commutator_decompose(u_so3) self.assertTrue(is_so3_matrix(v.product)) self.assertTrue(is_so3_matrix(w.product)) self.assertIsInstance(v, GateSequence) self.assertIsInstance(w, GateSequence) @data( _generate_x_rotation(0.1), _generate_y_rotation(0.2), _generate_z_rotation(0.3), np.dot(_generate_z_rotation(0.5), _generate_y_rotation(0.4)), np.dot(_generate_y_rotation(0.5), _generate_x_rotation(0.4)), ) def test_commutator_decompose_decomposes_correctly(self, u_so3): """Test that ``commutator_decompose`` exactly decomposes the input.""" v, w = commutator_decompose(u_so3) v_so3 = v.product w_so3 = w.product actual_commutator = np.dot(v_so3, np.dot(w_so3, np.dot(np.conj(v_so3).T, np.conj(w_so3).T))) self.assertTrue(np.allclose(actual_commutator, u_so3)) def test_generate_basis_approximation_gates(self): """Test the basis approximation generation works for all supported gates. Regression test of Qiskit/qiskit-terra#9585. """ basis = ["i", "x", "y", "z", "h", "t", "tdg", "s", "sdg"] approx = generate_basic_approximations(basis, depth=2) # This mainly checks that there are no errors in the generation (like # in computing the inverse as described in #9585), so a simple check is enough. self.assertGreater(len(approx), len(basis)) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit.visualization import plot_circuit_layout from qiskit.providers.fake_provider import FakeVigo backend = FakeVigo() ghz = QuantumCircuit(3, 3) ghz.h(0) ghz.cx(0,range(1,3)) ghz.barrier() ghz.measure(range(3), range(3)) # Virtual -> physical # 0 -> 3 # 1 -> 4 # 2 -> 2 my_ghz = transpile(ghz, backend, initial_layout=[3, 4, 2]) plot_circuit_layout(my_ghz, backend)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as drive_sched: d0 = pulse.drive_channel(0) a0 = pulse.acquire_channel(0) pulse.play(pulse.library.Constant(10, 1.0), d0) pulse.delay(20, d0) pulse.shift_phase(3.14/2, d0) pulse.set_phase(3.14, d0) pulse.shift_frequency(1e7, d0) pulse.set_frequency(5e9, d0) with pulse.build() as temp_sched: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), d0) pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), d0) pulse.call(temp_sched) pulse.acquire(30, a0, pulse.MemorySlot(0)) drive_sched.draw()
https://github.com/qiskit-community/qiskit-tket-passes
qiskit-community
from qiskit_tket_passes import ToQiskitPass import pytket.passes as tkps _pass1 = ToQiskitPass(tkps.SynthesiseTket) # If TKET pass' constructor expects some arguments, pass them after the class name _pass2 = ToQiskitPass(tkps.FullPeepholeOptimise, allow_swaps=True, target_2qb_gate='cx') from pytket.architecture import Architecture arc = Architecture([(0, 1), (1, 0), (1, 2), (1, 3), (2, 1), (3, 1), (3, 4), (4, 3)]) _pass = ToQiskitPass(tkps.AASRouting, arc=arc) _pass = ToQiskitPass(tkps.AASRouting, arc=[[0, 1], [1, 0], [1, 2], [1, 3], [2, 1], [3, 1], [3, 4], [4, 3]]) from qiskit.providers.fake_provider import FakeQuitoV2 backend = FakeQuitoV2() _pass = ToQiskitPass(tkps.AASRouting, target=backend.target) print(_pass.tket_argument('arc').to_dict()) from qiskit.circuit.random import random_circuit from pytket.extensions.qiskit import AerBackend from qiskit_tket_passes import TketPassManager qc = random_circuit(3, 10, seed=1) pm = TketPassManager(AerBackend(), optimization_level=2) transpiled_qc = pm.run(qc) from qiskit.circuit.random import random_circuit circ = random_circuit(7, 30, seed=1) circ.draw('mpl', fold=-1) from qiskit.transpiler.passes import ( UnitarySynthesis, Collect2qBlocks, ConsolidateBlocks, Unroll3qOrMore, ) from qiskit.transpiler import PassManager, StagedPassManager basis_gates = ["rx", "ry", "rxx"] init = PassManager([UnitarySynthesis(basis_gates, min_qubits=3), Unroll3qOrMore()]) translate = PassManager( [ Collect2qBlocks(), ConsolidateBlocks(basis_gates=basis_gates), UnitarySynthesis(basis_gates), ] ) staged_pm = StagedPassManager( stages=["init", "translation"], init=init, translation=translate ) tr_circ = staged_pm.run(circ) print('Depth:', tr_circ.depth()) optimize = PassManager( [ ToQiskitPass(tkps.RemoveRedundancies) ] ) staged_pm = StagedPassManager( stages=["init", "translation", "optimization"], init=init, translation=translate, optimization=optimize ) tr_circ = staged_pm.run(circ) print('Depth:', tr_circ.depth()) from pytket.extensions.qiskit import IBMQBackend from qiskit_tket_passes import TketPassManager qbackend = IBMQBackend('ibmq_jakarta') pm = TketPassManager(qbackend, optimization_level=2) #pm.draw() tr_circ = pm.run(circ) print('CNOTs:', tr_circ.count_ops()['cx']) print('Depth:', tr_circ.depth()) from qiskit_ibm_provider import IBMProvider provider = IBMProvider() backend = provider.get_backend('ibmq_jakarta') from qiskit import transpile tr_circ = transpile(circ, backend=backend, optimization_level=3) print('CNOTs:', tr_circ.count_ops()['cx']) print('Depth:', tr_circ.depth()) print('init:') circ_init = transpile(circ, backend=backend, optimization_level=3, init_method='tket') print('CNOTs:', circ_init.count_ops()['cx']) print('Depth:', circ_init.depth()) print('\ntranslation:') circ_trans = transpile(circ, backend=backend, optimization_level=3, translation_method='tket') print('CNOTs:', circ_trans.count_ops()['cx']) print('Depth:', circ_trans.depth()) print('\noptimization:') circ_opt = transpile(circ, backend=backend, optimization_level=3, optimization_method='tket') print('CNOTs:', circ_opt.count_ops()['cx']) print('Depth:', circ_opt.depth()) from colorama import Fore, Style def _callback(pass_, dag, time, property_set, count): is_tket_pass = pass_.name().startswith('TketPass_') print(Fore.GREEN if is_tket_pass else Fore.WHITE, pass_.name()) Style.RESET_ALL circ_layout = transpile(circ, backend=backend, optimization_level=3, init_method='tket', translation_method='tket', optimization_method='tket', callback=_callback)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="lq") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors=scale_factors) print("created zne_qcs (length:", len(zne_qcs), ")") t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") shots = 1 << 13 reps = 1 # unused # Number of trotter steps print("trotter step: ", num_steps) # execute: reps = 1 job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results) target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! rho = expvals_to_valid_rho(num_qubits, zne_expvals) fidelity = state_fidelity(rho, target_state) print(fidelity)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import json import time import warnings import matplotlib.pyplot as plt import numpy as np from IPython.display import clear_output from qiskit import ClassicalRegister, QuantumRegister from qiskit import QuantumCircuit from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import RealAmplitudes from qiskit.quantum_info import Statevector from qiskit.utils import algorithm_globals from qiskit_machine_learning.circuit.library import RawFeatureVector from qiskit_machine_learning.neural_networks import SamplerQNN algorithm_globals.random_seed = 42 def ansatz(num_qubits): return RealAmplitudes(num_qubits, reps=5) num_qubits = 5 circ = ansatz(num_qubits) circ.decompose().draw("mpl") def auto_encoder_circuit(num_latent, num_trash): qr = QuantumRegister(num_latent + 2 * num_trash + 1, "q") cr = ClassicalRegister(1, "c") circuit = QuantumCircuit(qr, cr) circuit.compose(ansatz(num_latent + num_trash), range(0, num_latent + num_trash), inplace=True) circuit.barrier() auxiliary_qubit = num_latent + 2 * num_trash # swap test circuit.h(auxiliary_qubit) for i in range(num_trash): circuit.cswap(auxiliary_qubit, num_latent + i, num_latent + num_trash + i) circuit.h(auxiliary_qubit) circuit.measure(auxiliary_qubit, cr[0]) return circuit num_latent = 3 num_trash = 2 circuit = auto_encoder_circuit(num_latent, num_trash) circuit.draw("mpl") def domain_wall(circuit, a, b): # Here we place the Domain Wall to qubits a - b in our circuit for i in np.arange(int(b / 2), int(b)): circuit.x(i) return circuit domain_wall_circuit = domain_wall(QuantumCircuit(5), 0, 5) domain_wall_circuit.draw("mpl") ae = auto_encoder_circuit(num_latent, num_trash) qc = QuantumCircuit(num_latent + 2 * num_trash + 1, 1) qc = qc.compose(domain_wall_circuit, range(num_latent + num_trash)) qc = qc.compose(ae) qc.draw("mpl") # Here we define our interpret for our SamplerQNN def identity_interpret(x): return x qnn = SamplerQNN( circuit=qc, input_params=[], weight_params=ae.parameters, interpret=identity_interpret, output_shape=2, ) def cost_func_domain(params_values): probabilities = qnn.forward([], params_values) # we pick a probability of getting 1 as the output of the network cost = np.sum(probabilities[:, 1]) # plotting part clear_output(wait=True) objective_func_vals.append(cost) 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() return cost opt = COBYLA(maxiter=150) initial_point = algorithm_globals.random.random(ae.num_parameters) objective_func_vals = [] # make the plot nicer plt.rcParams["figure.figsize"] = (12, 6) start = time.time() opt_result = opt.minimize(cost_func_domain, initial_point) elapsed = time.time() - start print(f"Fit in {elapsed:0.2f} seconds") test_qc = QuantumCircuit(num_latent + num_trash) test_qc = test_qc.compose(domain_wall_circuit) ansatz_qc = ansatz(num_latent + num_trash) test_qc = test_qc.compose(ansatz_qc) test_qc.barrier() test_qc.reset(4) test_qc.reset(3) test_qc.barrier() test_qc = test_qc.compose(ansatz_qc.inverse()) test_qc.draw("mpl") test_qc = test_qc.assign_parameters(opt_result.x) domain_wall_state = Statevector(domain_wall_circuit).data output_state = Statevector(test_qc).data fidelity = np.sqrt(np.dot(domain_wall_state.conj(), output_state) ** 2) print("Fidelity of our Output State with our Input State: ", fidelity.real) def zero_idx(j, i): # Index for zero pixels return [ [i, j], [i - 1, j - 1], [i - 1, j + 1], [i - 2, j - 1], [i - 2, j + 1], [i - 3, j - 1], [i - 3, j + 1], [i - 4, j - 1], [i - 4, j + 1], [i - 5, j], ] def one_idx(i, j): # Index for one pixels return [[i, j - 1], [i, j - 2], [i, j - 3], [i, j - 4], [i, j - 5], [i - 1, j - 4], [i, j]] def get_dataset_digits(num, draw=True): # Create Dataset containing zero and one train_images = [] train_labels = [] for i in range(int(num / 2)): # First we introduce background noise empty = np.array([algorithm_globals.random.uniform(0, 0.1) for i in range(32)]).reshape( 8, 4 ) # Now we insert the pixels for the one for i, j in one_idx(2, 6): empty[j][i] = algorithm_globals.random.uniform(0.9, 1) train_images.append(empty) train_labels.append(1) if draw: plt.title("This is a One") plt.imshow(train_images[-1]) plt.show() for i in range(int(num / 2)): empty = np.array([algorithm_globals.random.uniform(0, 0.1) for i in range(32)]).reshape( 8, 4 ) # Now we insert the pixels for the zero for k, j in zero_idx(2, 6): empty[k][j] = algorithm_globals.random.uniform(0.9, 1) train_images.append(empty) train_labels.append(0) if draw: plt.imshow(train_images[-1]) plt.title("This is a Zero") plt.show() train_images = np.array(train_images) train_images = train_images.reshape(len(train_images), 32) for i in range(len(train_images)): sum_sq = np.sum(train_images[i] ** 2) train_images[i] = train_images[i] / np.sqrt(sum_sq) return train_images, train_labels train_images, __ = get_dataset_digits(2) num_latent = 3 num_trash = 2 fm = RawFeatureVector(2 ** (num_latent + num_trash)) ae = auto_encoder_circuit(num_latent, num_trash) qc = QuantumCircuit(num_latent + 2 * num_trash + 1, 1) qc = qc.compose(fm, range(num_latent + num_trash)) qc = qc.compose(ae) qc.draw("mpl") def identity_interpret(x): return x qnn = SamplerQNN( circuit=qc, input_params=fm.parameters, weight_params=ae.parameters, interpret=identity_interpret, output_shape=2, ) def cost_func_digits(params_values): probabilities = qnn.forward(train_images, params_values) cost = np.sum(probabilities[:, 1]) / train_images.shape[0] # plotting part clear_output(wait=True) objective_func_vals.append(cost) 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() return cost with open("12_qae_initial_point.json", "r") as f: initial_point = json.load(f) opt = COBYLA(maxiter=150) objective_func_vals = [] # make the plot nicer plt.rcParams["figure.figsize"] = (12, 6) start = time.time() opt_result = opt.minimize(fun=cost_func_digits, x0=initial_point) elapsed = time.time() - start print(f"Fit in {elapsed:0.2f} seconds") # Test test_qc = QuantumCircuit(num_latent + num_trash) test_qc = test_qc.compose(fm) ansatz_qc = ansatz(num_latent + num_trash) test_qc = test_qc.compose(ansatz_qc) test_qc.barrier() test_qc.reset(4) test_qc.reset(3) test_qc.barrier() test_qc = test_qc.compose(ansatz_qc.inverse()) # sample new images test_images, test_labels = get_dataset_digits(2, draw=False) for image, label in zip(test_images, test_labels): original_qc = fm.assign_parameters(image) original_sv = Statevector(original_qc).data original_sv = np.reshape(np.abs(original_sv) ** 2, (8, 4)) param_values = np.concatenate((image, opt_result.x)) output_qc = test_qc.assign_parameters(param_values) output_sv = Statevector(output_qc).data output_sv = np.reshape(np.abs(output_sv) ** 2, (8, 4)) fig, (ax1, ax2) = plt.subplots(1, 2) ax1.imshow(original_sv) ax1.set_title("Input Data") ax2.imshow(output_sv) ax2.set_title("Output Data") plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 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 Qiskit's repeat instruction operation.""" import unittest from numpy import pi from qiskit.transpiler import PassManager from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit.test import QiskitTestCase from qiskit.extensions import UnitaryGate from qiskit.circuit.library import SGate, U3Gate, CXGate from qiskit.circuit import Instruction, Measure, Gate from qiskit.transpiler.passes import Unroller from qiskit.circuit.exceptions import CircuitError class TestRepeatInt1Q(QiskitTestCase): """Test gate_q1.repeat() with integer""" def test_standard_1Q_two(self): """Test standard gate.repeat(2) method.""" qr = QuantumRegister(1, "qr") expected_circ = QuantumCircuit(qr) expected_circ.append(SGate(), [qr[0]]) expected_circ.append(SGate(), [qr[0]]) expected = expected_circ.to_instruction() result = SGate().repeat(2) self.assertEqual(result.name, "s*2") self.assertEqual(result.definition, expected.definition) self.assertIsInstance(result, Gate) def test_standard_1Q_one(self): """Test standard gate.repeat(1) method.""" qr = QuantumRegister(1, "qr") expected_circ = QuantumCircuit(qr) expected_circ.append(SGate(), [qr[0]]) expected = expected_circ.to_instruction() result = SGate().repeat(1) self.assertEqual(result.name, "s*1") self.assertEqual(result.definition, expected.definition) self.assertIsInstance(result, Gate) class TestRepeatInt2Q(QiskitTestCase): """Test gate_q2.repeat() with integer""" def test_standard_2Q_two(self): """Test standard 2Q gate.repeat(2) method.""" qr = QuantumRegister(2, "qr") expected_circ = QuantumCircuit(qr) expected_circ.append(CXGate(), [qr[0], qr[1]]) expected_circ.append(CXGate(), [qr[0], qr[1]]) expected = expected_circ.to_instruction() result = CXGate().repeat(2) self.assertEqual(result.name, "cx*2") self.assertEqual(result.definition, expected.definition) self.assertIsInstance(result, Gate) def test_standard_2Q_one(self): """Test standard 2Q gate.repeat(1) method.""" qr = QuantumRegister(2, "qr") expected_circ = QuantumCircuit(qr) expected_circ.append(CXGate(), [qr[0], qr[1]]) expected = expected_circ.to_instruction() result = CXGate().repeat(1) self.assertEqual(result.name, "cx*1") self.assertEqual(result.definition, expected.definition) self.assertIsInstance(result, Gate) class TestRepeatIntMeasure(QiskitTestCase): """Test Measure.repeat() with integer""" def test_measure_two(self): """Test Measure.repeat(2) method.""" qr = QuantumRegister(1, "qr") cr = ClassicalRegister(1, "cr") expected_circ = QuantumCircuit(qr, cr) expected_circ.append(Measure(), [qr[0]], [cr[0]]) expected_circ.append(Measure(), [qr[0]], [cr[0]]) expected = expected_circ.to_instruction() result = Measure().repeat(2) self.assertEqual(result.name, "measure*2") self.assertEqual(result.definition, expected.definition) self.assertIsInstance(result, Instruction) self.assertNotIsInstance(result, Gate) def test_measure_one(self): """Test Measure.repeat(1) method.""" qr = QuantumRegister(1, "qr") cr = ClassicalRegister(1, "cr") expected_circ = QuantumCircuit(qr, cr) expected_circ.append(Measure(), [qr[0]], [cr[0]]) expected = expected_circ.to_instruction() result = Measure().repeat(1) self.assertEqual(result.name, "measure*1") self.assertEqual(result.definition, expected.definition) self.assertIsInstance(result, Instruction) self.assertNotIsInstance(result, Gate) class TestRepeatUnroller(QiskitTestCase): """Test unrolling Gate.repeat""" def test_unroller_two(self): """Test unrolling gate.repeat(2).""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(SGate().repeat(2), [qr[0]]) result = PassManager(Unroller("u3")).run(circuit) expected = QuantumCircuit(qr) expected.append(U3Gate(0, 0, pi / 2), [qr[0]]) expected.append(U3Gate(0, 0, pi / 2), [qr[0]]) self.assertEqual(result, expected) def test_unroller_one(self): """Test unrolling gate.repeat(1).""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(SGate().repeat(1), [qr[0]]) result = PassManager(Unroller("u3")).run(circuit) expected = QuantumCircuit(qr) expected.append(U3Gate(0, 0, pi / 2), [qr[0]]) self.assertEqual(result, expected) class TestRepeatErrors(QiskitTestCase): """Test when Gate.repeat() should raise.""" def test_unitary_no_int(self): """Test UnitaryGate.repeat(2/3) method. Raises, since n is not int.""" with self.assertRaises(CircuitError) as context: _ = UnitaryGate([[0, 1j], [-1j, 0]]).repeat(2 / 3) self.assertIn("strictly positive integer", str(context.exception)) def test_standard_no_int(self): """Test standard Gate.repeat(2/3) method. Raises, since n is not int.""" with self.assertRaises(CircuitError) as context: _ = SGate().repeat(2 / 3) self.assertIn("strictly positive integer", str(context.exception)) def test_measure_zero(self): """Test Measure.repeat(0) method. Raises, since n<1""" with self.assertRaises(CircuitError) as context: _ = Measure().repeat(0) self.assertIn("strictly positive integer", str(context.exception)) def test_standard_1Q_zero(self): """Test standard 2Q gate.repeat(0) method. Raises, since n<1.""" with self.assertRaises(CircuitError) as context: _ = SGate().repeat(0) self.assertIn("strictly positive integer", str(context.exception)) def test_standard_1Q_minus_one(self): """Test standard 2Q gate.repeat(-1) method. Raises, since n<1.""" with self.assertRaises(CircuitError) as context: _ = SGate().repeat(-1) self.assertIn("strictly positive integer", str(context.exception)) def test_standard_2Q_minus_one(self): """Test standard 2Q gate.repeat(-1) method. Raises, since n<1.""" with self.assertRaises(CircuitError) as context: _ = CXGate().repeat(-1) self.assertIn("strictly positive integer", str(context.exception)) def test_measure_minus_one(self): """Test Measure.repeat(-1) method. Raises, since n<1""" with self.assertRaises(CircuitError) as context: _ = Measure().repeat(-1) self.assertIn("strictly positive integer", str(context.exception)) def test_standard_2Q_zero(self): """Test standard 2Q gate.repeat(0) method. Raises, since n<1.""" with self.assertRaises(CircuitError) as context: _ = CXGate().repeat(0) self.assertIn("strictly positive integer", str(context.exception)) if __name__ == "__main__": unittest.main()
https://github.com/ahkatlio/QHSO_Basics_of_Qiskit
ahkatlio
# We import necessary libraries from Qiskit from qiskit import QuantumCircuit, Aer, execute # We create a quantum circuit with one qubit coin_flip_circuit = QuantumCircuit(1, 1) # We apply the H-gate (Hadamard gate) to create a superposition coin_flip_circuit.h(0) # We measure the qubit coin_flip_circuit.measure(0, 0) # We simulate the circuit on a classical simulator simulator = Aer.get_backend('qasm_simulator') result = execute(coin_flip_circuit, simulator, shots=1).result() counts = result.get_counts() from termcolor import colored # We print the outcome with colored text and ASCII art if '0' in counts: print(colored(" _______ \n / \\ \n| (•) (•) | \n| ^ | \n \\_______/ \n", 'red')) print(colored("The quantum coin landed on 'Heads' (|0⟩)!", 'red')) else: print(colored(" _______ \n / \\ \n| (•) (•) | \n| v | \n \\_______/ \n", 'green')) print(colored("The quantum coin landed on 'Tails' (|1⟩)!", 'green'))
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Contains functions used by the basic aer simulators. """ from string import ascii_uppercase, ascii_lowercase from typing import List, Optional import numpy as np import qiskit.circuit.library.standard_gates as gates from qiskit.exceptions import QiskitError # Single qubit gates supported by ``single_gate_params``. SINGLE_QUBIT_GATES = ("U", "u1", "u2", "u3", "rz", "sx", "x") def single_gate_matrix(gate: str, params: Optional[List[float]] = None): """Get the matrix for a single qubit. Args: gate: the single qubit gate name params: the operation parameters op['params'] Returns: array: A numpy array representing the matrix Raises: QiskitError: If a gate outside the supported set is passed in for the ``Gate`` argument. """ if params is None: params = [] if gate == "U": gc = gates.UGate elif gate == "u3": gc = gates.U3Gate elif gate == "u2": gc = gates.U2Gate elif gate == "u1": gc = gates.U1Gate elif gate == "rz": gc = gates.RZGate elif gate == "id": gc = gates.IGate elif gate == "sx": gc = gates.SXGate elif gate == "x": gc = gates.XGate else: raise QiskitError("Gate is not a valid basis gate for this simulator: %s" % gate) return gc(*params).to_matrix() # Cache CX matrix as no parameters. _CX_MATRIX = gates.CXGate().to_matrix() def cx_gate_matrix(): """Get the matrix for a controlled-NOT gate.""" return np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]], dtype=complex) def einsum_matmul_index(gate_indices, number_of_qubits): """Return the index string for Numpy.einsum matrix-matrix multiplication. The returned indices are to perform a matrix multiplication A.B where the matrix A is an M-qubit matrix, matrix B is an N-qubit matrix, and M <= N, and identity matrices are implied on the subsystems where A has no support on B. Args: gate_indices (list[int]): the indices of the right matrix subsystems to contract with the left matrix. number_of_qubits (int): the total number of qubits for the right matrix. Returns: str: An indices string for the Numpy.einsum function. """ mat_l, mat_r, tens_lin, tens_lout = _einsum_matmul_index_helper(gate_indices, number_of_qubits) # Right indices for the N-qubit input and output tensor tens_r = ascii_uppercase[:number_of_qubits] # Combine indices into matrix multiplication string format # for numpy.einsum function return "{mat_l}{mat_r}, ".format( mat_l=mat_l, mat_r=mat_r ) + "{tens_lin}{tens_r}->{tens_lout}{tens_r}".format( tens_lin=tens_lin, tens_lout=tens_lout, tens_r=tens_r ) def einsum_vecmul_index(gate_indices, number_of_qubits): """Return the index string for Numpy.einsum matrix-vector multiplication. The returned indices are to perform a matrix multiplication A.v where the matrix A is an M-qubit matrix, vector v is an N-qubit vector, and M <= N, and identity matrices are implied on the subsystems where A has no support on v. Args: gate_indices (list[int]): the indices of the right matrix subsystems to contract with the left matrix. number_of_qubits (int): the total number of qubits for the right matrix. Returns: str: An indices string for the Numpy.einsum function. """ mat_l, mat_r, tens_lin, tens_lout = _einsum_matmul_index_helper(gate_indices, number_of_qubits) # Combine indices into matrix multiplication string format # for numpy.einsum function return f"{mat_l}{mat_r}, " + "{tens_lin}->{tens_lout}".format( tens_lin=tens_lin, tens_lout=tens_lout ) def _einsum_matmul_index_helper(gate_indices, number_of_qubits): """Return the index string for Numpy.einsum matrix multiplication. The returned indices are to perform a matrix multiplication A.v where the matrix A is an M-qubit matrix, matrix v is an N-qubit vector, and M <= N, and identity matrices are implied on the subsystems where A has no support on v. Args: gate_indices (list[int]): the indices of the right matrix subsystems to contract with the left matrix. number_of_qubits (int): the total number of qubits for the right matrix. Returns: tuple: (mat_left, mat_right, tens_in, tens_out) of index strings for that may be combined into a Numpy.einsum function string. Raises: QiskitError: if the total number of qubits plus the number of contracted indices is greater than 26. """ # Since we use ASCII alphabet for einsum index labels we are limited # to 26 total free left (lowercase) and 26 right (uppercase) indexes. # The rank of the contracted tensor reduces this as we need to use that # many characters for the contracted indices if len(gate_indices) + number_of_qubits > 26: raise QiskitError("Total number of free indexes limited to 26") # Indices for N-qubit input tensor tens_in = ascii_lowercase[:number_of_qubits] # Indices for the N-qubit output tensor tens_out = list(tens_in) # Left and right indices for the M-qubit multiplying tensor mat_left = "" mat_right = "" # Update left indices for mat and output for pos, idx in enumerate(reversed(gate_indices)): mat_left += ascii_lowercase[-1 - pos] mat_right += tens_in[-1 - idx] tens_out[-1 - idx] = ascii_lowercase[-1 - pos] tens_out = "".join(tens_out) # Combine indices into matrix multiplication string format # for numpy.einsum function return mat_left, mat_right, tens_in, tens_out
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, execute from qiskit.visualization import plot_error_map from qiskit.providers.fake_provider import FakeVigoV2 backend = FakeVigoV2() plot_error_map(backend)
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
https://github.com/dkp-quantum/Tutorials
dkp-quantum
%matplotlib inline import numpy as np import matplotlib.pyplot as plt # Importing standard Qiskit libraries and configuring account from qiskit import * from qiskit.visualization import * from qiskit.circuit import Parameter # Simple example # Define two parameters, t1 and t2 theta1 = Parameter('t1') theta2 = Parameter('t2') # Build a 1-qubit circuit qc = QuantumCircuit(1, 1) # First parameter, t1, is used for a single qubit rotation of a controlled qubit qc.ry(theta1,0) qc.rz(theta2,0) qc.barrier() qc.measure(0, 0) qc.draw(output='mpl') theta1_range = np.linspace(0, 2 * np.pi, 20) theta2_range = np.linspace(0, np.pi, 2) circuits = [qc.bind_parameters({theta1: theta_val1, theta2: theta_val2}) for theta_val2 in theta2_range for theta_val1 in theta1_range ] # Visualize several circuits to check that correct circuits are generated correctly. display(circuits[0].draw(output='mpl')) display(circuits[1].draw(output='mpl')) display(circuits[20].draw(output='mpl')) # Execute multiple circuits job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots = 8192, parameter_binds=[{theta1: theta_val1, theta2: theta_val2} for theta_val2 in theta2_range for theta_val1 in theta1_range]) # Store all counts counts = [job.result().get_counts(i) for i in range(len(job.result().results))] # Plot to visualize the result plt.figure(figsize=(12,6)) plt.plot(range(len(theta1_range)*len(theta2_range)), list(map(lambda counts: (counts.get('0',0)-counts.get('1',1))/8192,counts))) plt.show() # IBMQ.disable_account() provider = IBMQ.enable_account('TOKEN') from qiskit.tools.monitor import backend_overview, backend_monitor, job_monitor from qiskit.tools.visualization import plot_gate_map, plot_error_map # Retrieve IBM Quantum device information backend_overview() # Execute multiple circuits job_exp = execute(qc, backend=provider.get_backend('ibmq_essex'), shots = 8192, parameter_binds=[{theta1: theta_val1, theta2: theta_val2} for theta_val2 in theta2_range for theta_val1 in theta1_range]) # Monitor job status job_monitor(job_exp) # Store all counts counts_exp = [job_exp.result().get_counts(i) for i in range(len(job_exp.result().results))] # Plot to visualize the result plt.figure(figsize=(12,6)) plt.rcParams.update({'font.size': 16}) plt.plot(range(len(theta1_range)*len(theta2_range)), list(map(lambda counts: (counts.get('0',0)-counts.get('1',1))/8192,counts)),'r',label='Simulation') plt.plot(range(len(theta1_range)*len(theta2_range)), list(map(lambda counts_exp: (counts_exp.get('0',0)-counts_exp.get('1',1))/8192,counts_exp)), 'b',label='Experiment') plt.legend(loc='best') plt.show() def swaptest(qc,ancilla,qubit1,qubit2): qc.h(ancilla) qc.cswap(ancilla,qubit1,qubit2) qc.h(ancilla) qr = QuantumRegister(5,'q') cr = ClassicalRegister(2,'c') qc = QuantumCircuit(qr,cr,name='qclassifier') # Put equal weights on the training data qc.h(1) # Prepare the test data quantum state theta1 = Parameter('t1') qc.rx(theta1,4) # Prepare the training data quantum state qc.h(2) qc.rz(-np.pi,2) qc.s(2) qc.cz(1,2) # Put the label qc.cx(1,3) qc.barrier() # Perform swap-test swaptest(qc,0,2,4) qc.barrier() # Measurement qc.measure(0,0) qc.measure(3,1) qc.draw(output='mpl') # Select the range of parameters theta1_range = np.linspace(0, 2 * np.pi, 20) # Execute multiple circuits job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots = 8192, parameter_binds=[{theta1: theta_val1} for theta_val1 in theta1_range]) # Store all counts counts = [job.result().get_counts(i) for i in range(len(job.result().results))] # Let's see how the 'counts' looks like counts # Plot to visualize the result plt.figure(figsize=(12,6)) plt.rcParams.update({'font.size': 20}) # How to extract <ZZ>? Answer: <ZZ> = P(00) - P(01) - P(10) + P(11) plt.plot(theta1_range, list(map(lambda counts: (counts.get('00')-counts.get('10')-counts.get('01')+counts.get('11'))/8192, counts))) plt.rc('text', usetex=True) plt.xlabel(r'$\theta$ (Parameter for test data)') plt.ylabel(r'$ \langle Z\otimes Z \rangle $') plt.show() # Let's also try the same experiment on the 5-qubit device. # Select the range of parameters theta1_range = np.linspace(0, 2 * np.pi, 20) # Execute multiple circuits job_classifier = execute(qc, backend=provider.get_backend('ibmq_essex'), shots = 8192, parameter_binds=[{theta1: theta_val1} for theta_val1 in theta1_range]) # Monitor job status job_monitor(job_classifier) # Store all counts counts_exp = [job_classifier.result().get_counts(i) for i in range(len(job_classifier.result().results))] # Plot to visualize the result plt.figure(figsize=(12,6)) plt.rcParams.update({'font.size': 20}) # Plot theory plt.plot(theta1_range, list(map(lambda counts: (counts.get('00')-counts.get('10')-counts.get('01')+counts.get('11'))/8192, counts)),'r',label='Theory') # Plot experimental result plt.plot(theta1_range, list(map(lambda counts_exp: 4*(counts_exp.get('00')-counts_exp.get('10') -counts_exp.get('01')+counts_exp.get('11'))/8192,counts_exp)),'b', label='Exp. (scaled by a factor of 4)') plt.rc('text', usetex=True) plt.xlabel(r'$\theta$ (Parameter for test data)') plt.ylabel(r'$ \langle Z\otimes Z \rangle $') plt.legend(loc='best') plt.show()
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. qiskit_chemistry_dict = { 'driver': {'name': 'PYSCF'}, 'PYSCF': {'atom': '', 'basis': 'sto3g'}, 'operator': {'name': 'hamiltonian', 'qubit_mapping': 'parity', 'two_qubit_reduction': True, 'freeze_core': True, 'orbital_reduction': []}, 'algorithm': {'name': ''}, 'optimizer': {'name': 'COBYLA', 'maxiter': 10000 }, 'variational_form': {'name': 'UCCSD'}, 'initial_state': {'name': 'HartreeFock'} } molecule = 'H .0 .0 -{0}; Na .0 .0 {0}' algorithms = ['VQE', 'ExactEigensolver'] pts = [x * 0.1 for x in range(10, 25)] pts += [x * 0.25 for x in range(10, 18)] pts += [4.5] energies = np.empty([len(algorithms), len(pts)]) hf_energies = np.empty(len(pts)) distances = np.empty(len(pts)) dipoles = np.empty([len(algorithms), len(pts)]) eval_counts = np.empty(len(pts)) print('Processing step __', end='') for i, d in enumerate(pts): print('\b\b{:2d}'.format(i), end='', flush=True) qiskit_chemistry_dict['PYSCF']['atom'] = molecule.format(d/2) for j in range(len(algorithms)): qiskit_chemistry_dict['algorithm']['name'] = algorithms[j] solver = QiskitChemistry() result = solver.run(qiskit_chemistry_dict) energies[j][i] = result['energy'] hf_energies[i] = result['hf_energy'] dipoles[j][i] = result['total_dipole_moment'] / 0.393430307 if algorithms[j] == 'VQE': eval_counts[i] = result['algorithm_retvals']['eval_count'] distances[i] = d print(' --- complete') print('Distances: ', distances) print('Energies:', energies) print('Hartree-Fock energies:', hf_energies) print('Dipoles:', dipoles) print('VQE num evaluations:', eval_counts) pylab.plot(distances, hf_energies, label='Hartree-Fock') for j in range(len(algorithms)): pylab.plot(distances, energies[j], label=algorithms[j]) pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('NaH Ground State Energy') pylab.legend(loc='upper right') pylab.plot(distances, np.subtract(hf_energies, energies[1]), label='Hartree-Fock') pylab.plot(distances, np.subtract(energies[0], energies[1]), label='VQE') pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('Energy difference from ExactEigensolver') pylab.legend(loc='upper left') for j in reversed(range(len(algorithms))): pylab.plot(distances, dipoles[j], label=algorithms[j]) pylab.xlabel('Interatomic distance') pylab.ylabel('Moment in debye') pylab.title('NaH Dipole Moment') pylab.legend(loc='upper right') pylab.plot(distances, eval_counts, '-o', color=[0.8500, 0.3250, 0.0980], label='VQE') pylab.xlabel('Interatomic distance') pylab.ylabel('Evaluations') pylab.title('VQE number of evaluations') pylab.legend(loc='upper left')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeAuckland backend = FakeAuckland() ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) depths = [] for _ in range(100): depths.append( transpile( ghz, backend, layout_method='trivial' # Fixed layout mapped in circuit order ).depth() ) plt.figure(figsize=(8, 6)) plt.hist(depths, align='left', color='#AC557C') plt.xlabel('Depth', fontsize=14) plt.ylabel('Counts', fontsize=14);
https://github.com/swe-train/qiskit__qiskit
swe-train
""" This file allows to test the various QFT implemented. The user must specify: 1) The number of qubits it wants the QFT to be implemented on 2) The kind of QFT want to implement, among the options: -> Normal QFT with SWAP gates at the end -> Normal QFT without SWAP gates at the end -> Inverse QFT with SWAP gates at the end -> Inverse QFT without SWAP gates at the end The user must can also specify, in the main function, the input quantum state. By default is a maximal superposition state This file uses as simulator the local simulator 'statevector_simulator' because this simulator saves the quantum state at the end of the circuit, which is exactly the goal of the test file. This simulator supports sufficient qubits to the size of the QFTs that are going to be used in Shor's Algorithm because the IBM simulator only supports up to 32 qubits """ """ Imports from qiskit""" from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, IBMQ, BasicAer """ Imports to Python functions """ import time """ Local Imports """ from qfunctions import create_QFT, create_inverse_QFT """ Function to properly print the final state of the simulation """ """ This is only possible in this way because the program uses the statevector_simulator """ def show_good_coef(results, n): i=0 max = pow(2,n) if max > 100: max = 100 """ Iterate to all possible states """ while i<max: binary = bin(i)[2:].zfill(n) number = results.item(i) number = round(number.real, 3) + round(number.imag, 3) * 1j """ Print the respective component of the state if it has a non-zero coefficient """ if number!=0: print('|{}>'.format(binary),number) i=i+1 """ Main program """ if __name__ == '__main__': """ Select how many qubits want to apply the QFT on """ n = int(input('\nPlease select how many qubits want to apply the QFT on: ')) """ Select the kind of QFT to apply using the variable what_to_test: what_to_test = 0: Apply normal QFT with the SWAP gates at the end what_to_test = 1: Apply normal QFT without the SWAP gates at the end what_to_test = 2: Apply inverse QFT with the SWAP gates at the end what_to_test = 3: Apply inverse QFT without the SWAP gates at the end """ print('\nSelect the kind of QFT to apply:') print('Select 0 to apply normal QFT with the SWAP gates at the end') print('Select 1 to apply normal QFT without the SWAP gates at the end') print('Select 2 to apply inverse QFT with the SWAP gates at the end') print('Select 3 to apply inverse QFT without the SWAP gates at the end\n') what_to_test = int(input('Select your option: ')) if what_to_test<0 or what_to_test>3: print('Please select one of the options') exit() print('\nTotal number of qubits used: {0}\n'.format(n)) print('Please check source file to change input quantum state. By default is a maximal superposition state with |+> in every qubit.\n') ts = time.time() """ Create quantum and classical registers """ quantum_reg = QuantumRegister(n) classic_reg = ClassicalRegister(n) """ Create Quantum Circuit """ circuit = QuantumCircuit(quantum_reg, classic_reg) """ Create the input state desired Please change this as you like, by default we put H gates in every qubit, initializing with a maximimal superposition state """ #circuit.h(quantum_reg) """ Test the right QFT according to the variable specified before""" if what_to_test == 0: create_QFT(circuit,quantum_reg,n,1) elif what_to_test == 1: create_QFT(circuit,quantum_reg,n,0) elif what_to_test == 2: create_inverse_QFT(circuit,quantum_reg,n,1) elif what_to_test == 3: create_inverse_QFT(circuit,quantum_reg,n,0) else: print('Noting to implement, exiting program') exit() """ show results of circuit creation """ create_time = round(time.time()-ts, 3) if n < 8: print(circuit) print(f"... circuit creation time = {create_time}") ts = time.time() """ Simulate the created Quantum Circuit """ simulation = execute(circuit, backend=BasicAer.get_backend('statevector_simulator'),shots=1) """ Get the results of the simulation in proper structure """ sim_result=simulation.result() """ Get the statevector of the final quantum state """ outputstate = sim_result.get_statevector(circuit, decimals=3) """ show execution time """ exec_time = round(time.time()-ts, 3) print(f"... circuit execute time = {exec_time}") """ Print final quantum state to user """ print('The final state after applying the QFT is:\n') show_good_coef(outputstate,n)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Code from commutative_analysis pass that checks commutation relations between DAG nodes.""" from functools import lru_cache from typing import List, Union import numpy as np from qiskit import QiskitError from qiskit.circuit import Qubit from qiskit.circuit.operation import Operation from qiskit.circuit.controlflow import CONTROL_FLOW_OP_NAMES from qiskit.quantum_info.operators import Operator _skipped_op_names = {"measure", "reset", "delay", "initialize"} _no_cache_op_names = {"annotated"} @lru_cache(maxsize=None) def _identity_op(num_qubits): """Cached identity matrix""" return Operator( np.eye(2**num_qubits), input_dims=(2,) * num_qubits, output_dims=(2,) * num_qubits ) class CommutationChecker: """This code is essentially copy-pasted from commutative_analysis.py. This code cleverly hashes commutativity and non-commutativity results between DAG nodes and seems quite efficient for large Clifford circuits. They may be other possible efficiency improvements: using rule-based commutativity analysis, evicting from the cache less useful entries, etc. """ def __init__(self, standard_gate_commutations: dict = None, cache_max_entries: int = 10**6): super().__init__() if standard_gate_commutations is None: self._standard_commutations = {} else: self._standard_commutations = standard_gate_commutations self._cache_max_entries = cache_max_entries # self._cached_commutation has the same structure as standard_gate_commutations, i.e. a # dict[pair of gate names][relative placement][tuple of gate parameters] := True/False self._cached_commutations = {} self._current_cache_entries = 0 self._cache_miss = 0 self._cache_hit = 0 def commute( self, op1: Operation, qargs1: List, cargs1: List, op2: Operation, qargs2: List, cargs2: List, max_num_qubits: int = 3, ) -> bool: """ Checks if two Operations commute. The return value of `True` means that the operations truly commute, and the return value of `False` means that either the operations do not commute or that the commutation check was skipped (for example, when the operations have conditions or have too many qubits). Args: op1: first operation. qargs1: first operation's qubits. cargs1: first operation's clbits. op2: second operation. qargs2: second operation's qubits. cargs2: second operation's clbits. max_num_qubits: the maximum number of qubits to consider, the check may be skipped if the number of qubits for either operation exceeds this amount. Returns: bool: whether two operations commute. """ structural_commutation = _commutation_precheck( op1, qargs1, cargs1, op2, qargs2, cargs2, max_num_qubits ) if structural_commutation is not None: return structural_commutation first_op_tuple, second_op_tuple = _order_operations( op1, qargs1, cargs1, op2, qargs2, cargs2 ) first_op, first_qargs, _ = first_op_tuple second_op, second_qargs, _ = second_op_tuple skip_cache = first_op.name in _no_cache_op_names or second_op.name in _no_cache_op_names if skip_cache: return _commute_matmul(first_op, first_qargs, second_op, second_qargs) commutation_lookup = self.check_commutation_entries( first_op, first_qargs, second_op, second_qargs ) if commutation_lookup is not None: return commutation_lookup # Compute commutation via matrix multiplication is_commuting = _commute_matmul(first_op, first_qargs, second_op, second_qargs) # Store result in this session's commutation_library # TODO implement LRU cache or similar # Rebuild cache if current cache exceeded max size if self._current_cache_entries >= self._cache_max_entries: self.clear_cached_commutations() first_params = getattr(first_op, "params", []) second_params = getattr(second_op, "params", []) if len(first_params) > 0 or len(second_params) > 0: self._cached_commutations.setdefault((first_op.name, second_op.name), {}).setdefault( _get_relative_placement(first_qargs, second_qargs), {} )[ (_hashable_parameters(first_params), _hashable_parameters(second_params)) ] = is_commuting else: self._cached_commutations.setdefault((first_op.name, second_op.name), {})[ _get_relative_placement(first_qargs, second_qargs) ] = is_commuting self._current_cache_entries += 1 return is_commuting def num_cached_entries(self): """Returns number of cached entries""" return self._current_cache_entries def clear_cached_commutations(self): """Clears the dictionary holding cached commutations""" self._current_cache_entries = 0 self._cache_miss = 0 self._cache_hit = 0 self._cached_commutations = {} def check_commutation_entries( self, first_op: Operation, first_qargs: List, second_op: Operation, second_qargs: List, ) -> Union[bool, None]: """Returns stored commutation relation if any Args: first_op: first operation. first_qargs: first operation's qubits. second_op: second operation. second_qargs: second operation's qubits. Return: bool: True if the gates commute and false if it is not the case. """ # We don't precompute commutations for parameterized gates, yet commutation = _query_commutation( first_op, first_qargs, second_op, second_qargs, self._standard_commutations, ) if commutation is not None: return commutation commutation = _query_commutation( first_op, first_qargs, second_op, second_qargs, self._cached_commutations, ) if commutation is None: self._cache_miss += 1 else: self._cache_hit += 1 return commutation def _hashable_parameters(params): """Convert the parameters of a gate into a hashable format for lookup in a dictionary. This aims to be fast in common cases, and is not intended to work outside of the lifetime of a single commutation pass; it does not handle mutable state correctly if the state is actually changed.""" try: hash(params) return params except TypeError: pass if isinstance(params, (list, tuple)): return tuple(_hashable_parameters(x) for x in params) if isinstance(params, np.ndarray): # Using the bytes of the matrix as key is runtime efficient but requires more space: 128 bits # times the number of parameters instead of a single 64 bit id. However, by using the bytes as # an id, we can reuse the cached commutations between different passes. return (np.ndarray, params.tobytes()) # Catch anything else with a slow conversion. return ("fallback", str(params)) def is_commutation_supported(op): """ Filter operations whose commutation is not supported due to bugs in transpiler passes invoking commutation analysis. Args: op (Operation): operation to be checked for commutation relation Return: True if determining the commutation of op is currently supported """ # Bug in CommutativeCancellation, e.g. see gh-8553 if getattr(op, "condition", False): return False # Commutation of ControlFlow gates also not supported yet. This may be pending a control flow graph. if op.name in CONTROL_FLOW_OP_NAMES: return False return True def is_commutation_skipped(op, qargs, max_num_qubits): """ Filter operations whose commutation will not be determined. Args: op (Operation): operation to be checked for commutation relation qargs (List): operation qubits max_num_qubits (int): the maximum number of qubits to consider, the check may be skipped if the number of qubits for either operation exceeds this amount. Return: True if determining the commutation of op is currently not supported """ if ( len(qargs) > max_num_qubits or getattr(op, "_directive", False) or op.name in _skipped_op_names ): return True if getattr(op, "is_parameterized", False) and op.is_parameterized(): return True # we can proceed if op has defined: to_operator, to_matrix and __array__, or if its definition can be # recursively resolved by operations that have a matrix. We check this by constructing an Operator. if (hasattr(op, "to_matrix") and hasattr(op, "__array__")) or hasattr(op, "to_operator"): return False return False def _commutation_precheck( op1: Operation, qargs1: List, cargs1: List, op2: Operation, qargs2: List, cargs2: List, max_num_qubits, ): if not is_commutation_supported(op1) or not is_commutation_supported(op2): return False if set(qargs1).isdisjoint(qargs2) and set(cargs1).isdisjoint(cargs2): return True if is_commutation_skipped(op1, qargs1, max_num_qubits) or is_commutation_skipped( op2, qargs2, max_num_qubits ): return False return None def _get_relative_placement(first_qargs: List[Qubit], second_qargs: List[Qubit]) -> tuple: """Determines the relative qubit placement of two gates. Note: this is NOT symmetric. Args: first_qargs (DAGOpNode): first gate second_qargs (DAGOpNode): second gate Return: A tuple that describes the relative qubit placement: E.g. _get_relative_placement(CX(0, 1), CX(1, 2)) would return (None, 0) as there is no overlap on the first qubit of the first gate but there is an overlap on the second qubit of the first gate, i.e. qubit 0 of the second gate. Likewise, _get_relative_placement(CX(1, 2), CX(0, 1)) would return (1, None) """ qubits_g2 = {q_g1: i_g1 for i_g1, q_g1 in enumerate(second_qargs)} return tuple(qubits_g2.get(q_g0, None) for q_g0 in first_qargs) @lru_cache(maxsize=10**3) def _persistent_id(op_name: str) -> int: """Returns an integer id of a string that is persistent over different python executions (note that hash() can not be used, i.e. its value can change over two python executions) Args: op_name (str): The string whose integer id should be determined. Return: The integer id of the input string. """ return int.from_bytes(bytes(op_name, encoding="utf-8"), byteorder="big", signed=True) def _order_operations( op1: Operation, qargs1: List, cargs1: List, op2: Operation, qargs2: List, cargs2: List ): """Orders two operations in a canonical way that is persistent over @different python versions and executions Args: op1: first operation. qargs1: first operation's qubits. cargs1: first operation's clbits. op2: second operation. qargs2: second operation's qubits. cargs2: second operation's clbits. Return: The input operations in a persistent, canonical order. """ op1_tuple = (op1, qargs1, cargs1) op2_tuple = (op2, qargs2, cargs2) least_qubits_op, most_qubits_op = ( (op1_tuple, op2_tuple) if op1.num_qubits < op2.num_qubits else (op2_tuple, op1_tuple) ) # prefer operation with the least number of qubits as first key as this results in shorter keys if op1.num_qubits != op2.num_qubits: return least_qubits_op, most_qubits_op else: return ( (op1_tuple, op2_tuple) if _persistent_id(op1.name) < _persistent_id(op2.name) else (op2_tuple, op1_tuple) ) def _query_commutation( first_op: Operation, first_qargs: List, second_op: Operation, second_qargs: List, _commutation_lib: dict, ) -> Union[bool, None]: """Queries and returns the commutation of a pair of operations from a provided commutation library Args: first_op: first operation. first_qargs: first operation's qubits. first_cargs: first operation's clbits. second_op: second operation. second_qargs: second operation's qubits. second_cargs: second operation's clbits. _commutation_lib (dict): dictionary of commutation relations Return: True if first_op and second_op commute, False if they do not commute and None if the commutation is not in the library """ commutation = _commutation_lib.get((first_op.name, second_op.name), None) # Return here if the commutation is constant over all relative placements of the operations if commutation is None or isinstance(commutation, bool): return commutation # If we arrive here, there is an entry in the commutation library but it depends on the # placement of the operations and also possibly on operation parameters if isinstance(commutation, dict): commutation_after_placement = commutation.get( _get_relative_placement(first_qargs, second_qargs), None ) # if we have another dict in commutation_after_placement, commutation depends on params if isinstance(commutation_after_placement, dict): # Param commutation entry exists and must be a dict first_params = getattr(first_op, "params", []) second_params = getattr(second_op, "params", []) return commutation_after_placement.get( (_hashable_parameters(first_params), _hashable_parameters(second_params)), None, ) else: # queried commutation is True, False or None return commutation_after_placement else: raise ValueError("Expected commutation to be None, bool or a dict") def _commute_matmul( first_ops: Operation, first_qargs: List, second_op: Operation, second_qargs: List ): qarg = {q: i for i, q in enumerate(first_qargs)} num_qubits = len(qarg) for q in second_qargs: if q not in qarg: qarg[q] = num_qubits num_qubits += 1 first_qarg = tuple(qarg[q] for q in first_qargs) second_qarg = tuple(qarg[q] for q in second_qargs) # try to generate an Operator out of op, if this succeeds we can determine commutativity, otherwise # return false try: operator_1 = Operator( first_ops, input_dims=(2,) * len(first_qarg), output_dims=(2,) * len(first_qarg) ) operator_2 = Operator( second_op, input_dims=(2,) * len(second_qarg), output_dims=(2,) * len(second_qarg) ) except QiskitError: return False if first_qarg == second_qarg: # Use full composition if possible to get the fastest matmul paths. op12 = operator_1.compose(operator_2) op21 = operator_2.compose(operator_1) else: # Expand operator_1 to be large enough to contain operator_2 as well; this relies on qargs1 # being the lowest possible indices so the identity can be tensored before it. extra_qarg2 = num_qubits - len(first_qarg) if extra_qarg2: id_op = _identity_op(extra_qarg2) operator_1 = id_op.tensor(operator_1) op12 = operator_1.compose(operator_2, qargs=second_qarg, front=False) op21 = operator_1.compose(operator_2, qargs=second_qarg, front=True) ret = op12 == op21 return ret
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/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_optimization.algorithms import MinimumEigenOptimizer from qiskit.utils import algorithm_globals from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit_optimization.applications.vertex_cover import VertexCover import networkx as nx seed = 123 algorithm_globals.random_seed = seed graph = nx.random_regular_graph(d=3, n=6, seed=seed) pos = nx.spring_layout(graph, seed=seed) prob = VertexCover(graph) prob.draw(pos=pos) qp = prob.to_quadratic_program() print(qp.prettyprint()) # Numpy Eigensolver meo = MinimumEigenOptimizer(min_eigen_solver=NumPyMinimumEigensolver()) result = meo.solve(qp) print(result.prettyprint()) print("\nsolution:", prob.interpret(result)) prob.draw(result, pos=pos) # QAOA meo = MinimumEigenOptimizer(min_eigen_solver=QAOA(reps=1, sampler=Sampler(), optimizer=COBYLA())) result = meo.solve(qp) print(result.prettyprint()) print("\nsolution:", prob.interpret(result)) print("\ntime:", result.min_eigen_solver_result.optimizer_time) prob.draw(result, pos=pos) from qiskit_optimization.applications import Knapsack prob = Knapsack(values=[3, 4, 5, 6, 7], weights=[2, 3, 4, 5, 6], max_weight=10) qp = prob.to_quadratic_program() print(qp.prettyprint()) # Numpy Eigensolver meo = MinimumEigenOptimizer(min_eigen_solver=NumPyMinimumEigensolver()) result = meo.solve(qp) print(result.prettyprint()) print("\nsolution:", prob.interpret(result)) # QAOA meo = MinimumEigenOptimizer(min_eigen_solver=QAOA(reps=1, sampler=Sampler(), optimizer=COBYLA())) result = meo.solve(qp) print(result.prettyprint()) print("\nsolution:", prob.interpret(result)) print("\ntime:", result.min_eigen_solver_result.optimizer_time) from qiskit_optimization.converters import QuadraticProgramToQubo # the same knapsack problem instance as in the previous section prob = Knapsack(values=[3, 4, 5, 6, 7], weights=[2, 3, 4, 5, 6], max_weight=10) qp = prob.to_quadratic_program() print(qp.prettyprint()) # intermediate QUBO form of the optimization problem conv = QuadraticProgramToQubo() qubo = conv.convert(qp) print(qubo.prettyprint()) # qubit Hamiltonian and offset op, offset = qubo.to_ising() print(f"num qubits: {op.num_qubits}, offset: {offset}\n") print(op) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/drobiu/quantum-project
drobiu
"""Python implementation of Grovers algorithm through use of the Qiskit library to find the value 3 (|11>) out of four possible values.""" #import numpy and plot library import matplotlib.pyplot as plt import numpy as np # importing Qiskit from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.quantum_info import Statevector # import basic plot tools from qiskit.visualization import plot_histogram # define variables, 1) initialize qubits to zero n = 2 grover_circuit = QuantumCircuit(n) #define initialization function def initialize_s(qc, qubits): '''Apply a H-gate to 'qubits' in qc''' for q in qubits: qc.h(q) return qc ### begin grovers circuit ### #2) Put qubits in equal state of superposition grover_circuit = initialize_s(grover_circuit, [0,1]) # 3) Apply oracle reflection to marked instance x_0 = 3, (|11>) grover_circuit.cz(0,1) statevec = job_sim.result().get_statevector() from qiskit_textbook.tools import vector2latex vector2latex(statevec, pretext="|\\psi\\rangle =") # 4) apply additional reflection (diffusion operator) grover_circuit.h([0,1]) grover_circuit.z([0,1]) grover_circuit.cz(0,1) grover_circuit.h([0,1]) # 5) measure the qubits grover_circuit.measure_all() # Load IBM Q account and get the least busy backend device provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) from qiskit.tools.monitor import job_monitor job = execute(grover_circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(grover_circuit) plot_histogram(answer) #highest amplitude should correspond with marked value x_0 (|11>)
https://github.com/abbarreto/qiskit2
abbarreto
hub=qc-spring-22-2, group=group-5 and project=recPrYILNAOsYMWIV
https://github.com/TheGupta2012/QPE-Algorithms
TheGupta2012
from qiskit import * import matplotlib.pyplot as plt from qiskit.extensions import UnitaryGate from qiskit.circuit import add_control from qiskit.tools.visualization import plot_bloch_multivector,plot_histogram import numpy as np import sys sys.path.append("..") from Modules.vanilla_qpe import QPE U= UnitaryGate(data = np.array([[1,0], [0,np.exp(2*np.pi*1j*(1/5))]])) qpe_circ1 = QPE(precision=4,unitary=U).get_QPE(show=True,save = False) q = QuantumCircuit(5,4) q.x(4) q.barrier() q = q.compose(qpe_circ1,qubits = [0,1,2,3,4]) q.draw('mpl') q.measure([0,1,2,3],[0,1,2,3]) q.draw('mpl') count = execute(q,backend=Aer.get_backend('qasm_simulator')).result().get_counts() fig = plot_histogram(count,title = "Phase estimates for $\\theta = 1/5$") fig.savefig("Phase 0.2 estimate.JPG",dpi = 200) fig q = QuantumCircuit(3,name = 'Unitary') q.cp(2*np.pi*(1/5),1,2) q.draw('mpl') qpe_circ2 = QPE(precision=4,unitary=q).get_QPE(show=True,save=True) q = QuantumCircuit(7,4) q.x([5,6]) q.barrier() q.append(qpe_circ2, qargs = [0,1,2,3,4,5,6]) q.measure([0,1,2,3],[0,1,2,3]) q.draw('mpl') count = execute(q,backend=Aer.get_backend('qasm_simulator')).result().get_counts() plot_histogram(count) q = QuantumCircuit(7,5) q.x(4) q.compose(qpe_circ1,qubits = [0,1,2,3,4], inplace = True) # q = q.compose(qpe_circ,qubits = [0,1,2,3,4]) q.draw('mpl') q.measure([0,1,2,3],[0,1,2,3]) q.draw('mpl') count = execute(q,backend=Aer.get_backend('qasm_simulator')).result().get_counts() plot_histogram(count)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# You can choose different colors for the real and imaginary parts of the density matrix. from qiskit import QuantumCircuit from qiskit.quantum_info import DensityMatrix from qiskit.visualization import plot_state_city qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = DensityMatrix(qc) plot_state_city(state, color=['midnightblue', 'crimson'], title="New State City")
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
mcoggins96
from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute,IBMQ from qiskit.tools.monitor import job_monitor from qiskit.circuit.library import RGQFTMultiplier IBMQ.enable_account('ENTER API KEY HERE') provider = IBMQ.get_provider(hub='ibm-q') backend = provider.get_backend('ibmq_qasm_simulator') q = QuantumRegister(8,'q') c = ClassicalRegister(4,'c') circuit = QuantumCircuit(q,c) # Operand A = 10 (2) circuit.x(q[1]) # Operand B = 11 (3) circuit.x(q[2]) circuit.x(q[3]) circuit1 = RGQFTMultiplier(num_state_qubits=2, num_result_qubits=4) circuit = circuit.compose(circuit1) circuit.measure(q[4],c[0]) circuit.measure(q[5],c[1]) circuit.measure(q[6],c[2]) circuit.measure(q[7],c[3]) print(circuit) job = execute(circuit, backend, shots=2000) result = job.result() counts = result.get_counts() print('2*3') print('---') print(counts)
https://github.com/MonitSharma/Qiskit-Hindi-Tutorials
MonitSharma
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() !pip install qutip -q !pip install qiskit -q !pip install qiskit[visualization] -q !pip install git+https://github.com/qiskit-community/qiskit-textbook.git#subdirectory=qiskit-textbook-src -q import numpy as np np.set_printoptions(precision=3, suppress=True) import qutip as qt from matplotlib import pyplot as plt %matplotlib inline import pandas as pd import sklearn as sk import qiskit as qk # Remember that qiskit has to be already installed in the Python environment. # Otherwise the import command will fail import qiskit as qk # A circuit composed of just one qubit qc = qk.QuantumCircuit(1) qc.draw('mpl') import qiskit as qiskit # A qubit initialized in the state |0> qc = qk.QuantumCircuit(1) qc.initialize([1,0]) qc.draw('mpl') import qiskit as qiskit # A qubit initialized in the state |0> qc = qk.QuantumCircuit(1) qc.initialize([1,0]) qc.draw('mpl') import qiskit as qiskit # A qubit initialized in the state |0> qc = qk.QuantumCircuit(1) qc.initialize([1,0]) qc.draw('mpl') import qiskit as qk qc = qk.QuantumCircuit(1) qc.initialize([1,0],0) qc.measure_all() # Let's choose the statevector simulator from the Aer backend backend = qk.Aer.get_backend('statevector_simulator') # And execute the circuit qc in the simulator backend # getting as final result the counts from 1.000 measures # of the qubit state result = qk.execute(qc, backend, shots=1000).result().get_counts() result import qiskit as qk qc = qk.QuantumCircuit(1) qc.initialize([1,0],0) qc.measure_all() backend = qk.Aer.get_backend('statevector_simulator') result = qk.execute(qc, backend, shots=1000).result().get_counts() qk.visualization.plot_histogram(result) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr, cr) qc.initialize([1,0],0) qc.measure(0,0) qc.draw('mpl') backend = qk.Aer.get_backend('statevector_simulator') result = qk.execute(qc, backend, shots=1000).result().get_counts() qk.visualization.plot_histogram(result) import numpy as np v0 = np.array([[1],[0]]);v0 v1 = np.array([[0],[1]]); v1 X = np.array([[0,1],[1,0]]); X X.dot(v0) X.dot(v1) import qiskit as qk qr = qk.QuantumRegister(1,"q0") cr = qk.ClassicalRegister(1,"c0") qc = qk.QuantumCircuit(qr, cr) qc.initialize([1,0],0) qc.x(0) qc.measure(qr[0], cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc, simulator, shots=1000).result().get_counts() results qk.visualization.plot_histogram(results) import numpy as np # Notice that we are creating the v0 matrix using the transpose operation v0 = np.array([[1,0]]).T; v0 # Here it is created again de X matrix X = np.array([[0,1],[1,0]]); X # Multiplying v0 by the X matrix twice you get again v0 X.dot(X).dot(v0) # Multiplying the X matrix by itself you get the Identity matrix X.dot(X) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr, cr) qc.initialize([1,0],0) qc.x(0) qc.x(0) qc.measure(qr[0],cr[0]) qc.draw('mpl') # The result of 1000 measures of the qubit above gives the |0> state as result # in all measures simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=1000).result().get_counts() results qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr,cr) qc.initialize([2**-0.5,2**-0.5],0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np v0 = np.array([[1,0]]).T; v0 H = np.array([[1,1],[1,-1]])/np.sqrt(2); H H.dot(v0) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.h(qr[0]) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc, simulator, shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr,cr) qc.initialize([2**-0.5,-(2**-0.5)],0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr,cr) qc.initialize([2**-0.5,-(2**-0.5)],0) qc.h(0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr,cr) qc.initialize([0,1],0) qc.h(0) qc.h(0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np # First let's start with the qubit in the state |psi> = (|0> - |1>)/sqrt(2) psi = np.array([[1,-1]]).T/(2**0.5); psi H = np.array([[1,1],[1,-1]])/2**0.5; H # Now let's pass the qubit Psi through an Hadamard gate. # The result is a qubit in the state |1> H.dot(psi) # Let's start with a qubit in the state |1>, pass it through a # a hadamard gate twice and check the result v0 = np.array([[0,1]]).T; v0 H.dot(H).dot(v0) # This means that if we multiply the H gate by itself the result # will be an Identity matrix. Let's check it. H.dot(H) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np psi1 = np.array([[1,0]]).T; psi1 psi2 = np.array([[1,0]]).T; psi2 # In numpy the tensor product is calculated with the function kron np.kron(psi1,psi2) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(0) qc.h(1) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np psi1 = np.array([[1,0]]).T;psi1 psi2 = np.array([[1,0]]).T;psi2 H = np.array([[1,1],[1,-1]])/2**0.5;H # When we want to combine two vector states or gate matrices we tensor product them. psi3 = np.kron(psi1,psi2);psi3 H2 = np.kron(H,H);H2 # When we want to pass a vetor through a gate we calculate the dot product # of the total gate matrix with the total vector. # As we have predicted, the resulting vector state has a=b=c=d=1/2 psi4 = H2.dot(psi3); psi4
https://github.com/qiskit-community/community.qiskit.org
qiskit-community
import numpy as np np.random.seed(999999) target_distr = np.random.rand(2) # We now convert the random vector into a valid probability vector target_distr /= sum(target_distr) from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister def get_var_form(params): qr = QuantumRegister(1, name="q") cr = ClassicalRegister(1, name='c') qc = QuantumCircuit(qr, cr) qc.u3(params[0], params[1], params[2], qr[0]) qc.measure(qr, cr[0]) return qc from qiskit import Aer, execute backend = Aer.get_backend("qasm_simulator") NUM_SHOTS = 10000 def get_probability_distribution(counts): output_distr = [v / NUM_SHOTS for v in counts.values()] if len(output_distr) == 1: output_distr.append(0) return output_distr def objective_function(params): # Obtain a quantum circuit instance from the paramters qc = get_var_form(params) # Execute the quantum circuit to obtain the probability distribution associated with the current parameters result = execute(qc, backend, shots=NUM_SHOTS).result() # Obtain the counts for each measured state, and convert those counts into a probability vector output_distr = get_probability_distribution(result.get_counts(qc)) # Calculate the cost as the distance between the output distribution and the target distribution cost = sum([np.abs(output_distr[i] - target_distr[i]) for i in range(2)]) return cost from qiskit.aqua.components.optimizers import COBYLA # Initialize the COBYLA optimizer optimizer = COBYLA(maxiter=500, tol=0.0001) # Create the initial parameters (noting that our single qubit variational form has 3 parameters) params = np.random.rand(3) ret = optimizer.optimize(num_vars=3, objective_function=objective_function, initial_point=params) # Obtain the output distribution using the final parameters qc = get_var_form(ret[0]) counts = execute(qc, backend, shots=NUM_SHOTS).result().get_counts(qc) output_distr = get_probability_distribution(counts) print("Target Distribution:", target_distr) print("Obtained Distribution:", output_distr) print("Output Error (Manhattan Distance):", ret[1]) print("Parameters Found:", ret[0]) from qiskit.aqua.components.variational_forms import RYRZ entanglements = ["linear", "full"] for entanglement in entanglements: form = RYRZ(num_qubits=4, depth=1, entanglement=entanglement) if entanglement == "linear": print("=============Linear Entanglement:=============") else: print("=============Full Entanglement:=============") # We initialize all parameters to 0 for this demonstration print(form.construct_circuit([0] * form.num_parameters).draw(line_length=100)) print() from qiskit.aqua.algorithms import VQE, ExactEigensolver import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit.chemistry.aqua_extensions.components.variational_forms import UCCSD from qiskit.aqua.components.variational_forms import RYRZ from qiskit.chemistry.aqua_extensions.components.initial_states import HartreeFock from qiskit.aqua.components.optimizers import COBYLA, SPSA, SLSQP from qiskit import IBMQ, BasicAer, Aer from qiskit.chemistry.drivers import PySCFDriver, UnitsType from qiskit.chemistry import FermionicOperator from qiskit import IBMQ from qiskit.providers.aer import noise from qiskit.aqua import QuantumInstance from qiskit.ignis.mitigation.measurement import CompleteMeasFitter def get_qubit_op(dist): driver = PySCFDriver(atom="Li .0 .0 .0; H .0 .0 " + str(dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') molecule = driver.run() freeze_list = [0] remove_list = [-3, -2] repulsion_energy = molecule.nuclear_repulsion_energy num_particles = molecule.num_alpha + molecule.num_beta num_spin_orbitals = molecule.num_orbitals * 2 remove_list = [x % molecule.num_orbitals for x in remove_list] freeze_list = [x % molecule.num_orbitals for x in freeze_list] remove_list = [x - len(freeze_list) for x in remove_list] remove_list += [x + molecule.num_orbitals - len(freeze_list) for x in remove_list] freeze_list += [x + molecule.num_orbitals for x in freeze_list] ferOp = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) ferOp, energy_shift = ferOp.fermion_mode_freezing(freeze_list) num_spin_orbitals -= len(freeze_list) num_particles -= len(freeze_list) ferOp = ferOp.fermion_mode_elimination(remove_list) num_spin_orbitals -= len(remove_list) qubitOp = ferOp.mapping(map_type='parity', threshold=0.00000001) qubitOp = qubitOp.two_qubit_reduced_operator(num_particles) shift = energy_shift + repulsion_energy return qubitOp, num_particles, num_spin_orbitals, shift backend = BasicAer.get_backend("statevector_simulator") distances = np.arange(0.5, 4.0, 0.1) exact_energies = [] vqe_energies = [] optimizer = SLSQP(maxiter=5) for dist in distances: qubitOp, num_particles, num_spin_orbitals, shift = get_qubit_op(dist) result = ExactEigensolver(qubitOp).run() exact_energies.append(result['energy'] + shift) initial_state = HartreeFock( qubitOp.num_qubits, num_spin_orbitals, num_particles, 'parity' ) var_form = UCCSD( qubitOp.num_qubits, depth=1, num_orbitals=num_spin_orbitals, num_particles=num_particles, initial_state=initial_state, qubit_mapping='parity' ) vqe = VQE(qubitOp, var_form, optimizer, 'matrix') results = vqe.run(backend)['energy'] + shift vqe_energies.append(results) print("Interatomic Distance:", np.round(dist, 2), "VQE Result:", results, "Exact Energy:", exact_energies[-1]) print("All energies have been calculated") plt.plot(distances, exact_energies, label="Exact Energy") plt.plot(distances, vqe_energies, label="VQE Energy") plt.xlabel('Atomic distance (Angstrom)') plt.ylabel('Energy') plt.legend() plt.show() driver = PySCFDriver(atom='H .0 .0 -0.3625; H .0 .0 0.3625', unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') molecule = driver.run() num_particles = molecule.num_alpha + molecule.num_beta qubitOp = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals).mapping(map_type='parity') qubitOp = qubitOp.two_qubit_reduced_operator(num_particles) IBMQ.load_account() IBMQ.get_provider(hub='ibm-q') backend = Aer.get_backend("qasm_simulator") device = provider.get_backend("ibmqx4") coupling_map = device.configuration().coupling_map noise_model = noise.device.basic_device_noise_model(device.properties()) quantum_instance = QuantumInstance(backend=backend, shots=1000, noise_model=noise_model, coupling_map=coupling_map, measurement_error_mitigation_cls=CompleteMeasFitter, cals_matrix_refresh_period=30,) exact_solution = ExactEigensolver(qubitOp).run() print("Exact Result:", exact_solution['energy']) optimizer = SPSA(max_trials=100) var_form = RYRZ(qubitOp.num_qubits, depth=1, entanglement="linear") vqe = VQE(qubitOp, var_form, optimizer=optimizer, operator_mode="grouped_paulis") ret = vqe.run(quantum_instance) print("VQE Result:", ret['energy'])
https://github.com/sergiogh/qpirates-qiskit-notebooks
sergiogh
# Dependencies and initial configuration %pylab inline from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit from qiskit import execute, Aer from qiskit.tools.visualization import plot_histogram from ipywidgets import interact import matplotlib.pyplot as plt import matplotlib.image as mpimg from qiskit.circuit.library.standard_gates import HGate, IGate, XGate def MoveA1(move_A1): global moveA1; moveA1=move_A1; def MoveB1(move_B1): global moveB1; moveB1=move_B1; def MoveA2(move_A2): global moveA2; moveA2=move_A2; def who_wins(counts): if len(counts)==1 : print('The winner is', 'A' if ("0" in counts) else 'B') if ("0" in counts): img = mpimg.imread('card.jpg') else: img = mpimg.imread('card_reverse.jpg') imgplot = plt.imshow(img) plt.axis('off') plt.show() else: count0=counts["0"] count1=counts["1"] print('The coin is in superposition of |0⟩ and |1⟩') print('A wins with probability', "%.1f%%" % (100.*count0/(count0+count1))) print('B wins with probability', "%.1f%%" % (100.*count1/(count0+count1))) return() def build_circuit(): q = QuantumRegister(1, name="coin") # create a quantum register with one qubit c = ClassicalRegister(1) qc = QuantumCircuit(q, c) # creates the quantum circuit h = HGate(label='MAGIC') i = IGate(label='Do Nothing') x = XGate(label='Flip') # 1. move of A if moveA1 == 0 : qc.append(i, [0]) #qc.i(q[0]) elif moveA1 == 1 : qc.append(x, [0]) #qc.x(q[0]) elif moveA1 == 2 : qc.append(h, [0]) #.h(q[0]) # 1. move of B if moveB1 == 0 : qc.append(i, [0]) elif moveB1 == 1 : qc.append(x, [0]) # 2. move of A if moveA2 == 0 : qc.append(i, [0]) elif moveA2 == 1 : qc.append(x, [0]) elif moveA2 == 2 : qc.append(h, [0]) qc.measure(q, c) # Measure the qubits return qc interact(MoveA1, move_A1={'Not Flip':0,'Flip':1}); interact(MoveB1, move_B1={'Not Flip':0,'Flip':1}); interact(MoveA2, move_A2={'Not Flip':0,'Flip':1}); # The Quantum Circuit qc = build_circuit() qc.draw('mpl') # execute the quantum circiut (coin moves) and identify the winner backend = Aer.get_backend('qasm_simulator') # define the backend job = execute(qc, backend, shots=200) # run the job simulation result = job.result() # grab the result counts = result.get_counts(qc) # results for the number of runs #print(counts); # print the results of the runs who_wins(counts); # celebrate the winner interact(MoveB1, move_B1={'Not Flip':0,'Flip':1}); # Quantum Computer uses Superposition! (2 is a "Hadamard Gate") MoveA1(2) MoveA2(2) qc = build_circuit() qc.draw('mpl') # execute the quantum circiut (coin moves) and identify the winner backend = Aer.get_backend('qasm_simulator') # define the backend job = execute(qc, backend, shots=200) # run the job simulation result = job.result() # grab the result counts = result.get_counts(qc) # results for the number of runs print(counts); # print the results of the runs who_wins(counts); # celebrate the winner plot_histogram(counts) # Visualise the results from qiskit.providers.aer.noise import NoiseModel, thermal_relaxation_error noise_model = NoiseModel() T1 = 0.001 T2 = 0.002 error = 0.001 thermal_error = thermal_relaxation_error(T1, T2, error) noise_model.add_quantum_error(thermal_error, "MAGIC", [0]) job = execute(qc, backend, shots=200, noise_model=noise_model) # run the job simulation result = job.result() # grab the result counts = result.get_counts(qc) # results for the number of runs print(counts); # print the results of the runs who_wins(counts); # celebrate the winner plot_histogram(counts) # Visualise the results
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="lq") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") t3_st_qcs = transpile(t3_st_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_st_qcs), ")") t3_st_qcs[-1].draw("mpl") # only view trotter gates # 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") shots = 8192 reps = 8 jobs = [] for _ in range(reps): # execute job = execute(t3_st_qcs, backend, shots=shots) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout=initial_layout) print('Job ID', cal_job.job_id()) dt_now = datetime.datetime.now() print(dt_now) with open("jobs_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open("job_ids_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) filename = "job_ids_jakarta_100step_20220412_171248_.pkl" # change here with open(filename, "rb") as f: job_ids_dict = pickle.load(f) job_ids = job_ids_dict["job_ids"] cal_job_id = job_ids_dict["cal_job_id"] retrieved_jobs = [] for job_id in job_ids: retrieved_jobs.append(backend.retrieve_job(job_id)) retrieved_cal_job = backend.retrieve_job(cal_job_id) cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') # set the target state target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: # mit_results = meas_fitter.filter.apply(job.result()) # apply QREM rho = StateTomographyFitter(job.result(), st_qcs).fit(method='lstsq') fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids))) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np import matplotlib.pyplot as plt try: import cplex from cplex.exceptions import CplexError except: print("Warning: Cplex not found.") import math from qiskit.utils import algorithm_globals from qiskit.algorithms.minimum_eigensolvers import SamplingVQE from qiskit.algorithms.optimizers import SPSA from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Sampler # Initialize the problem by defining the parameters n = 3 # number of nodes + depot (n+1) K = 2 # number of vehicles # Get the data class Initializer: def __init__(self, n): self.n = n def generate_instance(self): n = self.n # np.random.seed(33) np.random.seed(1543) xc = (np.random.rand(n) - 0.5) * 10 yc = (np.random.rand(n) - 0.5) * 10 instance = np.zeros([n, n]) for ii in range(0, n): for jj in range(ii + 1, n): instance[ii, jj] = (xc[ii] - xc[jj]) ** 2 + (yc[ii] - yc[jj]) ** 2 instance[jj, ii] = instance[ii, jj] return xc, yc, instance # Initialize the problem by randomly generating the instance initializer = Initializer(n) xc, yc, instance = initializer.generate_instance() class ClassicalOptimizer: def __init__(self, instance, n, K): self.instance = instance self.n = n # number of nodes self.K = K # number of vehicles def compute_allowed_combinations(self): f = math.factorial return f(self.n) / f(self.K) / f(self.n - self.K) def cplex_solution(self): # refactoring instance = self.instance n = self.n K = self.K my_obj = list(instance.reshape(1, n**2)[0]) + [0.0 for x in range(0, n - 1)] my_ub = [1 for x in range(0, n**2 + n - 1)] my_lb = [0 for x in range(0, n**2)] + [0.1 for x in range(0, n - 1)] my_ctype = "".join(["I" for x in range(0, n**2)]) + "".join( ["C" for x in range(0, n - 1)] ) my_rhs = ( 2 * ([K] + [1 for x in range(0, n - 1)]) + [1 - 0.1 for x in range(0, (n - 1) ** 2 - (n - 1))] + [0 for x in range(0, n)] ) my_sense = ( "".join(["E" for x in range(0, 2 * n)]) + "".join(["L" for x in range(0, (n - 1) ** 2 - (n - 1))]) + "".join(["E" for x in range(0, n)]) ) try: my_prob = cplex.Cplex() self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs) my_prob.solve() except CplexError as exc: print(exc) return x = my_prob.solution.get_values() x = np.array(x) cost = my_prob.solution.get_objective_value() return x, cost def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs): n = self.n prob.objective.set_sense(prob.objective.sense.minimize) prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype) prob.set_log_stream(None) prob.set_error_stream(None) prob.set_warning_stream(None) prob.set_results_stream(None) rows = [] for ii in range(0, n): col = [x for x in range(0 + n * ii, n + n * ii)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [x for x in range(0 + ii, n**2, n)] coef = [1 for x in range(0, n)] rows.append([col, coef]) # Sub-tour elimination constraints: for ii in range(0, n): for jj in range(0, n): if (ii != jj) and (ii * jj > 0): col = [ii + (jj * n), n**2 + ii - 1, n**2 + jj - 1] coef = [1, 1, -1] rows.append([col, coef]) for ii in range(0, n): col = [(ii) * (n + 1)] coef = [1] rows.append([col, coef]) prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs) # Instantiate the classical optimizer class classical_optimizer = ClassicalOptimizer(instance, n, K) # Print number of feasible solutions print("Number of feasible solutions = " + str(classical_optimizer.compute_allowed_combinations())) # Solve the problem in a classical fashion via CPLEX x = None z = None try: x, classical_cost = classical_optimizer.cplex_solution() # Put the solution in the z variable z = [x[ii] for ii in range(n**2) if ii // n != ii % n] # Print the solution print(z) except: print("CPLEX may be missing.") # Visualize the solution def visualize_solution(xc, yc, x, C, n, K, title_str): plt.figure() plt.scatter(xc, yc, s=200) for i in range(len(xc)): plt.annotate(i, (xc[i] + 0.15, yc[i]), size=16, color="r") plt.plot(xc[0], yc[0], "r*", ms=20) plt.grid() for ii in range(0, n**2): if x[ii] > 0: ix = ii // n iy = ii % n plt.arrow( xc[ix], yc[ix], xc[iy] - xc[ix], yc[iy] - yc[ix], length_includes_head=True, head_width=0.25, ) plt.title(title_str + " cost = " + str(int(C * 100) / 100.0)) plt.show() if x is not None: visualize_solution(xc, yc, x, classical_cost, n, K, "Classical") from qiskit_optimization import QuadraticProgram from qiskit_optimization.algorithms import MinimumEigenOptimizer class QuantumOptimizer: def __init__(self, instance, n, K): self.instance = instance self.n = n self.K = K def binary_representation(self, x_sol=0): instance = self.instance n = self.n K = self.K A = np.max(instance) * 100 # A parameter of cost function # Determine the weights w instance_vec = instance.reshape(n**2) w_list = [instance_vec[x] for x in range(n**2) if instance_vec[x] > 0] w = np.zeros(n * (n - 1)) for ii in range(len(w_list)): w[ii] = w_list[ii] # Some variables I will use Id_n = np.eye(n) Im_n_1 = np.ones([n - 1, n - 1]) Iv_n_1 = np.ones(n) Iv_n_1[0] = 0 Iv_n = np.ones(n - 1) neg_Iv_n_1 = np.ones(n) - Iv_n_1 v = np.zeros([n, n * (n - 1)]) for ii in range(n): count = ii - 1 for jj in range(n * (n - 1)): if jj // (n - 1) == ii: count = ii if jj // (n - 1) != ii and jj % (n - 1) == count: v[ii][jj] = 1.0 vn = np.sum(v[1:], axis=0) # Q defines the interactions between variables Q = A * (np.kron(Id_n, Im_n_1) + np.dot(v.T, v)) # g defines the contribution from the individual variables g = ( w - 2 * A * (np.kron(Iv_n_1, Iv_n) + vn.T) - 2 * A * K * (np.kron(neg_Iv_n_1, Iv_n) + v[0].T) ) # c is the constant offset c = 2 * A * (n - 1) + 2 * A * (K**2) try: max(x_sol) # Evaluates the cost distance from a binary representation of a path fun = ( lambda x: np.dot(np.around(x), np.dot(Q, np.around(x))) + np.dot(g, np.around(x)) + c ) cost = fun(x_sol) except: cost = 0 return Q, g, c, cost def construct_problem(self, Q, g, c) -> QuadraticProgram: qp = QuadraticProgram() for i in range(n * (n - 1)): qp.binary_var(str(i)) qp.objective.quadratic = Q qp.objective.linear = g qp.objective.constant = c return qp def solve_problem(self, qp): algorithm_globals.random_seed = 10598 vqe = SamplingVQE(sampler=Sampler(), optimizer=SPSA(), ansatz=RealAmplitudes()) optimizer = MinimumEigenOptimizer(min_eigen_solver=vqe) result = optimizer.solve(qp) # compute cost of the obtained result _, _, _, level = self.binary_representation(x_sol=result.x) return result.x, level # Instantiate the quantum optimizer class with parameters: quantum_optimizer = QuantumOptimizer(instance, n, K) # Check if the binary representation is correct try: if z is not None: Q, g, c, binary_cost = quantum_optimizer.binary_representation(x_sol=z) print("Binary cost:", binary_cost, "classical cost:", classical_cost) if np.abs(binary_cost - classical_cost) < 0.01: print("Binary formulation is correct") else: print("Error in the binary formulation") else: print("Could not verify the correctness, due to CPLEX solution being unavailable.") Q, g, c, binary_cost = quantum_optimizer.binary_representation() print("Binary cost:", binary_cost) except NameError as e: print("Warning: Please run the cells above first.") print(e) qp = quantum_optimizer.construct_problem(Q, g, c) quantum_solution, quantum_cost = quantum_optimizer.solve_problem(qp) print(quantum_solution, quantum_cost) # Put the solution in a way that is compatible with the classical variables x_quantum = np.zeros(n**2) kk = 0 for ii in range(n**2): if ii // n != ii % n: x_quantum[ii] = quantum_solution[kk] kk += 1 # visualize the solution visualize_solution(xc, yc, x_quantum, quantum_cost, n, K, "Quantum") # and visualize the classical for comparison if x is not None: visualize_solution(xc, yc, x, classical_cost, n, K, "Classical") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_right(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will start at t=80 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog.draw()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.pulse_v2 import draw, IQXDebugging from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() qc = transpile(qc, FakeBoeblingen(), layout_method='trivial') sched = schedule(qc, FakeBoeblingen()) draw(sched, style=IQXDebugging(), backend=FakeBoeblingen())
https://github.com/tomtuamnuq/compare-qiskit-ocean
tomtuamnuq
import os import shutil import time from docplex.mp.error_handler import DOcplexException 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 = "SPARSE"), ignore_errors=True) os.makedirs(getPath(directory = "SPARSE")) # create sparse random binary quadratic Programs # 3 variables with 2 constraints each max_qubits = 290 var = 3 cstr = 2 multiple = 10 while True: qp_bin = RandomQP.create_random_binary_prog("test_sparse_" + str(multiple), cstr, var, multiple=multiple) try: qp_bin.write_to_lp_file(getPath(qp_bin.name, directory = "SPARSE")) if qp_bin.complexity() > max_qubits : print(multiple) break if qp_bin.complexity() > 100 : multiple = multiple + 6 else: multiple = multiple + 3 except DOcplexException as ex: print(ex) print(qp_bin.complexity()) qp_bin.qubo.to_docplex().prettyprint()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.pulse_v2 import draw, IQXDebugging from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() qc = transpile(qc, FakeBoeblingen(), layout_method='trivial') sched = schedule(qc, FakeBoeblingen()) draw(sched, style=IQXDebugging(), backend=FakeBoeblingen())
https://github.com/alexyev/quantum_options_pricing
alexyev
#!pip install qiskit #!pip install qiskit_finance import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy.interpolate import griddata %matplotlib inline import numpy as np from qiskit import Aer, QuantumRegister, QuantumCircuit, execute, AncillaRegister, transpile from qiskit.utils import QuantumInstance from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import WeightedAdder, LinearAmplitudeFunction from qiskit_finance.circuit.library import LogNormalDistribution # to represent the two different underlyings, we map them to different dimensions # this variable represents the number of uncertainty qubits per dimension num_uncertainty_qubits = 2 # same parameters from European calls and puts spot = 2.0 vol = 0.2 rate = 0.05 T = 100 / 365 # 100 days till options expiry # resulting parameters for log-normal distribution mu = (rate - 0.5 * vol ** 2) * T + np.log(spot) sigma = vol * np.sqrt(T) mean = np.exp(mu + sigma ** 2 / 2) variance = (np.exp(sigma ** 2) - 1) * np.exp(2 * mu + sigma ** 2) stddev = np.sqrt(variance) # lowest and highest spot prices considered low = np.maximum(0, mean - 3 * stddev) high = mean + 3 * stddev # for simplicity in our use case, we'll say that they both have the same prob. dist. dimension = 2 num_qubits = [num_uncertainty_qubits] * dimension low = low * np.ones(dimension) high = high * np.ones(dimension) mu = mu * np.ones(dimension) cov = sigma ** 2 * np.eye(dimension) # constructing the circuit u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=list(zip(low, high))) # plotting the uncertainty model into a PDF x = [v[0] for v in u.values] y = [v[1] for v in u.values] z = u.probabilities resolution = np.array([2 ** n for n in num_qubits]) * 1j grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]] grid_z = griddata((x, y), z, (grid_x, grid_y)) fig = plt.figure(figsize=(10, 8)) ax = fig.gca(projection="3d") ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral) ax.set_xlabel("Spot Price $S_T^1$ (\$)", size=15) ax.set_ylabel("Spot Price $S_T^2$ (\$)", size=15) ax.set_zlabel("Probability (\%)", size=15) plt.show() # to integrate with the quantum adder circuit over the integers, # we need to map our expected spots to integer values, and then # convert them back. Here we calculate the # of qubits needed to do so weights = [] for n in num_qubits: for i in range(n): weights += [2 ** i] # aggregating circuit agg = WeightedAdder(sum(num_qubits), weights) n_s = agg.num_sum_qubits # num of summation qubits from the adder n_aux = agg.num_qubits - n_s - agg.num_state_qubits # num auxilliary qubits strike_price = 3.40 # mapping the strike price from the real #'s to integer values over # qubits max_value = 2 ** n_s - 1 low_ = low[0] high_ = high[0] mapped_strike_price = ( (strike_price - dimension * low_) / (high_ - low_) * (2 ** num_uncertainty_qubits - 1) ) # approximation error c_approx = 0.25 #creating a piecewise linear function that only pays # max(S1 + S2 - K, 0) breakpoints = [0, mapped_strike_price] slopes = [0, 1] offsets = [0, 0] f_min = 0 f_max = 2 * (2 ** num_uncertainty_qubits - 1) - mapped_strike_price basket_objective = LinearAmplitudeFunction( n_s, slopes, offsets, domain=(0, max_value), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define the problem in a formal framework qr_state = QuantumRegister(u.num_qubits, "state") # loads the prob. dist. qr_obj = QuantumRegister(1, "obj") # encodes function values ar_sum = AncillaRegister(n_s, "sum") # # of qubits used to encode the sum ar = AncillaRegister(max(n_aux, basket_objective.num_ancillas), "work") # additional ancilla qubits objective_index = u.num_qubits # qubit in which our answer lies #constructing the circuit basket_option = QuantumCircuit(qr_state, qr_obj, ar_sum, ar) basket_option.append(u, qr_state) basket_option.append(agg, qr_state[:] + ar_sum[:] + ar[:n_aux]) basket_option.append(basket_objective, ar_sum[:] + qr_obj[:] + ar[: basket_objective.num_ancillas]) print(basket_option.draw()) print("objective qubit index", objective_index) # plotting the exact payoff function x = np.linspace(sum(low), sum(high)) y = np.maximum(0, x - strike_price) plt.plot(x, y, "r-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Sum of Spot Prices ($S_T^1 + S_T^2)$", size=15) plt.ylabel("Payoff", size=15) plt.xticks(size=15, rotation=90) plt.yticks(size=15) plt.show() # evaluate exact expected value sum_values = np.sum(u.values, axis=1) exact_value = np.dot( u.probabilities[sum_values >= strike_price], sum_values[sum_values >= strike_price] - strike_price, ) print("exact expected value:\t%.4f" % exact_value) num_state_qubits = basket_option.num_qubits - basket_option.num_ancillas # # of qubits that encodes the state print("state qubits: ", num_state_qubits) transpiled = transpile(basket_option, basis_gates=["u", "cx"]) print("circuit width:", transpiled.width()) print("circuit depth:", transpiled.depth()) # running the circuit job = execute(basket_option, backend=Aer.get_backend("statevector_simulator")) # evaluating the statevector we get from the job value = 0 state = job.result().get_statevector() if not isinstance(state, np.ndarray): state = state.data for i, a in enumerate(state): b = ("{0:0%sb}" % num_state_qubits).format(i)[-num_state_qubits:] prob = np.abs(a) ** 2 if prob > 1e-4 and b[0] == "1": value += prob # undoing the earlier integer mapping mapped_value = ( basket_objective.post_processing(value) / (2 ** num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % mapped_value) print("Exact Expected Payoff: %.4f" % exact_value) # using amplitude estimation to recover the payoff # set target precision and confidence level epsilon = 0.01 alpha = 0.05 qi = QuantumInstance(Aer.get_backend("aer_simulator"), shots=100) problem = EstimationProblem( state_preparation=basket_option, objective_qubits=[objective_index], post_processing=basket_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation(epsilon, alpha=alpha, quantum_instance=qi) result = ae.estimate(problem) # check our confidence interval conf_int = ( np.array(result.confidence_interval_processed) / (2 ** num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact value: \t%.4f" % exact_value) print( "Estimated value: \t%.4f" % (result.estimation_processed / (2 ** num_uncertainty_qubits - 1) * (high_ - low_)) ) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
https://github.com/drobiu/quantum-project
drobiu
"""Example usage of the Quantum Inspire backend with the Qiskit SDK. A simple example that demonstrates how to use the SDK to create a circuit to demonstrate conditional gate execution. For documentation on how to use Qiskit we refer to [https://qiskit.org/](https://qiskit.org/). Specific to Quantum Inspire is the creation of the QI instance, which is used to set the authentication of the user and provides a Quantum Inspire backend that is used to execute the circuit. Copyright 2018-19 QuTech Delft. Licensed under the Apache License, Version 2.0. """ import os from qiskit import BasicAer, execute from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit from quantuminspire.credentials import get_authentication from quantuminspire.qiskit import QI QI_URL = os.getenv('API_URL', 'https://api.quantum-inspire.com/') authentication = get_authentication() QI.set_authentication(authentication, QI_URL) qi_backend = QI.get_backend('QX single-node simulator') q = QuantumRegister(3, "q") c0 = ClassicalRegister(1, "c0") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(1, "c2") qc = QuantumCircuit(q, c0, c1, c2, name="conditional") qc.h(q[0]) qc.h(q[1]).c_if(c0, 0) # h-gate on q[1] is executed qc.h(q[2]).c_if(c1, 1) # h-gate on q[2] is not executed qc.measure(q[0], c0) qc.measure(q[1], c1) qc.measure(q[2], c2) qi_job = execute(qc, backend=qi_backend, shots=1024) qi_result = qi_job.result() histogram = qi_result.get_counts(qc) print("\nResult from the remote Quantum Inspire backend:\n") print('State\tCounts') [print('{0}\t{1}'.format(state, counts)) for state, counts in histogram.items()] print("\nResult from the local Qiskit simulator backend:\n") backend = BasicAer.get_backend("qasm_simulator") job = execute(qc, backend=backend, shots=1024) result = job.result() print(result.get_counts(qc))
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. """UnitaryGate tests""" import json import numpy from numpy.testing import assert_allclose import qiskit from qiskit.extensions.unitary import UnitaryGate from qiskit.test import QiskitTestCase from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.transpiler import PassManager from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit.quantum_info.random import random_unitary from qiskit.quantum_info.operators import Operator from qiskit.transpiler.passes import CXCancellation class TestUnitaryGate(QiskitTestCase): """Tests for the Unitary class.""" def test_set_matrix(self): """Test instantiation""" try: UnitaryGate([[0, 1], [1, 0]]) # pylint: disable=broad-except except Exception as err: self.fail(f"unexpected exception in init of Unitary: {err}") def test_set_matrix_raises(self): """test non-unitary""" try: UnitaryGate([[1, 1], [1, 0]]) # pylint: disable=broad-except except Exception: pass else: self.fail("setting Unitary with non-unitary did not raise") def test_set_init_with_unitary(self): """test instantiation of new unitary with another one (copy)""" uni1 = UnitaryGate([[0, 1], [1, 0]]) uni2 = UnitaryGate(uni1) self.assertEqual(uni1, uni2) self.assertFalse(uni1 is uni2) def test_conjugate(self): """test conjugate""" ymat = numpy.array([[0, -1j], [1j, 0]]) uni = UnitaryGate([[0, 1j], [-1j, 0]]) self.assertTrue(numpy.array_equal(uni.conjugate().to_matrix(), ymat)) def test_adjoint(self): """test adjoint operation""" uni = UnitaryGate([[0, 1j], [-1j, 0]]) self.assertTrue(numpy.array_equal(uni.adjoint().to_matrix(), uni.to_matrix())) class TestUnitaryCircuit(QiskitTestCase): """Matrix gate circuit tests.""" def test_1q_unitary(self): """test 1 qubit unitary matrix""" qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) matrix = numpy.array([[1, 0], [0, 1]]) qc.x(qr[0]) qc.append(UnitaryGate(matrix), [qr[0]]) # test of qasm output self.log.info(qc.qasm()) # test of text drawer self.log.info(qc) dag = circuit_to_dag(qc) dag_nodes = dag.named_nodes("unitary") self.assertTrue(len(dag_nodes) == 1) dnode = dag_nodes[0] self.assertIsInstance(dnode.op, UnitaryGate) self.assertEqual(dnode.qargs, (qr[0],)) assert_allclose(dnode.op.to_matrix(), matrix) def test_2q_unitary(self): """test 2 qubit unitary matrix""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) sigmax = numpy.array([[0, 1], [1, 0]]) sigmay = numpy.array([[0, -1j], [1j, 0]]) matrix = numpy.kron(sigmax, sigmay) qc.x(qr[0]) uni2q = UnitaryGate(matrix) qc.append(uni2q, [qr[0], qr[1]]) passman = PassManager() passman.append(CXCancellation()) qc2 = passman.run(qc) # test of qasm output self.log.info(qc2.qasm()) # test of text drawer self.log.info(qc2) dag = circuit_to_dag(qc) nodes = dag.two_qubit_ops() self.assertEqual(len(nodes), 1) dnode = nodes[0] self.assertIsInstance(dnode.op, UnitaryGate) self.assertEqual(dnode.qargs, (qr[0], qr[1])) assert_allclose(dnode.op.to_matrix(), matrix) qc3 = dag_to_circuit(dag) self.assertEqual(qc2, qc3) def test_3q_unitary(self): """test 3 qubit unitary matrix on non-consecutive bits""" qr = QuantumRegister(4) qc = QuantumCircuit(qr) sigmax = numpy.array([[0, 1], [1, 0]]) sigmay = numpy.array([[0, -1j], [1j, 0]]) matrix = numpy.kron(sigmay, numpy.kron(sigmax, sigmay)) qc.x(qr[0]) uni3q = UnitaryGate(matrix) qc.append(uni3q, [qr[0], qr[1], qr[3]]) qc.cx(qr[3], qr[2]) # test of text drawer self.log.info(qc) dag = circuit_to_dag(qc) nodes = dag.multi_qubit_ops() self.assertEqual(len(nodes), 1) dnode = nodes[0] self.assertIsInstance(dnode.op, UnitaryGate) self.assertEqual(dnode.qargs, (qr[0], qr[1], qr[3])) assert_allclose(dnode.op.to_matrix(), matrix) def test_1q_unitary_int_qargs(self): """test single qubit unitary matrix with 'int' and 'list of ints' qubits argument""" sigmax = numpy.array([[0, 1], [1, 0]]) sigmaz = numpy.array([[1, 0], [0, -1]]) # new syntax qr = QuantumRegister(2) qc = QuantumCircuit(qr) qc.unitary(sigmax, 0) qc.unitary(sigmax, qr[1]) qc.unitary(sigmaz, [0, 1]) # expected circuit qc_target = QuantumCircuit(qr) qc_target.append(UnitaryGate(sigmax), [0]) qc_target.append(UnitaryGate(sigmax), [qr[1]]) qc_target.append(UnitaryGate(sigmaz), [[0, 1]]) self.assertEqual(qc, qc_target) def test_qobj_with_unitary_matrix(self): """test qobj output with unitary matrix""" qr = QuantumRegister(4) qc = QuantumCircuit(qr) sigmax = numpy.array([[0, 1], [1, 0]]) sigmay = numpy.array([[0, -1j], [1j, 0]]) matrix = numpy.kron(sigmay, numpy.kron(sigmax, sigmay)) qc.rx(numpy.pi / 4, qr[0]) uni = UnitaryGate(matrix) qc.append(uni, [qr[0], qr[1], qr[3]]) qc.cx(qr[3], qr[2]) qobj = qiskit.compiler.assemble(qc) instr = qobj.experiments[0].instructions[1] self.assertEqual(instr.name, "unitary") assert_allclose(numpy.array(instr.params[0]).astype(numpy.complex64), matrix) # check conversion to dict qobj_dict = qobj.to_dict() class NumpyEncoder(json.JSONEncoder): """Class for encoding json str with complex and numpy arrays.""" def default(self, obj): if isinstance(obj, numpy.ndarray): return obj.tolist() if isinstance(obj, complex): return (obj.real, obj.imag) return json.JSONEncoder.default(self, obj) # check json serialization self.assertTrue(isinstance(json.dumps(qobj_dict, cls=NumpyEncoder), str)) def test_labeled_unitary(self): """test qobj output with unitary matrix""" qr = QuantumRegister(4) qc = QuantumCircuit(qr) sigmax = numpy.array([[0, 1], [1, 0]]) sigmay = numpy.array([[0, -1j], [1j, 0]]) matrix = numpy.kron(sigmax, sigmay) uni = UnitaryGate(matrix, label="xy") qc.append(uni, [qr[0], qr[1]]) qobj = qiskit.compiler.assemble(qc) instr = qobj.experiments[0].instructions[0] self.assertEqual(instr.name, "unitary") self.assertEqual(instr.label, "xy") def test_qasm_unitary_only_one_def(self): """test that a custom unitary can be converted to qasm and the definition is only written once""" qr = QuantumRegister(2, "q0") cr = ClassicalRegister(1, "c0") qc = QuantumCircuit(qr, cr) matrix = numpy.array([[1, 0], [0, 1]]) unitary_gate = UnitaryGate(matrix) qc.x(qr[0]) qc.append(unitary_gate, [qr[0]]) qc.append(unitary_gate, [qr[1]]) expected_qasm = ( "OPENQASM 2.0;\n" 'include "qelib1.inc";\n' "gate unitary q0 { u(0,0,0) q0; }\n" "qreg q0[2];\ncreg c0[1];\n" "x q0[0];\n" "unitary q0[0];\n" "unitary q0[1];\n" ) self.assertEqual(expected_qasm, qc.qasm()) def test_qasm_unitary_twice(self): """test that a custom unitary can be converted to qasm and that if the qasm is called twice it is the same every time""" qr = QuantumRegister(2, "q0") cr = ClassicalRegister(1, "c0") qc = QuantumCircuit(qr, cr) matrix = numpy.array([[1, 0], [0, 1]]) unitary_gate = UnitaryGate(matrix) qc.x(qr[0]) qc.append(unitary_gate, [qr[0]]) qc.append(unitary_gate, [qr[1]]) expected_qasm = ( "OPENQASM 2.0;\n" 'include "qelib1.inc";\n' "gate unitary q0 { u(0,0,0) q0; }\n" "qreg q0[2];\ncreg c0[1];\n" "x q0[0];\n" "unitary q0[0];\n" "unitary q0[1];\n" ) self.assertEqual(expected_qasm, qc.qasm()) self.assertEqual(expected_qasm, qc.qasm()) def test_qasm_2q_unitary(self): """test that a 2 qubit custom unitary can be converted to qasm""" qr = QuantumRegister(2, "q0") cr = ClassicalRegister(1, "c0") qc = QuantumCircuit(qr, cr) matrix = numpy.asarray([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]]) unitary_gate = UnitaryGate(matrix) qc.x(qr[0]) qc.append(unitary_gate, [qr[0], qr[1]]) qc.append(unitary_gate, [qr[1], qr[0]]) expected_qasm = ( "OPENQASM 2.0;\n" 'include "qelib1.inc";\n' "gate unitary q0,q1 { u(pi,-pi/2,pi/2) q0; u(pi,pi/2,-pi/2) q1; }\n" "qreg q0[2];\n" "creg c0[1];\n" "x q0[0];\n" "unitary q0[0],q0[1];\n" "unitary q0[1],q0[0];\n" ) self.assertEqual(expected_qasm, qc.qasm()) def test_qasm_unitary_noop(self): """Test that an identity unitary can be converted to OpenQASM 2""" qc = QuantumCircuit(QuantumRegister(3, "q0")) qc.unitary(numpy.eye(8), qc.qubits) expected_qasm = ( "OPENQASM 2.0;\n" 'include "qelib1.inc";\n' "gate unitary q0,q1,q2 { }\n" "qreg q0[3];\n" "unitary q0[0],q0[1],q0[2];\n" ) self.assertEqual(expected_qasm, qc.qasm()) def test_unitary_decomposition(self): """Test decomposition for unitary gates over 2 qubits.""" qc = QuantumCircuit(3) qc.unitary(random_unitary(8, seed=42), [0, 1, 2]) self.assertTrue(Operator(qc).equiv(Operator(qc.decompose()))) def test_unitary_decomposition_via_definition(self): """Test decomposition for 1Q unitary via definition.""" mat = numpy.array([[0, 1], [1, 0]]) self.assertTrue(numpy.allclose(Operator(UnitaryGate(mat).definition).data, mat)) def test_unitary_decomposition_via_definition_2q(self): """Test decomposition for 2Q unitary via definition.""" mat = numpy.array([[0, 0, 1, 0], [0, 0, 0, -1], [1, 0, 0, 0], [0, -1, 0, 0]]) self.assertTrue(numpy.allclose(Operator(UnitaryGate(mat).definition).data, mat)) def test_unitary_control(self): """Test parameters of controlled - unitary.""" mat = numpy.array([[0, 1], [1, 0]]) gate = UnitaryGate(mat).control() self.assertTrue(numpy.allclose(gate.params, mat)) self.assertTrue(numpy.allclose(gate.base_gate.params, mat))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit.visualization import plot_circuit_layout from qiskit.providers.fake_provider import FakeVigo backend = FakeVigo() ghz = QuantumCircuit(3, 3) ghz.h(0) ghz.cx(0,range(1,3)) ghz.barrier() ghz.measure(range(3), range(3)) # Virtual -> physical # 0 -> 3 # 1 -> 4 # 2 -> 2 my_ghz = transpile(ghz, backend, initial_layout=[3, 4, 2]) plot_circuit_layout(my_ghz, backend)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=no-member,invalid-name,missing-docstring,no-name-in-module # pylint: disable=attribute-defined-outside-init,unsubscriptable-object import os from qiskit import QuantumCircuit from qiskit.compiler import transpile from qiskit.test.mock import FakeToronto class TranspilerQualitativeBench: params = ([0, 1, 2, 3], ["stochastic", "sabre"], ["dense", "noise_adaptive", "sabre"]) param_names = ["optimization level", "routing method", "layout method"] timeout = 600 # pylint: disable=unused-argument def setup(self, optimization_level, routing_method, layout_method): self.backend = FakeToronto() self.qasm_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "qasm")) self.depth_4gt10_v1_81 = QuantumCircuit.from_qasm_file( os.path.join(self.qasm_path, "depth_4gt10-v1_81.qasm") ) self.depth_4mod5_v0_19 = QuantumCircuit.from_qasm_file( os.path.join(self.qasm_path, "depth_4mod5-v0_19.qasm") ) self.depth_mod8_10_178 = QuantumCircuit.from_qasm_file( os.path.join(self.qasm_path, "depth_mod8-10_178.qasm") ) self.time_cnt3_5_179 = QuantumCircuit.from_qasm_file( os.path.join(self.qasm_path, "time_cnt3-5_179.qasm") ) self.time_cnt3_5_180 = QuantumCircuit.from_qasm_file( os.path.join(self.qasm_path, "time_cnt3-5_180.qasm") ) self.time_qft_16 = QuantumCircuit.from_qasm_file( os.path.join(self.qasm_path, "time_qft_16.qasm") ) def track_depth_transpile_4gt10_v1_81(self, optimization_level, routing_method, layout_method): return transpile( self.depth_4gt10_v1_81, self.backend, routing_method=routing_method, layout_method=layout_method, optimization_level=optimization_level, seed_transpiler=0, ).depth() def track_depth_transpile_4mod5_v0_19(self, optimization_level, routing_method, layout_method): return transpile( self.depth_4mod5_v0_19, self.backend, routing_method=routing_method, layout_method=layout_method, optimization_level=optimization_level, seed_transpiler=0, ).depth() def track_depth_transpile_mod8_10_178(self, optimization_level, routing_method, layout_method): return transpile( self.depth_mod8_10_178, self.backend, routing_method=routing_method, layout_method=layout_method, optimization_level=optimization_level, seed_transpiler=0, ).depth() def time_transpile_time_cnt3_5_179(self, optimization_level, routing_method, layout_method): transpile( self.time_cnt3_5_179, self.backend, routing_method=routing_method, layout_method=layout_method, optimization_level=optimization_level, seed_transpiler=0, ) def time_transpile_time_cnt3_5_180(self, optimization_level, routing_method, layout_method): transpile( self.time_cnt3_5_180, self.backend, routing_method=routing_method, layout_method=layout_method, optimization_level=optimization_level, seed_transpiler=0, ) def time_transpile_time_qft_16(self, optimization_level, routing_method, layout_method): transpile( self.time_qft_16, self.backend, routing_method=routing_method, layout_method=layout_method, optimization_level=optimization_level, seed_transpiler=0, )
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.quantum_info import SparsePauliOp H2_op = SparsePauliOp.from_list( [ ("II", -1.052373245772859), ("IZ", 0.39793742484318045), ("ZI", -0.39793742484318045), ("ZZ", -0.01128010425623538), ("XX", 0.18093119978423156), ] ) from qiskit.circuit.library import TwoLocal from qiskit.algorithms.optimizers import SLSQP ansatz = TwoLocal(3, rotation_blocks=["ry", "rz"], entanglement_blocks="cz", reps=1) optimizer = SLSQP() ansatz.decompose().draw('mpl') from qiskit.primitives import Sampler, Estimator from qiskit.algorithms.state_fidelities import ComputeUncompute estimator = Estimator() sampler = Sampler() fidelity = ComputeUncompute(sampler) k = 3 betas = [33, 33, 33] counts = [] values = [] steps = [] def callback(eval_count, params, value, meta, step): counts.append(eval_count) values.append(value) steps.append(step) from qiskit.algorithms.eigensolvers import VQD vqd = VQD(estimator, fidelity, ansatz, optimizer, k=k, betas=betas, callback=callback) result = vqd.compute_eigenvalues(operator = H2_op) vqd_values = result.optimal_values print(vqd_values) import numpy as np import pylab pylab.rcParams["figure.figsize"] = (12, 8) steps = np.asarray(steps) counts = np.asarray(counts) values = np.asarray(values) for i in range(1,4): _counts = counts[np.where(steps == i)] _values = values[np.where(steps == i)] pylab.plot(_counts, _values, label=f"State {i-1}") pylab.xlabel("Eval count") pylab.ylabel("Energy") pylab.title("Energy convergence for each computed state") pylab.legend(loc="upper right"); from qiskit.algorithms.eigensolvers import NumPyEigensolver from qiskit.opflow import PauliSumOp exact_solver = NumPyEigensolver(k=3) exact_result = exact_solver.compute_eigenvalues(PauliSumOp(H2_op)) ref_values = exact_result.eigenvalues print(f"Reference values: {ref_values}") print(f"VQD values: {vqd_values}") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/contepablod/QCNNCancerBinaryClassifier
contepablod
from IPython.display import Image Image('https://raw.githubusercontent.com/contepablod/QCNNCancerClassifier/master/Esophagus%20Cancer.JPG') import os # módulo para manejar carpetas y archivos en nuestro ordenador import random # módulo para aleatorizar import numpy as np # biblioteca para manejar matrices y operaciones de matrices import pandas as pd # biblioteca para manejar tablas de datos #Skimage (Scikit-image): biblioteca para procesamiento de imágenes from skimage import io #Modulo para leer una imagen (librería para procesamiento de imagenes) #Sklearn (Scikit-learn): biblioteca para machine learning from sklearn.model_selection import train_test_split from sklearn.linear_model import Perceptron from sklearn.metrics import accuracy_score #Bibliotecas para gráficar y visualizar import matplotlib.pyplot as plt import seaborn as sns #Matriz de confusión def matrix_confusion(yt, yp): data = {'Y_Real': yt, 'Y_Prediccion': yp} df = pd.DataFrame(data, columns=['Y_Real','Y_Prediccion']) confusion_matrix = pd.crosstab(df['Y_Real'], df['Y_Prediccion'], rownames=['Real'], colnames=['Predicted']) sns.heatmap(confusion_matrix, annot=True, fmt='g') plt.show() #Leemos los datos datos = pd.read_csv("https://raw.githubusercontent.com/AnIsAsPe/ClassificadorCancerEsofago/master/Datos/ClasesImagenes.csv", usecols=[1,2]) datos.info() #muestra los primeros cinco registros #¿cuántas imagenes tenemos de cada clase? datos['class_number'].value_counts(sort=False) Y = datos['class_number'] #Guardamos las etiquetas de las imagenes como serie de pandas datos['image_filename'] path = "C:\\Users\\conte\\OneDrive\\Escritorio\\Colegio Bourbaki\\ML-AI-WA\\Perceptron\\CarpetaImagenes\\" %time img = datos['image_filename'].apply(lambda x: io.imread(path + x, as_gray=True)) img.shape img[0].shape IMG = np.stack(img, axis=0) # Toma una secuencia de matrices y las apila a lo largo # de un tercer eje para hacer una solo arreglo IMG.shape X = IMG.reshape(5063, -1) # se puede poner 67600 en vez de -1 X.shape #El método GroupBy de Pandas separa un data frame en varios data frames porClase = datos.groupby('class_number') #elije al azar n muestras de cada subconjunto y guarda la posición de las figuras elegidas en una lista n = 20 c = random.sample(porClase.get_group(1).index.tolist(), n) # indices de las imagenes cancerígenas seleccionadas s = random.sample(porClase.get_group(0).index.tolist(), n) # indices de las imagenes sanas seleccionadas # Grafica 20 imágenes aleatorias de tejido con cáncer y 20 de tejido sano fig = plt.figure(figsize=(16, 8)) columns = 10 rows = 4 for i in range(0, columns * rows): fig.add_subplot(rows, columns, i+1) if i < 20: plt.imshow(img[c[i]], cmap='Greys_r') plt.title('cancer') plt.xticks([]) plt.yticks([]) else: plt.imshow(img[s[i-20]], cmap='Greys_r') plt.title('tejido sano') plt.xticks([]) plt.yticks([]) plt.show() X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.3, shuffle=True, random_state=0) #random_state es el valor semilla # ¿Cómo son los conjuntos de entrenamiento y prueba? print("Training set") print("X: ", X_train.shape) print("Y: ", y_train.shape) unique, counts = np.unique(y_train, return_counts=True) print('Tejido Sano: ', counts[0],'\nDisplasia o Cáncer: ', counts[1],'\n') print("Test set") print("X: ", X_test.shape) print("Y: ", y_test.shape) unique, counts = np.unique(y_test, return_counts=True) print('Tejido Sano: ', counts[0],'\nDisplasia o Cáncer: ', counts[1],'\n') model_p = Perceptron(max_iter=50, random_state=0, verbose=True) model_p.fit(X_train,y_train) y_pred = model_p.predict(X_test) #pasa cada una de las imágenes de X_test por el modelo print("Accuracy: %.2f%%" % (accuracy_score(y_test, y_pred)*100)) print("Precisión conjunto entrenamiento: %.2f%%" % (model_p.score(X_train, y_train)*100.0)) print("Precisión conjunto prueba: %.2f%%" % (model_p.score(X_test, y_test)*100.0)) matrix_confusion(y_test, y_pred) model_mp = Perceptron(max_iter=1000, random_state=0, verbose=False, alpha=0.0001) model_mp.fit(X_train,y_train) print("Precisión conjunto entrenamiento: %.2f%%" % (model_mp.score(X_train, y_train)*100.0)) print("Precisión conjunto prueba: %.2f%%" % (model_mp.score(X_test, y_test)*100.0)) y_pred = model_mp.predict(X_test) #pasa cada una de las imágenes de X_test por el modelo print("Accuracy: %.2f%%" % (accuracy_score(y_test, y_pred)*100)) matrix_confusion(y_test, y_pred) model_mp1 = Perceptron(max_iter=1000, random_state=0, verbose=False, alpha=0.000001, penalty='l2') # Mas margen y con penalidad model_mp1.fit(X_train,y_train) print("Precisión conjunto entrenamiento: %.2f%%" % (model_mp1.score(X_train, y_train)*100.0)) print("Precisión conjunto prueba: %.2f%%" % (model_mp1.score(X_test, y_test)*100.0)) y_pred = model_mp1.predict(X_test) #pasa cada una de las imágenes de X_test por el modelo print("Accuracy: %.2f%%" % (accuracy_score(y_test, y_pred)*100)) matrix_confusion(y_test, y_pred) # Pytorch import torch, torchvision, torch.utils from torch import Tensor from torch import cat from torch.autograd.grad_mode import no_grad from torch.utils.data import DataLoader from torchvision import datasets, transforms import torch.optim as optim from torch.nn import ( Module, Conv2d, Linear, Dropout2d, NLLLoss, BCELoss, CrossEntropyLoss, MSELoss, MaxPool2d, Flatten, Sequential, ReLU, ) import torch.nn.functional as F from torchviz import make_dot from torchsummary import summary # Qiskit from qiskit import Aer, QuantumCircuit from qiskit.utils import QuantumInstance from qiskit.opflow import AerPauliExpectation from qiskit.circuit import Parameter from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap from qiskit.quantum_info import DensityMatrix, entanglement_of_formation from qiskit.quantum_info import DensityMatrix from qiskit.visualization import plot_state_city from qiskit_machine_learning.neural_networks import TwoLayerQNN from qiskit_machine_learning.connectors import TorchConnector train_data = torchvision.datasets.ImageFolder('C:\\Users\\conte\\OneDrive\\Escritorio\\Colegio Bourbaki\\ML-AI-WA\\Perceptron\\Imagenes_Clasificadas_Random_Split\\Train', transform=transforms.Compose([transforms.ToTensor()])) test_data = torchvision.datasets.ImageFolder('C:\\Users\\conte\\OneDrive\\Escritorio\\Colegio Bourbaki\\ML-AI-WA\\Perceptron\\Imagenes_Clasificadas_Random_Split\\Test', transform=transforms.Compose([transforms.ToTensor()])) train_data[0][0].shape train_loader = DataLoader(train_data, shuffle=True, batch_size=1) test_loader = DataLoader(test_data, shuffle=True, batch_size=1) # False significa que no hay cancer (0) y True que sí (1) print((train_loader.dataset.class_to_idx)) n_samples_show = 6 data_iter = iter(train_loader) fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 10)) while n_samples_show > 0: images, targets = data_iter.__next__() axes[n_samples_show - 1].imshow(images[0, 0].numpy().squeeze(), cmap=plt.cm.rainbow) axes[n_samples_show - 1].set_xticks([]) axes[n_samples_show - 1].set_yticks([]) axes[n_samples_show - 1].set_title(f"Labeled: {targets[0].item()}") n_samples_show -= 1 Image(url='https://raw.githubusercontent.com/contepablod/QCNNCancerClassifier/master/hybridnetwork.png') # Declaramos Instancia Cuantica qi = QuantumInstance(Aer.get_backend("aer_simulator_statevector")) Image(url='https://raw.githubusercontent.com/contepablod/QCNNCancerClassifier/master/neuralnetworkQC.png') # Definimos y creamos la red neuronal cuántica def create_qnn(): feature_map = ZZFeatureMap(2) ansatz = RealAmplitudes(2, reps=1) # input_gradients=True para gradiente híbrido qnn = TwoLayerQNN( 2, #numero de Qubits, solo son posibles dos estados feature_map, ansatz, input_gradients=True, exp_val=AerPauliExpectation(), quantum_instance=qi, ) return qnn qnn = create_qnn() qnn.circuit.draw(output='mpl') qnn.feature_map.decompose().draw(output='mpl') qnn.ansatz.decompose().draw(output='mpl') qnn.circuit.parameters params = np.random.uniform(-1, 1, len(qnn.circuit.parameters)) params rho_01 = DensityMatrix.from_instruction(qnn.circuit.bind_parameters(params)) plot_state_city(rho_01.data, title='Density Matrix') gamma_p = rho_01.purity() display(rho_01.draw('latex', prefix='\\rho_p = ')) print("State purity: ", np.round(np.real(gamma_p))) print(f'{entanglement_of_formation(rho_01):.4f}') # Red Neuronal en Pytorch class Net(Module): def __init__(self, qnn): super().__init__() self.conv1 = Conv2d(3, 128, kernel_size=5) self.conv2 = Conv2d(128, 128, kernel_size=3) self.dropout = Dropout2d() self.fc1 = Linear(508032, 128) self.fc2 = Linear(128, 2) # Input bidimensional para la red neuronal cuántica self.qnn = TorchConnector(qnn) # Aplicamos el conector Pytorch para conectar la red neuronal y el circuito self.fc3 = Linear(1, 1) # Salida unidimensional del circuito cuántico def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) x = x.view(x.shape[0], -1) x = F.relu(self.fc1(x)) x = self.fc2(x) x = self.qnn(x) # Aplicamos la red cuántica nuevamente en la sección forward x = self.fc3(x) return cat((x, 1 - x), -1) model = Net(qnn) model = model.to('cuda') print(model) summary(model, (3, 260, 260), batch_size=-1, device='cuda') # dummy_tensor = next(iter(train_loader))[0].to('cuda') # make_dot(model(dummy_tensor), params=dict(list(model.named_parameters())), show_saved=True, show_attrs=True).render("rnn_torchviz", format="png") #Image('https://raw.githubusercontent.com/contepablod/QCNNCancerClassifier/master/rnn_torchviz.png') Image(r'C:\Users\conte\OneDrive\Escritorio\qiskit-fall-fest-peru-2022-main\qiskit-community-tutorials-master\qiskit-community-tutorials-master\drafts\rnn_torchviz.png', width=2000, height=2250) # Definimos optimizador y función de pérdida optimizer = optim.Adam(model.parameters(), lr=0.00001) loss_func = CrossEntropyLoss().to('cuda') # Empezamos entrenamiento epochs = 50 # Número de épocas model.train() # Modelo en modo entrenamiento loss_list = [] total_accuracy = [] for epoch in range(epochs): correct = 0 total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad(set_to_none=True) # Se inicializa gradiente output = model(data.to('cuda')) # Forward pass, Datos a GPU loss = loss_func(output, target.to('cuda')) #Etiquetas a GPU loss.backward() # Backward pass optimizer.step() # Optimizamos pesos total_loss.append(loss.item()) # Cálculo de la función de pérdida train_pred = output.argmax(dim=1, keepdim=True) correct += train_pred.eq(target.to('cuda').view_as(train_pred)).sum().item() loss_list.append(sum(total_loss) / len(total_loss)) accuracy = 100 * correct / len(train_loader) #Cálculo de precisión total_accuracy.append(accuracy) print(f"Training [{100.0 * (epoch + 1) / epochs:.0f}%]\tLoss: {loss_list[-1]:.4f}\tAccuracy: {accuracy:.2f}%") # Grafico de Convergencia de la función de pérdida y precisión fig, ax1 = plt.subplots() ax1.plot(loss_list, 'g-') ax2 = ax1.twinx() ax2.plot(total_accuracy, 'b') plt.title("Hybrid NN Training Convergence", color='red') ax1.set_xlabel("Training Iterations") ax1.set_ylabel("Cross Entropy Loss", color='g') ax2.set_ylabel("Accuracy (%)", color='b') plt.show() torch.save(model.state_dict(), "model.pt") qnn1 = create_qnn() model1 = Net(qnn1) model1.load_state_dict(torch.load("model.pt")) model1= model1.to('cuda') batch_size=1 model1.eval() # Evaluación del Modelo pred_targets = [] test_targets= [] with no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model1(data.to('cuda')) if len(output.shape) == 1: output = output.reshape(1, *output.shape) pred = output.argmax(dim=1, keepdim=True) pred_targets.append(pred.item()) test_targets.append(target.item()) correct += pred.eq(target.to('cuda').view_as(pred)).sum().item() loss = loss_func(output, target.to('cuda')) total_loss.append(loss.item()) print( "Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.2f}%".format( sum(total_loss) / len(total_loss), correct / len(test_loader) / batch_size * 100 ) ) # Ploteo de Imagenes Predichas from PIL import Image n_samples_show = 6 count = 0 fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) model1.eval() with no_grad(): for batch_idx, (data, target) in enumerate(test_loader): if count == n_samples_show: break output = model1(data.to('cuda')[0:1]) if len(output.shape) == 1: output = output.reshape(3, *output.shape) pred = output.argmax(dim=1, keepdim=True) axes[count].imshow(torchvision.transforms.ToPILImage(mode='RGB')(data[0].squeeze()), cmap=plt.cm.rainbow) axes[count].set_xticks([]) axes[count].set_yticks([]) axes[count].set_title("Predicted {}".format(pred.item())) count += 1 matrix_confusion(test_targets, pred_targets)
https://github.com/ashishpatel26/IBM-Quantum-Challenge-Fall-2021
ashishpatel26
from qiskit_nature.drivers import Molecule from qiskit_nature.drivers.second_quantization import ElectronicStructureDriverType, ElectronicStructureMoleculeDriver # PSPCz molecule geometry = [['C', [ -0.2316640, 1.1348450, 0.6956120]], ['C', [ -0.8886300, 0.3253780, -0.2344140]], ['C', [ -0.1842470, -0.1935670, -1.3239330]], ['C', [ 1.1662930, 0.0801450, -1.4737160]], ['C', [ 1.8089230, 0.8832220, -0.5383540]], ['C', [ 1.1155860, 1.4218050, 0.5392780]], ['S', [ 3.5450920, 1.2449890, -0.7349240]], ['O', [ 3.8606900, 1.0881590, -2.1541690]], ['C', [ 4.3889120, -0.0620730, 0.1436780]], ['O', [ 3.8088290, 2.4916780, -0.0174650]], ['C', [ 4.6830900, 0.1064460, 1.4918230]], ['C', [ 5.3364470, -0.9144080, 2.1705280]], ['C', [ 5.6895490, -2.0818670, 1.5007820]], ['C', [ 5.4000540, -2.2323130, 0.1481350]], ['C', [ 4.7467230, -1.2180160, -0.5404770]], ['N', [ -2.2589180, 0.0399120, -0.0793330]], ['C', [ -2.8394600, -1.2343990, -0.1494160]], ['C', [ -4.2635450, -1.0769890, 0.0660760]], ['C', [ -4.5212550, 0.2638010, 0.2662190]], ['C', [ -3.2669630, 0.9823890, 0.1722720]], ['C', [ -2.2678900, -2.4598950, -0.3287380]], ['C', [ -3.1299420, -3.6058560, -0.3236210]], ['C', [ -4.5179520, -3.4797390, -0.1395160]], ['C', [ -5.1056310, -2.2512990, 0.0536940]], ['C', [ -5.7352450, 1.0074800, 0.5140960]], ['C', [ -5.6563790, 2.3761270, 0.6274610]], ['C', [ -4.4287740, 3.0501460, 0.5083650]], ['C', [ -3.2040560, 2.3409470, 0.2746950]], ['H', [ -0.7813570, 1.5286610, 1.5426490]], ['H', [ -0.7079140, -0.7911480, -2.0611600]], ['H', [ 1.7161320, -0.2933710, -2.3302930]], ['H', [ 1.6308220, 2.0660550, 1.2427990]], ['H', [ 4.4214900, 1.0345500, 1.9875450]], ['H', [ 5.5773000, -0.7951290, 3.2218590]], ['H', [ 6.2017810, -2.8762260, 2.0345740]], ['H', [ 5.6906680, -3.1381740, -0.3739110]], ['H', [ 4.5337010, -1.3031330, -1.6001680]], ['H', [ -1.1998460, -2.5827750, -0.4596910]], ['H', [ -2.6937370, -4.5881470, -0.4657540]], ['H', [ -5.1332290, -4.3740010, -0.1501080]], ['H', [ -6.1752900, -2.1516170, 0.1987120]], ['H', [ -6.6812260, 0.4853900, 0.6017680]], ['H', [ -6.5574610, 2.9529350, 0.8109620]], ['H', [ -4.3980410, 4.1305040, 0.5929440]], ['H', [ -2.2726630, 2.8838620, 0.1712760]]] molecule = Molecule(geometry=geometry, charge=0, multiplicity=1) driver = ElectronicStructureMoleculeDriver(molecule=molecule, basis='631g*', driver_type=ElectronicStructureDriverType.PYSCF) C_counter = 0 H_counter = 0 N_counter = 0 O_counter = 0 S_counter = 0 for i in range(len(molecule.geometry)): if molecule.geometry[i][0] == "C": C_counter = C_counter + 1 elif molecule.geometry[i][0] == "H": H_counter = H_counter + 1 elif molecule.geometry[i][0] == "N": N_counter = N_counter + 1 elif molecule.geometry[i][0] == "O": O_counter = O_counter + 1 elif molecule.geometry[i][0] == "S": S_counter = S_counter + 1 num_ao = { 'C': 14, 'H': 2, 'N': 14, 'O': 14, 'S': 18, } ############################## # Provide your code here num_C_atom = C_counter num_H_atom = H_counter num_N_atom = N_counter num_O_atom = O_counter num_S_atom = S_counter num_atoms_total = len(molecule.atoms) num_AO_total = (14*num_C_atom)+(2*num_H_atom)+(14*num_N_atom)+(14*num_O_atom)+(18*num_S_atom) num_MO_total = num_AO_total ############################## answer_ex2a ={ 'C': num_C_atom, 'H': num_H_atom, 'N': num_N_atom, 'O': num_O_atom, 'S': num_S_atom, 'atoms': num_atoms_total, 'AOs': num_AO_total, 'MOs': num_MO_total } print(answer_ex2a) # Check your answer and submit using the following code from qc_grader import grade_ex2a grade_ex2a(answer_ex2a) from qiskit_nature.drivers.second_quantization import HDF5Driver driver_reduced = HDF5Driver("resources/PSPCz_reduced.hdf5") properties = driver_reduced.run() #print(properties) from qiskit_nature.properties.second_quantization.electronic import ElectronicEnergy electronic_energy = properties.get_property(ElectronicEnergy) print(electronic_energy) from qiskit_nature.results import ElectronicStructureResult import numpy as np # some dummy result result = ElectronicStructureResult() result.eigenenergies = np.asarray([-1]) result.computed_energies = np.asarray([-1]) # now, let's interpret it electronic_energy.interpret(result) print(result) from qiskit_nature.properties.second_quantization.electronic import ParticleNumber particle = (ParticleNumber(4, (2,2))) print( particle) from qiskit_nature.properties.second_quantization.electronic import ParticleNumber ############################## # Provide your code here #particle_number = electronic_energy. num_electron = 2 # 2 electrons num_MO = 2 # 2 molecular orbitals: Alpha-Beta num_SO = 4 # 4 SOs num_qubits = 4 # 4 qubits = 16 combinations: AlphaAlpha, AlphaBeta, BetaAlpha, BetaBeta ############################## answer_ex2b = { 'electrons': num_electron, 'MOs': num_MO, 'SOs': num_SO, 'qubits': num_qubits } print(answer_ex2b) # Check your answer and submit using the following code from qc_grader import grade_ex2b grade_ex2b(answer_ex2b) from qiskit_nature.problems.second_quantization import ElectronicStructureProblem ############################## # Provide your code here es_problem = ElectronicStructureProblem(driver_reduced) ############################## second_q_op = es_problem.second_q_ops() print(second_q_op[0]) from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.mappers.second_quantization import JordanWignerMapper, ParityMapper, BravyiKitaevMapper ############################## # Provide your code here qubit_converter = QubitConverter(mapper=JordanWignerMapper()) ############################## qubit_op = qubit_converter.convert(second_q_op[0]) print(qubit_op) from qiskit_nature.circuit.library import HartreeFock ############################## # Provide your code here init_state = HartreeFock(num_spin_orbitals= num_SO, num_particles= es_problem.num_particles, qubit_converter= qubit_converter) ############################## init_state.draw() from qiskit.circuit.library import EfficientSU2, TwoLocal, NLocal, PauliTwoDesign from qiskit_nature.circuit.library import UCCSD, PUCCD, SUCCD ############################## # Provide your code here ansatz = TwoLocal(num_qubits=num_qubits, rotation_blocks=(["h","ry"]), entanglement_blocks="cz",entanglement="linear", reps=2) ############################## ansatz.decompose().draw() from qiskit.algorithms import NumPyMinimumEigensolver from qiskit_nature.algorithms import GroundStateEigensolver ############################## # Provide your code here numpy_solver = NumPyMinimumEigensolver() numpy_ground_state_solver = GroundStateEigensolver(qubit_converter, numpy_solver) numpy_results = numpy_ground_state_solver.solve(es_problem) ############################## exact_energy = numpy_results.computed_energies[0] print(f"Exact electronic energy: {exact_energy:.6f} Hartree\n") print(numpy_results) # Check your answer and submit using the following code from qc_grader import grade_ex2c grade_ex2c(numpy_results) from qiskit.providers.aer import StatevectorSimulator, QasmSimulator from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA, SLSQP ############################## # Provide your code here backend = StatevectorSimulator() optimizer = COBYLA(maxiter=1000) ############################## from qiskit.algorithms import VQE from qiskit_nature.algorithms import VQEUCCFactory, GroundStateEigensolver from jupyterplot import ProgressPlot import numpy as np error_threshold = 10 # mHartree np.random.seed(5) # fix seed for reproducibility initial_point = np.random.random(ansatz.num_parameters) # for live plotting pp = ProgressPlot(plot_names=['Energy'], line_names=['Runtime VQE', f'Target + {error_threshold}mH', 'Target']) intermediate_info = { 'nfev': [], 'parameters': [], 'energy': [], 'stddev': [] } def callback(nfev, parameters, energy, stddev): intermediate_info['nfev'].append(nfev) intermediate_info['parameters'].append(parameters) intermediate_info['energy'].append(energy) intermediate_info['stddev'].append(stddev) pp.update([[energy, exact_energy+error_threshold/1000, exact_energy]]) ############################## # Provide your code here vqe = VQE(ansatz = ansatz, quantum_instance = backend) vqe_ground_state_solver = GroundStateEigensolver(qubit_converter, vqe) vqe_results = vqe_ground_state_solver.solve(es_problem) ############################## print(vqe_results) error = (vqe_results.computed_energies[0] - exact_energy) * 1000 # mHartree print(f'Error is: {error:.3f} mHartree') # Check your answer and submit using the following code from qc_grader import grade_ex2d grade_ex2d(vqe_results) from qiskit_nature.algorithms import QEOM ############################## # Provide your code here qeom_excited_state_solver = QEOM(vqe_ground_state_solver, "sd") qeom_results = qeom_excited_state_solver.solve(problem=es_problem) ############################## print(qeom_results) # Check your answer and submit using the following code from qc_grader import grade_ex2e grade_ex2e(qeom_results) bandgap = qeom_results.computed_energies[1] - qeom_results.computed_energies[0] bandgap # in Hartree from qiskit import IBMQ IBMQ.load_account() from qc_grader.util import get_challenge_provider provider = get_challenge_provider() if provider: backend = provider.get_backend('ibmq_qasm_simulator') from qiskit_nature.runtime import VQEProgram error_threshold = 10 # mHartree # for live plotting pp = ProgressPlot(plot_names=['Energy'], line_names=['Runtime VQE', f'Target + {error_threshold}mH', 'Target']) intermediate_info = { 'nfev': [], 'parameters': [], 'energy': [], 'stddev': [] } # Provide your code here optimizer = { 'name': 'QN-SPSA', # leverage the Quantum Natural SPSA # 'name': 'SPSA', # set to ordinary SPSA 'maxiter': 100, } def callback(nfev, parameters, energy, stddev): intermediate_info['nfev'].append(nfev) intermediate_info['parameters'].append(parameters) intermediate_info['energy'].append(energy) intermediate_info['stddev'].append(stddev) pp.update([[energy,exact_energy+error_threshold/1000, exact_energy]]) ############################## runtime_vqe = VQEProgram(ansatz=ansatz, optimizer=optimizer, initial_point=initial_point, provider=provider, backend=backend, shots=1024, callback=callback) ############################## # Submit a runtime job using the following code from qc_grader import prepare_ex2f runtime_job = prepare_ex2f(runtime_vqe, qubit_converter, es_problem) # Check your answer and submit using the following code from qc_grader import grade_ex2f grade_ex2f(runtime_job) print(runtime_job.result().get("eigenvalue")) # Please change backend to ibm_perth before running the following code runtime_job_real_device = prepare_ex2f(runtime_vqe, qubit_converter, es_problem, real_device=True) print(runtime_job_real_device.result().get("eigenvalue"))
https://github.com/bagmk/qiskit-quantum-state-classifier
bagmk
import numpy as np import copy from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, Aer, execute, transpile, assemble from qiskit.tools.visualization import * from qiskit.ignis.mitigation.measurement import (complete_meas_cal, tensored_meas_cal, CompleteMeasFitter, TensoredMeasFitter) import json from scipy.signal import savgol_filter import time from o_utils import ora # classifier utilities from o_plot import opl # utilities for result plot from c_utils import cut # circuit building utilities data_directory = "data_files/" def json_dic_loader(dic_name): f = open(data_directory+dic_name+'.json') return json.load(f) simulator = Aer.get_backend('qasm_simulator') #specify the layout of the devices used_qubits = 5 qubit_list = [0,1,2,3,4] program_name="QAD" # in hommage of the Qiskit advocates Flag_char = "DS" # this for a mix of GHZ Psi+ and W Phi+ separable states if len(Flag_char) >= 2: unique_char = "M" else: unique_char = Flag_char # These dictionaries for the devices used in the study fidelity_dic = {'ibmq_athens': 0.925110, 'ibmq_valencia': 0.809101, 'ibmq_ourense': 0.802380, "ibmqx2": 0.627392, 'ibmq_santiago': 0.919399, 'ibmq_vigo': 0.908840, 'ideal_device': 1.0} QV_dic = {'ibmq_athens': 32.0, 'ibmq_valencia': 16.0, 'ibmq_ourense': 8.0, "ibmqx2": 8.0, 'ibmq_santiago': 32.0, 'ibmq_vigo': 16.0, 'ideal_device': np.inf} dev_dic = {'ibmq_santiago': "San",'ibmq_athens': "Ath", 'ibmq_valencia': "Val", 'ibmq_vigo': 'Vig','ibmq_ourense': "Our", "ibmqx2": 'Yor', 'ideal_device': "Ide"} # specify the device: here first the ideal noise-free device project_device = 'ideal_device' device_name = dev_dic[project_device] # specify the nb of id gates between state creation and measurements # zero for the ideal device of course id_gates = 0 str_nb_id = str(id_gates) zfilled = str_nb_id.zfill(4-len(str_nb_id)) # tail of the file names for RAM storage mitig_name = program_name + "_" + device_name project_name = mitig_name + "_" + unique_char + zfilled print(mitig_name) print(project_name) # establish the result label list # meas_calibs will be used for mitigation in the real device section qr = QuantumRegister(used_qubits) # meas_calibs, label_list = complete_meas_cal(qubit_list=qubit_list, qr=qr, circlabel='mcal') nb_labels=len(label_list) print(nb_labels,label_list) len(meas_calibs) # permutation list # here it is simple to write down the list, # but a version using itertools will be wellcome for >5 qubits projects q_perm = [[0, 1, 2, 3, 4], [0, 1, 3, 2, 4], [0, 1, 4, 2, 3], [0, 2, 3, 1, 4], [0, 2, 4, 1, 3], [0, 3, 4, 1, 2], [1, 2, 3, 0, 4], [1, 2, 4, 0, 3], [1, 3, 4, 0, 2], [2, 3, 4, 0, 1]] # version 20 circuits for demonstration # (in the version run on real devices: two batches of 10 circuits, "shallow" and "deep") # these circuits limited to state creation are ready to be saved # for ultimately building circuits adapted to noisy simulator and real devices # as option, these circuits will include a row of id gates between creation and measurements circ_ori = [] for state_1 in ("W", "GHZ"): if state_1 == "GHZ": state_2 = "Psi+" if state_1 == "W": state_2 = "Phi+" for perm in q_perm: mycircuit = QuantumCircuit(used_qubits, used_qubits) mycircuit = cut.circuit_builder(mycircuit, perm, state_1,state_2) circ_ori.append(mycircuit) # add measurement section to the circuit set newly created: nb_states = len(circ_ori) circ_ideal = copy.deepcopy(circ_ori) for i_state in range(nb_states): cut.add_barrier_and_measure(circ_ideal[i_state],qubit_list) # execute on noise free simulator s_sim = 12000 job_simul = execute(circ_ideal, backend=simulator, shots=s_sim) tot_results_simul = job_simul.result() # establish a dictionary of count results on noise free simulator: # (this step is only useful if ram storage is performed) void_counts = dict(zip(label_list, np.zeros(2**used_qubits, dtype=int))) tot_results_sim_dic = {} ideal_dic = {} for i_state in range(nb_states): counts_simul = copy.deepcopy(void_counts) counts_simul.update(tot_results_simul.get_counts(i_state)) ideal_dic[str(i_state)]=counts_simul i_state_test = 5 print(device_name, "circuit #",i_state_test) circ_ideal[i_state_test].draw(output='mpl') print(device_name, "circuit #",i_state_test) plot_histogram(ideal_dic[str(i_state_test)], legend=['noise free simulation'], color = "b", figsize=(10.,5.)) i_state_test = 19 print(device_name, "circuit #",i_state_test) circ_ideal[i_state_test].draw(output='mpl') print(device_name, "circuit #",i_state_test) plot_histogram(ideal_dic[str(i_state_test)], legend=['noise free simulation'], color = "b", figsize=(10.,5.)) PD_ideal = np.ndarray((nb_states,nb_labels)) for i_state in range(nb_states): PD_ideal[i_state, :] = list(ideal_dic[str(i_state)].values()) # now a little trick to get the ideal values from the simulator approximated values with np.errstate(divide='ignore'): # ignore the divide by zero warning PD_ideal = 1/np.round(s_sim/(PD_ideal)) # have a look at the matrix head and tail: print("first and last state probability distributions:") print(np.round(np.vstack((PD_ideal[0:1,:],PD_ideal[-1:,:])),4)) # common code for the different options def add_single_dic(target_data_list): start_time = time.time() print("started",time.strftime('%d/%m/%Y %H:%M:%S'),mitig_name, "mitigation",mit_str,o_metric,model_name) # added for D,S,M choice. Mainstream : mixed set of 20 states first = 0 last = nb_states if unique_char == "D": last = int(nb_states/2) elif unique_char == "S": first = int(nb_states/2) # get the classifier error curve in function of the number of shot and the "safe shot number" error_curve, safe_rate, ernb = ora.provide_error_curve(PD_model=model_dic[model_name][first:last,:], PD_test=PD_test[first:last,:], trials=trials, window=window, epsilon=epsilon, max_shots=max_shots, pol=pol, verbosality=verbosality) tail = savgol_filter(ernb, window, pol, axis=0) len_curve = len(error_curve) safe_shot_nb = len_curve - int((window-1)/2) # OK print('safe_shot_nb',safe_shot_nb, 'safe_rate',safe_rate, "nb trials:",trials) err_rates = tail[int((window-1)/2),:]/trials err_rate_max = np.max(err_rates) err_rate_min = np.min(err_rates) r=4 print("savgol interpolated error rate mean:", np.round(np.mean(err_rates),r), "min:", np.round(err_rate_min,r), "max:", np.round(err_rate_max,r), "for", [ien for ien, jen in enumerate(err_rates) if jen == err_rate_max]) end_time = time.time() #save the data in a list of dictionaries : single_dic={"project":mitig_name, "id_gates":id_gates, "mitigation":mit_str, "model":model_name, "metric":o_metric, "device":project_device, "curve_length":len_curve, "shots": safe_shot_nb, "shots_rate": safe_rate, "error_curve":error_curve, "trials":trials,"window":window, "epsilon":epsilon,"SG_pol": pol, "computation_time":end_time-start_time, "time_completed":time.strftime('%d/%m/%Y %H:%M:%S'), "trials":trials, "QV": QV_dic[project_device], "fidelity": fidelity_dic[project_device], "error_nb":ernb} target_data_list.append(single_dic) print("completed",time.strftime('%d/%m/%Y %H:%M:%S'),mitig_name, "mitigation",mit_str,o_metric,model_name,"\n") # here will be appended the data we want for the curve plot ideal_data_list=[] # you may want to skip this cell as it will require a long time # because of the high number of trials required by the Monte Carlo simulation for each nb o shots value # the following values are defined in the study summary (readme file): trials=10000 window=5 # shorter window than for the real device counts epsilon = .001 min_shots = 5 max_shots = 100 pol=2 subset = None # variable not used here verbosality = 5 # printing step for intermediate results when increasing the experiment shot number PD_test = PD_ideal mitigation_dic = {"Na": None} o_metrics_desired = ['jensenshannon', 'sqeuclidean'] model_dic = {"ideal_sim": PD_ideal} for mit_str, mitigation in mitigation_dic.items(): if mitigation != None: # thus only for counts on real device PD_exper = get_clean_matrix(empirical_dic, mitigation=mitigation, m_filter=meas_filter) for o_metric in o_metrics_desired: for model_name in model_dic.keys(): add_single_dic(ideal_data_list) # get the stored results of the Monte Carlo simulation in case you skipped the previous step if len(ideal_data_list) == 0: ideal_data_list = json_dic_loader("ideal_device_data_list_"+project_name) # have a look at the mean error rate curves and error rate at save shot number n_s # NB the r_hat_mean curves and legend reported r_hat_max errors the unsmoothed values opl.plot_curves(ideal_data_list,np.array([0,1]), "Jensen-Shannon vs squared euclidean distance - $\epsilon=0.001$" , ["model"], ["device","metric"], right_xlimit = 15, bottom_ylimit = -0.01, top_ylimit = 0.3) from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') print(provider.backends()) project_device = 'ibmq_vigo'# you may choice here a different backend device_name = dev_dic[project_device] id_gates = 0 str_nb_id = str(id_gates) zfilled = str_nb_id.zfill(4-len(str_nb_id)) mitig_name = program_name + "_" + device_name project_name = mitig_name + "_" + unique_char + zfilled print(mitig_name) print(project_name) # determine here the backend device = provider.get_backend(project_device) # the backend names are listed here above properties = device.properties() coupling_map = device.configuration().coupling_map # transpile verbose = True summary_dic = {} seed_transpiler_list = list(range(nb_states)) start_time = time.strftime('%d/%m/%Y %H:%M:%S') print("Start at DMY: ",start_time) for i_state in list(range(nb_states)): # prepare circuit to be transpiled circuit = copy.deepcopy(circ_ori[i_state]) if id_gates > 0: circuit.barrier() for id_gates_index in range(id_gates): for index, value in enumerate(qubit_list): circuit.id(value) cut.add_barrier_and_measure(circuit, qubit_list) summary = [] depth_list = [] Q_state_opt_new = transpile(circuit, backend=device, coupling_map = coupling_map, seed_transpiler=seed_transpiler_list[i_state], optimization_level=2, initial_layout=qubit_list) summary_dic[i_state] = {"depth": Q_state_opt_new.depth(), 'circuit':Q_state_opt_new} if verbose: print("circuit %2i" % i_state,"length",summary_dic[i_state]["depth"], "DMY: ",time.strftime('%d/%m/%Y %H:%M:%S')) end_time = time.strftime('%d/%m/%Y %H:%M:%S') print("Completed at DMY: ",end_time) i_state_test = 0 print(project_device, "circuit #",i_state_test, "circuit length:", summary_dic[i_state_test]['depth']) # you may want to skip this if large nb of id gates before measurement summary_dic[i_state_test]['circuit'].draw(output='mpl') job_simul = execute(summary_dic[i_state_test]['circuit'], backend=simulator, shots=s_sim) print(project_device, "circuit #",i_state_test, "on noise free simulator") plot_histogram(job_simul.result().get_counts(), legend=['noise free simulation'], color = "b", figsize=(10.,5.)) data_directory = "data_files/" def json_dic_loader(dic_name): f = open(data_directory+dic_name+'.json') return json.load(f) # changing keys of dictionary for merging: def key_change(ini_dict, i_subset): ini_list = [] len_ini = len(ini_dict) for i in range(len_ini): ini_list.append(str(i+i_subset*len_ini)) return dict(zip(ini_list, list(ini_dict.values()))) # retrieve the data corresponding to this project lfc = list(Flag_char) circ_ideal =[] empirical_dic = {} for i_subset, subset in enumerate(lfc): qasm_circs_dic = json_dic_loader('qasm_circs_dic_QAD_'+device_name+'_'+ subset + zfilled) j=0 # j included for project with several transpilation sessions for each device - not used here qasm_circs = qasm_circs_dic[str(j)] nb_circs = len(qasm_circs) for i_circs in range(nb_circs): circ_ideal.append(QuantumCircuit().from_qasm_str(qasm_circs[i_circs])) empirical_dic = {**empirical_dic, **key_change(json_dic_loader("experimental"+"_"+mitig_name +"_"\ +subset+zfilled), i_subset)} nb_states = len(circ_ideal) # retrieve the corresponding measurement mitigation filter obtained at experimental time # use a fake job because the caL_results were stored as dictionary simulator = Aer.get_backend('qasm_simulator') fake_job_cal = execute(meas_calibs, backend=simulator, shots=1) fake_cal_results = fake_job_cal.result() cal_results_dic = json_dic_loader("cal_results_dic_"+mitig_name) cal_results = fake_cal_results.from_dict(cal_results_dic) meas_fitter = CompleteMeasFitter(cal_results, label_list, qubit_list=qubit_list, circlabel='mcal') meas_filter = meas_fitter.filter # have a look at the average measurement fidefily of this device: print("Average Measurement Fidelity was: %f" % meas_fitter.readout_fidelity(), "for",project_device) def rectify_counts(tot_res, test_cqi,mitigation,m_filter) : # IMPORTANT MODIFICATION try: counts_results_real_test = tot_res[str(test_cqi)] except KeyError as error: counts_results_real_test = tot_res[test_cqi] raw_counts_test = copy.deepcopy(void_counts) raw_counts_test.update(counts_results_real_test) if mitigation: mitigated_results_test = meas_filter.apply(raw_counts_test, method = 'least_squares') returned_counts = copy.deepcopy(void_counts) returned_counts.update(mitigated_results_test) else: returned_counts = copy.deepcopy(raw_counts_test) return returned_counts def get_clean_matrix(dic, mitigation,m_filter): clean_matrix = np.ndarray((nb_states,nb_labels)) for i_state in range(nb_states): rectified_counts = rectify_counts(dic,i_state, mitigation,m_filter) # get a rectified counts dictionary clean_matrix[i_state, :] = list(rectified_counts.values()) clean_matrix = clean_matrix/clean_matrix.sum(axis=1, keepdims=True) return clean_matrix # We need to create a first matrix version. It will then vary for each considered set of distribution mitigation = True PD_exper = get_clean_matrix(empirical_dic, mitigation=mitigation, m_filter=meas_filter) print("first and last state probability distributions:") print(np.round(np.vstack((PD_exper[0:1,:],PD_exper[-1:,:])),4)) # here will be appended the data we want for the final plot of this notebook empirical_data_list=[] # you may want to skip this cell as it will require a long time # because of the high number of trials required by the Monte Carlo simulation for each nb o shots value # the following values are defined in the study summary notebook: trials=1000 window=11 epsilon = .001 max_shots = 500 pol=2 verbosality = 10 # printing step for intermediate results when increasing the experiment shot number mitigation_dic = {"no": False,"yes" : True} o_metrics_desired = ['jensenshannon', 'sqeuclidean'] model_dic = {"empirical": PD_exper, "ideal_sim": PD_ideal} for mit_str, mitigation in mitigation_dic.items(): # here we toggle PD_exper as we toggled mitigation status PD_exper = get_clean_matrix(empirical_dic, mitigation=mitigation, m_filter=meas_filter) PD_test = PD_exper for o_metric in o_metrics_desired: print(project_name, model_dic.keys(), o_metric) for model_name in model_dic.keys(): add_single_dic(empirical_data_list) # get the stored results of the Monte Carlo simulation in case you skipped the previous step if len(empirical_data_list) == 0: empirical_data_list = json_dic_loader('nemp_data_list_'+project_name) 'nemp_data_list_'+project_name # have a look at the mean error rate curves and error rate at save shot number n_s # NB the r_hat_mean curves and legend reported r_hat_max errors are the unsmoothed values opl.plot_curves(ideal_data_list + empirical_data_list, np.array(range(2+len(empirical_data_list))), "$\epsilon=0.001$" , ["device"], ["model","metric","mitigation","id_gates"], right_xlimit = 30, bottom_ylimit = -0.02, top_ylimit = 0.3) import winsound duration = 2000 # milliseconds freq = 800 # Hz winsound.Beep(freq, duration) import qiskit.tools.jupyter %qiskit_version_table