repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/ggridin/QiskitTests
ggridin
from qiskit import transpile, transpiler, qasm2 class QuantumPlatform: def __init__(self, provider = None, backend_name = None): self.provider = None self.backend = None self.transpiled_qc = None self.provider = provider if self.provider is None: raise "Cannot initialize quantum provider" if backend_name is not None: self.backend = self.provider.get_backend(backend_name) if self.backend is None: raise f'Cannot initialize backend {backend_name}' def get_provider(self): return self.provider def get_backend_info(self, coupling_map_filename=None, target_info_filename=None): print(f'Backends={self.provider.backends()}') print(f'Operation names={self.backend.operation_names}') # print(f'Properties={self.backend.properties()}') # print(f'Configuration={self.backend.configuration()}') # print(f'Status={self.backend.status()}') print(f'Options={self.backend.options}') # if target_info_filename is not None: # f = open(target_info_filename, "w") # f.write(self.backend.target) # f.close() if coupling_map_filename is not None: coupling_map = transpiler.CouplingMap(self.backend.coupling_map) image = coupling_map.draw() image.save(coupling_map_filename) def get_backend(self): return self.backend def schedule_job(self, circuit, shots=1, dry_run=False, qc_filename=None, qc_image_filename=None, transpiled_filename=None, transpiled_image_filename=None): if qc_filename is not None: qasm2.dump(circuit, qc_filename) if qc_image_filename is not None: circuit.draw(output='mpl', filename=qc_image_filename) self.transpiled_qc = transpile(circuit, self.backend) if transpiled_filename is not None: qasm2.dump(self.transpiled_qc, transpiled_filename) if transpiled_image_filename is not None: self.transpiled_qc.draw(output='mpl', filename=transpiled_image_filename) if dry_run is True: return None return self.backend.run(self.transpiled_qc, shots=shots) def get_async_job(self, job_id): return self.provider.retrieve_job(job_id)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeAuckland backend = FakeAuckland() ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) ghz.draw(output='mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit 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_nature.drivers.second_quantization import GaussianForcesDriver from qiskit_nature.problems.second_quantization import VibrationalStructureProblem from qiskit_nature.settings import settings settings.dict_aux_operators = True driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") problem = VibrationalStructureProblem(driver, num_modals=[2, 2, 3, 4], truncation_order=2) # Note: at this point, `driver.run()` has NOT been called yet. We can trigger this indirectly like so: second_q_ops = problem.second_q_ops() hamiltonian = second_q_ops["VibrationalEnergy"] print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."])) from qiskit_nature.second_q.drivers import GaussianForcesDriver from qiskit_nature.second_q.problems import HarmonicBasis driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") basis = HarmonicBasis(num_modals=[2, 2, 3, 4]) # this is now done explicitly and already requires the basis problem = driver.run(basis=basis) problem.hamiltonian.truncation_order = 2 hamiltonian = problem.hamiltonian.second_q_op() print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."])) from qiskit_nature.drivers.second_quantization import GaussianLogResult from qiskit_nature.properties.second_quantization.vibrational.bases import HarmonicBasis from qiskit_nature.settings import settings settings.dict_aux_operators = True log_result = GaussianLogResult("aux_files/CO2_freq_B3LYP_631g.log") hamiltonian = log_result.get_vibrational_energy() print(hamiltonian) hamiltonian.basis = HarmonicBasis([2, 2, 3, 4]) op = hamiltonian.second_q_ops()["VibrationalEnergy"] print("\n".join(str(op).splitlines()[:10] + ["..."])) from qiskit_nature.second_q.drivers import GaussianLogResult from qiskit_nature.second_q.formats import watson_to_problem from qiskit_nature.second_q.problems import HarmonicBasis log_result = GaussianLogResult("aux_files/CO2_freq_B3LYP_631g.log") watson = log_result.get_watson_hamiltonian() print(watson) basis = HarmonicBasis(num_modals=[2, 2, 3, 4]) problem = watson_to_problem(watson, basis) hamiltonian = problem.hamiltonian.second_q_op() print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."])) from qiskit_nature.drivers.second_quantization import GaussianForcesDriver from qiskit_nature.problems.second_quantization import VibrationalStructureProblem driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") problem = VibrationalStructureProblem(driver, num_modals=[2, 2, 3, 4], truncation_order=2) # we trigger driver.run() implicitly like so: second_q_ops = problem.second_q_ops() hamiltonian_op = second_q_ops.pop("VibrationalEnergy") aux_ops = second_q_ops from qiskit_nature.second_q.drivers import GaussianForcesDriver from qiskit_nature.second_q.problems import HarmonicBasis driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") basis = HarmonicBasis(num_modals=[2, 2, 3, 4]) problem = driver.run(basis=basis) problem.hamiltonian.truncation_order = 2 hamiltonian_op, aux_ops = problem.second_q_ops() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/TheGupta2012/QPE-Algorithms
TheGupta2012
from qiskit import QuantumCircuit, execute, transpile, Aer from qiskit.extensions import UnitaryGate,Initialize from qiskit.tools.visualization import plot_histogram from qiskit.compiler import assemble import numpy as np from time import sleep from qiskit.tools.monitor import job_monitor from qiskit.extensions import UnitaryGate from qiskit.quantum_info import Statevector import sys from scipy.stats import unitary_group import matplotlib.pyplot as plt class SPEA(): ''' This is a class which implements the Statistical Phase Estimation algorithm paper1 - https://arxiv.org/pdf/2104.10285.pdf paper2 - https://arxiv.org/pdf/1906.11401.pdf(discussion) Attributes : resolution(int) : the number of intervals the angle range has to be divided into dims(int) : dimensions of the passed unitary matrix c_unitary_gate(Unitary Gate) : the controlled unitary gate in our algorithm error(int) : the number of places after decimal, upto which the cost of the algorithm would be estimated itrations(int) : the maximum iterations after which the algorithm ends the computation basis(list of np.ndarray) : the basis generated at the start of the algorithm unitary_circuit(QuantumCircuit): a pre-transpiled QuantumCircuit which is applied during the algorithm Methods : __get_basis_vectors(randomize) : Get the d dimensional basis for the initializtion of the algorithm __get_unitary_circuit(backend) : Get the pre-transpiled circuit for the unitary matrix __get_alternate_cost(angle,state,backend,shots) : Get the cost through the alternate method specified in the algorithm __get_standard_cost(angle,state,backend,shots) : Get the cost through the standard method specified in the algorithm __get_circuit(state,angle,backend,shots) : Get the completed circuit used inside the algorithm to estimate the phase get_eigen_pair(backend, algo='alternate', theta_left,theta_right,progress, randomize, target_cost, basis, basis_ind,shots) : Get the eigenstate and eigenphase phase for the unitary matrix ''' def __init__(self, unitary, resolution=50, error=3, max_iters=20): # handle resolution if not isinstance(resolution, int): raise TypeError( "Please enter the number of intervals as an integer value") if resolution < 10 or resolution > 1e6: raise ValueError( "Resolution needs to be atleast 0.1 and greater than 0.000001") self.resolution = resolution # handle unitary if not isinstance(unitary, np.ndarray) and not isinstance(unitary, QuantumCircuit)\ and not isinstance(unitary, UnitaryGate): raise TypeError( "A numpy array or Quantum Circuit or UnitaryGate needs to be passed as the unitary matrix") # convert circuit to numpy array for uniformity if isinstance(unitary, UnitaryGate): U = unitary.to_matrix() else: # both QC and ndarray type U = unitary # note - the unitary here is not just a single qubit unitary if isinstance(U, np.ndarray): self.dims = U.shape[0] else: self.dims = 2**(U.num_qubits) if isinstance(U, np.ndarray): self.c_unitary_gate = UnitaryGate(data=U).control( num_ctrl_qubits=1, label='CU', ctrl_state='1') else: self.c_unitary_gate = U.control( num_ctrl_qubits=1, label='CU', ctrl_state='1') # handle error if not isinstance(error, int): raise TypeError( "The allowable error should be provided as an int. Interpreted as 10**(-error)") if error <= 0: raise ValueError( "The error threshold must be finite and greater than 0.") self.error = error # handle max_iters if not isinstance(max_iters, int): raise TypeError("Max iterations must be of integer type") if max_iters <= 0 and max_iters > 1e5: raise ValueError( "Max iterations should be atleast 1 and less than 1e5") self.iterations = max_iters self.basis = [] def __get_basis_vectors(self, randomize=True): ''' Get the d dimensional basis for the unitary provided Args : randomize (bool) : whether to pick a random basis or not Returns: a list of np.ndarrays which are used as the basis vectors ''' if randomize == True: UR = unitary_group.rvs(self.dims) else: UR = np.identity(self.dims) basis = [] for k in UR: basis.append(np.array(k, dtype=complex)) return basis def __get_unitary_circuit(self, backend): '''Return the pretranspiled circuit Args: backend : the IBMQBackend on which we want to transpile. If None, Default : 'qasm_simulator' Returns: QuantumCircuit containing the transpiled circuit for the controlled unitary ''' if backend is None: backend = Aer.get_backend('qasm_simulator') qc = QuantumCircuit(1 + int(np.log2(self.dims))) # make the circuit qc.h(0) qc = qc.compose(self.c_unitary_gate, qubits=range( 1+int(np.log2(self.dims)))) qc.barrier() # RANDOMNESS 1 qc = transpile(qc,backend=backend,optimization_level = 3) return qc def __get_circuit(self, state, backend, shots,angle=None): '''Given an initial state , return the assembled and transpiled circuit that is generated with inverse rotation Args: state(np.ndarray) : The eigenvector guess state for the initialization backend(IBMQBackend) : the backend on which this circuit is going to be executed shots(int) : the number of shots in our experiments angle(float) : whether the returned circuit contains an inverse rotation gate or not. If angle is None, no rotation gate attached Else, cp(angle) is attached on control qubit 0 Returns: QuantumCircuit which is pre-transpiled according to the backend provided ''' # all theta values are iterated over for the same state phi = Initialize(state) qc1 = QuantumCircuit(1 + int(np.log2(self.dims)), 1) # initialize the circuit qc1 = qc1.compose(phi, qubits=list( range(1, int(np.log2(self.dims))+1))) qc1.barrier() # RANDOMNESS 2 qc1 = transpile(qc1, backend=backend,optimization_level=1) # get the circuit2 qc2 = self.unitary_circuit qc3 = QuantumCircuit(1 + int(np.log2(self.dims)), 1) if angle is not None: # add inverse rotation on the first qubit qc3.p(-2*np.pi*angle, 0) # add hadamard qc3.h(0) qc3 = transpile(qc3, backend=backend,optimization_level=1) # make final circuit qc = qc1 + qc2 + qc3 # measure qc.measure([0], [0]) return qc def __get_standard_cost(self, angles, state, backend,shots): '''Given an initial state and a set of angles, return the best cost and the associated angle. Implements the standard method as specified in the paper. Args : angles(np.ndarray) : the set of angles on which we execute the circuits state(np.ndarray) : the initialization state provided backend(IBMQBackend): the backend on which this circuit needs to be executed shots(int) : the number of shots used to execute this circuit Returns : result(dict) : {result : (float), theta : (float)} result - the best cost given this set of angles theta - the best theta value amongst this set of angles''' result = {'cost': -1, 'theta': -1} # all theta values are iterated over for the same state circuits = [] for theta in angles: qc = self.__get_circuit(state,backend,shots,theta) circuits.append(qc) # RANDOMNESS 3 # execute only once... counts = backend.run(circuits, shots=shots).result().get_counts() # get the cost for this theta for k, theta in zip(counts, angles): # for all experiments you ran try: C_val = (k['0'])/shots except: C_val = 0 if C_val > result['cost']: # means this is a better theta value result['theta'] = theta result['cost'] = C_val return result def __get_alternate_cost(self, angles, state, backend,shots): '''Given an initial state and a set of angles, return the best cost and the associated angle. Implements the alternate method as specified in the paper1 and discussion of paper2. Args : angles(np.ndarray) : the set of angles on which we execute the circuits state(np.ndarray) : the initialization state provided backend(IBMQBackend): the backend on which this circuit needs to be executed shots(int) : the number of shots used to execute this circuit Returns : result(dict) : {result : (float), theta : (float)} result - the best cost given this set of angles theta - the best theta value amongst this set of angles''' result = {'cost': -1, 'theta': -1} # all theta values are iterated over for the same state qc = self.__get_circuit(state,backend,shots) # execute only once... counts = backend.run(qc, shots=shots).result().get_counts() # generate experimental probabilities try: p0 = counts['0']/shots except: p0 = 0 try: p1 = counts['1']/shots except: p1 = 0 # now, find the best theta as specified by the # alternate method classically min_s = 1e5 for theta in angles: # generate theoretical probabilities c0 = (np.cos(np.pi*theta))**2 c1 = 1 - c0 # generate s value s = (p0-c0)**2 + (p1-c1)**2 if s < min_s: result['theta'] = theta min_s = s # now , we have the best theta stored in phi # run circuit once again to get the value of C* # RANDOMNESS 4 qc = self.__get_circuit(state, backend, shots, result['theta']) counts = backend.run(qc, shots=shots).result().get_counts() try: result['cost'] = counts['0']/shots except: result['cost'] = 0 # no 0 counts present # return the result return result def get_eigen_pair(self, backend, algo='alternate', theta_left = 0,theta_right = 1,progress=False, randomize=True, target_cost=None, basis = None, basis_ind = None,shots=512): '''Finding the eigenstate pair for the unitary Args : backend(IBMQBackend) : the backend on which the circuit needs to be executed algo(str) : ['alternate','standard'] the algorithm to use as specified in the paper1 section 3. theta_left(float): the left bound for the search of eigenvalue. Default : 0 theta_right(float): the right bound for the search of eigenvalue. Default : 1 progress(bool) : Whether to show the progress as the algorithm runs randomize(bool): Whether to choose random initialization of basis states or not If False, computational basis is chosen. target_cost(float) : the min cost required to be achieved by the algorithm basis(list of np.ndarray) : The basis to be used in the algorithm. Note, if basis is specified, randomize value is ignored basis_ind(int) : the index of the basis vector to be used as the initial state vector Returns : result(dict) : {cost :(float), theta :(float), state : (np.ndarray) cost - the cost with which the algorithm terminates theta - the eigenvalue estimated by SPEA state - the eigenvector estimated by SPEA ''' # handle algorithm... self.unitary_circuit = self.__get_unitary_circuit(backend) if(theta_left > theta_right): raise ValueError("Left bound for theta should be smaller than the right bound") elif (theta_left<0) or (theta_right>1): raise ValueError("Bounds of theta are [0,1].") if not isinstance(algo, str): raise TypeError( "Algorithm must be mentioned as a string from the values {alternate,standard}") elif algo not in ['alternate', 'standard']: raise ValueError( "Algorithm must be specified as 'alternate' or 'standard' ") if not isinstance(progress, bool): raise TypeError("Progress must be a boolean variable") if not isinstance(randomize, bool): raise Exception("Randomize must be a boolean variable") if target_cost is not None: if not isinstance(target_cost, float): raise TypeError("Target cost must be a float") if (target_cost <= 0 or target_cost >= 1): raise ValueError( "Target cost must be a float value between 0 and 1") results = dict() # first initialize the state phi if basis is None: self.basis = self.__get_basis_vectors(randomize) else: # is basis is specified, given as array of vectors... self.basis = basis # choose a random index if basis_ind is None: ind = np.random.choice(self.dims) else: # choose the index given in that basis ind = basis_ind phi = self.basis[ind] # doing the method 1 of our algorithm # define resolution of angles and precision if target_cost == None: precision = 1/10**self.error else: precision = 1 - target_cost samples = self.resolution # initialization of range left, right = theta_left, theta_right # generate the angles angles = np.linspace(left, right, samples) # iterate once if algo == 'alternate': result = self.__get_alternate_cost(angles, phi, backend,shots) else: result = self.__get_standard_cost(angles, phi, backend,shots) # get initial estimates cost = min(1,result['cost']) theta_max = result['theta'] best_phi = phi # the range upto which theta extends iin each iteration angle_range = (right - left)/2 # a parameter a = 1 # start algorithm iters = 0 found = True while 1 - cost >= precision: # get angles, note if theta didn't change, then we need to # again generate the same range again right = min(theta_right, theta_max + angle_range/2) left = max(theta_left, theta_max - angle_range/2) if progress: print("Right :", right) print("Left :", left) # generate the angles only if the theta has been updated if found == True: angles = np.linspace(left, right, samples) found = False # for this iteration if progress: print("ITERATION NUMBER", iters+1, "...") for i in range((2*self.dims)): # everyone is supplied with the same range of theta in one iteration # define z if i < self.dims: z = 1 else: z = 1j # alter and normalise phi curr_phi = best_phi + z*a*(1 - cost)*self.basis[i % self.dims] curr_phi = curr_phi / np.linalg.norm(curr_phi) # iterate (angles would be same until theta is changed) if algo == 'alternate': res = self.__get_alternate_cost(angles, curr_phi, backend,shots) else: res = self.__get_standard_cost(angles, curr_phi, backend,shots) curr_cost = res['cost'] curr_theta = res['theta'] # at this point I have the best Cost for the state PHI and the if curr_cost > cost: theta_max = float(curr_theta) cost = min(1.0,float(curr_cost)) best_phi = curr_phi found = True if progress: sys.stdout.write('\r') sys.stdout.write("%f %%completed" % (100*(i+1)/(2*self.dims))) sys.stdout.flush() # iteration completes if found == False: # phi was not updated , change a a = a/2 if progress: print("\nNo change, updating a...") else: angle_range /= 2 # updated phi and thus theta too -> refine theta range iters += 1 if progress: print("\nCOST :", cost) print("THETA :", theta_max) if iters >= self.iterations: print( "Maximum iterations reached for the estimation.\nTerminating algorithm...") break # add the warning that iters maxed out # add cost, eigenvector and theta to the dict results['cost'] = cost results['theta'] = theta_max results['state'] = best_phi return results
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 123456 from sklearn.datasets import make_blobs features, labels = make_blobs( n_samples=20, centers=2, center_box=(-1, 1), cluster_std=0.1, random_state=algorithm_globals.random_seed, ) from qiskit import BasicAer from qiskit.utils import QuantumInstance sv_qi = QuantumInstance( BasicAer.get_backend("statevector_simulator"), seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed, ) from qiskit.circuit.library import ZZFeatureMap from qiskit_machine_learning.kernels import QuantumKernel feature_map = ZZFeatureMap(2) previous_kernel = QuantumKernel(feature_map=feature_map, quantum_instance=sv_qi) from qiskit_machine_learning.algorithms import QSVC qsvc = QSVC(quantum_kernel=previous_kernel) qsvc.fit(features, labels) qsvc.score(features, labels) from qiskit.algorithms.state_fidelities import ComputeUncompute from qiskit.primitives import Sampler fidelity = ComputeUncompute(sampler=Sampler()) from qiskit_machine_learning.kernels import FidelityQuantumKernel feature_map = ZZFeatureMap(2) new_kernel = FidelityQuantumKernel(feature_map=feature_map, fidelity=fidelity) from qiskit_machine_learning.algorithms import QSVC qsvc = QSVC(quantum_kernel=new_kernel) qsvc.fit(features, labels) qsvc.score(features, labels) from qiskit import QuantumCircuit from qiskit.circuit.library import RealAmplitudes num_inputs = 2 feature_map = ZZFeatureMap(num_inputs) ansatz = RealAmplitudes(num_inputs, reps=1) circuit = QuantumCircuit(num_inputs) circuit.compose(feature_map, inplace=True) circuit.compose(ansatz, inplace=True) def parity(x): return "{:b}".format(x).count("1") % 2 initial_point = algorithm_globals.random.random(ansatz.num_parameters) from qiskit_machine_learning.neural_networks import CircuitQNN circuit_qnn = CircuitQNN( circuit=circuit, input_params=feature_map.parameters, weight_params=ansatz.parameters, interpret=parity, output_shape=2, quantum_instance=sv_qi, ) from qiskit.algorithms.optimizers import COBYLA from qiskit_machine_learning.algorithms import NeuralNetworkClassifier classifier = NeuralNetworkClassifier( neural_network=circuit_qnn, loss="cross_entropy", one_hot=True, optimizer=COBYLA(maxiter=40), initial_point=initial_point, ) classifier.fit(features, labels) classifier.score(features, labels) from qiskit.primitives import Sampler sampler = Sampler() from qiskit_machine_learning.neural_networks import SamplerQNN sampler_qnn = SamplerQNN( circuit=circuit, input_params=feature_map.parameters, weight_params=ansatz.parameters, interpret=parity, output_shape=2, sampler=sampler, ) classifier = NeuralNetworkClassifier( neural_network=sampler_qnn, loss="cross_entropy", one_hot=True, optimizer=COBYLA(maxiter=40), initial_point=initial_point, ) classifier.fit(features, labels) classifier.score(features, labels) import numpy as np num_samples = 20 eps = 0.2 lb, ub = -np.pi, np.pi features = (ub - lb) * np.random.rand(num_samples, 1) + lb labels = np.sin(features[:, 0]) + eps * (2 * np.random.rand(num_samples) - 1) from qiskit.circuit import Parameter num_inputs = 1 feature_map = QuantumCircuit(1) feature_map.ry(Parameter("input"), 0) ansatz = QuantumCircuit(1) ansatz.ry(Parameter("weight"), 0) circuit = QuantumCircuit(num_inputs) circuit.compose(feature_map, inplace=True) circuit.compose(ansatz, inplace=True) initial_point = algorithm_globals.random.random(ansatz.num_parameters) from qiskit.opflow import PauliSumOp, StateFn from qiskit_machine_learning.neural_networks import OpflowQNN observable = PauliSumOp.from_list([("Z", 1)]) operator = StateFn(observable, is_measurement=True) @ StateFn(circuit) opflow_qnn = OpflowQNN( operator=operator, input_params=feature_map.parameters, weight_params=ansatz.parameters, quantum_instance=sv_qi, ) from qiskit.algorithms.optimizers import L_BFGS_B from qiskit_machine_learning.algorithms import NeuralNetworkRegressor regressor = NeuralNetworkRegressor( neural_network=opflow_qnn, optimizer=L_BFGS_B(maxiter=5), initial_point=initial_point, ) regressor.fit(features, labels) regressor.score(features, labels) from qiskit.primitives import Estimator estimator = Estimator() from qiskit_machine_learning.neural_networks import EstimatorQNN estimator_qnn = EstimatorQNN( circuit=circuit, input_params=feature_map.parameters, weight_params=ansatz.parameters, estimator=estimator, ) from qiskit.algorithms.optimizers import L_BFGS_B from qiskit_machine_learning.algorithms import VQR regressor = NeuralNetworkRegressor( neural_network=estimator_qnn, optimizer=L_BFGS_B(maxiter=5), initial_point=initial_point, ) regressor.fit(features, labels) regressor.score(features, labels) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/dkp-quantum/Tutorials
dkp-quantum
import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) import qiskit as qk qr0 = qk.QuantumRegister(1,name='qb') # qb for "qubit", but the name is optional cr0 = qk.ClassicalRegister(1,name='b') # b for "bit", but the name is optional qc0 = qk.QuantumCircuit(qr0,cr0) qc0.draw(output='mpl') # this is to visualize the circuit. Remove the output option for a different style. from qiskit.tools.visualization import plot_bloch_vector import math theta = math.pi/2 # You can try to change the parameters theta and phi phi = math.pi/4 # to see how the vector moves on the sphere plot_bloch_vector([math.cos(phi)*math.sin(theta),math.sin(phi)*math.sin(theta),math.cos(theta)]) # Entries of the # input vector are # coordinates [x,y,z] qc0.measure(qr0[0],cr0[0]) qc0.draw(output='mpl') backend = qk.Aer.get_backend('qasm_simulator') job = qk.execute(qc0, backend, shots=1024) result = job.result() counts = result.get_counts() print(counts) qc1 = qk.QuantumCircuit(qr0,cr0) qc1.x(qr0[0]) # A X gate targeting the first (and only) qubit in register qr0 qc1.measure(qr0[0],cr0[0]) qc1.draw(output='mpl') backend = qk.Aer.get_backend('qasm_simulator') job1 = qk.execute(qc1, backend, shots=1024) result1 = job1.result() counts1 = result1.get_counts() print(counts1) from qiskit.tools.visualization import plot_bloch_multivector vec_backend = qk.Aer.get_backend('statevector_simulator') result_vec0 = qk.execute(qc0, vec_backend).result() result_vec1 = qk.execute(qc1, vec_backend).result() psi0 = result_vec0.get_statevector() psi1 = result_vec1.get_statevector() plot_bloch_multivector(psi0) plot_bloch_multivector(psi1) qc2 = qk.QuantumCircuit(qr0,cr0) qc2.h(qr0[0]) qc2.measure(qr0[0],cr0[0]) qc2.draw(output='mpl') job2 = qk.execute(qc2, backend, shots=1024) result2 = job2.result() counts2 = result2.get_counts() print(counts2) qc2_bis = qk.QuantumCircuit(qr0,cr0) qc2_bis.h(qr0[0]) result_vec2 = qk.execute(qc2_bis, vec_backend).result() psi2 = result_vec2.get_statevector() plot_bloch_multivector(psi2) qc3 = qk.QuantumCircuit(qr0,cr0) qc3.h(qr0[0]) qc3.s(qr0[0]) # Use sdg instead of s for the adjoint qc3.measure(qr0[0],cr0[0]) qc3.draw(output='mpl') job3 = qk.execute(qc3, backend, shots=1024) result3 = job3.result() counts3 = result3.get_counts() print(counts3) qc3_bis = qk.QuantumCircuit(qr0,cr0) qc3_bis.h(qr0[0]) qc3_bis.s(qr0[0]) result_vec3 = qk.execute(qc3_bis, vec_backend).result() psi3 = result_vec3.get_statevector() plot_bloch_multivector(psi3) qc4 = qk.QuantumCircuit(qr0,cr0) qc4.h(qr0[0]) qc4.t(qr0[0]) # Use tdg instead of t for the adjoint qc4.measure(qr0[0],cr0[0]) qc4.draw(output='mpl') job4 = qk.execute(qc4, backend, shots=1024) result4 = job4.result() counts4 = result4.get_counts() print(counts4) qc4_bis = qk.QuantumCircuit(qr0,cr0) qc4_bis.h(qr0[0]) qc4_bis.t(qr0[0]) result_vec4 = qk.execute(qc4_bis, vec_backend).result() psi4 = result_vec4.get_statevector() plot_bloch_multivector(psi4) lmbd = 1.2 # Change this value to rotate the output vector on the equator of the Bloch sphere qc5 = qk.QuantumCircuit(qr0,cr0) qc5.h(qr0[0]) qc5.u1(lmbd, qr0[0]) qc5.draw(output='mpl') result_vec5 = qk.execute(qc5, vec_backend).result() psi5 = result_vec5.get_statevector() plot_bloch_multivector(psi5) qc6 = qk.QuantumCircuit(qr0,cr0) qc6.u2(0,math.pi, qr0[0]) result_vec6 = qk.execute(qc6, vec_backend).result() psi6 = result_vec6.get_statevector() plot_bloch_multivector(psi6) theta = 0.5 phi = math.pi/4 lmb = math.pi/8 qc7 = qk.QuantumCircuit(qr0,cr0) qc7.u3(theta,phi, lmb, qr0[0]) result_vec7 = qk.execute(qc7, vec_backend).result() psi7 = result_vec7.get_statevector() plot_bloch_multivector(psi7) qr = qk.QuantumRegister(2,name='qr') # we need a 2-qubit register now cr = qk.ClassicalRegister(2,name='cr') cnot_example = qk.QuantumCircuit(qr,cr) cnot_example.x(qr[0]) cnot_example.cx(qr[0],qr[1]) # First entry is control, the second is the target cnot_example.measure(qr[0],cr[0]) cnot_example.measure(qr[1],cr[1]) cnot_example.draw(output='mpl') job_cnot = qk.execute(cnot_example, backend, shots=1024) result_cnot = job_cnot.result() counts_cnot = result_cnot.get_counts() print(counts_cnot) cnot_reversed = qk.QuantumCircuit(qr,cr) cnot_reversed.x(qr[0]) # This part uses cx(qr[1],qr[0]) but is equivalent to cx(qr[0],qr[1]) cnot_reversed.h(qr[0]) cnot_reversed.h(qr[1]) cnot_reversed.cx(qr[1],qr[0]) cnot_reversed.h(qr[0]) cnot_reversed.h(qr[1]) # cnot_reversed.measure(qr[0],cr[0]) cnot_reversed.measure(qr[1],cr[1]) cnot_reversed.draw(output='mpl') job_cnot_rev = qk.execute(cnot_reversed, backend, shots=1024) result_cnot_rev = job_cnot_rev.result() counts_cnot_rev = result_cnot_rev.get_counts() print(counts_cnot_rev) bell_phi_p = qk.QuantumCircuit(qr,cr) bell_phi_p.h(qr[0]) bell_phi_p.cx(qr[0],qr[1]) bell_phi_p.measure(qr[0],cr[0]) bell_phi_p.measure(qr[1],cr[1]) bell_phi_p.draw(output='mpl') job_bell_phi_p = qk.execute(bell_phi_p, backend, shots=1024) result_bell_phi_p = job_bell_phi_p.result() counts_bell_phi_p = result_bell_phi_p.get_counts() print(counts_bell_phi_p) cz_example = qk.QuantumCircuit(qr) cz_example.cz(qr[0],qr[1]) cz_example.draw(output='mpl') cz_from_cnot = qk.QuantumCircuit(qr) cz_from_cnot.h(qr[1]) cz_from_cnot.cx(qr[0],qr[1]) cz_from_cnot.h(qr[1]) cz_from_cnot.draw(output='mpl') delta = 0.5 cphase_test = qk.QuantumCircuit(qr) cphase_test.cu1(delta,qr[0],qr[1]) cphase_test.draw(output='mpl') delta = 0.5 cphase_from_cnot = qk.QuantumCircuit(qr) cphase_from_cnot.u1(delta/2,qr[1]) cphase_from_cnot.cx(qr[0],qr[1]) cphase_from_cnot.u1(-delta/2,qr[1]) cphase_from_cnot.cx(qr[0],qr[1]) cphase_from_cnot.u1(delta/2,qr[0]) cphase_from_cnot.draw(output='mpl') swap_test = qk.QuantumCircuit(qr) swap_test.swap(qr[0],qr[1]) swap_test.draw(output='mpl') swap_from_cnot = qk.QuantumCircuit(qr) swap_from_cnot.cx(qr[0],qr[1]) swap_from_cnot.cx(qr[1],qr[0]) swap_from_cnot.cx(qr[0],qr[1]) swap_from_cnot.draw(output='mpl') qr_many = qk.QuantumRegister(5) control_example = qk.QuantumCircuit(qr_many) control_example.cy(qr_many[0],qr_many[1]) control_example.ch(qr_many[1],qr_many[2]) control_example.crz(0.2,qr_many[2],qr_many[3]) control_example.cu3(0.5, 0, 0, qr_many[3],qr_many[4]) control_example.draw(output='mpl') qrthree = qk.QuantumRegister(3) toffoli_example = qk.QuantumCircuit(qrthree) toffoli_example.ccx(qrthree[0],qrthree[1],qrthree[2]) toffoli_example.draw(output='mpl') toffoli_from_cnot = qk.QuantumCircuit(qrthree) toffoli_from_cnot.h(qrthree[2]) toffoli_from_cnot.cx(qrthree[1],qrthree[2]) toffoli_from_cnot.tdg(qrthree[2]) toffoli_from_cnot.cx(qrthree[0],qrthree[2]) toffoli_from_cnot.t(qrthree[2]) toffoli_from_cnot.cx(qrthree[1],qrthree[2]) toffoli_from_cnot.tdg(qrthree[2]) toffoli_from_cnot.cx(qrthree[0],qrthree[2]) toffoli_from_cnot.tdg(qrthree[1]) toffoli_from_cnot.t(qrthree[2]) toffoli_from_cnot.h(qrthree[2]) toffoli_from_cnot.cx(qrthree[0],qrthree[1]) toffoli_from_cnot.tdg(qrthree[1]) toffoli_from_cnot.cx(qrthree[0],qrthree[1]) toffoli_from_cnot.s(qrthree[1]) toffoli_from_cnot.t(qrthree[0]) toffoli_from_cnot.draw(output='mpl') crsingle = qk.ClassicalRegister(1) deutsch = qk.QuantumCircuit(qr,crsingle) deutsch.x(qr[1]) deutsch.h(qr[1]) deutsch.draw(output='mpl') deutsch.h(qr[0]) deutsch.draw(output='mpl') deutsch.cx(qr[0],qr[1]) deutsch.h(qr[0]) deutsch.measure(qr[0],crsingle[0]) deutsch.draw(output='mpl') N = 4 qrQFT = qk.QuantumRegister(N,'qftr') QFT = qk.QuantumCircuit(qrQFT) for i in range(N): QFT.h(qrQFT[i]) for k in range(i+1,N): l = k-i+1 QFT.cu1(2*math.pi/(2**l),qrQFT[k],qrQFT[i]) QFT.draw(output='mpl')
https://github.com/filipecorrea/deutsch-jozsa
filipecorrea
import numpy as np import qiskit from qiskit import IBMQ, BasicAer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, execute from qiskit.visualization import plot_histogram qiskit.__qiskit_version__ # set the length of the n-bit input string n = 3 balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) balanced_oracle.draw(output='mpl') balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() balanced_oracle.draw(output='mpl') balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Show oracle balanced_oracle.draw(output='mpl') dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) dj_circuit.draw(output='mpl') dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit += balanced_oracle dj_circuit.draw(output='mpl') dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit += balanced_oracle # Repeat H-gates for qubit in range(n): dj_circuit.h(qubit) dj_circuit.barrier() # Measure for i in range(n): dj_circuit.measure(i, i) # Display circuit dj_circuit.draw(output='mpl') # use local simulator backend = BasicAer.get_backend('qasm_simulator') shots = 1024 results = execute(dj_circuit, backend=backend, shots=shots).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeBoeblingen backend = FakeBoeblingen() ghz = QuantumCircuit(5) ghz.h(0) ghz.cx(0,range(1,5)) circ = transpile(ghz, backend, scheduling_method="asap") circ.draw(output='mpl')
https://github.com/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/1ucian0/qiskit-openqasm2
1ucian0
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Created on Wed Mar 11 18:03:12 2020 Support via qiskit.qasm for functional interface to Qasm2 source loading and exporting in functions.py @author: jax """ # from importlib import import_module # from os import linesep # from typing import List from qiskit import QuantumCircuit # , QiskitError from qiskit.converters import ast_to_dag from qiskit.converters import dag_to_circuit from qiskit_openqasm2 import Qasm def qasm_load(qasm: Qasm) -> QuantumCircuit: """ Factory OpenQASM src into QuantumCircuit using qiskit.qasm code. Parameters ---------- qasm : Qasm The Qasm object of source to load. Returns ------- QuantumCircuit The resulting QuantumCircuit. """ ast = qasm.parse() dag = ast_to_dag(ast) return dag_to_circuit(dag) def qasm_export(qc: QuantumCircuit) -> str: """ Return OpenQASM string using qiskit.qasm code. Parameters ---------- qc : QuantumCircuit The circuit to be disassembled into OpenQASM source Returns ------- str OpenQASM source for the circuit. """ string_temp = qc.header + "\n" string_temp += qc.extension_lib + "\n" for register in qc.qregs: string_temp += register.qasm() + "\n" for register in qc.cregs: string_temp += register.qasm() + "\n" unitary_gates = [] for instruction, qargs, cargs in qc._data: if instruction.name == 'measure': qubit = qargs[0] clbit = cargs[0] string_temp += "%s %s[%d] -> %s[%d];\n" % (instruction.qasm(), qubit.register.name, qubit.index, clbit.register.name, clbit.index) else: string_temp += "%s %s;\n" % (instruction.qasm(), ",".join(["%s[%d]" % (j.register.name, j.index) for j in qargs + cargs])) if instruction.name == 'unitary': unitary_gates.append(instruction) # this resets them, so if another call to qasm() is made the gate def is added again for gate in unitary_gates: gate._qasm_def_written = False return string_temp
https://github.com/TheGupta2012/QPE-Algorithms
TheGupta2012
error = 0.002 thresholds, targets = [], [] while error < 0.4: thresholds.append(error) targets.append(round(1-error, 3)) error *= 2 print("Threshold :", thresholds) print("Target costs :", targets) from qiskit import IBMQ from qiskit import QuantumCircuit, execute, transpile, Aer from qiskit.extensions import UnitaryGate, Initialize from qiskit.quantum_info import Statevector from qiskit.tools.visualization import plot_bloch_vector from qiskit.tools.visualization import plot_histogram, plot_bloch_multivector import numpy as np from time import sleep import sys sys.path.append("../..") import os from scipy.stats import unitary_group import matplotlib.pyplot as plt %matplotlib inline IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-education') # santiago = provider.get_backend('ibmq_santiago') # casablanca = provider.get_backend('ibmq_casablanca') # bogota = provider.get_backend('ibmq_bogota') sim = Aer.get_backend('qasm_simulator') # athens = provider.get_backend('ibmq_athens') from Modules.normal_SPEA import SPEA from Modules.changed_SPEA import global_max_SPEA def generate_plots(unitary_size, costs, overlaps, errors_eigen, errors_cost, algorithm): import random colors = ['red', 'brown', 'cyan', 'green', 'grey', 'blue', 'purple', 'black', 'orange'] c1, c2, c3, c4 = random.sample(colors, 4) # plot os.makedirs("Experiment_3/"+str(unitary_size) + "_qubit(random)/", exist_ok=True) # plot 1 fig = plt.figure(figsize=(13, 6)) ax1 = fig.add_subplot(1, 2, 1) ax1.set_title(str(unitary_size)+" qubit "+algorithm + " Cost vs Error threshold", fontsize=16) ax1.set_xlabel("Target costs ", fontsize=15) ax1.set_ylabel("Metrics Returned for unitary ", fontsize=15) # plot metrics ax1.plot(targets, costs, label='Costs of Unitary', marker='o', color=c1, alpha=0.7) ax1.plot(targets, overlaps, label='Average overlap from nearest eigenvector', marker='s', color=c2, alpha=0.6) ax1.plot() ax1.legend(loc='best') ax1.grid() # plot 2 ax2 = fig.add_subplot(1, 2, 2) ax2.set_title(str(unitary_size)+" qubit "+algorithm + " % Errors v/s thresholds", fontsize=16) ax2.set_xlabel("Target Costs", fontsize=15) ax2.set_ylabel("% errors", fontsize=15) # plot errors ax2.plot(targets, errors_eigen, label='Average error from nearest eigenvalue', marker='o', color=c3, alpha=0.6) ax2.plot(targets, errors_cost, label='Average deviation from desired cost', marker='s', color=c4, alpha=0.7) ax2.legend(loc='best') ax2.grid() # save axure fig.savefig("Experiment_3/"+str(unitary_size)+"_qubit(random)/" + algorithm+" Algorithm (alternate).JPG", dpi=200) def get_results(eig_vals, eig_vect, bases, basis_indices, unitary, algorithm, experiments): '''Return the results of running the algorithm for this particular unitary matrix''' costs_g = [] errors_eig_g = [] max_overlaps_g = [] errors_costs_g = [] # find how the cost converges with increasing iterations for error, target in zip(thresholds, targets): costs = [] errors_eig = [] errors_costs = [] overlaps = [] i = 0 # run the experiments ... while len(costs) < experiments: if algorithm == 'original': spea = SPEA(unitary, resolution=30, max_iters=10) else: spea = global_max_SPEA(unitary, resolution=30, max_iters=10) result = spea.get_eigen_pair( progress=False, backend=sim, target_cost=target, basis=bases[i], basis_ind=basis_indices[i], algo='alternate', randomize=False,shots=256) # results theta = result['theta'] res_state = result['state'] # get the results if result['cost'] < 0.75: continue i+=1 # find the abs difference in this theta with the closest eigenvalue # and append that to the errors ... min_error = 1e5 for e in eig_vals: error = abs(e - theta) if error < min_error: min_error = error perc_error = ((error)/e)*100 # get costs costs.append(result['cost']) # get eigenvalue error errors_eig.append(perc_error) # append the perc error from original target cost if target >= result['cost']: deviation = abs(target - result['cost'])/(target) else: # if we have stopped with a better cost, no sense of deviation deviation = 0 errors_costs.append(deviation*100) # find overlaps max_overlap = -1 for k in eig_vect: dot = np.linalg.norm(np.dot(k, res_state.conjugate().T))**2 max_overlap = max(max_overlap, dot) overlaps.append(max_overlap) print(costs, errors_costs) print("Result with", target, " target cost :") print("AVG. COST :", np.average(costs)) print("AVG. EIGENVALUE ERROR :", np.average(errors_eig)) print("AVG. DEVIATION FROM TARGET COST", np.average(errors_costs)) # append the average result of your algorithm ... costs_g.append(np.average(costs)) errors_eig_g.append(np.average(errors_eig)) errors_costs_g.append(np.average(errors_costs)) max_overlaps_g.append(np.average(overlaps)) return costs_g, errors_eig_g, errors_costs_g, max_overlaps_g unit_2 = unitary_group.rvs(4) unit_2 eig_vals2, eig_vect2 = np.linalg.eig(unit_2) eig_vals2 = np.angle(eig_vals2) e = [] for k in eig_vals2: if k < 0: v = (k + 2*np.pi)/(2*np.pi) else: v = (k)/(2*np.pi) e.append(v) eig_vals2 = np.array(e) print("Eigenstates :", eig_vect2) print("Eigenvalues :", eig_vals2) bases2 , basis_indices2 = [], [] for _ in range(4): sample = unitary_group.rvs(4) basis = [] for k in sample: basis.append(np.array(k, dtype=complex)) ind = np.random.choice(range(4)) bases2.append(basis) basis_indices2.append(ind) print("Basis set :",bases2) print("Basis indices :",basis_indices2) costs_2qubit_b, errors_eig_2qubit_b, errors_costs_2qubit_b, max_overlaps_2qubit_b = get_results( eig_vals2, eig_vect2, bases2, basis_indices2, unit_2, 'original', 4) generate_plots(2, costs_2qubit_b, max_overlaps_2qubit_b, errors_eig_2qubit_b, errors_costs_2qubit_b, "Original") costs_2qubit_c, errors_eig_2qubit_c, errors_costs_2qubit_c, max_overlaps_2qubit_c = get_results( eig_vals2, eig_vect2, bases2, basis_indices2, unit_2, 'modified', 4) generate_plots(2, costs_2qubit_c, max_overlaps_2qubit_c, errors_eig_2qubit_c, errors_costs_2qubit_c, "Modified") unit_3 = unitary_group.rvs(8) eig_vals3, eig_vect3 = np.linalg.eig(unit_3) eig_vals3 = np.angle(eig_vals3) e = [] for k in eig_vals3: if k < 0: v = (k + 2*np.pi)/(2*np.pi) else: v = (k)/(2*np.pi) e.append(v) eig_vals3 = np.array(e) print("Eigenstates :", eig_vect3) print("Eigenvalues :", eig_vals3) bases3 , basis_indices3 = [], [] for _ in range(4): sample = unitary_group.rvs(8) basis = [] for k in sample: basis.append(np.array(k, dtype=complex)) ind = np.random.choice(range(8)) bases3.append(basis) basis_indices3.append(ind) print("Basis indices :",basis_indices3) costs_3qubit_b, errors_eig_3qubit_b, errors_costs_3qubit_b, max_overlaps_3qubit_b = get_results( eig_vals3, eig_vect3, bases3, basis_indices3, unit_3, 'original', 4) generate_plots(3, costs_3qubit_b, max_overlaps_3qubit_b, errors_eig_3qubit_b, errors_costs_3qubit_b, "Original") costs_3qubit_c, errors_eig_3qubit_c, errors_costs_3qubit_c, max_overlaps_3qubit_c = get_results( eig_vals3, eig_vect3, bases3, basis_indices3, unit_3, 'modified', 4) generate_plots(3, costs_3qubit_c, max_overlaps_3qubit_c, errors_eig_3qubit_c, errors_costs_3qubit_c, "Modified") unit_4 = unitary_group.rvs(16) # unit_4 eig_vals4, eig_vect4 = np.linalg.eig(unit_4) eig_vals4 = np.angle(eig_vals4) e = [] for k in eig_vals4: if k < 0: v = (k + 2*np.pi)/(2*np.pi) else: v = (k)/(2*np.pi) e.append(v) eig_vals4 = np.array(e) print("Eigenstates :", eig_vect4) print("Eigenvalues :", eig_vals4) bases4 , basis_indices4 = [], [] for _ in range(4): sample = unitary_group.rvs(16) basis = [] for k in sample: basis.append(np.array(k, dtype=complex)) ind = np.random.choice(range(16)) bases4.append(basis) basis_indices4.append(ind) print("Basis indices :",basis_indices4) costs_4qubit_b, errors_eig_4qubit_b, errors_costs_4qubit_b, max_overlaps_4qubit_b = get_results( eig_vals4, eig_vect4, bases4, basis_indices4, unit_4, 'original', 4) generate_plots(4, costs_4qubit_b, max_overlaps_4qubit_b, errors_eig_4qubit_b, errors_costs_4qubit_b, "Original") costs_4qubit_c, errors_eig_4qubit_c, errors_costs_4qubit_c, max_overlaps_4qubit_c = get_results( eig_vals4, eig_vect4, bases4, basis_indices4, unit_4, 'modified', 4) generate_plots(4, costs_4qubit_c, max_overlaps_4qubit_c, errors_eig_4qubit_c, errors_costs_4qubit_c, "Modified")
https://github.com/mickahell/quantum_pokemon-fight
mickahell
from train.robot_vs_robot import team, battle from stats.gen_data import gen_unity_data from src.class_custom.attacks import Attack from src.class_custom.player import Player from src.class_custom.pokemon import Pokemon from src.class_custom.type import Type from qiskit import Aer, QuantumCircuit, QuantumRegister import warnings class Unity: def __init__(self): warnings.filterwarnings("ignore", category=DeprecationWarning) # Init Qasm simulator backend qasm = Aer.get_backend("qasm_simulator") backend_sim = qasm # Choose your backend : <quantum_computer> or <qasm> for u in range(2): # Types creation --> Sources : https://boutique-pokemon.com/blogs/blog-pokemon/table-types-pokemon fire = Type("Fire") normal = Type("Normal") water = Type("Water") grass = Type("Grass") electric = Type("Electric") fly = Type("Fly") poison = Type("Poison") bug = Type("Bug") ghost = Type("Ghost") ground = Type("Ground") dark = Type("Dark") ice = Type("Ice") steel = Type("Steel") resistance = [bug, grass, fire, ice, steel] weakness = [water, ground] imunite = ["None"] fire.add_info(resistance, weakness, imunite) resistance = ["None"] weakness = ["None"] imunite = [ghost] normal.add_info(resistance, weakness, imunite) resistance = [grass, ground] weakness = [fire, fly] imunite = ["None"] bug.add_info(resistance, weakness, imunite) resistance = [water, fire, steel] weakness = [grass, electric] imunite = ["None"] water.add_info(resistance, weakness, imunite) resistance = [water, electric, grass, ground] weakness = [fire, bug, poison, fly, ice] imunite = ["None"] grass.add_info(resistance, weakness, imunite) resistance = [electric, fly, steel] weakness = [ground] imunite = ["None"] electric.add_info(resistance, weakness, imunite) resistance = [bug, grass] weakness = [electric, ice] imunite = [ground] fly.add_info(resistance, weakness, imunite) resistance = [ghost, dark] weakness = [bug] imunite = ["None"] dark.add_info(resistance, weakness, imunite) resistance = [bug, poison] weakness = [ghost, dark] imunite = [normal] ghost.add_info(resistance, weakness, imunite) resistance = [bug, grass, poison] weakness = [ground] imunite = ["None"] poison.add_info(resistance, weakness, imunite) resistance = [poison] weakness = [water, grass, ice] imunite = [electric] ground.add_info(resistance, weakness, imunite) resistance = [ice] weakness = [fire, steel] imunite = ["None"] ice.add_info(resistance, weakness, imunite) resistance = [steel, ice, bug, normal, grass, fly] weakness = [fire, ground] imunite = [poison] steel.add_info(resistance, weakness, imunite) # type qubits creation fire.qubit = QuantumRegister(1, "fire") normal.qubit = QuantumRegister(1, "normal") water.qubit = QuantumRegister(1, "water") grass.qubit = QuantumRegister(1, "grass") electric.qubit = QuantumRegister(1, "electric") fly.qubit = QuantumRegister(1, "fly") poison.qubit = QuantumRegister(1, "poison") bug.qubit = QuantumRegister(1, "bug") ghost.qubit = QuantumRegister(1, "ghost") ground.qubit = QuantumRegister(1, "ground") dark.qubit = QuantumRegister(1, "dark") ice.qubit = QuantumRegister(1, "ice") steel.qubit = QuantumRegister(1, "steel") qc_type = QuantumCircuit( steel.qubit, fire.qubit, normal.qubit, water.qubit, grass.qubit, electric.qubit, fly.qubit, poison.qubit, bug.qubit, ghost.qubit, ground.qubit, dark.qubit, ice.qubit, ) # Attacks creation fire_blast = Attack("Fire Blast", fire, 110, 0.85, "special") hurricane = Attack("Hurricane", fly, 110, 0.70, "special") earthquake = Attack("Earthquake", ground, 100, 1, "physical") leaf_storm = Attack("Leaf Storm", grass, 90, 1, "special") shadow_ball = Attack("Shadow Ball", ghost, 80, 1, "special") sludge_bomb = Attack("Sludge Bomb", poison, 90, 1, "special") thunder = Attack("Thunder", electric, 110, 0.70, "special") dark_pulse = Attack("Dark Pulse", dark, 80, 1, "special") ice_beam = Attack("Ice Beam", ice, 90, 1, "special") hydroblast = Attack("Hydroblast", water, 110, 0.8, "special") iron_tail = Attack("Iron Tail", steel, 100, 0.75, "physical") slam = Attack("Slam", normal, 80, 0.75, "physical") grass_knot = Attack("Grass Knot", grass, 80, 1, "special") flash_cannon = Attack("Flash Cannon", steel, 80, 1, "special") giga_impact = Attack("Giga-Impact", normal, 150, 0.9, "physical") bite = Attack("Bite", dark, 60, 1, "physical") tri_attack = Attack("Triplattaque", normal, 80, 1, "special") #hyper_beam = Attack("Hyper Beam", normal, 150, 0.9, "special") throat_chop = Attack("Throat Chop", dark, 80, 1, "physical") fire_punch = Attack("Fire Punch", fire, 75, 1, "physical") # Pokémon creation --> Sources : https://www.pokepedia.fr/Pikachu#Statistiques-remarques1 charizard = Pokemon("Charizard", [fire, fly], 360, 267, 255, 317, 269, 299) gengar = Pokemon("Gengar", [ghost, poison], 324, 229, 219, 359, 249, 319) blastoise = Pokemon("Blastoise", [water], 362, 265, 299, 269, 309, 255) pikachu = Pokemon("Pikachu", [electric], 294, 259, 199, 249, 219, 339) glaceon = Pokemon("Glaceon", [ice], 334, 219, 319, 359, 289, 229) porygonz = Pokemon("Porygon-Z", [normal], 374, 259, 239, 369, 249, 279) abomasnow = Pokemon("Abomasnow", [grass, ice], 384, 283, 249, 283, 269, 219) toxtricity = Pokemon( "Toxtricity", [electric, poison], 354, 295, 239, 327, 239, 249 ) # Attacks learning charizard.learn_attacks([fire_blast, hurricane, earthquake, leaf_storm]) gengar.learn_attacks([sludge_bomb, dark_pulse, shadow_ball, thunder]) blastoise.learn_attacks([ice_beam, hydroblast, flash_cannon, giga_impact]) pikachu.learn_attacks([thunder, iron_tail, slam, grass_knot]) glaceon.learn_attacks([ice_beam, slam, iron_tail, bite]) porygonz.learn_attacks([thunder, ice_beam, tri_attack, dark_pulse]) abomasnow.learn_attacks([ice_beam, leaf_storm, earthquake, giga_impact]) toxtricity.learn_attacks([sludge_bomb, thunder, throat_chop, fire_punch]) # Player creation me = Player("Oak", "j1", "human") him = Player("Agatha", "j2", "robot") ############################################################## # GAME print( """ ################################################### # Welcome in the Quantum Pokémon fight - CLI # Will you succeed to win against the Quantum AI ? # # Good Luck !!! ################################################### """ ) team(me, him, nb_team=1) winner, looser = battle(me, him, qc_type, backend_sim) for i, y in zip(winner.register_team, looser.register_team): gen_unity_data(winner=i, looser=y) print("Fight {} is finished !".format(u + 1)) print("Gen team data program ended !")
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
import numpy as np def cnot_matrix_ab(d): cn = np.zeros((d**2,d**2),dtype=int) for p in range(0,d): # d^2 elementos não nulos for q in range(0,d): cn[p*d+(p+q)%d,p*d+q] = 1 return cn d=2; cn = cnot_matrix_ab(d); print(cn) d=3; cn = cnot_matrix_ab(d); print(cn) d=4; cn = cnot_matrix_ab(d); print(cn) import numpy as np def cnot_matrix(d, ctr): cn = np.zeros((d**2,d**2),dtype=int) if ctr == 'a': for p in range(0,d): for q in range(0,d): cn[p*d+(p+q)%d,p*d+q] = 1 elif ctr == 'b': for p in range(0,d): for q in range(0,d): cn[((q+p)%d)*d+q,p*d+q] = 1 return cn d=2; print(cnot_matrix(d, 'b')) # ok! d=3; print(cnot_matrix(d, 'b')) def den2dec(local,d): # local = list with the local computational base state values # d = individual qudit dimension N = len(local) j = 0 for k in range(0,N): j += local[k]*d**(N-1-k) return j # value of the global computational basis index # example: 3 qutrits d = 3; N = 3 local = [0,0,0] for j0 in range(0,3): for j1 in range(0,3): for j2 in range(0,3): local = [j0,j1,j2] j = den2dec(local,d) print('j0 j1 j2 =',j0,j1,j2,', j =',j) def dec2den(j,N,d): den = [0 for k in range(0,N)] jv = j for k in range(0,N): if jv >= d**(N-1-k): den[k] = jv//(d**(N-1-k)) jv = jv - den[k]*d**(N-1-k) return den N = 3; d = 3 for j in range(0,d**N): print('j=',j,', den=', dec2den(j,N,d)) def dec2den_opt(j,N,d): # optmized version den = [0 for k in range(0,N)] if j < d: den[N-1] = j; return den rem = [] # list for the remainders k = j while k >= d: rem.append(k%d) k = k//d rem.append(k%d) for j in range(0,len(rem)): den[N-1-j] = rem[j] return den N = 3; d = 3 for j in range(0,d**N): print('j=',j,', den=', dec2den_opt(j,N,d)) def cnot_qudits(d,N,t,c): # d = qudit dimension; N = No. of qudits; t = target qudit (0,...,N-1); c = control qudit (0,...,N-1) D = d**N; cnot = np.zeros((D,D), dtype=int) # set all d^2N elements to 0 for k in range (0,d**N): localr = dec2den_opt(k,N,d) # sequence os values for the local basis locall = localr.copy() # copy the right list to the left list locall[t] = (localr[t]+localr[c])%d globall = den2dec(locall,d) cnot[globall,k] = 1 return cnot d=2; N=2; t=1; c=0; cnot = cnot_qudits(d,N,t,c); print(cnot) # ok! d=2; N=2; t=0; c=1; cnot = cnot_qudits(d,N,t,c); print(cnot) # ok! d=3; N=2; t=1; c=0; cnot = cnot_qudits(d,N,t,c); print(cnot) # ok! d=2; N=3; t=2; c=0; cnot = cnot_qudits(d,N,t,c); print(cnot) # ok from sympy import init_printing, Matrix init_printing(use_unicode=True) from sympy.physics.quantum import TensorProduct def tp(x,y): return TensorProduct(x,y) s1 = Matrix([[0,1],[1,0]]); s0 = Matrix([[1,0],[0,1]]); P0 = Matrix([[1,0],[0,0]]); P1 = Matrix([[0,0],[0,1]]) cnot03 = tp(tp(P0,s0),s0) + tp(tp(P1,s0),s1); cnot03 d=3; N=3; t=1; c=0; cnot = cnot_qudits(d,N,t,c); print(cnot) # ok
https://github.com/alpine-quantum-technologies/qiskit-aqt-provider-rc
alpine-quantum-technologies
# This code is part of Qiskit. # # (C) Copyright IBM 2019, Alpine Quantum Technologies GmbH 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import warnings from dataclasses import dataclass from typing import ( TYPE_CHECKING, Any, Dict, List, Literal, Optional, Type, TypeVar, Union, ) from uuid import UUID from qiskit import QuantumCircuit from qiskit.circuit.library import RXGate, RXXGate, RZGate from qiskit.circuit.measure import Measure from qiskit.circuit.parameter import Parameter from qiskit.providers import BackendV2 as Backend from qiskit.providers import Options as QiskitOptions from qiskit.providers.models import BackendConfiguration from qiskit.transpiler import Target from qiskit_aer import AerJob, AerSimulator, noise from qiskit_aqt_provider import api_models from qiskit_aqt_provider.aqt_job import AQTJob from qiskit_aqt_provider.aqt_options import AQTOptions from qiskit_aqt_provider.circuit_to_aqt import circuits_to_aqt_job if TYPE_CHECKING: # pragma: no cover from qiskit_aqt_provider.aqt_provider import AQTProvider TargetT = TypeVar("TargetT", bound=Target) def make_transpiler_target(target_cls: Type[TargetT], num_qubits: int) -> TargetT: """Factory for transpilation targets of AQT resources. Args: target_cls: base class to use for the returned instance num_qubits: maximum number of qubits supported by the resource. Returns: A Qiskit transpilation target for an AQT resource. """ target: TargetT = target_cls(num_qubits=num_qubits) theta = Parameter("θ") lam = Parameter("λ") # configure the transpiler to use RX/RZ/RXX # the custom scheduling pass rewrites RX to R to comply to the Arnica API format. target.add_instruction(RZGate(lam)) target.add_instruction(RXGate(theta)) target.add_instruction(RXXGate(theta)) target.add_instruction(Measure()) return target class AQTResource(Backend): def __init__( self, provider: "AQTProvider", *, workspace_id: str, resource_id: str, resource_name: str, resource_type: Literal["device", "simulator", "offline_simulator"], ): super().__init__(name=resource_id, provider=provider) self.resource_id = resource_id self.resource_name = resource_name self.resource_type = resource_type self.workspace_id = workspace_id self._http_client = provider._http_client num_qubits = 20 self._configuration = BackendConfiguration.from_dict( { "backend_name": resource_name, "backend_version": 2, "url": provider.portal_url, "simulator": True, "local": False, "coupling_map": None, "description": "AQT trapped-ion device simulator", "basis_gates": ["r", "rz", "rxx"], # the actual basis gates "memory": True, "n_qubits": num_qubits, "conditional": False, "max_shots": 200, "max_experiments": 1, "open_pulse": False, "gates": [ {"name": "rz", "parameters": ["theta"], "qasm_def": "TODO"}, {"name": "r", "parameters": ["theta", "phi"], "qasm_def": "TODO"}, {"name": "rxx", "parameters": ["theta"], "qasm_def": "TODO"}, ], } ) self._target = make_transpiler_target(Target, num_qubits) self._options = AQTOptions() def submit(self, circuits: List[QuantumCircuit], shots: int) -> UUID: """Submit a quantum circuits job to the AQT backend. Args: circuits: circuits to execute shots: number of repetitions per circuit. Returns: The unique identifier of the submitted job. """ payload = circuits_to_aqt_job(circuits, shots) resp = self._http_client.post( f"/submit/{self.workspace_id}/{self.resource_id}", json=payload.dict() ) resp.raise_for_status() return api_models.Response.parse_obj(resp.json()).job.job_id def result(self, job_id: UUID) -> api_models.JobResponse: """Query the result for a specific job. Parameters: job_id: The unique identifier for the target job. Returns: Full returned payload. """ resp = self._http_client.get(f"/result/{job_id}") resp.raise_for_status() return api_models.Response.parse_obj(resp.json()) def configuration(self) -> BackendConfiguration: warnings.warn( "The configuration() method is deprecated and will be removed in a " "future release. Instead you should access these attributes directly " "off the object or via the .target attribute. You can refer to qiskit " "backend interface transition guide for the exact changes: " "https://qiskit.org/documentation/apidoc/providers.html#backendv1-backendv2", DeprecationWarning, ) return self._configuration def properties(self) -> None: warnings.warn( # pragma: no cover "The properties() method is deprecated and will be removed in a " "future release. Instead you should access these attributes directly " "off the object or via the .target attribute. You can refer to qiskit " "backend interface transition guide for the exact changes: " "https://qiskit.org/documentation/apidoc/providers.html#backendv1-backendv2", DeprecationWarning, ) @property def max_circuits(self) -> int: return 2000 @property def target(self) -> Target: return self._target @classmethod def _default_options(cls) -> QiskitOptions: return QiskitOptions() @property def options(self) -> AQTOptions: return self._options def get_scheduling_stage_plugin(self) -> str: return "aqt" def get_translation_stage_plugin(self) -> str: return "aqt" def run(self, circuits: Union[QuantumCircuit, List[QuantumCircuit]], **options: Any) -> AQTJob: """Submit circuits for execution on this resource. Additional keywork arguments are treated as overrides for this resource's options. Keywords that are not valid options for this resource are ignored with a warning. Args: circuits: circuits to execute options: overrides for this resource's options. Returns: A job handle. """ if not isinstance(circuits, list): circuits = [circuits] valid_options = {key: value for key, value in options.items() if key in self.options} unknown_options = set(options) - set(valid_options) if unknown_options: for unknown_option in unknown_options: warnings.warn( f"Option {unknown_option} is not used by this backend", UserWarning, stacklevel=2, ) options_copy = self.options.copy() options_copy.update_options(**valid_options) job = AQTJob( self, circuits, options_copy, ) job.submit() return job def qubit_states_from_int(state: int, num_qubits: int) -> List[int]: """Convert the Qiskit state representation to the AQT states samples one. Args: state: Qiskit quantum register state representation num_qubits: number of qubits in the register. Returns: AQT qubit states representation. Raises: ValueError: the passed state is too large for the passed register size. Examples: >>> qubit_states_from_int(0, 3) [0, 0, 0] >>> qubit_states_from_int(0b11, 3) [1, 1, 0] >>> qubit_states_from_int(0b01, 3) [1, 0, 0] >>> qubit_states_from_int(123, 7) [1, 1, 0, 1, 1, 1, 1] >>> qubit_states_from_int(123, 3) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: Cannot represent state=123 on num_qubits=3. """ if state.bit_length() > num_qubits: raise ValueError(f"Cannot represent {state=} on {num_qubits=}.") return [(state >> qubit) & 1 for qubit in range(num_qubits)] @dataclass(frozen=True) class SimulatorJob: job: AerJob circuits: List[QuantumCircuit] shots: int @property def job_id(self) -> UUID: return UUID(hex=self.job.job_id()) class OfflineSimulatorResource(AQTResource): """AQT-compatible offline simulator resource that uses the Qiskit-Aer backend.""" def __init__( self, provider: "AQTProvider", *, workspace_id: str, resource_id: str, resource_name: str, noisy: bool, ) -> None: super().__init__( provider, workspace_id=workspace_id, resource_id=resource_id, resource_name=resource_name, resource_type="offline_simulator", ) self.job: Optional[SimulatorJob] = None if not noisy: noise_model = None else: # the transpiler lowers all operations to the gate set supported by the AQT API, # not to the resource target's one. noise_model = noise.NoiseModel(basis_gates=["r", "rz", "rxx"]) noise_model.add_all_qubit_quantum_error(noise.depolarizing_error(0.003, 1), ["r"]) noise_model.add_all_qubit_quantum_error(noise.depolarizing_error(0.01, 2), ["rxx"]) self.simulator = AerSimulator(method="statevector", noise_model=noise_model) @property def noisy(self) -> bool: return self.simulator.options.noise_model is not None def submit(self, circuits: List[QuantumCircuit], shots: int) -> UUID: """Submit circuits for execution on the simulator. Args: circuits: circuits to execute shots: number of repetitions per circuit. Returns: Unique identifier of the simulator job. """ self.job = SimulatorJob( job=self.simulator.run(circuits, shots=shots), circuits=circuits, shots=shots, ) return self.job.job_id def result(self, job_id: UUID) -> api_models.JobResponse: """Query results for a simulator job. Args: job_id: identifier of the job to retrieve results for. Returns: AQT API payload with the job results. Raises: UnknownJobError: the passed identifier doesn't correspond to a simulator job on this resource. """ if self.job is None or job_id != self.job.job_id: raise api_models.UnknownJobError(str(job_id)) qiskit_result = self.job.job.result() results: Dict[str, List[List[int]]] = {} for circuit_index, circuit in enumerate(self.job.circuits): samples: List[List[int]] = [] # Use data()["counts"] instead of get_counts() to access the raw counts # instead of the classical memory-mapped ones. counts: Dict[str, int] = qiskit_result.data(circuit_index)["counts"] for hex_state, occurences in counts.items(): samples.extend( [ qubit_states_from_int(int(hex_state, 16), circuit.num_qubits) for _ in range(occurences) ] ) results[str(circuit_index)] = samples return api_models.Response.finished( job_id=job_id, workspace_id=self.workspace_id, resource_id=self.resource_id, results=results, )
https://github.com/stfnmangini/VQE_from_scratch
stfnmangini
import qiskit as qk qc = qk.QuantumCircuit(2,1) qc.barrier() qc.cx(0,1) qc.measure(1,0) print("Measurement in the ZZ basis") qc.draw(output="mpl") qc = qk.QuantumCircuit(2,1) qc.barrier() qc.h(0) qc.h(1) qc.cx(0,1) qc.measure(1,0) print("Measurement in the XX basis") qc.draw(output="mpl") qc = qk.QuantumCircuit(2,1) qc.barrier() qc.sdg(0) qc.sdg(1) qc.h(0) qc.h(1) qc.cx(0,1) qc.measure(1,0) print("Measurement in the YY basis") qc.draw(output="mpl") from qiskit import Aer import numpy as np from scipy.optimize import minimize_scalar, minimize from numpy import pi sim_bknd = qk.Aer.get_backend('qasm_simulator') def ansatz(qc, qr, theta): """ Builds the trial state using the ansatz: (RX I) CX (H I)|00> Arguments ----------- qc: is a QuantumCircuit object from Qiskit qr: is a QuantumRegister object used in the quantum circuit qc theta (real): is the parameter parametrizing the trial state Return --------- qc: returns the input quantum circuit added with the gates creating the trial state """ qc.h(qr[0]) qc.cx(qr[0],qr[1]) qc.rx(theta, qr[0]) return qc def measurements(qc, qr, cr, op): """ Implements the quantum measurements in different basis: XX, YY and ZZ. Arguments ----------- qc: is a QuantumCircuit object from Qiskit qr: is a QuantumRegister object used in the quantum circuit qc cr: is a ClassicalRegister object used in the quantum circuit qc op (str): is a string with possible values: XX, YY and ZZ. Return --------- qc: returns the input quantum circuit added with the appropriate gates to measure in the selected basis. """ if op == "XX": # Change of basis, since X = HZH qc.h(qr[0]) qc.h(qr[1]) # CNOT used to measure ZZ operator qc.cx(qr[0],qr[1]) # Measurement of qubit 1 on classical register 0 qc.measure(qr[1],cr[0]) elif op == "YY": # Change of basis, since Y = (HS†)Z(HS†) qc.sdg(qr[0]) qc.sdg(qr[1]) qc.h(qr[0]) qc.h(qr[1]) # CNOT used to measure ZZ operator qc.cx(qr[0],qr[1]) # Measurement of qubit 1 on classical register 0 qc.measure(qr[1],cr[0]) elif op == "ZZ": # CNOT used to measure ZZ operator qc.cx(qr[0],qr[1]) # Measurement of qubit 1 on classical register 0 qc.measure(qr[1],cr[0]) else: print(f"WARNING: Measurement on the {op} basis not supported") return return qc def hamiltonian(params): """ Evaulates the Energy of the trial state using the mean values of the operators XX, YY and ZZ. Arguments ----------- params (dict): is an dictionary containing the mean values form the measurements of the operators XX, YY, ZZ; Return --------- en (real): energy of the system """ # H = 1/2 * (Id + ZZ - XX - YY) en = (1 + params['ZZ'] - params['XX'] - params['YY']) / 2 return en def vqe_step(theta, verbose = True): """ Executes the VQE algorithm. Creates and executes three quantum circuits (one for each of the observables XX, YY and ZZ), then evaluates the energy. Arguments ----------- theta (real): is the parameter parametrizing the trial state Return -------- energy (real): the energy of the system qc_list (dict): a dictionary containing the three quantum circuits for the observables XX, YY and ZZ """ # Number of executions for each quantum circuit shots=8192 vqe_res = dict() qc_list = dict() for op in ["XX", "YY", "ZZ"]: qr = qk.QuantumRegister(2, "qr") cr = qk.ClassicalRegister(1, "cr") qc = qk.QuantumCircuit(qr, cr) # Implementation of the ansatz qc = ansatz(qc, qr, theta) # Just for plotting purposes qc.barrier() # Measurements in the appropriate basis (XX, YY, ZZ) are implemented qc = measurements(qc, qr, cr, op) # Get the measurements results counts = qk.execute(qc, sim_bknd, shots=shots).result().get_counts() # Check the results, and evaluate the mean value dividing by the number of shots if len(counts) == 1: try: counts['0'] mean_val = 1 except: mean_val = -1 else: # Evaluates the mean value of Z operator, as the difference in the number of # 0s and 1s in the measurement outcomes mean_val = (counts['0']-counts['1'])/shots vqe_res[op] = mean_val qc_list[op] = qc energy = hamiltonian(vqe_res) if verbose: print("Mean values from measurement results:\n", vqe_res) print(f"\n{'Theta':<10} {'Energy':<10} {'<XX>':<10} {'<YY>':<10} {'<ZZ>':<10}") print(f"{theta:<10f} {energy:<10f} {vqe_res['XX']:<10f} {vqe_res['YY']:<10f} {vqe_res['ZZ']:<10f}") return energy, qc_list else: return energy # Set the value of theta theta = 0.2 # Run the VQE step to evaluate the energy (eigenvalue of the Hamiltonian) of the state with given theta energy, qc_list = vqe_step(theta) # Plot the circuit used for the measurement of YY op = 'YY' print(f"\nQuantum circuit for the measurement of {op}") qc_list[op].draw(output="mpl") minimize_scalar(vqe_step, args=(False), bounds = (0, pi), method = "bounded") lowest, _ = vqe_step(pi) # Definition of one qubit Pauli matrices I = np.array([[1,0],[0,1]]) X = np.array([[0,1],[1,0]]) Y = np.array([[0,-1j],[1j,0]]) Z = np.array([[1,0],[0,-1]]) # Evaluation of two qubit Pauli matrices II = np.kron(I,I) XX = np.kron(X,X) YY = np.kron(Y,Y) ZZ = np.kron(Z,Z) # Calculation of the Hamiltonian H = (1/2) * (II+ZZ) - (1/2) * (XX+YY) print("Desired Hamiltionian H = \n", H) import scipy # Calculate eigenvalues and eigenvectors of H eigenvalues, eigenvectors = scipy.linalg.eig(H) print("Eigenvalues:", eigenvalues)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.circuit.random import random_circuit circuit = random_circuit(2, 2, seed=0, measure=True).decompose(reps=1) display(circuit.draw("mpl")) from qiskit.primitives import Sampler sampler = Sampler() job = sampler.run(circuit) print(f">>> Job ID: {job.job_id()}") print(f">>> Job Status: {job.status()}") result = job.result() print(f">>> {result}") print(f" > Quasi-distribution: {result.quasi_dists[0]}") circuit = random_circuit(2, 2, seed=1, measure=True).decompose(reps=1) job = sampler.run(circuit) result = job.result() display(circuit.draw("mpl")) print(f">>> Quasi-distribution: {result.quasi_dists[0]}") circuits = ( random_circuit(2, 2, seed=0, measure=True).decompose(reps=1), random_circuit(2, 2, seed=1, measure=True).decompose(reps=1), ) job = sampler.run(circuits) result = job.result() [display(cir.draw("mpl")) for cir in circuits] print(f">>> Quasi-distribution: {result.quasi_dists}") from qiskit.circuit.library import RealAmplitudes circuit = RealAmplitudes(num_qubits=2, reps=2).decompose(reps=1) circuit.measure_all() parameter_values = [0, 1, 2, 3, 4, 5] job = sampler.run(circuit, parameter_values) result = job.result() display(circuit.draw("mpl")) print(f">>> Parameter values: {parameter_values}") print(f">>> Quasi-distribution: {result.quasi_dists[0]}") from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService(channel="ibm_quantum") backend = service.backend("ibmq_qasm_simulator") from qiskit.circuit.random import random_circuit circuit = random_circuit(2, 2, seed=0, measure=True).decompose(reps=1) display(circuit.draw("mpl")) from qiskit_ibm_runtime import Sampler sampler = Sampler(session=backend) job = sampler.run(circuit) print(f">>> Job ID: {job.job_id()}") print(f">>> Job Status: {job.status()}") result = job.result() print(f">>> {result}") print(f" > Quasi-distribution: {result.quasi_dists[0]}") print(f" > Metadata: {result.metadata[0]}") from qiskit_ibm_runtime import Options options = Options(optimization_level=3, environment={"log_level": "INFO"}) from qiskit_ibm_runtime import Options options = Options() options.resilience_level = 1 options.execution.shots = 2048 sampler = Sampler(session=backend, options=options) result = sampler.run(circuit).result() print(f">>> Metadata: {result.metadata[0]}") sampler = Sampler(session=backend, options=options) result = sampler.run(circuit, shots=1024).result() print(f">>> Metadata: {result.metadata[0]}") from qiskit_ibm_runtime import Options # optimization_level=3 adds dynamical decoupling # resilience_level=1 adds readout error mitigation options = Options(optimization_level=3, resilience_level=1) sampler = Sampler(session=backend, options=options) result = sampler.run(circuit).result() print(f">>> Quasi-distribution: {result.quasi_dists[0]}") print(f">>> Metadata: {result.metadata[0]}") from qiskit_ibm_runtime import Session, Estimator with Session(backend=backend, max_time="1h"): sampler = Sampler() result = sampler.run(circuit).result() print(f">>> Quasi-distribution from the first run: {result.quasi_dists[0]}") result = sampler.run(circuit).result() print(f">>> Quasi-distribution from the second run: {result.quasi_dists[0]}") from qiskit.circuit.random import random_circuit from qiskit.quantum_info import SparsePauliOp estimator_circuit = random_circuit(2, 2, seed=0).decompose(reps=1) display(estimator_circuit.draw("mpl")) observable = SparsePauliOp("XZ") print(f">>> Observable: {observable.paulis}") from qiskit_ibm_runtime import Session, Sampler, Estimator with Session(backend=backend): sampler = Sampler() estimator = Estimator() result = sampler.run(circuit).result() print(f">>> Quasi Distribution from the sampler job: {result.quasi_dists[0]}") result = estimator.run(estimator_circuit, observable).result() print(f">>> Expectation value from the estimator job: {result.values[0]}") from qiskit_ibm_runtime import Session, Sampler, Estimator with Session(backend=backend): sampler = Sampler() estimator = Estimator() sampler_job = sampler.run(circuit) estimator_job = estimator.run(estimator_circuit, observable) print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}") print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}") from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler, Estimator, Options # 1. Initialize account service = QiskitRuntimeService(channel="ibm_quantum") # 2. Specify options, such as enabling error mitigation options = Options(resilience_level=1) # 3. Select a backend. backend = service.backend("ibmq_qasm_simulator") # 4. Create a session with Session(backend=backend): # 5. Create primitive instances sampler = Sampler(options=options) estimator = Estimator(options=options) # 6. Submit jobs sampler_job = sampler.run(circuit) estimator_job = estimator.run(estimator_circuit, observable) # 7. Get results print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}") print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}") import qiskit_ibm_runtime qiskit_ibm_runtime.version.get_version_info() from qiskit.tools.jupyter import * %qiskit_version_table %qiskit_copyright
https://github.com/apcarrik/qiskit-dev
apcarrik
from qiskit import transpile, QuantumCircuit import qiskit.quantum_info as qi from qiskit.providers.aer import AerSimulator from qiskit.providers.aer.noise import NoiseModel, amplitude_damping_error from qiskit.tools.visualization import plot_histogram ## Creating Matrix Operators # CNOT matrix operator with qubit-0 as control and qubit-1 as target cx_op = qi.Operator([ [1,0,0,0], [0,0,0,1], [0,0,1,0], [0,1,0,0] ]) # iSWAP matrix operator iswap_op = qi.Operator([ [1,0,0,0], [0,0,1j,0], [0,1j,0,0], [0,0,0,1] ]) ## Using Operators in Circuits # CNOT in terms of iSWAP and single-qubit gates cx_circ = QuantumCircuit(2, name='cx<iSWAP>') cx_circ.sdg(1) cx_circ.h(1) cx_circ.sdg(0) cx_circ.unitary(iswap_op, [0,1], label='iswap') cx_circ.sdg(0) cx_circ.h(0) cx_circ.sdg(0) cx_circ.unitary(iswap_op, [0,1], label='iswap') cx_circ.s(1) print(cx_circ) # Simulate the unitary for the circuit using Operator: unitary = qi.Operator(cx_circ) print(unitary) f_avg = qi.average_gate_fidelity(cx_op, unitary) print("Average gate fidelity: F = {:f}".format(f_avg)) ### Creating a Custom Unitary in a Noise Model print('unitary' in AerSimulator().configuration().basis_gates) # error parameters param_q0 = 0.05 # damping parameter for qubit-0 param_q1 = 0.1 # damping parameter for qubit-1 # construct the error qerror_q0 = amplitude_damping_error(param_q0) qerror_q1 = amplitude_damping_error(param_q1) iswap_error = qerror_q1.tensor(qerror_q0) # Build the noise model by adding the error to the iSWAP gate noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(iswap_error,'iswap') noise_model.add_basis_gates(['unitary']) print(noise_model.basis_gates) ## Simulating a Custom Unitary Noise Model # Bell state circuit where iSWAPS should be placed at barrier locations bell_circ = QuantumCircuit(2,2,name='bell') bell_circ.h(0) bell_circ.append(cx_circ,[0,1]) bell_circ.measure([0,1],[0,1]) print(bell_circ) # create ideal simulator backend and transpile circuit sim_ideal = AerSimulator() tbell_circ = transpile(bell_circ,sim_ideal) ideal_result = sim_ideal.run(tbell_circ).result() ideal_counts = ideal_result.get_counts(0) plot_histogram(ideal_counts, title='Ideal output for iSWAP bell-state preparation').show() ## Noisy Circuit Execution # create noisy simulator and transpile circuit sim_noise = AerSimulator(noise_model=noise_model) tbell_circ_noise = transpile(bell_circ,sim_noise) # run on the simulator with noise noise_result = sim_noise.run(tbell_circ_noise).result() noise_counts = noise_result.get_counts(0) plot_histogram(noise_counts, title='Noisy output for iSWAP bell-state preparation').show()
https://github.com/ttlion/ShorAlgQiskit
ttlion
""" 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/QuantumBarcelona/Qiskit-Hackathon-BCN
QuantumBarcelona
https://github.com/grossiM/Qiskit_workshop1019
grossiM
import qiskit qiskit.__qiskit_version__ # useful additional packages import numpy as np import matplotlib.pyplot as plt %matplotlib inline # importing Qiskit from qiskit import BasicAer, IBMQ from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.compiler import transpile from qiskit.tools.monitor import job_monitor # import basic plot tools from qiskit.tools.visualization import plot_histogram #IBMQ.save_account('API-TOKEN') # Load our saved IBMQ accounts IBMQ.load_accounts() n = 13 # the length of the first register for querying the oracle # Choose a type of oracle at random. With probability half it is constant, # and with the same probability it is balanced oracleType, oracleValue = np.random.randint(2), np.random.randint(2) if oracleType == 0: print("The oracle returns a constant value ", oracleValue) else: print("The oracle returns a balanced function") a = np.random.randint(1,2**n) # this is a hidden parameter for balanced oracle. # Creating registers # n qubits for querying the oracle and one qubit for storing the answer qr = QuantumRegister(n+1) #all qubits are initialized to zero # for recording the measurement on the first register cr = ClassicalRegister(n) circuitName = "DeutschJozsa" djCircuit = QuantumCircuit(qr, cr) # Create the superposition of all input queries in the first register by applying the Hadamard gate to each qubit. for i in range(n): djCircuit.h(qr[i]) # Flip the second register and apply the Hadamard gate. djCircuit.x(qr[n]) djCircuit.h(qr[n]) # Apply barrier to mark the beginning of the oracle djCircuit.barrier() if oracleType == 0:#If the oracleType is "0", the oracle returns oracleValue for all input. if oracleValue == 1: djCircuit.x(qr[n]) else: djCircuit.iden(qr[n]) else: # Otherwise, it returns the inner product of the input with a (non-zero bitstring) for i in range(n): if (a & (1 << i)): djCircuit.cx(qr[i], qr[n]) # Apply barrier to mark the end of the oracle djCircuit.barrier() # Apply Hadamard gates after querying the oracle for i in range(n): djCircuit.h(qr[i]) # Measurement djCircuit.barrier() for i in range(n): djCircuit.measure(qr[i], cr[i]) #draw the circuit djCircuit.draw(output='mpl',scale=0.5) backend = BasicAer.get_backend('qasm_simulator') shots = 1000 job = execute(djCircuit, backend=backend, shots=shots) results = job.result() answer = results.get_counts() plot_histogram(answer) backend = IBMQ.get_backend('ibmq_16_melbourne') djCompiled = transpile(djCircuit, backend=backend, optimization_level=1) djCompiled.draw(output='mpl',scale=0.5) job = execute(djCompiled, backend=backend, shots=1024) job_monitor(job) results = job.result() answer = results.get_counts() threshold = int(0.01 * shots) # the threshold of plotting significant measurements filteredAnswer = {k: v for k,v in answer.items() if v >= threshold} # filter the answer for better view of plots removedCounts = np.sum([ v for k,v in answer.items() if v < threshold ]) # number of counts removed filteredAnswer['other_bitstrings'] = removedCounts # the removed counts are assigned to a new index plot_histogram(filteredAnswer) print(filteredAnswer)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
%matplotlib inline from qiskit import * from qiskit.visualization import * from qiskit.tools.monitor import * circ_random = QuantumCircuit(1,1) # We need qubit and one classical bit circ_random.h(0) #We apply the H gate circ_random.measure(range(1),range(1)) # Measure circ_random.draw(output='mpl') n = 100 # Number of bits that we are going to use # Alice generates n random bits (some of these bits will form the key) backend = Aer.get_backend('qasm_simulator') job = execute(circ_random, backend, shots=n, memory = True) # We set the 'memory' parameter to true to be able to access the string of results bits_alice = [int(q) for q in job.result().get_memory()] print(bits_alice) # Alice randomly chooses the bases in which she is going to measure job = execute(circ_random, backend, shots=n, memory = True) basis_alice = [int(q) for q in job.result().get_memory()] print(basis_alice) # Bob also chooses at random the bases in which he will measure job = execute(circ_random, backend, shots=n, memory = True) basis_bob = [int(q) for q in job.result().get_memory()] print(basis_bob) # Now, Alice codes each bit of her initial string as a qubit and sends it to Bob, who measures in his basis bits_bob = [] for i in range(n): circ_send = QuantumCircuit(1,1) if bits_alice[i]: # Alice has to send '1' circ_send.x(0) if basis_alice[i]: # Alice codes in basis |+>, |-> circ_send.h(0) # Alice sends the qubit to Bob and he measures if basis_bob[i]: # Bob has to measure in basis |+>, |-> circ_send.h(0) circ_send.measure(0,0) job = execute(circ_send, backend, shots = 1, memory = True) bits_bob.append(int(job.result().get_memory()[0])) print(bits_bob) # Bob tells Alice the basis he used for his measurements # Alice confirms which of the basis are correct key = [] for i in range(n): if basis_alice[i] == basis_bob[i]: key.append(bits_bob[i]) print("Key length", len(key)) print(key)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.wrapper import available_backends, get_backend from qiskit.wrapper import execute as q_execute q = QuantumRegister(2, name='q') c = ClassicalRegister(2, name='c') qc = QuantumCircuit(q,c) qc.h(q[0]) qc.h(q[1]) qc.cx(q[0], q[1]) qc.measure(q, c) z = 0.995004165 + 1j * 0.099833417 z = z / abs(z) u_error = np.array([[1, 0], [0, z]]) noise_params = {'U': {'gate_time': 1, 'p_depol': 0.001, 'p_pauli': [0, 0, 0.01], 'U_error': u_error } } config = {"noise_params": noise_params} ret = q_execute(qc, 'local_qasm_simulator_cpp', shots=1024, config=config) ret = ret.result() print(ret.get_counts())
https://github.com/Harcipan/QAI_GroverSim
Harcipan
# Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * # qiskit-ibmq-provider has been deprecated. # Please see the Migration Guides in https://ibm.biz/provider_migration_guide for more detail. from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Estimator, Session, Options # Loading your IBM Quantum account(s) service = QiskitRuntimeService(channel="ibm_quantum") IBMQ.load_account() from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute, IBMQ from qiskit.tools.monitor import job_monitor from qiskit.circuit.library import QFT import numpy as np pi = np.pi # IBMQ.enable_account('ENTER API KEY HERE') provider = IBMQ.get_provider(hub='ibm-q') backend = provider.get_backend('ibmq_qasm_simulator') q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') circuit = QuantumCircuit(q, c) circuit.x(q[2]) circuit.x(q[0]) qft_gate = QFT(num_qubits=3, approximation_degree=0, do_swaps=True, inverse=False, insert_barriers=False, name='qft') circuit.append(qft_gate, q) circuit.measure(q, c) circuit.draw(output='mpl', filename='qft1.png') print(circuit) job = execute(circuit, backend, shots=1000) job_monitor(job) counts = job.result().get_counts() print("\n QFT Output") print("-------------") print(counts) #Idealis phase estimation from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.visualization import plot_histogram # Define the number of qubits and the phase estimation precision n = 3 # number of qubits precision = 2**n # Create quantum and classical registers qreg_upper = QuantumRegister(1, 'q_upper') # Upper qubit qreg_lower = QuantumRegister(n, 'q_lower') # Lower qubits creg = ClassicalRegister(n, 'c') # Classical register for measurement outcomes # Create quantum circuit circuit = QuantumCircuit(qreg_upper, qreg_lower, creg) # Initialize the lower qubits with the eigenvector |u # Note: You need to provide the specific eigenvector |u as initial state # For simplicity, let's assume |u = |0 for demonstration purposes circuit.initialize([1] + [0] * (2**n - 1), qreg_lower) # Apply Hadamard gate to the upper qubit circuit.h(qreg_upper[0]) # Apply controlled unitary operations based on the phase estimation algorithm for qubit in range(n): circuit.cp(2 * 3.141592653589793 / (2**(n - qubit)), qreg_upper[0], qreg_lower[qubit]) # Apply the inverse quantum Fourier transform (IQFT) circuit.h(qreg_upper[0]) for qubit in range(n): circuit.cp(-2 * 3.141592653589793 / (2**(qubit + 1)), qreg_upper[0], qreg_lower[qubit]) # Measure the lower qubits circuit.measure(qreg_lower, creg) # Simulate the circuit simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, simulator, shots=1000) result = job.result() print(circuit) # Display the histogram of measurement outcomes counts = result.get_counts() print("\nMeasurement outcomes:") print("---------------------") print(counts) # Plot the histogram plot_histogram(counts) #Idealis phase estimation #CASE 1 from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.visualization import plot_histogram # Define the number of qubits and the phase estimation precision n = 3 # number of qubits precision = 2**n PI = 3.141592653589793 # Create quantum and classical registers qreg_upper = QuantumRegister(1, 'q_upper') # Upper qubit qreg_lower = QuantumRegister(n, 'q_lower') # Lower qubits creg = ClassicalRegister(n, 'c') # Classical register for measurement outcomes # Create quantum circuit circuit = QuantumCircuit(qreg_upper, qreg_lower, creg) # Initialize the lower qubits with the eigenvector |u # Note: You need to provide the specific eigenvector |u as initial state # For simplicity, let's assume |u = |0 for demonstration purposes circuit.initialize([1] + [0] * (2**n - 1), qreg_lower) # Apply Hadamard gate to the upper qubit circuit.h(qreg_upper[0]) """circuit.h(qreg_lower[1]) circuit.h(qreg_lower[2])""" # Apply controlled unitary operations based on the phase estimation algorithm for qubit in range(n): circuit.cp(2 * PI / (2**(n - qubit)), qreg_upper[0], qreg_lower[qubit]) # Apply the inverse quantum Fourier transform (IQFT) circuit.h(qreg_upper[0]) for qubit in range(n): circuit.cp(-2 * PI / (2**(qubit + 1)), qreg_upper[0], qreg_lower[qubit]) # Measure the lower qubits circuit.measure(qreg_lower, creg) # Simulate the circuit simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, simulator, shots=1000) result = job.result() print(circuit) # Display the histogram of measurement outcomes counts = result.get_counts() print("\nMeasurement outcomes:") print("---------------------") print(counts) # Plot the histogram plot_histogram(counts) #CASE 2 from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit.library import QFT from qiskit.visualization import plot_histogram import numpy as np PI = np.pi n = 4 # number of qubits #---------INIT----------# # Create quantum and classical registers #qreg_upper = QuantumRegister(1, 'q_upper') # Upper qubit qreg_lower = QuantumRegister(n, 'q_lower') # Lower qubits creg = ClassicalRegister(n, 'c') # Classical register for measurement outcomes # Create quantum circuit #circuit = QuantumCircuit(qreg_upper, qreg_lower, creg) circuit = QuantumCircuit(qreg_lower, creg) # Initialize the lower qubits with the eigenvector |u # Note: You need to provide the specific eigenvector |u as the initial state # For simplicity, let's assume |u = |0 for demonstration purposes circuit.initialize([1] + [0] * (2**n - 1), qreg_lower) #-------------MAKING INPUT----------# # Apply controlled unitary operations based on the phase estimation algorithm for qubit in range(n-1): #circuit.cy(qreg_lower[0], qreg_lower[qubit+1]) #circuit.ch(qreg_lower[0], qreg_lower[qubit+1]) #egyik init circuit.cp(2 * PI / (2**(n - qubit)), qreg_lower[0], qreg_lower[qubit+1]) #masik init circuit.h(qreg_lower[0]) """circuit.h(qreg_lower[1]) circuit.h(qreg_lower[2])""" #--------------IQFT----------------# # preparing for IQFT circuit.x(qreg_lower[2]) circuit.x(qreg_lower[0]) #circuit.x(qreg_lower[4]) # Apply Hadamard gate to the upper qubit #circuit.h(qreg_lower[0]) # Apply inverse QFT qft_gate = QFT(num_qubits=n, approximation_degree=0, do_swaps=True, inverse=True, insert_barriers=True, name='qft') circuit.append(qft_gate, qreg_lower) """for qubit in range(n-1): circuit.cp(-2 * PI / (2**(qubit + 1)), qreg_lower[0], qreg_lower[qubit+1])""" #----------MEASUREMENT-----------# circuit.measure(qreg_lower, creg) # Display the circuit #circuit.draw(output='mpl', filename='qft1.png') print(circuit) # Execute the circuit on the simulator backend = Aer.get_backend('qasm_simulator') job = execute(circuit, backend, shots=1000) # Monitor the job job_monitor(job) # Get and display the measurement results counts = job.result().get_counts() print("\nIQFT Output") print("-------------") print(counts) plot_histogram(counts) #CASE 3 from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit.library import QFT from qiskit.visualization import plot_histogram import numpy as np PI = np.pi n = 4 # number of qubits #---------INIT----------# # Create quantum and classical registers #qreg_upper = QuantumRegister(1, 'q_upper') # Upper qubit qreg_lower = QuantumRegister(n, 'q_lower') # Lower qubits creg = ClassicalRegister(n, 'c') # Classical register for measurement outcomes # Create quantum circuit #circuit = QuantumCircuit(qreg_upper, qreg_lower, creg) circuit = QuantumCircuit(qreg_lower, creg) # Initialize the lower qubits with the eigenvector |u # Note: You need to provide the specific eigenvector |u as the initial state # For simplicity, let's assume |u = |0 for demonstration purposes circuit.initialize([1] + [0] * (2**n - 1), qreg_lower) #-------------MAKING INPUT----------# # Apply controlled unitary operations based on the phase estimation algorithm for qubit in range(n-1): #circuit.cy(qreg_lower[0], qreg_lower[qubit+1]) #circuit.ch(qreg_lower[0], qreg_lower[qubit+1]) #egyik init circuit.cp(2 * PI / (2**(n - qubit)), qreg_lower[0], qreg_lower[qubit+1]) #masik init #circuit.h(qreg_lower[0]) """circuit.h(qreg_lower[1]) circuit.h(qreg_lower[2])""" #--------------IQFT----------------# # preparing for IQFT circuit.x(qreg_lower[2]) circuit.x(qreg_lower[0]) #circuit.x(qreg_lower[4]) # Apply Hadamard gate to the upper qubit circuit.h(qreg_lower[0]) # Apply inverse QFT qft_gate = QFT(num_qubits=n, approximation_degree=0, do_swaps=True, inverse=True, insert_barriers=True, name='qft') circuit.append(qft_gate, qreg_lower) """for qubit in range(n-1): circuit.cp(-2 * PI / (2**(qubit + 1)), qreg_lower[0], qreg_lower[qubit+1])""" #----------MEASUREMENT-----------# circuit.measure(qreg_lower, creg) # Display the circuit #circuit.draw(output='mpl', filename='qft1.png') print(circuit) # Execute the circuit on the simulator backend = Aer.get_backend('qasm_simulator') job = execute(circuit, backend, shots=1000) # Monitor the job job_monitor(job) # Get and display the measurement results counts = job.result().get_counts() print("\nIQFT Output") print("-------------") print(counts) plot_histogram(counts) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit.library import QFT from qiskit.visualization import plot_histogram import numpy as np PI = np.pi n = 4 # number of qubits from qiskit import IBMQ #provider = IBMQ.load_account() # Load your IBM Quantum Experience account # Choose an available backend #backend = provider.get_backend('your_preferred_backend_name') #---------INIT----------# # Create quantum and classical registers #qreg_upper = QuantumRegister(1, 'q_upper') # Upper qubit qreg_lower = QuantumRegister(n, 'q_lower') # Lower qubits creg = ClassicalRegister(n, 'c') # Classical register for measurement outcomes # Create quantum circuit #circuit = QuantumCircuit(qreg_upper, qreg_lower, creg) circuit = QuantumCircuit(qreg_lower, creg) # Initialize the lower qubits with the eigenvector |u # Note: You need to provide the specific eigenvector |u as the initial state # For simplicity, let's assume |u = |0 for demonstration purposes circuit.initialize([0] * (2**n - 1)+[1], qreg_lower) #-------------MAKING INPUT----------# # Apply controlled unitary operations based on the phase estimation algorithm for qubit in range(n-1): #circuit.cy(qreg_lower[0], qreg_lower[qubit+1]) #circuit.ch(qreg_lower[0], qreg_lower[qubit+1]) #egyik init circuit.cp(2 * PI / (2**(n - qubit)), qreg_lower[0], qreg_lower[qubit+1]) #masik init for qubit in range(n-1): circuit.h(qreg_lower[qubit+1]) """circuit.h(qreg_lower[1]) circuit.h(qreg_lower[2])""" #--------------IQFT----------------# # preparing for IQFT circuit.x(qreg_lower[2]) circuit.x(qreg_lower[0]) #circuit.x(qreg_lower[4]) # Apply Hadamard gate to the upper qubit #circuit.h(qreg_lower[0]) # Apply inverse QFT qft_gate = QFT(num_qubits=n, approximation_degree=0, do_swaps=True, inverse=True, insert_barriers=True, name='qft') circuit.append(qft_gate, qreg_lower) """for qubit in range(n-1): circuit.cp(-2 * PI / (2**(qubit + 1)), qreg_lower[0], qreg_lower[qubit+1])""" #----------MEASUREMENT-----------# """for i in range(circuit.num_qubits-1): circuit.measure(qreg_lower[i], creg[i])""" circuit.measure(qreg_lower[0], creg[0]) # Display the circuit #circuit.draw(output='mpl', filename='qft1.png') print(circuit) # Execute the circuit on the simulator backend = Aer.get_backend('qasm_simulator') job = execute(circuit, backend, shots=1000) # Monitor the job job_monitor(job) # Get and display the measurement results counts = job.result().get_counts() print("\nIQFT Output") print("-------------") print(counts) plot_histogram(counts) # Phase estimator - in the initialized input 1 is in the first or the second half => output: 0 or 1 from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit.library import QFT from qiskit.visualization import plot_histogram import numpy as np from qiskit import IBMQ, Aer, transpile, assemble from qiskit.tools.monitor import job_monitor from qiskit.visualization import plot_histogram from qiskit.providers.ibmq import least_busy PI = np.pi n = 4 # number of qubits # Az IBMQ fiókaink betöltése és a legkevésbé leterhelt háttértároló eszköz megszerzése, amelynek (n+1) kubit vagy több van #IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') """backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and not x.configuration().simulator and x.status().operational==True)) print("Legkevésbé leterhelt backend: ", backend)""" #---------INIT----------# # Create quantum and classical registers qreg = QuantumRegister(n, 'q') #qubits creg = ClassicalRegister(n, 'c') # Classical register for measurement outcomes # Create quantum circuit #circuit = QuantumCircuit(qreg_upper, qreg_lower, creg) circuit = QuantumCircuit(qreg, creg) # Initialize the lower qubits with the eigenvector |u # Note: You need to provide the specific eigenvector |u as the initial state # For simplicity, let's assume |u = |0 for demonstration purposes #circuit.initialize([1 + [0] * (2**n - 1), qreg) #circuit.initialize([0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0], qreg) circuit.initialize([1,0], qreg[n-1]) for qubit in range(n-1): circuit.h(qreg[qubit]) #-------------MAKING INPUT----------# # Apply controlled unitary operations based on the phase estimation algorithm for qubit in range(n-1): circuit.cx(qreg[n-qubit-2],qreg[n-1]) #--------------IQFT----------------# # Apply Hadamard gate to the upper qubit #circuit.h(qreg[0]) # Apply inverse QFT circuit.append(QFT(num_qubits=n, inverse=True), qreg) #----------MEASUREMENT-----------# #circuit.measure(qreg[0], creg[0]) for i in range(circuit.num_qubits-1): circuit.measure(qreg[i], creg[i]) # Display the circuit #circuit.draw(output='mpl', filename='qft1.png') print(circuit) # Execute the circuit on the simulator backend = Aer.get_backend('qasm_simulator') job = execute(circuit, backend, shots=1000) """ # futtatas kv.szamitogepen transpiled_circuit = transpile(circuit, backend, optimization_level=3) job = backend.run(transpiled_circuit)""" # Monitor the job job_monitor(job, interval=2) # Get and display the measurement results counts = job.result().get_counts() print("\nIQFT Output") print("-------------") print(counts) plot_histogram(counts) # Phase estimator - in the initialized input 1 is in the first or the second half => output: 0 or 1 from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit.library import QFT from qiskit.visualization import plot_histogram import numpy as np from qiskit import IBMQ, Aer, transpile, assemble from qiskit.tools.monitor import job_monitor from qiskit.visualization import plot_histogram from qiskit.providers.ibmq import least_busy PI = np.pi t=1 n=4 # Create quantum registers upper_register = QuantumRegister(n, 'upper') bottom_register = QuantumRegister(t, 'bottom') classical_reg = ClassicalRegister(n, 'creg') # Construct quantum circuit qc = QuantumCircuit(upper_register, bottom_register, classical_reg) #qc.initialize([1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], upper_register) #alapbol 0-ra van inicializalva qc.initialize([1,0], bottom_register) # Apply Hadamard gates on upper register qc.h(upper_register) for qubit in range(n-1): qc.cx(upper_register[n-qubit-2],bottom_register) #qc.cx(upper_register,bottom_register) # Apply Inverse Quantum Fourier Transform (IQFT) qc.append(QFT(n, inverse=True), upper_register) # Measure upper register qc.measure(upper_register, classical_reg) print(qc) # Execute the circuit on a simulator simulator = Aer.get_backend('qasm_simulator') job = execute(qc, simulator, shots=1024) result = job.result() # Get the counts counts = result.get_counts(qc) # Visualize the counts plot_histogram(counts) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, Aer, transpile from qiskit.providers.ibmq import least_busy, IBMQ from qiskit.tools.monitor import job_monitor from qiskit.visualization import plot_histogram # Load IBM Quantum Experience account IBMQ.load_account() # Define your quantum and classical registers n = 4 t = 1 upper_register = QuantumRegister(n, 'upper') bottom_register = QuantumRegister(t, 'bottom') classical_reg = ClassicalRegister(n, 'creg') # Construct quantum circuit qc = QuantumCircuit(upper_register, bottom_register, classical_reg) # Initialize the bottom register qc.initialize([1, 0], bottom_register) # Apply Hadamard gates on upper register qc.h(upper_register) # Apply controlled-NOT gates for qubit in range(n - 1): qc.cx(upper_register[n - qubit - 2], bottom_register) # Apply Inverse Quantum Fourier Transform (IQFT) qc.append(QFT(n, inverse=True), upper_register) # Measure the upper register qc.measure(upper_register, classical_reg) # Choose an IBM Quantum device to run the circuit provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= n and not x.configuration().simulator and x.status().operational==True)) # Transpile the circuit for the selected backend qc_transpiled = transpile(qc, backend) # Execute the circuit on the selected backend job = backend.run(qc_transpiled) # Monitor the job job_monitor(job) # Get the results result = job.result() # Get the counts counts = result.get_counts(qc) # Visualize the counts plot_histogram(counts) #Deutsch–Jozsa circuit as a simple phase estimator from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit.library import QFT from qiskit.visualization import plot_histogram import numpy as np from qiskit import IBMQ, Aer, transpile, assemble from qiskit.tools.monitor import job_monitor from qiskit.visualization import plot_histogram from qiskit.providers.ibmq import least_busy PI = np.pi n = 2 # number of qubits # Az IBMQ fiókaink betöltése és a legkevésbé leterhelt háttértároló eszköz megszerzése, amelynek (n+1) kubit vagy több van #IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') """backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and not x.configuration().simulator and x.status().operational==True)) print("Legkevésbé leterhelt backend: ", backend)""" #---------INIT----------# # Create quantum and classical registers qreg = QuantumRegister(n, 'q') #qubits creg = ClassicalRegister(n, 'c') # Classical register for measurement outcomes # Create quantum circuit circuit = QuantumCircuit(qreg, creg) initial_state = [0, 1, 0, 0] # Amplitudes for |00⟩, |01⟩, |10⟩, |11⟩ circuit.initialize(initial_state, qreg) for qubit in range(n): circuit.h(qreg[qubit]) circuit.cx(qreg[0],qreg[1]) circuit.h(qreg[0]) #----------MEASUREMENT-----------# circuit.measure(qreg[0], creg[0]) # Display the circuit print(circuit) # Execute the circuit on the simulator backend = Aer.get_backend('qasm_simulator') job = execute(circuit, backend, shots=1000) """ # futtatas kv.szamitogepen transpiled_circuit = transpile(circuit, backend, optimization_level=3) job = backend.run(transpiled_circuit)""" # Monitor the job job_monitor(job, interval=2) # Get and display the measurement results counts = job.result().get_counts() print("\nIQFT Output") print("-------------") print(counts) plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import datetime import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt plt.rcParams.update({"text.usetex": True}) plt.rcParams["figure.figsize"] = (6,4) mpl.rcParams["figure.dpi"] = 200 from qiskit_ibm_runtime import Estimator, Session, QiskitRuntimeService, Options from qiskit.quantum_info import SparsePauliOp from qiskit import QuantumCircuit service = QiskitRuntimeService() backend_simulator = "backend_simulator" backend = "ibmq_montreal" qubits = 4 trotter_layer = QuantumCircuit(qubits) trotter_layer.rx(0.1, range(qubits)) trotter_layer.cx(0, 1) trotter_layer.cx(2, 3) trotter_layer.rz(-0.2, [1, 3]) trotter_layer.cx(0, 1) trotter_layer.cx(2, 3) trotter_layer.cx(1, 2) trotter_layer.rz(-0.2, 2) trotter_layer.cx(1, 2) num_steps = 6 trotter_circuit_list = [] for i in range(1, num_steps): trotter_circuit = QuantumCircuit(qubits) for _ in range(i): trotter_circuit = trotter_circuit.compose(trotter_layer) trotter_circuit_list.append(trotter_circuit) print(f'Trotter circuit with {i} Trotter steps`) display(trotter_circuit.draw(fold=-1)) obs = SparsePauliOp("Z"*qubits) obs_list = [obs]*len(trotter_circuit_list) options = Options() options.execution.shots = 1000 options.optimization_level = 0 # No optimization options.resilience_level = 0 # No mitigation with Session(service=service, backend=backend_simulator) as session: estimator_sim = Estimator(session=session, options=options) job_sim = estimator_sim.run(circuits=trotter_circuit_list, observables=obs_list) print('job id:', job_sim.job_id) print(job_sim.result()) expvals_ideal = job_sim.result().values expvals_ideal_variance = [metadata['variance']/metadata['shots'] for metadata in job_sim.result().metadata] std_error_ideal = np.sqrt(expvals_ideal_variance) options = Options() options.execution.shots = 1000 options.optimization_level = 0 # No optimization options.resilience_level = 0 # No error mitigation with Session(service=service, backend=backend) as session: estimator = Estimator(session=session, options=options) job = estimator.run(circuits=trotter_circuit_list, observables=obs_list) print('job id:', job.job_id) print(job.result()) expvals_unmit = job.result().values expvals_unmit_variance = [metadata['variance']/metadata['shots'] for metadata in job.result().metadata] std_error_unmit = np.sqrt(expvals_unmit_variance) options = Options() options.execution.shots = 1000 options.optimization_level = 3 # Dynamical decoupling options.resilience_level = 0 # No error mitigation with Session(service=service, backend=backend) as session: estimator = Estimator(session=session, options=options) job_dd = estimator.run(circuits=trotter_circuit_list, observables=obs_list) print('job id:', job_dd.job_id) print(job_dd.result()) expvals_unmit_dd = job_dd.result().values expvals_unmit_dd_variance = [metadata['variance']/metadata['shots'] for metadata in job_dd.result().metadata] std_error_dd = np.sqrt(expvals_unmit_dd_variance) plt.title('Trotter circuits expectation value') plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal') plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation') plt.errorbar(range(1, num_steps), expvals_unmit_dd, std_error_dd, fmt = 'o', linestyle = '-', capsize=4, c='blue', label='Dynamical decoupling') plt.ylabel(f"$\langle ZZZZ \\rangle$") plt.xlabel('No. Trotter Steps') plt.xticks([1, 2, 3, 4, 5]) plt.legend() plt.show() options = Options() options.resilience_level = 1 # T-REx options.optimization_level = 0 # No optimization options.execution.shots = 1000 with Session(service=service, backend=backend) as session: estimator = Estimator(session=session, options=options) job_trex = estimator.run(circuits=trotter_circuit_list, observables=obs_list) print('job id:', job_trex.job_id) print(job_trex.result()) expvals_unmit_trex = job_trex.result().values expvals_unmit_trex_variance = [metadata['variance']/metadata['shots'] for metadata in job_trex.result().metadata] std_error_trex = np.sqrt(expvals_unmit_trex_variance) plt.title('Trotter circuits expectation value') plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal') plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation') plt.errorbar(range(1, num_steps), expvals_unmit_trex, std_error_trex, fmt = 'o', linestyle = '-', capsize=4, c='violet', label='T-REx') plt.ylabel(f"$\langle ZZZZ \\rangle$") plt.xlabel('No. Trotter Steps') plt.xticks([1, 2, 3, 4, 5]) plt.legend() plt.show() options = Options() options.execution.shots = 1000 options.optimization_level = 0 # No optimization options.resilience_level = 2 # ZNE with Session(service=service, backend=backend) as session: estimator = Estimator(session=session, options=options) job_zne = estimator.run(circuits=trotter_circuit_list, observables=obs_list) print('job id:', job_zne.job_id) print(job_zne.result()) expvals_unmit_zne = job_zne.result().values # Standard error: coming soon! plt.title('Trotter circuits expectation value') plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal') plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation') plt.errorbar(range(1, num_steps), expvals_unmit_zne, [0]*(num_steps-1), fmt = 'o', linestyle = '-', capsize=4, c='cyan', label='ZNE') plt.xlabel('No. Trotter Steps') plt.ylabel(f"$\langle ZZZZ \\rangle$") plt.xticks([1, 2, 3, 4, 5]) plt.legend() plt.show() def interim_results_callback(job_id, result): now = datetime.datetime.now() print(now, "*** Callback ***", result, "\n") options = Options() options.optimization_level = 0 # No optimization options.execution.shots = 100 options.resilience_level = 3 # PEC options.environment.callback = interim_results_callback with Session(service=service, backend=backend) as session: estimator_pec = Estimator(session=session, options=options) job_pec = estimator_pec.run(circuits=trotter_circuit_list, observables=obs_list) print('job id:', job_pec.job_id) expvals_pec = job_pec.result().values std_error_pec = [metadata['standard_error'] for metadata in job_pec.result().metadata] plt.title('Trotter circuits expectation value') plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal') plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation') plt.errorbar(range(1, num_steps), expvals_pec, std_error_pec, fmt = 'd', linestyle = '-', capsize=4, c='orange', label='PEC') plt.ylabel(f"$\langle ZZZZ \\rangle$") plt.xlabel('No. Trotter Steps') plt.xticks([1, 2, 3, 4, 5]) plt.legend() plt.show() print(job_pec.result()) pec_metadata = job_pec.result().metadata fig, ax = plt.subplots() fig.subplots_adjust(right=0.75) twin1 = ax.twinx() twin2 = ax.twinx() twin3 = ax.twinx() twin2.spines.right.set_position(("axes", 1.2)) twin3.spines.right.set_position(("axes", 1.4)) p1, = ax.plot(range(1, num_steps), [m["total_mitigated_layers"] for m in pec_metadata] , "b-", label="Total mitigated layers") p2, = twin1.plot(range(1, num_steps), [m["sampling_overhead"] for m in pec_metadata], "r-", label="Sampling overhead") p3, = twin2.plot(range(1, num_steps), [m["samples"] for m in pec_metadata], "g-", label="Samples") p4, = twin3.plot(range(1, num_steps), [m["shots"] for m in pec_metadata], "c-", label="Shots") ax.set_ylim(0, 20) twin1.set_ylim(0, 2.8) twin2.set_ylim(0, 300) twin3.set_ylim(0, 35000) ax.set_xlabel("No. Trotter Steps") ax.set_ylabel("Total mitigated layers") twin1.set_ylabel("Sampling overhead") twin2.set_ylabel("Samples") twin3.set_ylabel("Shots") ax.yaxis.label.set_color(p1.get_color()) twin1.yaxis.label.set_color(p2.get_color()) twin2.yaxis.label.set_color(p3.get_color()) twin3.yaxis.label.set_color(p4.get_color()) tkw = dict(size=4, width=1.5) ax.tick_params(axis='y', colors=p1.get_color(), **tkw) twin1.tick_params(axis='y', colors=p2.get_color(), **tkw) twin2.tick_params(axis='y', colors=p3.get_color(), **tkw) twin3.tick_params(axis='y', colors=p4.get_color(), **tkw) plt.xticks([1, 2, 3, 4, 5]) ax.legend(handles=[p1, p2, p3, p4]) plt.title('PEC metadata') plt.show() from matplotlib.pyplot import figure plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal') plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation') plt.errorbar(range(1, num_steps), expvals_unmit_trex, std_error_trex, fmt = 'o', linestyle = '-', capsize=4, c='violet', label='T-REx') plt.errorbar(range(1, num_steps), expvals_unmit_zne, [0]*(num_steps-1), fmt = 'o', linestyle = '-', capsize=4, c='cyan', label='ZNE') plt.errorbar(range(1, num_steps), expvals_pec, std_error_pec, fmt = 'd', linestyle = '-', capsize=4, c='orange', label='PEC') plt.title('Trotter circuits expectation value') plt.ylabel(f"$\langle ZZZZ \\rangle$") plt.xlabel('No. Trotter Steps') plt.xticks([1, 2, 3, 4, 5]) plt.legend() plt.show() options = Options() options.execution.shots = 1000 options.optimization_level = 0 # no optimization options.resilience_level = 2 # ZNE options.resilience.noise_factors = [1, 2, 3, 4] options.resilience.noise_amplifier = "LocalFoldingAmplifier" options.resilience.extrapolator = "QuadraticExtrapolator" with Session(service=service, backend='ibmq_montreal') as session: estimator = Estimator(session=session, options=options) job_zne_options = estimator.run(circuits=trotter_circuit_list, observables=obs_list) print('job id:', job_zne_options.job_id) print(job_zne_options.result()) from qiskit.tools import jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import time import itertools import numpy as np import qiskit from qiskit import * from qiskit.quantum_info import Statevector from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA from qiskit.opflow.state_fns import StateFn, CircuitStateFn from qiskit.providers.aer import StatevectorSimulator, AerSimulator from qiskit.opflow import CircuitSampler from qiskit.ignis.mitigation.measurement import CompleteMeasFitter # you will need to pip install qiskit-ignis from qiskit.ignis.mitigation.measurement import complete_meas_cal import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator from matplotlib.colors import BoundaryNorm cmap = plt.get_cmap("plasma") #'viridis' from modules.utils import * from qae import * import datetime import tenpy from tenpy.networks.mps import MPS from tenpy.models.hubbard import BoseHubbardChain from tenpy.models.tf_ising import TFIChain from tenpy.algorithms import dmrg from tenpy.linalg import np_conserved def DMRG_EBH(L, V, t_list, chi_max=30, bc_MPS='infinite'): model_params = dict(n_max=1, filling=0.5, bc_MPS=bc_MPS, t=t_list, L=L, V=V, mu=0, conserve='N') M = BoseHubbardChain(model_params) vector=[] for i in range(M.lat.N_sites): if i%2: vector.append(1) else: vector.append(0) psi = MPS.from_product_state(M.lat.mps_sites(), vector, bc=M.lat.bc_MPS) dmrg_params = { 'mixer': True, 'trunc_params': { 'chi_max': chi_max, }, 'max_E_err': 1.e-16, #'verbose': 0 } info = dmrg.run(psi, M, dmrg_params) return info['E'], psi def DMRG_Ising(L, J, g, chi_max=30, bc_MPS='finite'): model_params = dict(bc_MPS=bc_MPS, bc_x="open", L=L, J=J, g=g, conserve="best") M = TFIChain(model_params) product_state = ["up"] * M.lat.N_sites psi = MPS.from_product_state(M.lat.mps_sites(), product_state, bc=M.lat.bc_MPS) dmrg_params = { 'mixer': True, 'trunc_params': { 'chi_max': chi_max, }, 'max_E_err': 1e-16, #'verbose': 0 } info = dmrg.run(psi, M, dmrg_params) return info['E'], psi ### Preliminaries qiskit_chi = 100 L = 8 num_trash = int(np.log(L)/np.log(2)) anti = 1 # 1 for ferromagnetic Ising model, -1 for antiferromagnet g = 0.05 J=anti filename = "data/QAEAnsatz_scaling_MPS_script" backend = qiskit.providers.aer.AerSimulator(method="matrix_product_state", precision="single", matrix_product_state_max_bond_dimension = qiskit_chi, matrix_product_state_truncation_threshold = 1e-10, #mps_sample_measure_algorithm = "mps_apply_measure", #alt: "mps_probabilities" ) from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 333 def qiskit_state(psi0): # G is only the local tensor (not multiplied by any singular values) - see https://tenpy.readthedocs.io/en/latest/reference/tenpy.networks.mps.html A_list = [psi0.get_B(i, form="G").to_ndarray().transpose([1,0,2]) for i in range(L)] for i,A in enumerate(A_list): A_list[i] = (A[0], A[1]) S_list = [psi0.get_SR(i) for i in range(L-1)] # skip trivial last bond; hast to be of size L-1 return (A_list, S_list) def prepare_circuit(thetas, L=6, num_trash=2, init_state=None, measurement=True,vqe=False): # QAE ansatz QAE_circ = QAEAnsatz(num_qubits = L, num_trash_qubits= num_trash, trash_qubits_idxs = list(range(L//2-1,L//2-1+num_trash)), measure_trash=measurement).assign_parameters(thetas) # initialize state vector initcirc = QuantumCircuit(QuantumRegister(L,"q"),ClassicalRegister(num_trash, 'c')) if init_state != None: initcirc.set_matrix_product_state(qiskit_state(init_state)) # compose circuits fullcirc = initcirc.compose(QAE_circ) return fullcirc ### Execute circuit count = 0 def run_circuit(thetas, L, num_trash, init_state, vqe=False, shots=100, meas_fitter = None): #global count #count += 1 #print(count, "thetas: ", thetas) #print(L, num_trash) circ = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe) #circ.draw("mpl") #tcirc = qiskit.transpile(circ, backend) # Execute the circuit job_sim = backend.run(circ, shots=shots, seed_simulator=333, seed_transpiler=444) #fix seed to make it reproducible result = job_sim.result() # Results without mitigation counts = result.get_counts() if meas_fitter != None: # Get the filter object meas_filter = meas_fitter.filter # Results with mitigation mitigated_results = meas_filter.apply(result) counts = mitigated_results.get_counts(0) return counts def count_ones(string): return np.sum([int(_) for _ in string]) ### Optimize circuit def cost_function_single(thetas, L, num_trash, init_state, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None): """ Optimizes circuit """ if param_encoding: thetas = feature_encoding(thetas, x) out = run_circuit(thetas, L, num_trash, init_state, vqe=vqe, shots=shots, meas_fitter=meas_fitter) cost = np.sum([out[_]*count_ones(_) for _ in out if _ != "0" * num_trash]) # all measurement results except "000" return cost/shots def cost_function(thetas, L, num_trash, init_states, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None): """ Optimizes circuit """ cost = 0. for init_state in init_states: cost += cost_function_single(thetas, L, num_trash, init_state, shots, vqe, param_encoding, meas_fitter=meas_fitter) return cost/len(init_states) def optimize(init_states, L=6, num_trash=2, thetas=None, shots=1000, max_iter=400, vqe=True, param_encoding=False, x=0, pick_optimizer = None, meas_fitter=None): if thetas is None: n_params = (num_trash*L+num_trasg)*2 if param_encoding else (num_trash*L+num_trash) thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding #print("Initial cost: {:.3f}".format(cost_function(thetas, L, num_trash, init_states, shots, vqe, param_encoding, x))) counts, values, accepted = [], [], [] def store_intermediate_result(eval_count, parameters, mean, std, ac): # counts.append(eval_count) values.append(mean) accepted.append(ac) # Initialize optimizer if pick_optimizer == "cobyla": optimizer = COBYLA(maxiter=max_iter, tol=0.0001) if pick_optimizer == "adam" or pick_optimizer == "ADAM": optimizer = qiskit.algorithms.optimizers.ADAM(maxiter=max_iter) # optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08) if pick_optimizer == "spsa" or pick_optimizer == None: optimizer = SPSA(maxiter=max_iter, #blocking=True, callback=store_intermediate_result, #learning_rate=0.3, #perturbation=0.1 ) # recommended from qiskit (first iteraction takes quite long) # to reduce time figure out optimal learning rate and perturbation in advance start_time = time.time() ret = optimizer.optimize( num_vars=len(thetas), objective_function=(lambda thetas: cost_function(thetas, L, num_trash, init_states, shots, vqe, param_encoding, x, meas_fitter=meas_fitter)), initial_point=thetas ) print("Time: {:.5f} sec".format(time.time()-start_time)) print(ret) return ret[0], values, accepted Ls = [12,12,12,12] # [3,4,8,10,12,14,16,20, 32, 32, 32] max_iter = [400] * len(Ls) num_trashs = np.log(Ls)/np.log(2) num_trashs = np.array(num_trashs, dtype="int") losses = [None] * len(Ls); accepted = [None] * len(Ls); thetas_opt= [None] * len(Ls) times = [None] * len(Ls) for j,L in enumerate(Ls): L = Ls[j] num_trash = num_trashs[j] # BH V = 1 deltat=-1 chi = 100 g=0.05 # ordered phase to make things a bit more interesting print(f"bond dimension {chi}, max_iter {max_iter[j]}, L {L}, num_trash {num_trash}") t_list = np.ones(L-1) for i in range(len(t_list)): t_list[i] -= deltat*(-1)**i #E0, psi0 = DMRG_EBH(L, V, t_list, chi_max=chi, bc_MPS='finite') E0, psi0 = DMRG_Ising(L, J, g, chi_max=chi, bc_MPS='finite') SZ = psi0.expectation_value("Sigmaz") print(f"Psi magnetization: {SZ}") # note that in tenpy Sz and Sx roles are reversed, i.e. in tenpy its -SxSx - g Sz t0 = time.time() thetas_opt[j], losses[j], accepted[j] = optimize([psi0], max_iter=max_iter[j], L=L, num_trash=num_trash, meas_fitter=None) #, pick_optimizer="adam") times[j] = time.time() - t0 loss_final = cost_function_single(thetas_opt[j], L, num_trash, psi0, shots=1000) print(f"opt loss = {loss_final}, min loss = {np.min(losses[j])}, computation time = {times[j]} sec") print(f"losses vs steps: ", losses[j]) # to save computation time, dont save intermediate results and just compute the loss in the end np.savez(filename + "_results", thetas_opt=thetas_opt, losses=losses, accepted=accepted,Ls=Ls, max_iter=max_iter, times=times)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """Mock functions for qiskit.IBMQ.""" from unittest.mock import MagicMock import qiskit from qiskit.providers import fake_provider as backend_mocks def mock_get_backend(backend): """Replace qiskit.IBMQ with a mock that returns a single backend. Note this will set the value of qiskit.IBMQ to a MagicMock object. It is intended to be run as part of docstrings with jupyter-example in a hidden cell so that later examples which rely on ibmq devices so that the docs can be built without requiring configured credentials. If used outside of this context be aware that you will have to manually restore qiskit.IBMQ the value to qiskit.providers.ibmq.IBMQ after you finish using your mock. Args: backend (str): The class name as a string for the fake device to return from the mock IBMQ object. For example, FakeVigo. Raises: NameError: If the specified value of backend """ mock_ibmq = MagicMock() mock_provider = MagicMock() if not hasattr(backend_mocks, backend): raise NameError( "The specified backend name is not a valid mock from qiskit.providers.fake_provider." ) fake_backend = getattr(backend_mocks, backend)() mock_provider.get_backend.return_value = fake_backend mock_ibmq.get_provider.return_value = mock_provider qiskit.IBMQ = mock_ibmq
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
# Imports from qiskit.circuit.random import random_circuit from qiskit.circuit.library import XGate, YGate from qiskit_ibm_runtime.fake_provider import FakeTorino, FakeOsaka from qiskit.transpiler import InstructionProperties, PassManager from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit.transpiler.preset_passmanagers.plugin import list_stage_plugins from qiskit.transpiler.timing_constraints import TimingConstraints from qiskit.transpiler.passes.scheduling import ASAPScheduleAnalysis,PadDynamicalDecoupling from qiskit.visualization.timeline import draw, IQXStandard from qiskit.transpiler import StagedPassManager from qiskit.visualization import plot_circuit_layout import matplotlib.pyplot as plt import numpy as np # Setup the grader from qc_grader.challenges.iqc_2024 import ( grade_lab2_ex1, grade_lab2_ex2, grade_lab2_ex3, grade_lab2_ex4, grade_lab2_ex5 ) from util import version_check version_check() ans = {} # Place the correct letter next to the corresponding stage, inside a parenthesis # example: ans["test"] = "M" ans["init"] = "C" ans["layout"] = "D" ans["routing"] = "B" ans["translation"] = "F" ans["optimization"] = "A" ans["scheduling"] = "E" # Submit your answer using following code grade_lab2_ex1(ans) ### Create the scoring function def scoring( qc, backend): from util import transpile_scoring layout = qc.layout ##your code here fidelity = transpile_scoring(qc, layout, backend) score = 1 - fidelity ##your code here return score # Submit your answer using following code grade_lab2_ex2(scoring) ### Create a random circuit ## DO NOT CHANGE THE SEED NUMBER seed = 10000 ## Create circuit num_qubits = 6 depth = 4 qc = random_circuit(num_qubits,depth,measure=False, seed=seed) qc.draw('mpl') ## Save FakeTorino as backend backend = FakeTorino() circuit_depths = { 'opt_lv_0': None, 'opt_lv_1': None, 'opt_lv_2': None, 'opt_lv_3': None, } gate_counts = { 'opt_lv_0': None, 'opt_lv_1': None, 'opt_lv_2': None, 'opt_lv_3': None, } scores = { 'opt_lv_0': None, 'opt_lv_1': None, 'opt_lv_2': None, 'opt_lv_3': None, } # Make a pass manager with our desired optimization level and backend pm_lv0 = generate_preset_pass_manager(backend=backend, optimization_level=0, seed_transpiler=seed) # Run for our random circuit tr_lv0 = pm_lv0.run(qc) # uncomment the next line to draw circuit tr_lv0.draw('mpl', idle_wires=False, fold=60) ### Your code here ### circuit_depths['opt_lv_0'] = qc.depth() gate_counts['opt_lv_0'] = qc.size() scores['opt_lv_0'] = scoring(qc, backend) ### Don't change code after this line ### print("Optimization level 0 results") print("====================") print("Circuit depth:", circuit_depths['opt_lv_0']) print("Gate count:", gate_counts['opt_lv_0']) print("Score:", scores['opt_lv_0']) # Make a pass manager with our desired optimization level and backend pm_lv1 = generate_preset_pass_manager(optimization_level=1, backend = backend, seed_transpiler = seed) ### your code here ### # Run for our random circuit tr_lv1 = pm_lv1.run(qc) # uncomment the next line to draw circuit tr_lv1.draw('mpl', idle_wires=False, fold=60) ### Your code here ### circuit_depths['opt_lv_1'] = tr_lv1.depth() gate_counts['opt_lv_1'] = tr_lv1.size() scores['opt_lv_1'] = scoring(tr_lv1, backend) ### Don't change code after this line ### print("Optimization level 1 results") print("====================") print("Circuit depth:", circuit_depths['opt_lv_1']) print("Gate count:", gate_counts['opt_lv_1']) print("Score:", scores['opt_lv_1']) # Make a pass manager with our desired optimization level and backend pm_lv2 = generate_preset_pass_manager(optimization_level=2, backend = backend, seed_transpiler = seed)### your code here ### # Run for our random circuit tr_lv2 = pm_lv2.run(qc) # uncomment the next line to draw circuit tr_lv2.draw('mpl', idle_wires=False, fold=60) ### Your code here ### circuit_depths['opt_lv_2'] = tr_lv2.depth() gate_counts['opt_lv_2'] = tr_lv2.size() scores['opt_lv_2'] = scoring(tr_lv2, backend) ### Don't change code after this line ### print("Optimization level 2 results") print("====================") print("Circuit depth:", circuit_depths['opt_lv_2']) print("Gate count:", gate_counts['opt_lv_2']) print("Score:", scores['opt_lv_2']) pm_lv3 = generate_preset_pass_manager(optimization_level=3, backend = backend, seed_transpiler = seed) ### your code here ### tr_lv3 = pm_lv3.run(qc) ### your code here ### # uncomment to draw circuit tr_lv3.draw('mpl', idle_wires=False, fold=60) ### Your code here ### circuit_depths['opt_lv_3'] = tr_lv3.depth() gate_counts['opt_lv_3'] = tr_lv3.size() scores['opt_lv_3'] = scoring(tr_lv3, backend) ### Don't change code after this line ### print("Optimization level 3 results") print("====================") print("Circuit depth:", circuit_depths['opt_lv_3']) print("Gate count:", gate_counts['opt_lv_3']) print("Score:", scores['opt_lv_3']) colors = ['#FF6666', '#66B2FF'] ax = ["opt_lv_0", "opt_lv_1", "opt_lv_2", "opt_lv_3"] fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(10, 12)) # Plot 1: Circuit Depth ax1.semilogy(ax, [circuit_depths[key] for key in ax],'o-',markersize=9, color='#FF6666', label="Depth") ax1.set_xlabel("Optimization Level", fontsize=12) ax1.set_ylabel("Depth", fontsize=12) ax1.set_title("Circuit Depth", fontsize=14) ax1.legend(fontsize=10) # Plot 2: Total Number of Gates ax2.semilogy(ax, [gate_counts[key] for key in ax],'^-',markersize=9, color='#66B2FF', label="Counts") ax2.set_xlabel("Optimization Level", fontsize=12) ax2.set_ylabel("Gate Count", fontsize=12) ax2.set_title("Gate Count", fontsize=14) ax2.legend(fontsize=10) # Plot 3: Score of Transpiled Circuit ax3.semilogy(ax, [scores[key] for key in ax],'*-',markersize=9, label="Score") ax3.set_xlabel("Optimization Level", fontsize=12) ax3.set_ylabel("Score", fontsize=12) ax3.set_title("Score", fontsize=14) ax3.legend(fontsize=10) fig.tight_layout() plt.show() # Submit your answer using following code ans = [pm_lv0, pm_lv1, pm_lv2, pm_lv3] grade_lab2_ex3(ans) list_stage_plugins("init") print("Plugins run by default init stage") print("=================================") for i in range(4): print(f"\nOptimization level {i}:") pm = generate_preset_pass_manager(backend=backend, optimization_level=i, init_method="default", seed_transpiler=1000) for task in pm.init.to_flow_controller().tasks: print(" -", type(task).__name__) list_stage_plugins("layout") print("Plugins run by default layout stage") print("=================================") for i in range(4): print(f"\nOptimization level {i}:") pm = generate_preset_pass_manager(backend=backend, optimization_level=i, layout_method='default', seed_transpiler=seed) qc_tr = pm.run(qc) for controller_group in pm.layout.to_flow_controller().tasks: tasks = getattr(controller_group, "tasks", []) for task in tasks: print(" - " , str(type(task).__name__)) print(qc_tr.layout.final_index_layout()) display(plot_circuit_layout(pm.run(qc), backend)) for option in list_stage_plugins("layout"): pm = generate_preset_pass_manager(backend=backend, optimization_level=3, layout_method=option, seed_transpiler=seed) qc_tr = pm.run(qc) score = scoring(qc_tr, backend) print(f"Layout method = {option}") print(f"Score: {score:.6f}") print(f"Layout: {qc_tr.layout.final_index_layout()}\n") list_stage_plugins("routing") print("Number of each gates of transpiled circuit and the score") print("=================================") for i in range(4): print(f"\nOptimization level {i}:") pm = generate_preset_pass_manager(backend=backend, optimization_level=i, routing_method='basic', seed_transpiler=seed) qc_tr = pm.run(qc) score = scoring(qc_tr, backend) for key, value in qc_tr.count_ops().items(): print(key, ":", value) print(f"Score: {score:.6f}") print("Plugins run by basic routing stage") print("=================================") for i in range(4): print(f"\nOptimization level {i}:") pm = generate_preset_pass_manager(backend=backend, optimization_level=i, routing_method='basic', seed_transpiler=seed) for controller_group in pm.routing.to_flow_controller().tasks: tasks = getattr(controller_group, "tasks", []) for task in tasks: print(" - " , str(type(task).__name__)) display(pm.routing.draw()) print(pm.run(qc).layout.final_index_layout()) ## process stopped due to lookahead options = ['basic','sabre', 'stochastic'] for option in options: print(f"Layout option = {option}:") pm = generate_preset_pass_manager(backend=backend, optimization_level=3, routing_method=option, seed_transpiler=seed) qc_tr = pm.run(qc) score = scoring(qc_tr, backend) print(f"Score: {score:.6f}") for key, value in qc_tr.count_ops().items(): print(key, ":", value) print("\n") list_stage_plugins("translation") print("Number of each gates of transpiled circuit") print("=================================") for i in range(4): print(f"\nOptimization level {i}:") pm = generate_preset_pass_manager(backend=backend, optimization_level=i, translation_method='translator', seed_transpiler=seed) qc_tr = pm.run(qc) score = scoring(qc_tr, backend) for key, value in qc_tr.count_ops().items(): print(key, ":", value) print(f"Score: {score:.6f}") options = ['translator', 'synthesis'] print("Number of each gates of transpiled circuit") print("=================================") for option in options: print(f"Layout option = {option}:") pm = generate_preset_pass_manager(backend=backend, optimization_level=3, translation_method=option, seed_transpiler=seed) qc_tr = pm.run(qc) score = scoring(qc_tr, backend) for key, value in qc_tr.count_ops().items(): print(key, ":", value) print(f"Score: {score:.6f}") print("\n") tr_depths = [] tr_gate_counts = [] tr_scores = [] options = ['translator', 'synthesis'] for i in range(4): for option in options: pm = generate_preset_pass_manager(backend=backend, optimization_level=i, translation_method=option, seed_transpiler=seed) tr_depths.append(pm.run(qc).depth()) tr_gate_counts.append(sum(pm.run(qc).count_ops().values())) tr_scores.append(scoring(pm.run(qc), backend)) colors = ['#FF6666', '#66B2FF'] markers = [ '^', '*'] linestyles = ['-.', ':'] opt_list = [] for i in range(4): opt_list.append(f"Optimization Level {i}") ax = opt_list fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(10, 12)) # Plot 1: Circuit Depth for i in range(2): ax1.plot(ax, tr_depths[i:i+4], label=options[i], marker=markers[i], markersize=9, linestyle=linestyles[i], color=colors[i], linewidth=2) ax1.set_xlabel("translation options", fontsize=12) ax1.set_ylabel("Depth", fontsize=12) ax1.set_title("Circuit Depth of Transpiled Circuit", fontsize=14) ax1.legend(fontsize=10) # Plot 2: Total Number of Gates for i in range(2): ax2.plot(ax, tr_gate_counts[i:i+4], label=options[i], marker=markers[i], markersize=9, linestyle=linestyles[i], color=colors[i], linewidth=2) ax2.set_xlabel("translation options", fontsize=12) ax2.set_ylabel("# of Total Gates", fontsize=12) ax2.set_title("Total Number of Gates of Transpiled Circuit", fontsize=14) ax2.legend(fontsize=10) # Plot 3: Score of Transpiled Circuit for i in range(2): ax3.plot(ax, tr_scores[i:i+4], label=options[i], marker=markers[i],markersize=9, linestyle=linestyles[i], color=colors[i], linewidth=2) ax3.set_xlabel("translation options", fontsize=12) ax3.set_ylabel("Score of Transpiled Circuit", fontsize=12) ax3.set_title("Score of Transpiled Circuit", fontsize=14) ax3.legend(fontsize=10) fig.tight_layout() plt.show() """tr_depths = [] tr_gate_counts = [] tr_scores = [] approximation_degree_list = np.linspace(0,1,10) for i in range(4): for j in approximation_degree_list: # your code here # # your code here # """ """ colors = ['#FF6666', '#FFCC66', '#99FF99', '#66B2FF'] markers = ['o', 's', '^', '*'] linestyles = ['-', '--', '-.', ':'] ax = approximation_degree_list fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(10, 12)) # Plot 1: Circuit Depth for i in range(4): ax1.plot(ax, tr_depths[i::4], label=f"Optimization Level {i}", marker=markers[i], markersize=9, linestyle=linestyles[i], color=colors[i], linewidth=2) ax1.set_xlabel("Approximation Degree", fontsize=12) ax1.set_ylabel("Depth", fontsize=12) ax1.set_title("Circuit Depth of Transpiled Circuit", fontsize=14) ax1.legend(fontsize=10) # Plot 2: Total Number of Gates for i in range(4): ax2.plot(ax, tr_gate_counts[i::4], label=f"Optimization Level {i}", marker=markers[i], markersize=9, linestyle=linestyles[i], color=colors[i], linewidth=2) ax2.set_xlabel("Approximation Degree", fontsize=12) ax2.set_ylabel("# of Total Gates", fontsize=12) ax2.set_title("Total Number of Gates of Transpiled Circuit", fontsize=14) ax2.legend(fontsize=10) # Plot 3: Score of Transpiled Circuit for i in range(4): ax3.plot(ax, tr_scores[i::4], label=f"Optimization Level {i}", marker=markers[i],markersize=9, linestyle=linestyles[i], color=colors[i], linewidth=2) ax3.set_xlabel("Approximation Degree", fontsize=12) ax3.set_ylabel("Score of Transpiled Circuit", fontsize=12) ax3.set_title("Score of Transpiled Circuit", fontsize=14) ax3.legend(fontsize=10) fig.tight_layout() plt.show() """ list_stage_plugins("scheduling") backend_timing = backend.target.timing_constraints() timing_constraints = TimingConstraints( granularity=backend_timing.granularity, min_length=backend_timing.min_length, pulse_alignment=backend_timing.pulse_alignment, acquire_alignment=backend_timing.acquire_alignment ) # Run with optimization level 3 and 'asap' scheduling pass pm_asap = generate_preset_pass_manager( optimization_level=3, backend=backend, timing_constraints=timing_constraints, scheduling_method="asap", seed_transpiler=seed, ) my_style = { 'formatter.general.fig_width': 40, 'formatter.general.fig_unit_height': 1, } draw(pm_asap.run(qc), style=IQXStandard(**my_style), show_idle=False, show_delays=True) pm_alap = generate_preset_pass_manager( optimization_level=3, backend=backend, timing_constraints=timing_constraints, scheduling_method="alap", seed_transpiler=seed, ) draw(pm_alap.run(qc), style=IQXStandard(**my_style), show_idle=False, show_delays=True) print("Score") print("===============") print(f"asap: {scoring(pm_asap.run(qc), backend):.6f}") print(f"alap: {scoring(pm_alap.run(qc), backend):.6f}") pm_ex4 = generate_preset_pass_manager( backend=backend, ### Write your code below here ### optimization_level = 3, layout_method = 'sabre', routing_method = 'sabre', translation_method = 'synthesis' ### Don't change any code past this line ### ) # Submit your answer using following code grade_lab2_ex4(pm_ex4) X = XGate() Y = YGate() dd_sequence = [X, Y, X, Y] backend=FakeTorino() target = backend.target y_gate_properties = {} for qubit in range(target.num_qubits): y_gate_properties.update( { (qubit,): InstructionProperties( duration=target["x"][(qubit,)].duration, error=target["x"][(qubit,)].error, ) } ) target.add_instruction(YGate(), y_gate_properties) dd_pm = PassManager( [ ## your code here ASAPScheduleAnalysis(target=target), PadDynamicalDecoupling(target=target, dd_sequence=dd_sequence), ## your code here ] ) draw(pm_asap.run(qc), style=IQXStandard(**my_style), show_idle=False, show_delays=True) staged_pm_dd = StagedPassManager( stages=["scheduling"], scheduling=dd_pm ) qc_tr = pm_asap.run(qc) draw(staged_pm_dd.run(qc_tr), style=IQXStandard(**my_style), show_idle=False, show_delays=True) # Submit your answer using following code grade_lab2_ex5(staged_pm_dd)
https://github.com/quantumjim/pewpew_qiskit_workshops
quantumjim
%matplotlib notebook import pew # setting up tools for the pewpew from microqiskit import QuantumCircuit, simulate # setting up tools for quantum pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen qc = QuantumCircuit(2,2) # create an empty circuit with two qubits and two output bits # create circuits with the required measurements, so we can add them in easily meas = [{},{}] for j in range(2): meas[j]['Z'] = QuantumCircuit(2,2) meas[j]['Z'].measure(j,j) meas[j]['X'] = QuantumCircuit(2,2) meas[j]['X'].h(j) meas[j]['X'].measure(j,j) basis = ['Z','Z'] # set the initial measurement basis for each qubit # loop over the squares centered on (1,2), (6,2) (1,4) and (6,4) and make all dim for (X,Y) in [(1,2),(6,2),(1,4),(6,4)]: for dX in [+1,0,-1]: for dY in [+1,0,-1]: screen.pixel(X+dX,Y+dY,2) pew.show(screen) for (X,Y) in [(1,2),(6,2),(1,4),(6,4)]: screen.pixel(X,Y,0) # turn off the center pixels of the squares old_keys = 0 while True: # loop which checks for user input and responds # look for and act upon key presses keys = pew.keys() # get current key presses if keys!=0 and keys!=old_keys: if keys&pew.K_O: basis[0] = 'X'*(basis[0]=='Z') + 'Z'*(basis[0]=='X') # toggle basis for right qubit if keys&pew.K_X: basis[1] = 'X'*(basis[1]=='Z') + 'Z'*(basis[1]=='X') # toggle basis for left qubit old_keys = keys # execute the circuit and get a single sample of memory for the given measurement bases m = simulate(qc+meas[0][basis[0]]+meas[1][basis[1]],shots=1,get='memory') # turn the pixels (1,2) and (1,4) (depending on basis[1]) on or off (depending on m[0][0]) if m[0][0]=='1': if basis[1]=='Z': screen.pixel(1,2,3) else: screen.pixel(1,4,3) else: if basis[1]=='Z': screen.pixel(1,2,0) else: screen.pixel(1,4,0) # do the same for pixels (6,2) and (6,4) if m[0][1]=='1': if basis[0]=='Z': screen.pixel(6,2,3) else: screen.pixel(6,4,3) else: if basis[0]=='Z': screen.pixel(6,2,0) else: screen.pixel(6,4,0) # turn the pixels not used to display m[0] to dim if basis[1]=='Z': screen.pixel(1,4,2) else: screen.pixel(1,2,2) if basis[0]=='Z': screen.pixel(6,4,2) else: screen.pixel(6,2,2) pew.show(screen) # update screen to display the above changes pew.tick(1/6) # pause for a sixth of a second import pew # setting up tools for the pewpew from microqiskit import QuantumCircuit, simulate # setting up tools for quantum pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen qc = QuantumCircuit(2,2) # create an empty circuit with two qubits and two output bits # create circuits with the required measurements, so we can add them in easily meas = [{},{}] for j in range(2): meas[j]['Z'] = QuantumCircuit(2,2) meas[j]['Z'].measure(j,j) meas[j]['X'] = QuantumCircuit(2,2) meas[j]['X'].h(j) meas[j]['X'].measure(j,j) basis = ['Z','Z'] # set the initial measurement basis for each qubit # loop over the squares centered on (1,2), (6,2) (1,4) and (6,4) and make all dim for (X,Y) in [(1,2),(6,2),(1,4),(6,4)]: for dX in [+1,0,-1]: for dY in [+1,0,-1]: screen.pixel(X+dX,Y+dY,2) pew.show(screen) for (X,Y) in [(1,2),(6,2),(1,4),(6,4)]: screen.pixel(X,Y,0) # turn off the center pixels of the squares old_keys = 0 while True: # loop which checks for user input and responds # look for and act upon key presses keys = pew.keys() # get current key presses if keys!=0 and keys!=old_keys: if keys&pew.K_O: basis[0] = 'X'*(basis[0]=='Z') + 'Z'*(basis[0]=='X') # toggle basis for right qubit if keys&pew.K_X: basis[1] = 'X'*(basis[1]=='Z') + 'Z'*(basis[1]=='X') # toggle basis for left qubit if keys&pew.K_UP: qc.x(0) # x for qubit 0 when UP is pressed if keys&pew.K_LEFT: qc.x(1) # x for qubit 1 when LEFT is pressed if keys&pew.K_RIGHT: qc.h(0) # h for qubit 0 when RIGHT is pressed if keys&pew.K_DOWN: qc.h(1) # h for qubit 1 when DOWN is pressed old_keys = keys # execute the circuit and get a single sample of memory for the given measurement bases m = simulate(qc+meas[0][basis[0]]+meas[1][basis[1]],shots=1,get='memory') # turn the pixels (1,2) and (1,4) (depending on basis[1]) on or off (depending on m[0][0]) if m[0][0]=='1': if basis[1]=='Z': screen.pixel(1,2,3) else: screen.pixel(1,4,3) else: if basis[1]=='Z': screen.pixel(1,2,0) else: screen.pixel(1,4,0) # do the same for pixels (6,2) and (6,4) if m[0][1]=='1': if basis[0]=='Z': screen.pixel(6,2,3) else: screen.pixel(6,4,3) else: if basis[0]=='Z': screen.pixel(6,2,0) else: screen.pixel(6,4,0) # turn the pixels not used to display m[0] to dim if basis[1]=='Z': screen.pixel(1,4,2) else: screen.pixel(1,2,2) if basis[0]=='Z': screen.pixel(6,4,2) else: screen.pixel(6,2,2) pew.show(screen) # update screen to display the above changes pew.tick(1/6) # pause for a sixth of a second import pew # setting up tools for the pewpew from microqiskit import QuantumCircuit, simulate # setting up tools for quantum pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen qc = QuantumCircuit(2,2) # create an empty circuit with two qubits and two output bits qc.h(0) qc.cx(0,1) # create circuits with the required measurements, so we can add them in easily meas = [{},{}] for j in range(2): meas[j]['Z'] = QuantumCircuit(2,2) meas[j]['Z'].measure(j,j) meas[j]['X'] = QuantumCircuit(2,2) meas[j]['X'].h(j) meas[j]['X'].measure(j,j) basis = ['Z','Z'] # set the initial measurement basis for each qubit # loop over the squares centered on (1,2), (6,2) (1,4) and (6,4) and make all dim for (X,Y) in [(1,2),(6,2),(1,4),(6,4)]: for dX in [+1,0,-1]: for dY in [+1,0,-1]: screen.pixel(X+dX,Y+dY,2) pew.show(screen) for (X,Y) in [(1,2),(6,2),(1,4),(6,4)]: screen.pixel(X,Y,0) # turn off the center pixels of the squares old_keys = 0 while True: # loop which checks for user input and responds # look for and act upon key presses keys = pew.keys() # get current key presses if keys!=0 and keys!=old_keys: if keys==pew.K_O: basis[0] = 'X'*(basis[0]=='Z') + 'Z'*(basis[0]=='X') # toggle basis for right qubit if keys==pew.K_X: basis[1] = 'X'*(basis[1]=='Z') + 'Z'*(basis[1]=='X') # toggle basis for left qubit if keys==pew.K_UP: qc.x(0) # x for qubit 0 when UP is pressed if keys==pew.K_LEFT: qc.x(1) # x for qubit 1 when LEFT is pressed if keys==pew.K_RIGHT: qc.h(0) # h for qubit 0 when RIGHT is pressed if keys==pew.K_DOWN: qc.h(1) # h for qubit 1 when DOWN is pressed old_keys = keys # execute the circuit and get a single sample of memory for the given measurement bases m = simulate(qc+meas[0][basis[0]]+meas[1][basis[1]],shots=1,get='memory') # turn the pixels (1,2) and (1,4) (depending on basis[1]) on or off (depending on m[0][0]) if m[0][0]=='1': if basis[1]=='Z': screen.pixel(1,2,3) else: screen.pixel(1,4,3) else: if basis[1]=='Z': screen.pixel(1,2,0) else: screen.pixel(1,4,0) # do the same for pixels (6,2) and (6,4) if m[0][1]=='1': if basis[0]=='Z': screen.pixel(6,2,3) else: screen.pixel(6,4,3) else: if basis[0]=='Z': screen.pixel(6,2,0) else: screen.pixel(6,4,0) # turn the pixels not used to display m[0] to dim if basis[1]=='Z': screen.pixel(1,4,2) else: screen.pixel(1,2,2) if basis[0]=='Z': screen.pixel(6,4,2) else: screen.pixel(6,2,2) # flag up the '11' output by lighting up pixels in the bottom-center if m[0]=='11': screen.pixel(3,6,3) screen.pixel(4,6,3) else: screen.pixel(3,6,0) screen.pixel(4,6,0) # same with '00' and the top center if m[0]=='00': screen.pixel(3,0,3) screen.pixel(4,0,3) else: screen.pixel(3,0,0) screen.pixel(4,0,0) pew.show(screen) # update screen to display the above changes pew.tick(1/6) # pause for a sixth of a second import pew # setting up tools for the pewpew from microqiskit import QuantumCircuit, simulate # setting up tools for quantum pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen qc = QuantumCircuit(2,2) # create an empty circuit with two qubits and two output bits qc.initialize([0,0.57735,0.57735,0.57735]) # create circuits with the required measurements, so we can add them in easily meas = [{},{}] for j in range(2): meas[j]['Z'] = QuantumCircuit(2,2) meas[j]['Z'].measure(j,j) meas[j]['X'] = QuantumCircuit(2,2) meas[j]['X'].h(j) meas[j]['X'].measure(j,j) basis = ['Z','Z'] # set the initial measurement basis for each qubit # loop over the squares centered on (1,2), (6,2) (1,4) and (6,4) and make all dim for (X,Y) in [(1,2),(6,2),(1,4),(6,4)]: for dX in [+1,0,-1]: for dY in [+1,0,-1]: screen.pixel(X+dX,Y+dY,2) pew.show(screen) for (X,Y) in [(1,2),(6,2),(1,4),(6,4)]: screen.pixel(X,Y,0) # turn off the center pixels of the squares old_keys = 0 while True: # loop which checks for user input and responds # look for and act upon key presses keys = pew.keys() # get current key presses if keys!=0 and keys!=old_keys: if keys&pew.K_O: basis[0] = 'X'*(basis[0]=='Z') + 'Z'*(basis[0]=='X') # toggle basis for right qubit if keys&pew.K_X: basis[1] = 'X'*(basis[1]=='Z') + 'Z'*(basis[1]=='X') # toggle basis for left qubit if keys&pew.K_UP: qc.x(0) # x for qubit 0 when UP is pressed if keys&pew.K_LEFT: qc.x(1) # x for qubit 1 when LEFT is pressed if keys&pew.K_RIGHT: qc.h(0) # h for qubit 0 when RIGHT is pressed if keys&pew.K_DOWN: qc.h(1) # h for qubit 1 when DOWN is pressed old_keys = keys # execute the circuit and get a single sample of memory for the given measurement bases m = simulate(qc+meas[0][basis[0]]+meas[1][basis[1]],shots=1,get='memory') # turn the pixels (1,2) and (1,4) (depending on basis[1]) on or off (depending on m[0][0]) if m[0][0]=='1': if basis[1]=='Z': screen.pixel(1,2,3) else: screen.pixel(1,4,3) else: if basis[1]=='Z': screen.pixel(1,2,0) else: screen.pixel(1,4,0) # do the same for pixels (6,2) and (6,4) if m[0][1]=='1': if basis[0]=='Z': screen.pixel(6,2,3) else: screen.pixel(6,4,3) else: if basis[0]=='Z': screen.pixel(6,2,0) else: screen.pixel(6,4,0) # turn the pixels not used to display m[0] to dim if basis[1]=='Z': screen.pixel(1,4,2) else: screen.pixel(1,2,2) if basis[0]=='Z': screen.pixel(6,4,2) else: screen.pixel(6,2,2) # flag up the '11' output by lighting up pixels in the bottom-center if m[0]=='11': screen.pixel(3,6,3) screen.pixel(4,6,3) else: screen.pixel(3,6,0) screen.pixel(4,6,0) # same with '00' and the top center if m[0]=='00': screen.pixel(3,0,3) screen.pixel(4,0,3) else: screen.pixel(3,0,0) screen.pixel(4,0,0) pew.show(screen) # update screen to display the above changes pew.tick(1/6) # pause for a sixth of a second
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute, assemble, Aer from qiskit.tools.visualization import plot_histogram from math import pi import matplotlib.pyplot as plt q = QuantumRegister(1,'q') c = ClassicalRegister(1,'c') qc = QuantumCircuit(q, c) qc.h(0) qc.measure(0,0) qc.x(0).c_if(c, 0) qc.draw(output='mpl') q = QuantumRegister(3,'q') c = ClassicalRegister(3,'c') qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.barrier() qc.measure(q,c) qc.draw('mpl') print(bin(3)) print(bin(7)) q = QuantumRegister(3,'q') c = ClassicalRegister(3,'c') qc = QuantumCircuit(q, c) qc.h(0) qc.h(1) qc.h(2) qc.barrier() qc.measure(q,c) qc.x(2).c_if(c, 3) # for the 011 case qc.x(2).c_if(c, 7) # for the 111 case qc.draw(output='mpl') nq = 2 m = 2 q = QuantumRegister(nq,'q') c = ClassicalRegister(m,'c') qc_S = QuantumCircuit(q,c) qc_S.h(0) qc_S.x(1) qc_S.draw('mpl') cu_circ = QuantumCircuit(2) cu_circ.cp(pi/2,0,1) cu_circ.draw('mpl') for _ in range(2**(m-1)): qc_S.cp(pi/2,0,1) qc_S.draw('mpl') def x_measurement(qc, qubit, cbit): """Measure 'qubit' in the X-basis, and store the result in 'cbit'""" qc.h(qubit) qc.measure(qubit, cbit) x_measurement(qc_S, q[0], c[0]) qc_S.draw('mpl') qc_S.reset(0) qc_S.h(0) qc_S.draw('mpl') qc_S.p(-pi/2,0).c_if(c,1) qc_S.draw('mpl') ## 2^t c-U operations (with t=m-2) for _ in range(2**(m-2)): qc_S.cp(pi/2,0,1) x_measurement(qc_S, q[0], c[1]) qc_S.draw('mpl') sim = Aer.get_backend('qasm_simulator') count0 = execute(qc_S, sim).result().get_counts() key_new = [str(int(key,2)/2**m) for key in list(count0.keys())] count1 = dict(zip(key_new, count0.values())) fig, ax = plt.subplots(1,2) plot_histogram(count0, ax=ax[0]) plot_histogram(count1, ax=ax[1]) plt.tight_layout() nq = 3 # number of qubits m = 3 # number of classical bits q = QuantumRegister(nq,'q') c = ClassicalRegister(m,'c') qc = QuantumCircuit(q,c) qc.h(0) qc.x([1,2]) qc.draw('mpl') cu_circ = QuantumCircuit(nq) cu_circ.mcp(pi/4,[0,1],2) cu_circ.draw('mpl') for _ in range(2**(m-1)): qc.mcp(pi/4,[0,1],2) qc.draw('mpl') x_measurement(qc, q[0], c[0]) qc.draw('mpl') qc.reset(0) qc.h(0) qc.draw('mpl') qc.p(-pi/2,0).c_if(c,1) qc.draw('mpl') for _ in range(2**(m-2)): qc.mcp(pi/4,[0,1],2) x_measurement(qc, q[0], c[1]) qc.draw('mpl') # initialization of qubit q0 qc.reset(0) qc.h(0) # phase correction qc.p(-pi/4,0).c_if(c,1) qc.p(-pi/2,0).c_if(c,2) qc.p(-3*pi/4,0).c_if(c,3) # c-U operations for _ in range(2**(m-3)): qc.mcp(pi/4,[0,1],2) # X measurement qc.h(0) qc.measure(0,2) qc.draw('mpl') count0 = execute(qc, sim).result().get_counts() key_new = [str(int(key,2)/2**m) for key in list(count0.keys())] count1 = dict(zip(key_new, count0.values())) fig, ax = plt.subplots(1,2) plot_histogram(count0, ax=ax[0]) plot_histogram(count1, ax=ax[1]) fig.tight_layout() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/JohnBurke4/qaoa_testing_framework
JohnBurke4
from qiskit import QuantumCircuit from QAOA_Mixer import Mixer from QAOA_Cost_Hamiltonian import CostHamiltonian from QAOA_Initialization import QAOAInit from Helper_Functions import groverDiffuser class QAOACircuit: circuit = None parameters = [] def __init__(self, numQubits, layers=1, mixerType='classic', problem='maxcut', problemType=None, initType='x_high_eigenstate'): self.numQubits = numQubits self.problem = problem self.problemType = problemType self.initType = initType self.mixerType = mixerType self.layers = layers def build(self): self.circuit = None self.parameters = [] qc = QuantumCircuit(self.numQubits) parameters = [] init = QAOAInit(self.numQubits, 1, self.initType) init.build() mixer = Mixer(self.numQubits, self.layers, self.mixerType) mixer.build() problem = CostHamiltonian(self.numQubits, self.layers, self.problemType, self.problem) problem.build() (initCirc, initParams) = init.getCircuitAtLayer(0) qc.append(initCirc, list(range(0, self.numQubits))) parameters += initParams for l in range(0, self.layers): (problemCirc, problemParams) = problem.getCircuitAtLayer(l) qc.append(problemCirc, list(range(0, self.numQubits))) parameters += problemParams (mixerCirc, mixerParams) = mixer.getCircuitAtLayer(l) qc.append(mixerCirc, list(range(0, self.numQubits))) parameters += mixerParams # diff = groverDiffuser(self.numQubits) # qc.append(diff, list(range(0, self.numQubits))) # qc.h(range(0, self.numQubits)) qc.measure_all() self.circuit = qc self.parameters = parameters def getCircuitWithParameters(self, parameterValues): qc = self.circuit parameters = self.parameters parameterMap = {} for i in range(0, len(parameters)): parameterMap[parameters[i]] = parameterValues[i] return qc.assign_parameters(parameterMap) def getNumberOfParameters(self): return len(self.parameters)
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/Pitt-JonesLab/mirror-gates
Pitt-JonesLab
from transpile_benchy.metrics.gate_counts import ( DepthMetric, TotalMetric, TotalSwaps, ) from qiskit.circuit.library import iSwapGate from qiskit.transpiler import CouplingMap from mirror_gates.pass_managers import Mirage, QiskitLevel3 from mirror_gates.utilities import SubsMetric from mirror_gates.logging import transpile_benchy_logger # N = 4 # coupling_map = CouplingMap.from_line(N) # coupling_map = CouplingMap.from_heavy_hex(5) coupling_map = CouplingMap.from_grid(6, 6) from transpile_benchy.library import CircuitLibrary library = CircuitLibrary.from_txt("../../../circuits/medium_circuits.txt") # library = CircuitLibrary.from_txt("../../circuits/debug.txt") # XXX set consolidate to False # this is allowed only because my pass manager will preserve consolidation # see post_stage, I call fastconsolidate manually # NOTE: use TotalSwaps to verify baselines have > 0 swaps # otherwise, there is no room for improvement. # we can include these if we want to show our methods will still work # but somewhat trivial since we just append VF2Layout metrics = [ DepthMetric(consolidate=False), TotalMetric(consolidate=False), TotalSwaps(consolidate=False), SubsMetric(), ] transpilers = [ # QiskitLevel3(coupling_map, cx_basis=True), # Mirage(coupling_map, cx_basis=True, parallel=0), QiskitLevel3(coupling_map), Mirage(coupling_map, logger=transpile_benchy_logger), ] from transpile_benchy.benchmark import Benchmark benchmark = Benchmark( transpilers=transpilers, circuit_library=library, metrics=metrics, logger=transpile_benchy_logger, num_runs=5, ) benchmark.run() # print(benchmark) print(benchmark) benchmark.summary_statistics(transpilers[0], transpilers[1]) from transpile_benchy.render import plot_benchmark plot_benchmark(benchmark, save=1, legend_show=0, filename="grid", color_override=[0, 3])
https://github.com/minnukota381/Quantum-Computing-Qiskit
minnukota381
from qiskit import * from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram # Create a quantum circuit with 2 qubits # The default initial state of qubits will be |0> or [1,0] B3 = QuantumCircuit(2) B3.h(0) B3.x(1) B3.cx(0,1) B3.draw('mpl') #Get the backend for the circuit to display unitary matrix backend = Aer.get_backend('unitary_simulator') #execute the circuit using the backend out = execute(B3,backend).result().get_unitary() #import qiskit_textbook and display the combined unitary matrix from qiskit_textbook.tools import array_to_latex array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ") #Get the backend for the circuit (simulator or realtime system) backend = Aer.get_backend('statevector_simulator') #execute the circuit using the backend out = execute(B3,backend).result().get_statevector() #import qiskit_textbook and display the statevector #from qiskit_textbook.tools import array_to_latex array_to_latex(out, pretext = "\\text{Statevector} = ") #execute the circuit and get the plain result out = execute(B3,backend).result() #getting the count of the result counts = out.get_counts() #plotting the histogram plot_histogram(counts)
https://github.com/dkp-quantum/Tutorials
dkp-quantum
# If you already have saved IBM credentials with previous version, # update your credentials that is stored in disk from qiskit import IBMQ IBMQ.update_account() # import from qiskit import * import numpy as np from qiskit.visualization import plot_histogram, plot_state_city, plot_state_paulivec from qiskit.quantum_info import Pauli, state_fidelity, basis_state, process_fidelity from qiskit.tools.monitor import backend_overview, backend_monitor, job_monitor # Create a quantum register with 2 qubits q = QuantumRegister(2,'q') # Form a quantum circuit # Note that the circuit name is optional qc = QuantumCircuit(q,name="first_qc") # Display the quantum circuit qc.draw() # Create a classical register with 2 bits c = ClassicalRegister(2,'c') meas = QuantumCircuit(q,c,name="first_m") meas.barrier(q) meas.measure(q[0], c[0]) meas.measure(q[1], c[1]) #meas.measure(q[3], c[3]) #meas.measure(q[4], c[4]) meas.draw() # Add a x gate on qubit 0. qc.x(0) # Add a Hadamard gate on qubit 0, putting this in superposition. qc.h(0) # Add a CX (CNOT) gate on control qubit 0 # and target qubit 1 to create an entangled state. qc.cx(0, 1) qc.draw() # Quantum circuits can be added with + operations # Add two pre-defined circuits qc_comp=qc+meas qc_comp.draw() # Draw the quantum circuit in a different (slightly better) format qc_comp.draw(output='mpl') # Create the quantum circuit with the measurement in one go. qc_tot = QuantumCircuit(q,c,name="2q_all") qc_tot.x(0) qc_tot.h(0) qc_tot.cx(0,1) qc_tot.barrier() qc_tot.measure(0,0) qc_tot.measure(1,1) qc_tot.draw(output='mpl') # Use Aer's qasm_simulator backend_q = 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 default. job_sim1 = execute(qc_comp, backend_q, shots=1024) job_sim1.status() # Grab the results from the job. result_sim1 = job_sim1.result() result_sim1 result_sim1.get_counts(qc_comp) plot_histogram(result_sim1.get_counts(qc_comp)) # Use Aer's statevector_simulator backend_sv = Aer.get_backend('statevector_simulator') # Execute the circuit on the statevector simulator. job_sim2 = execute(qc, backend_sv) # Grab the results from the job. result_sim2 = job_sim2.result() # Output the entire result job_sim2.result() # See output state as a vector outputstate = result_sim2.get_statevector(qc, decimals=5) print(outputstate) # Visualize density matrix plot_state_city(outputstate) # Examine state fidelity, compare with a basis state |111> sf1=state_fidelity(basis_state('11', 2), outputstate) # Examine state fidelity w.r.t the desired state desired_state=[1,0,0,-1]/np.sqrt(2) sf2=state_fidelity(desired_state, outputstate) print(sf1) print(sf2) # Create a quantum register with 4 qubits q4 = QuantumRegister(4,'q') # Create classical registers for measurement c4 = ClassicalRegister(4,'c') # Form a quantum circuit # Note that the circuit name is optional ex1_qc = QuantumCircuit(q4,c4,name="ex1") # Display the quantum circuit ex1_qc.draw() # Add gates to the quantum circuit ex1_qc.h(0) ex1_qc.cx(0,1) ex1_qc.cx(0,2) ex1_qc.cx(0,3) # Measurement ex1_qc.barrier() ex1_qc.measure(0,0) ex1_qc.measure(1,1) ex1_qc.measure(2,2) ex1_qc.measure(3,3) ex1_qc.draw(output='mpl') # Simpler code ex1_qc = QuantumCircuit(q4,c4,name="first_m") # Gates ex1_qc.h(0) for i in range(3): ex1_qc.cx(0,i+1) # Measurement ex1_qc.barrier() for i in range(4): ex1_qc.measure(i,i) ex1_qc.draw(output='mpl') # Use Aer's qasm_simulator backend_q = 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 default. job_ex1 = execute(ex1_qc, backend_q, shots=1024) plot_histogram(job_ex1.result().get_counts(ex1_qc)) # Create a simple quantum register with 2 qubit # to examine unitary simulator qu2 = QuantumRegister(2,'qu') # Form a quantum circuit # Note that the circuit name is optional qu = QuantumCircuit(qu2,name="unitary_qc") # Add a single qubit rotation qu.z(0) qu.z(1) # Display the quantum circuit qu.draw(output='mpl') # Use Aer's unitary_simulator backend_u = Aer.get_backend('unitary_simulator') # Execute the circuit on the unitary simulator. job_usim = execute(qu, backend_u) # Grab the results from the job. result_usim = job_usim.result() result_usim # Output the unitary matrix unitary = result_usim.get_unitary(qu) print('%s\n' % unitary) # Check process fidelity pf1=process_fidelity(Pauli(label='IX').to_matrix(), unitary) pf2=process_fidelity(Pauli(label='ZZ').to_matrix(), unitary) print('%s\n' % pf1) print('%s\n' % pf2) from qiskit.quantum_info import process_fidelity def compare_qc(qc_ref,qc_test): # Use Aer's unitary_simulator backend_u = Aer.get_backend('unitary_simulator') # Output the refernce unitary matrix u_ref = execute(qc_ref,backend_u).result().get_unitary(qc_ref) # Output the test unitary matrix u_test = execute(qc_test,backend_u).result().get_unitary(qc_test) return process_fidelity(u_ref,u_test) # Create a reference circuit swap_c_ref = QuantumCircuit(2) swap_c_ref.swap(0,1) display(swap_c_ref.draw(output='mpl')) # Create a test circuit with 3 cnot gates instead of a swap gate swap_c_test = QuantumCircuit(2) swap_c_test.cx(0,1) swap_c_test.cx(1,0) swap_c_test.cx(0,1) display(swap_c_test.draw(output='mpl')) # Compare two unitaries compare_qc(swap_c_ref,swap_c_test) from qiskit.quantum_info import state_fidelity def compare_sv(qc_ref,qc_test): # Use Aer's unitary_simulator backend_v = Aer.get_backend('statevector_simulator') # Output the refernce unitary matrix sv_ref = execute(qc_ref,backend_v).result().get_statevector(qc_ref,decimals=7) # Output the test unitary matrix sv_test = execute(qc_test,backend_v).result().get_statevector(qc_test,decimals=7) return state_fidelity(sv_ref,sv_test) import random as r # Apply a random 1-qubit rotation around x and y ay = r.random()*np.pi ax = r.random()*np.pi # Create a circuit for preparing an initial state swap_c_init = QuantumCircuit(3) swap_c_init.h(0) swap_c_init.ry(ay,1) swap_c_init.rx(ax,2) display(swap_c_init.draw(output='mpl')) # Create a reference circuit cswap_c_ref = QuantumCircuit(3) cswap_c_ref.append(swap_c_init,[0,1,2]) cswap_c_ref.cswap(0,1,2) display(cswap_c_ref.draw(output='mpl')) # Create a test circuit with 3 cnot gates instead of a swap gate cswap_c_test = QuantumCircuit(3) cswap_c_test.append(swap_c_init,[0,1,2]) cswap_c_test.cx(2,1) cswap_c_test.ccx(0,1,2) cswap_c_test.cx(2,1) display(cswap_c_test.draw(output='mpl')) # Compare two states compare_sv(cswap_c_ref,cswap_c_test) # Measure an expectation value of a Pauli observable Z = np.array([[1, 0], [0, -1]]) X = np.array([[0, 1], [1, 0]]) Y = np.array([[0, -1j], [1j, 0]]) ZZ=np.kron(Z,Z) XX=np.kron(X,X) # Or use qiskit's built-in function to define Pauli matrices ZI = Pauli(label='ZI').to_matrix() XI = Pauli(label='XI').to_matrix() YI = Pauli(label='YI').to_matrix() # Create some functions for measuring expectation values # For pure states def expectation_state(state, Operator): return np.dot(state.conj(), np.dot(Operator, state)) # For density matrices def expectation_density(density, Operator): return np.trace(Operator @ density) # We'll use statevector simulator, so no need to define classical registers q2 = QuantumRegister(2,'q') # Create a quantum circuit for 00 + 11 state ex2_qc1 = QuantumCircuit(q2) ex2_qc1.h(0) ex2_qc1.cx(0,1) # Create a quantum circuit for 00 - 11 state ex2_qc2 = QuantumCircuit(q2) ex2_qc2.x(0) ex2_qc2.h(0) ex2_qc2.cx(0,1) print('00+11 circuit:') display(ex2_qc1.draw(output='mpl')) print('00-11 circuit:') display(ex2_qc2.draw(output='mpl')) # Use Aer's statevector_simulator backend_sv = Aer.get_backend('statevector_simulator') # Execute the first circuit on the statevector simulator. job_ex2_1 = execute(ex2_qc1, backend_sv) output1 = job_ex2_1.result().get_statevector(ex2_qc1, decimals=5) # Execute the second circuit on the statevector simulator. job_ex2_2 = execute(ex2_qc2, backend_sv) output2 = job_ex2_2.result().get_statevector(ex2_qc2, decimals=5) # Measure the expectation values zz1 = expectation_state(output1,ZZ) zz2 = expectation_state(output2,ZZ) xx1 = expectation_state(output1,XX) xx2 = expectation_state(output2,XX) print('<ZZ> on circuit 1 = %s' % zz1) print('<ZZ> on circuit 2 = %s' % zz2) print('<XX> on circuit 1 = %s' % xx1) print('<XX> on circuit 2 = %s' % xx2) IBMQ.enable_account('YOUR_TOKEN') print(IBMQ.stored_account()) print(IBMQ.active_account()) my_provider=IBMQ.get_provider() my_provider.backends() # Retrieve IBM Quantum device information backend_overview() backend_qx2 = my_provider.get_backend('ibmqx2') backend_vigo = my_provider.get_backend('ibmq_vigo') backend_vigo.properties() # Retrieve a specific IBM Quantum device information # ibmq_16_melbourne as an example backend_mel = my_provider.get_backend('ibmq_16_melbourne') backend_monitor(backend_mel) # Let's look at one more example backend_qx2 = my_provider.get_backend('ibmqx2') backend_monitor(backend_qx2) # Create a 3-qubit GHZ state ghz3_q = QuantumRegister(3,'q') ghz3_c = ClassicalRegister(3,'c') ghz3= QuantumCircuit(ghz3_q,ghz3_c) ghz3.h(0) ghz3.cx(0,1) ghz3.cx(0,2) ghz3.barrier() for i in range(3): ghz3.measure(i,i) ghz3.draw(output='mpl') # Define backend as one of the real devices (5-qubit systems for now) backend_vigo = my_provider.get_backend('ibmq_vigo') backend_es = my_provider.get_backend('ibmq_essex') backend_ou = my_provider.get_backend('ibmq_ourense') # Run 3-qubit GHZ experiment on a 5-qubit device (try vigo) job_exp = execute(ghz3, backend=backend_vigo) job_monitor(job_exp) # Grab experimental results result_vigo = job_exp.result() counts_vigo = result_vigo.get_counts(ghz3) plot_histogram(counts_vigo) # Finally, run the same experiment on the 14-qubit device. job_exp2 = execute(ghz3, backend=backend_mel) job_monitor(job_exp2) # Grab experimental results result_mel = job_exp2.result() counts_mel = result_mel.get_counts(ghz3) plot_histogram(counts_mel) # Now, compare to theory by running it on qasm_simulator job_qasm = execute(ghz3,backend=backend_q) result_qasm = job_qasm.result() counts_qasm = result_qasm.get_counts(ghz3) # Plot both experimental and ideal results plot_histogram([counts_qasm,counts_vigo,counts_mel], color=['black','green','blue'], legend=['QASM','Vigo','Melbourne']) import random as r # Define a 3-qubit circuit with 3 classical registers qtel = QuantumCircuit(3,3) # Apply a random 1-qubit rotation around y a1 = r.random()*np.pi a2 = r.random()*np.pi qtel.ry(a1,0) qtel.rz(a2,0) qtel.barrier() qtel.draw(output='mpl') # Prepare a 2-qubit bell state qtel.h(1) qtel.cx(1,2) qtel.draw(output='mpl') # Apply bell measurement on qubit 0 and 1 qtel.cx(0,1) qtel.h(0) qtel.barrier() qtel.measure([0, 1],[0, 1]) qtel.draw(output='mpl') # Apply controlled gates to complete the teleportation qtel.barrier() qtel.cx(1,2) qtel.cz(0,2) qtel.draw(output='mpl') # Check the answer by applying the inverse unitary qtel.rz(-a2,2) qtel.ry(-a1,2) qtel.measure(2,2) print('Quantum teleportation circuit:') qtel.draw(output='mpl') # n is the number of shots n=10000 job_qtel = execute(qtel, backend_q, shots=n) display(plot_histogram(job_qtel.result().get_counts(qtel))) qtel_c = job_qtel.result().get_counts(qtel) print(qtel_c) # Simple example from qiskit.circuit import Parameter # Define two parameters, t1 and t2 theta1 = Parameter('t1') theta2 = Parameter('t2') # Build a 5-qubit circuit qc = QuantumCircuit(3, 1) # First parameter, t1, is used for a single qubit rotation of a controlled qubit qc.ry(theta1,0) for i in range(2): qc.cx(i, i+1) qc.barrier() # Second parameter, t2, is used here qc.rz(theta2,range(3)) qc.barrier() for i in reversed(range(2)): qc.cx(i, i+1) qc.ry(theta1,0) qc.measure(0, 0) qc.draw(output='mpl') theta1_range = np.linspace(0, np.pi/2, 2) theta2_range = np.linspace(0, 2 * np.pi, 16) circuits = [qc.bind_parameters({theta1: theta_val1, theta2: theta_val2}) for theta_val1 in theta1_range for theta_val2 in theta2_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[16].draw(output='mpl')) # Execute multiple circuits job = execute(qc, backend=Aer.get_backend('qasm_simulator'), parameter_binds=[{theta1: theta_val1, theta2: theta_val2} for theta_val1 in theta1_range for theta_val2 in theta2_range]) # Store all counts counts = [job.result().get_counts(i) for i in range(len(job.result().results))] # Plot to visualize the result import matplotlib.pyplot as plt 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))/1024,counts))) plt.show() # Exercise 4. a) # Create the measurement circuit m_ZZI = QuantumCircuit(4,1) m_ZZI.h(3) m_ZZI.cz(3,0) m_ZZI.cz(3,1) m_ZZI.h(3) m_ZZI.barrier() m_ZZI.measure(3,0) m_ZZI.draw(output='mpl') # #m_ZIZ = QuantumCircuit(4,1) #m_ZIZ.h(3) #m_ZIZ.cz(3,0) #m_ZIZ.cz(3,2) #m_ZIZ.h(3) #m_ZIZ.barrier() #m_ZIZ.measure(3,0) #display(m_ZIZ.draw(output='mpl')) # Exercise 4. a) # Create the state preparation circuit for a|000> + b|111> and a|010> + b|101> # for various values of a & b from qiskit.circuit import Parameter # Define parameter t1 and t2 theta1 = Parameter('t1') theta2 = Parameter('t2') qs_a = QuantumCircuit(4,1) qs_a.ry(theta1,0) qs_a.cx(0,1) qs_a.cx(0,2) qs_a.ry(theta2,1) qs_a.barrier() display(qs_a.draw(output='mpl')) # Add state prep. and measurement circuits qc_ZZI = qs_a+m_ZZI qc_ZZI.draw(output='mpl') theta1_range = np.linspace(0, np.pi, 16) theta2_range = np.linspace(0, np.pi, 2) # Bind parameters and create multiple circuits # Test for various a & b for a|000> + b|111> first, # then vary the amplitudes for a|010> + b|101> : # Fix theta2 first, and vary theta1: circuits_ZZI = [qc_ZZI.bind_parameters({theta1: theta_val1, theta2: theta_val2}) for theta_val2 in theta2_range for theta_val1 in theta1_range ] # Execute multiple circuits job_ZZI = execute(circuits_ZZI, backend=Aer.get_backend('qasm_simulator')) # Store all counts counts_ZZI = [job_ZZI.result().get_counts(i) for i in range(len(job_ZZI.result().results))] # Plot to visualize the result import matplotlib.pyplot as plt plt.figure(figsize=(12,6)) plt.plot(range(len(theta1_range)*len(theta2_range)), list(map(lambda counts_ZZI: (counts_ZZI.get('0',0)-counts_ZZI.get('1',1))/1024, counts_ZZI))) plt.show() # Exercise 4. b) # Create the measurement circuit m_XXI = QuantumCircuit(4,1) m_XXI.h(3) m_XXI.cx(3,0) m_XXI.cx(3,1) m_XXI.h(3) m_XXI.barrier() m_XXI.measure(3,0) m_XXI.draw(output='mpl') # #m_XIX = QuantumCircuit(4,1) #m_XIX.h(3) #m_XIX.cx(3,0) #m_XIX.cx(3,2) #m_XIX.h(3) #m_XIX.barrier() #m_XIX.measure(3,0) #display(m_XIX.draw(output='mpl')) # Exercise 4. b) # Create the state preparation circuit for a|+++> + b|---> and a|+-+> + b|-+-> # for various values of a & b qs_b = QuantumCircuit(4,1) qs_b.ry(theta1,0) qs_b.cx(0,1) qs_b.cx(0,2) for i in range(3): qs_b.h(i) # To flip |+> to |->, we need a phase flip gate qs_b.rz(theta2,1) qs_b.barrier() display(qs_b.draw(output='mpl')) # Add state prep. and measurement circuits qc_XXI = qs_b+m_XXI qc_XXI.draw(output='mpl') # Bind parameters and create multiple circuits # Test for various a & b for a|000> + b|111> first, # then vary the amplitudes for a|010> + b|101> : # Fix theta2 first, and vary theta1: circuits_XXI = [qc_XXI.bind_parameters({theta1: theta_val1, theta2: theta_val2}) for theta_val2 in theta2_range for theta_val1 in theta1_range ] # Execute multiple circuits job_XXI = execute(circuits_XXI, backend=Aer.get_backend('qasm_simulator')) # Store all counts counts_XXI = [job_XXI.result().get_counts(i) for i in range(len(job_XXI.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_XXI: (counts_XXI.get('0',0)-counts_XXI.get('1',1))/1024, counts_XXI))) plt.show() # Create a quantum register with 3 qubits q = QuantumRegister(3,'q') # Form a quantum circuit qent = QuantumCircuit(q) qent.initialize([1, 0, 0, 0, 0, 0, 0, 1] / np.sqrt(2), [q[0], q[1], q[2]]) # Display the quantum circuit qent.draw(output='mpl') # Use Aer's state vector simulator backend_sv = Aer.get_backend('statevector_simulator') # Execute and plot output state output_ent = execute(qent, backend_sv).result().get_statevector(0, decimals=3) plot_state_city(output_ent) # Build a sub-circuit # sub_ghz(n,c,t) creates a quantum circuit for creating an n-qubit GHZ state. # n is the total number of qubits, c is an index for a control qubit, t is a vector of indices for target qubits. def sub_ghz(n,c,t): sub_q = QuantumRegister(n) sub_circ = QuantumCircuit(sub_q, name='sub_ghz') sub_circ.h(c) for i in t: sub_circ.cx(c,i) return sub_circ # Create a sub-circuit for 3-qubit GHZ state prep. sub_ghz3 = sub_ghz(3,0,[1,2]) sub_inst3 = sub_ghz3.to_instruction() # Create a sub-circuit consisting of T gate and cnot. sub_tcnot = QuantumCircuit(QuantumRegister(2),name='t+cnot') sub_tcnot.t(0) sub_tcnot.cx(0,1) q = QuantumRegister(5, 'q') circ = QuantumCircuit(q) # Now create a quantum circuit using sub-circuits. # Apply Hadamard on all gates. for i in range(5): circ.h(i) # circ.barrier() # Appy 2-qubit GHZ preparation on qubits 0 and 1, and on qubits 3 and 4. circ.append(sub_tcnot, [q[0],q[1]]) circ.append(sub_tcnot, [q[3], q[4]]) # circ.barrier() # Apply 3-qubit GHZ preparation on all 3 neighbouring qubits. for i in range(3): circ.append(sub_inst3, [q[i], q[i+1],q[i+2]]) circ.draw(output='mpl') # We can also decompose the circuit that is constructed using sub-circuits. circ.decompose().draw(output='mpl') # Reset operation forces the target qubit to go to |0> q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.reset(0) qc.measure(q, c) display(qc.draw(output='mpl')) # Test the result job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots=1024) job.result().get_counts(qc) # Controlled qubit operation, controlled by classical bits # This could be useful for designing a post-selection scheme of a quantum algorithm q2 = QuantumRegister(2,'q') cont = ClassicalRegister(1,'cont') qc = QuantumCircuit(q2,cont) qc.x(0) # Swap qubits 1 and 2 if the classical bit is 0 qc.swap(0,1).c_if(cont, 0) qc.measure(0,cont) display(qc.draw(output='mpl')) job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots=1024) print(job.result().get_counts(qc)) from qiskit.compiler import transpile from qiskit.transpiler import PassManager, Layout from qiskit.tools.visualization import plot_gate_map # Let's take a look at the layout of physical devices with the gate directions display(plot_gate_map(backend_qx2,plot_directed=True)) display(plot_gate_map(my_provider.get_backend('ibmq_burlington'),plot_directed=True)) display(plot_gate_map(my_provider.get_backend('ibmq_london'),plot_directed=True)) # Create a dummy circuit for default transpiler demonstration qr = QuantumRegister(3) cr = ClassicalRegister(3) qc = QuantumCircuit(qr,cr) qc.h(0) qc.swap(0,1) qc.cx(1,0) qc.s(2) qc.x(2) qc.h(2) qc.measure(qr[2],cr[2]) qc.h(0) qc.cx(0,1) qc.cx(0,1) qc.h(0) qc.measure(qr[0],cr[0]) qc.measure(qr[1],cr[1]) print('Original circuit') display(qc.draw(output='mpl')) # Transpile the circuit to run on ibmqx2 qt_qx4 = transpile(qc,backend_qx2) print('Transpiled circuit for ibmqx2') display(qt_qx4.draw(output='mpl')) # Transpile the circuit to run on ibmq_burlington qt_ou = transpile(qc,my_provider.get_backend('ibmq_burlington')) print('Transpiled circuit for ibmqx_Burlington') display(qt_ou.draw(output='mpl')) qr = QuantumRegister(5,'q') qc = QuantumCircuit(qr) qc.h(0) for i in range(4): qc.cx(0,i+1) qc.draw(output='mpl') qc_t = transpile(qc, basis_gates=['u1','u2','u3','cx']) # Display transpiled circuit display(qc_t.draw(output='mpl')) # Print out some circuit properties # Total nunmber of operations print("Number of operations = %s" % qc_t.size()) # Circuit depth print("Circuit depth = %s" % qc_t.depth()) # Number of qubits print("Number of qubits = %s" % qc_t.width()) # Breakdown of operations by type print("Operations: %s" % qc_t.count_ops()) # Number of unentangled subcircuits in this circuit. # In principle, each subcircuit can be executed on a different quantum device. print("Number of unentangled subcircuits = %s" % qc_t.num_tensor_factors()) # Map it onto 5 qubit backend ibmqx2 qc_qx2 = transpile(qc, backend_qx2, basis_gates=['u1','u2','u3','cx']) display(qc_qx2.draw(output='mpl')) display(plot_gate_map(backend_qx2,plot_directed=True)) # Print out some circuit properties # Total nunmber of operations print("Number of operations = %s" % qc_qx2.size()) # Circuit depth print("Circuit depth = %s" % qc_qx2.depth()) # Map it onto 5 qubit backend ibmq_vigo qc_vigo = transpile(qc, backend_vigo,basis_gates=['u1','u2','u3','cx']) display(qc_vigo.draw(output='mpl')) display(plot_gate_map(backend_vigo,plot_directed=True)) # Print out some circuit properties # Total nunmber of operations print("Number of operations = %s" % qc_vigo.size()) # Circuit depth print("Circuit depth = %s" % qc_vigo.depth()) # Customize the layout layout = Layout({qr[0]: 2, qr[1]: 1, qr[2]: 0, qr[3]:3, qr[4]:4}) # Map it onto 5 qubit backend ibmqx2 qc_qx2_new = transpile(qc, backend_qx2, initial_layout=layout,basis_gates=['u1','u2','u3','cx']) display(qc_qx2_new.draw(output='mpl')) # Print out some circuit properties # Total nunmber of operations print("Number of operations = %s" % qc_qx2_new.size()) # Circuit depth print("Circuit depth = %s" % qc_qx2_new.depth()) # Test transpilation with a 5-qubit circuit including a Toffoli gate qr = QuantumRegister(5,'q') qccx = QuantumCircuit(qr) qccx.h(0) qccx.ccx(1,2,3) qccx.x(4) qccx.cz(0,4) display(qccx.draw(output='mpl')) print('Decompose in terms of a one and two qubit universal gate set') display(qccx.decompose().draw(output='mpl')) # Check device properties. # The device information such as gate error and T1 and T2 also should be considered # when picking a device for a given quantum circuit. display(plot_gate_map(my_provider.get_backend('ibmq_vigo'),plot_directed=True)) backend_monitor(my_provider.get_backend('ibmq_vigo')) # Customize the layout 5 qubit backend ibmq_vigo layout = Layout({qr[0]: 1, qr[1]: 2, qr[2]: 3, qr[3]:0, qr[4]:4}) # Map it onto 5 qubit backend ibmq_vigo without changing the layout qccx_vigo_naive = transpile(qccx, backend_vigo,basis_gates=['u1','u2','u3','cx']) # Map it onto 5 qubit backend ibmq_vigo with the above layout qccx_vigo_layout = transpile(qccx, backend_vigo, initial_layout=layout,basis_gates=['u1','u2','u3','cx']) display(qccx_vigo_naive.draw(output='mpl')) # Print out some circuit properties for the circuit without layout change print("Circuit complexity when transpiled without layout change:") print("Number of operations = %s" % qccx_vigo_naive.size()) print("Circuit depth = %s" % qccx_vigo_naive.depth()) print("Number of cx operations = %s" % qccx_vigo_naive.count_ops()['cx']) display(qccx_vigo_layout.draw(output='mpl')) # Print out some circuit properties for the circuit with layout change print("Circuit complexity when transpiled with layout change:") print("Number of operations = %s" % qccx_vigo_layout.size()) print("Circuit depth = %s" % qccx_vigo_layout.depth()) print("Number of cx operations = %s" % qccx_vigo_layout.count_ops()['cx']) # Apply 4-qubit controlled x gate qr = QuantumRegister(5,'q') c4z = QuantumCircuit(qr) c4z.h(0) c4z.h(1) c4z.h(3) c4z.ccx(0,1,2) c4z.ccx(2,3,4) c4z.ccx(0,1,2) display(c4z.draw(output='mpl')) # Print out some circuit properties # Total nunmber of operations print("Number of operations = %s" % c4z.size()) # Count different types of operations print("Operation counts = %s" % c4z.count_ops()) # Circuit depth print("Circuit depth = %s" % c4z.depth()) backend_london = my_provider.get_backend('ibmq_london') c4z_t = transpile(c4z, backend_london) display(c4z_t.draw(output='mpl')) # Print out some circuit properties # Total nunmber of operations print("Number of operations = %s" % c4z_t.size()) # Count different types of operations print("Operation counts = %s" % c4z_t.count_ops()) # Circuit depth print("Circuit depth = %s" % c4z_t.depth()) # Transpile many times (100 times in this example) and pick the best one # Use ibmq_london for example tcircs0 = transpile([c4z]*20, backend_london,optimization_level=0) tcircs1 = transpile([c4z]*20, backend_london,optimization_level=1) tcircs2 = transpile([c4z]*20, backend_london,optimization_level=2) tcircs3 = transpile([c4z]*20, backend_london,optimization_level=3) import matplotlib.pyplot as plt num_cx0 = [c.count_ops()['cx'] for c in tcircs0] num_cx1 = [c.count_ops()['cx'] for c in tcircs1] num_cx2 = [c.count_ops()['cx'] for c in tcircs2] num_cx3 = [c.count_ops()['cx'] for c in tcircs3] num_tot0 = [c.size() for c in tcircs0] num_tot1 = [c.size() for c in tcircs1] num_tot2 = [c.size() for c in tcircs2] num_tot3 = [c.size() for c in tcircs3] num_depth0 = [c.depth() for c in tcircs0] num_depth1 = [c.depth() for c in tcircs1] num_depth2 = [c.depth() for c in tcircs2] num_depth3 = [c.depth() for c in tcircs3] plt.rcParams.update({'font.size': 16}) # Plot the number of CNOT gates plt.figure(figsize=(12,6)) plt.plot(range(len(num_cx0)),num_cx0,'r',label='level 0') plt.plot(range(len(num_cx1)),num_cx1,'b',label='level 1') plt.plot(range(len(num_cx2)),num_cx2,'g',label='level 2') plt.plot(range(len(num_cx3)),num_cx3,'k',label='level 3') plt.legend(loc='upper left') plt.xlabel('Random trial') plt.ylabel('# of cx gates') plt.show() # Plot total number of gates plt.figure(figsize=(12,6)) plt.plot(range(len(num_tot0)),num_tot0,'r',label='level 0') plt.plot(range(len(num_tot1)),num_tot1,'b',label='level 1') plt.plot(range(len(num_tot2)),num_tot2,'g',label='level 2') plt.plot(range(len(num_tot3)),num_tot3,'k',label='level 3') plt.legend(loc='upper left') plt.xlabel('Random trial') plt.ylabel('# of total gates') plt.show() # Plot the number of CNOT gates plt.figure(figsize=(12,6)) plt.plot(range(len(num_depth0)),num_depth0,'r',label='level 0') plt.plot(range(len(num_depth1)),num_depth1,'b',label='level 1') plt.plot(range(len(num_depth2)),num_depth2,'g',label='level 2') plt.plot(range(len(num_depth3)),num_depth3,'k',label='level 3') plt.legend(loc='upper left') plt.xlabel('Random trial') plt.ylabel('Circuit depth') plt.show() print('Opt0: Minimum # of cx gates = %s' % min(num_cx0)) print('Opt0: The best circuit is the circut %s' % num_cx0.index(min(num_cx0))) print('Opt1: Minimum # of cx gates = %s' % min(num_cx1)) print('Opt1: The best circuit is the circut %s' % num_cx1.index(min(num_cx1))) print('Opt2: Minimum # of cx gates = %s' % min(num_cx2)) print('Opt2: The best circuit is the circut %s' % num_cx2.index(min(num_cx2))) print('Opt3: Minimum # of cx gates = %s' % min(num_cx3)) print('Opt3: The best circuit is the circut %s' % num_cx3.index(min(num_cx3)))
https://github.com/acfilok96/Quantum-Computation
acfilok96
from qiskit import * from qiskit.tools.visualization import plot_bloch_multivector circuit = QuantumCircuit(1,1) circuit.x(0) simulator = Aer.get_backend('statevector_simulator') result = execute(circuit, backend=simulator).result() statevector = result.get_statevector() print(statevector) %matplotlib inline circuit.draw(output='mpl') # bloch sphere plot_bloch_multivector(statevector) # measurement circuit.measure([0],[0]) backend = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=backend, shots=1024).result() counts = result.get_counts() from qiskit.tools.visualization import plot_histogram plot_histogram(counts) circuit = QuantumCircuit(1,1) circuit.x(0) simulator = Aer.get_backend('unitary_simulator') result = execute(circuit, backend=simulator).result() unitary = result.get_unitary() print(unitary) %matplotlib inline circuit.draw(output='mpl') # bloch sphere plot_bloch_multivector(unitary)
https://github.com/h-rathee851/Pulse_application_qiskit
h-rathee851
""" Object to calibrate pulse of backend and qubit of interest. """ # Importing required python packages from warnings import warn import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit from scipy.signal import find_peaks from sklearn.model_selection import train_test_split from sklearn.discriminant_analysis import LinearDiscriminantAnalysis # Importing standard Qiskit libraries from qiskit import IBMQ, execute, pulse from qiskit.providers.ibmq import IBMQBackend from qiskit.pulse import DriveChannel, Schedule, Play from qiskit.pulse import library as pulse_lib from qiskit.pulse.library import Waveform, Gaussian from qiskit.tools.monitor import job_monitor from qiskit.providers.exceptions import QiskitBackendNotFoundError, BackendConfigurationError # Loading your IBM Q account(s) #IBMQ.load_account() #provider = IBMQ.get_provider() class PulseCalibration(): """Creates an object that is used for pulse calibration. Args: backend (IBMQBackend) : The IBMQBackend for which pulse calibration needs to be done. qubit (int) : The qubit for which the pulse calibration is done. qubit_freq_ground (float) : Custom frequency for 0->1 transition. qubit_freq_excited (float) : Custom frequency for 1->2 transition. pi_amp_ground (float) : Custom pi amplitude for 0->1 transition. The value should be between 0 and 1. pi_amp_excited (float) : Custom pi amplitude for 1->2 transition. The value should be between 0 and 1. pulse_dur (int) : The duration of the pi pulse to be used for calibration. pulse_sigma (int) : The standard deviation of the pi pulse to be used for calibration. """ def __init__(self, backend, qubit, qubit_freq_ground=None, qubit_freq_excited=None, pi_amp_ground=None, pi_amp_excited=None, pulse_dur=None, pulse_sigma=None): # pylint: disable=too-many-locals # pylint: disable=too-many-arguments if not isinstance(backend, IBMQBackend): raise QiskitBackendNotFoundError("Provided backend not available." + "Please provide backend after obtaining from IBMQ.") self._backend = backend self._back_config = backend.configuration() if qubit >= self._back_config.n_qubits: raise BackendConfigurationError(f"Qubit {qubit} not present in the provided backend.") self._qubit = qubit self._back_defaults = backend.defaults() self._dt = self._back_config.dt self._qubit_freq = self._back_defaults.qubit_freq_est[self._qubit] self._inst_sched_map = self._back_defaults.instruction_schedule_map self._drive_chan = DriveChannel(qubit) if pulse_sigma: self._pulse_sigma = pulse_sigma else: self._pulse_sigma = 40 if pulse_dur: self._pulse_duration = pulse_dur else: self._pulse_duration = (4*self._pulse_sigma)-((4*self._pulse_sigma) % 16) self._qubit_freq_ground = qubit_freq_ground self._qubit_freq_excited = qubit_freq_excited self._pi_amp_ground = pi_amp_ground self._pi_amp_excited = pi_amp_excited self._state_discriminator_012 = None # Find out which measurement map index is needed for this qubit meas_map_idx = None for i, measure_group in enumerate(self._back_config.meas_map): if qubit in measure_group: meas_map_idx = i break assert meas_map_idx is not None, f"Couldn't find qubit {qubit} in the meas_map!" # The measurement pulse for measuring the qubit of interest. self._measure = self._inst_sched_map.get('measure', qubits=self._back_config.meas_map[meas_map_idx]) def create_cal_circuit(self, amp): """Constructs and returns a schedule containing Gaussian pulse with amplitude as 'amp', sigma as 'pulse_sigma' and duration as 'pulse_duration'.""" sched = Schedule() sched += Play(Gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma, amp=amp), self._drive_chan) sched += self._measure << sched.duration return sched def create_cal_circuit_excited(self, base_pulse, freq): """ Constructs and returns a schedule containing a pi pulse for 0->1 transition followed by a sidebanded pulse which corresponds to applying 'base_pulse' at frequency 'freq'.""" sched = Schedule() sched += Play(Gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma, amp=self._pi_amp_ground), self._drive_chan) sched += Play(self.apply_sideband(base_pulse, freq), self._drive_chan) sched += self._measure << sched.duration return sched @staticmethod def _fit_function(x_values, y_values, function, init_params): """ A function fitter. Returns the fit parameters of 'function'.""" fitparams, _ = curve_fit(function, x_values, y_values, init_params) y_fit = function(x_values, *fitparams) return fitparams, y_fit @staticmethod def _baseline_remove(values): """Centering data around zero.""" return np.array(values) - np.mean(values) def apply_sideband(self, pulse, frequency): """Apply a sine sideband to 'pulse' at frequency 'freq'. Args: pulse (Waveform): The pulse to which sidebanding is to be applied. frequency (float): LO frequency at which the pulse is to be applied. Returns: Waveform: The sidebanded pulse. """ t_samples = np.linspace(0, self._dt*self._pulse_duration, self._pulse_duration) sine_pulse = np.sin(2*np.pi*(frequency-self._qubit_freq_ground)*t_samples) sideband_pulse = Waveform(np.multiply(np.real(pulse.samples), sine_pulse), name='sideband_pulse') return sideband_pulse def get_job_data(self, job, average): """Retrieve data from a job that has already run. Args: job (Job): The job whose data you want. average (bool): If True, gets the data assuming data is an average. If False, gets the data assuming it is for single shots. Return: list: List containing job result data. """ scale_factor = 1e-14 job_results = job.result(timeout=120) # timeout parameter set to 120 s result_data = [] for i in range(len(job_results.results)): if average: # get avg data result_data.append(job_results.get_memory(i)[self._qubit]*scale_factor) else: # get single data result_data.append(job_results.get_memory(i)[:, self._qubit]*scale_factor) return result_data # Prints out relative maxima frequencies in output_data; height gives lower bound (abs val) @staticmethod def _rel_maxima(freqs, output_data, height, distance): """Prints out relative maxima frequencies in output_data (can see peaks); height gives upper bound (abs val). Be sure to set the height properly or the peak will be ignored! Args: freqs (list): frequency list output_data (list): list of resulting signals height (float): upper bound (abs val) on a peak width (float): Returns: list: List containing relative maxima frequencies """ peaks, _ = find_peaks(x=output_data, height=height, distance=distance) return freqs[peaks] def find_freq_ground(self, verbose=False, visual=False): """Sets and returns the calibrated frequency corresponding to 0->1 transition.""" # pylint: disable=too-many-locals sched_list = [self.create_cal_circuit(0.5)]*75 freq_list = np.linspace(self._qubit_freq-(40*1e+6), self._qubit_freq+(40*1e+6), 75) sweep_job = execute(sched_list, backend=self._backend, meas_level=1, meas_return='avg', shots=1024, schedule_los = [{self._drive_chan: freq} for freq in freq_list]) if verbose: print("Executing the Frequency sweep job for 0->1 transition.") job_monitor(sweep_job) sweep_result = sweep_job.result() sweep_values = [] for i in range(len(sweep_result.results)): # Get the results from the ith experiment res = sweep_result.get_memory(i)*1e-14 # Get the results for `qubit` from this experiment sweep_values.append(res[self._qubit]) freq_list_GHz = freq_list/1e+9 if visual: print("The frequency-signal plot for frequency sweep: ") plt.scatter(freq_list_GHz, np.real(sweep_values), color='black') plt.xlim([min(freq_list_GHz), max(freq_list_GHz)]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured Signal [a.u.]") plt.show() def find_init_params(res_values): est_baseline=np.mean(res_values) est_slope=-5 if est_baseline-np.min(res_values)> 2 else 5 return [est_slope, self._qubit_freq/1e9, 1, est_baseline] init_params = find_init_params(np.real(sweep_values)) # Obtain the optimal paramters that fit the result data. def lorentzian(xval, scale, q_freq, hwhm, shift): return (scale / np.pi) * (hwhm / ((xval - q_freq)**2 + hwhm**2)) + shift fit_params, y_fit = self._fit_function(freq_list_GHz, np.real(sweep_values), lorentzian, init_params # init parameters for curve_fit ) if visual: print("The frequency-signal plot for frequency sweep: ") plt.scatter(freq_list_GHz, np.real(sweep_values), color='black') plt.plot(freq_list_GHz, y_fit, color='red') plt.xlim([min(freq_list_GHz), max(freq_list_GHz)]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured Signal [a.u.]") plt.show() _, qubit_freq_new, _, _ = fit_params self._qubit_freq_ground = qubit_freq_new*1e9 if verbose: print(f"The calibrate frequency for the 0->1 transition is {self._qubit_freq_ground}") return self._qubit_freq_ground def find_pi_amp_ground(self, verbose=False, visual=False): """Sets and returns the amplitude of the pi pulse corresponding to 0->1 transition.""" # pylint: disable=too-many-locals if not self._qubit_freq_ground: warn("ground_qubit_freq not computed yet and custom qubit freq not provided." + "Computing ground_qubit_freq now.") self._qubit_freq_ground = self.find_freq_ground(verbose, visual) amp_list = np.linspace(0, 0.74, 75) rabi_sched_list = [self.create_cal_circuit(amp) for amp in amp_list] rabi_list_len = len(rabi_sched_list) rabi_job = execute(rabi_sched_list,backend=self._backend, meas_level=1, meas_return='avg', shots=1024, schedule_los=[{self._drive_chan: self._qubit_freq_ground}]*len(rabi_sched_list)) if verbose: print("Executing the rabi oscillation job to get Pi pulse for 0->1 transition.") job_monitor(rabi_job) rabi_results = rabi_job.result() scale_factor = 1e-14 rabi_values = [] for i in range(75): # Get the results for `qubit` from the ith experiment rabi_values.append(rabi_results.get_memory(i)[self._qubit]*scale_factor) rabi_values = np.real(self._baseline_remove(rabi_values)) # Obtain the optimal paramters that fit the result data. fit_params, y_fit = self._fit_function(amp_list, rabi_values, lambda x, A, B, drive_period, phi: (A*np.sin(2*np.pi*x/drive_period - phi) + B), [3e-7, 0, 0.3, 0]) drive_period = fit_params[2] self._pi_amp_ground = drive_period/2 if verbose: print(f"The Pi amplitude of 0->1 transition is {self._pi_amp_ground}.") if visual: print("The amplitude-signal plot for rabi oscillation for 0->1 transition.") plt.figure() plt.scatter(amp_list, rabi_values, color='black') plt.plot(amp_list, y_fit, color='red') plt.axvline(drive_period/2, color='red', linestyle='--') plt.axvline(drive_period, color='red', linestyle='--') plt.annotate("", xy=(drive_period, 0), xytext=(drive_period/2, 0), arrowprops=dict(arrowstyle="<->", color='red')) #plt.annotate("$\pi$", xy=(drive_period/2-0.03, 0.1), color='red') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() return self._pi_amp_ground def find_freq_excited(self, verbose=False, visual=False): """Sets and returns the frequency corresponding to 1->2 transition.""" # pylint: disable=too-many-locals if not self._qubit_freq_ground: raise ValueError("The qubit_freq_ground is not determined. Please determine" + "qubit_freq_ground first.") if not self._pi_amp_ground: raise ValueError("The pi_amp_ground is not determined.\ Please determine pi_amp_ground first.") base_pulse = pulse_lib.gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma, amp=0.3) sched_list = [] # Here we assume that the anharmocity is about 8% for all qubits. excited_freq_list = self._qubit_freq_ground-0.33e9 + np.linspace(-100*1e+6, 100*1e+6, 75) for freq in excited_freq_list: sched_list.append(self.create_cal_circuit_excited(base_pulse, freq)) excited_sweep_job = execute(sched_list, backend=self._backend, meas_level=1, meas_return='avg', shots=1024, schedule_los=[{self._drive_chan: self._qubit_freq_ground}]*len(excited_freq_list) ) if verbose: print("Executing the Frequency sweep job for 1->2 transition.") job_monitor(excited_sweep_job) excited_sweep_data = self.get_job_data(excited_sweep_job, average=True) if visual: print("The frequency-signal plot of frequency sweep for 1->2 transition.") # Note: we are only plotting the real part of the signal plt.scatter(excited_freq_list/1e+9, excited_sweep_data, color='black') plt.xlim([min(excited_freq_list/1e+9), max(excited_freq_list/1e+9)]) plt.xlabel("Frequency [GHz]", fontsize=15) plt.ylabel("Measured Signal [a.u.]", fontsize=15) plt.title("1->2 Frequency Sweep", fontsize=15) plt.show() def lorentzian(xval, scale, q_freq, hwhm, shift): return (scale / np.pi) * (hwhm / ((xval - q_freq)**2 + hwhm**2)) + shift # do fit in Hz excited_sweep_fit_params, excited_sweep_y_fit = self._fit_function(excited_freq_list, excited_sweep_data, lorentzian, [12, self._qubit_freq_ground*0.92, 0.05*1e+9, 1e-7] ) if visual: print("The frequency-signal plot of frequency sweep for 1->2 transition.") # Note: we are only plotting the real part of the signal plt.scatter(excited_freq_list/1e+9, excited_sweep_data, color='black') plt.plot(excited_freq_list/1e+9, excited_sweep_y_fit, color='red') plt.xlim([min(excited_freq_list/1e+9), max(excited_freq_list/1e+9)]) plt.xlabel("Frequency [GHz]", fontsize=15) plt.ylabel("Measured Signal [a.u.]", fontsize=15) plt.title("1->2 Frequency Sweep", fontsize=15) plt.show() _, qubit_freq_12, _, _ = excited_sweep_fit_params self._qubit_freq_excited = qubit_freq_12 if verbose: print(f"The calibrated frequency for the 1->2 transition\ is {self._qubit_freq_excited}.") return self._qubit_freq_excited def find_pi_amp_excited(self, verbose=False, visual=False): """Sets and returns the amplitude of the pi pulse corresponding to 1->2 transition.""" if not self._qubit_freq_excited: warn("ground_qubit_freq not computed yet and custom qubit freq not provided." + "Computing ground_qubit_freq now.") self._qubit_freq_ground = self.find_freq_excited(verbose, visual) amp_list = np.linspace(0, 1.0, 75) rabi_sched_list = [] for amp in amp_list: base_pulse = pulse_lib.gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma, amp=amp) rabi_sched_list.append(self.create_cal_circuit_excited(base_pulse, self._qubit_freq_excited)) rabi_job = execute(rabi_sched_list, backend=self._backend, meas_level=1, meas_return='avg', shots=1024, schedule_los=[{self._drive_chan: self._qubit_freq_ground}]*75 ) if verbose: print("Executing the rabi oscillation job for 1->2 transition.") job_monitor(rabi_job) rabi_data = self.get_job_data(rabi_job, average=True) rabi_data = np.real(self._baseline_remove(rabi_data)) if visual: print("The amplitude-signal plot of rabi oscillation for 1->2 transition.") plt.figure() plt.scatter(amp_list, rabi_data, color='black') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.title('Rabi Experiment (1->2)', fontsize=20) plt.show() (rabi_fit_params, rabi_y_fit) = self._fit_function(amp_list, rabi_data, lambda x, A, B, drive_period, phi: (A*np.cos(2*np.pi*x/drive_period - phi) + B), [3e-8, 0, 0.4, np.pi/2]) drive_period_excited = rabi_fit_params[2] pi_amp_excited = (drive_period_excited/2/np.pi) * (np.pi+rabi_fit_params[3]) self._pi_amp_excited = pi_amp_excited if visual: print("The amplitude-signal plot of rabi oscillation for 1->2 transition.") plt.figure() plt.scatter(amp_list, rabi_data, color='black') plt.plot(amp_list, rabi_y_fit, color='red') # account for phi in computing pi amp plt.axvline(self._pi_amp_excited, color='red', linestyle='--') plt.axvline(self._pi_amp_excited+drive_period_excited/2, color='red', linestyle='--') plt.annotate("", xy=(self._pi_amp_excited+drive_period_excited/2, 0), xytext=(self._pi_amp_excited, 0), arrowprops=dict(arrowstyle="<->", color='red')) #plt.annotate("$\\pi$", xy=(self._pi_amp_excited-0.03, 0.1), color='red') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.title('Rabi Experiment (1->2)', fontsize=20) plt.show() return self._pi_amp_excited def get_pi_pulse_ground(self): """Returns a pi pulse of the 0->1 transition.""" pulse = pulse_lib.gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma, amp=self._pi_amp_ground) return pulse def get_pi_pulse_excited(self): """Returns a pi pulse of the 1->2 transition.""" pulse = pulse_lib.gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma, amp=self._pi_amp_excited) excited_pulse = self.apply_sideband(pulse, self._qubit_freq_excited) return excited_pulse def get_x90_pulse_ground(self): """Returns a pi/2 pulse of the 0->1 transition.""" pulse = pulse_lib.gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma, amp=self._pi_amp_ground/2) return pulse def get_x90_pulse_excited(self): """Returns a pi/2 pulse of the 1->2 transition.""" pulse = pulse_lib.gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma, amp=self._pi_amp_excited/2) excited_pulse = self.apply_sideband(pulse, self._qubit_freq_excited) return excited_pulse def get_zero_sched(self): """Returns a schedule that performs only a measurement.""" zero_sched = Schedule() zero_sched += self._measure return zero_sched def get_one_sched(self): """Returns a schedule that creates a |1> state from |0> by applying a pi pulse of 0->1 transition and performs a measurement.""" one_sched = Schedule() one_sched += Play(self.get_pi_pulse_ground(), self._drive_chan) one_sched += self._measure << one_sched.duration return one_sched def get_two_sched(self): """Returns a schedule that creates a |2> state from |0> by applying a pi pulse of 0->1 transition followed by applying a pi pulse of 1->2 transition and performs a measurement.""" two_sched = Schedule() two_sched += Play(self.get_pi_pulse_ground(), self._drive_chan) two_sched += Play(self.get_pi_pulse_excited(), self._drive_chan) two_sched += self._measure << two_sched.duration return two_sched @staticmethod def _create_iq_plot(zero_data, one_data, two_data): """Helper function for plotting IQ plane for 0, 1, 2. Limits of plot given as arguments.""" # zero data plotted in blue plt.scatter(np.real(zero_data), np.imag(zero_data), s=5, cmap='viridis', c='blue', alpha=0.5, label=r'$|0\rangle$') # one data plotted in red plt.scatter(np.real(one_data), np.imag(one_data), s=5, cmap='viridis', c='red', alpha=0.5, label=r'$|1\rangle$') # two data plotted in green plt.scatter(np.real(two_data), np.imag(two_data), s=5, cmap='viridis', c='green', alpha=0.5, label=r'$|2\rangle$') x_min = np.min(np.append(np.real(zero_data), np.append(np.real(one_data), np.real(two_data))))-5 x_max = np.max(np.append(np.real(zero_data), np.append(np.real(one_data), np.real(two_data))))+5 y_min = np.min(np.append(np.imag(zero_data), np.append(np.imag(one_data), np.imag(two_data))))-5 y_max = np.max(np.append(np.imag(zero_data), np.append(np.imag(one_data), np.imag(two_data))))+5 # Plot a large dot for the average result of the 0, 1 and 2 states. mean_zero = np.mean(zero_data) # takes mean of both real and imaginary parts mean_one = np.mean(one_data) mean_two = np.mean(two_data) plt.scatter(np.real(mean_zero), np.imag(mean_zero), s=200, cmap='viridis', c='black', alpha=1.0) plt.scatter(np.real(mean_one), np.imag(mean_one), s=200, cmap='viridis', c='black', alpha=1.0) plt.scatter(np.real(mean_two), np.imag(mean_two), s=200, cmap='viridis', c='black', alpha=1.0) plt.xlim(x_min, x_max) plt.ylim(y_min, y_max) plt.legend() plt.ylabel('I [a.u.]', fontsize=15) plt.xlabel('Q [a.u.]', fontsize=15) plt.title("0-1-2 discrimination", fontsize=15) return x_min, x_max, y_min, y_max @staticmethod def reshape_complex_vec(vec): """Take in complex vector vec and return 2d array w/ real, imag entries. This is needed for the learning. Args: vec (list): complex vector of data Returns: list: vector w/ entries given by (real(vec], imag(vec)) """ length = len(vec) vec_reshaped = np.zeros((length, 2)) for i, item in enumerate(vec): vec_reshaped[i] = [np.real(item), np.imag(item)] return vec_reshaped def find_three_level_discriminator(self, verbose=False, visual=False): """Returns a discriminator for discriminating 0-1-2 states.""" # pylint: disable=too-many-locals zero_sched = self.get_zero_sched() one_sched = self.get_one_sched() two_sched = self.get_two_sched() iq_job = execute([zero_sched, one_sched, two_sched], backend=self._backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{self._drive_chan: self._qubit_freq_ground}]*3 ) if verbose: job_monitor(iq_job) iq_data = self.get_job_data(iq_job, average=False) zero_data = iq_data[0] one_data = iq_data[1] two_data = iq_data[2] if visual: print("The discriminator plot for 0-1-2 discrimination.") x_min, x_max, y_min, y_max = self._create_iq_plot(zero_data, one_data, two_data) # Create IQ vector (split real, imag parts) zero_data_reshaped = self.reshape_complex_vec(zero_data) one_data_reshaped = self.reshape_complex_vec(one_data) two_data_reshaped = self.reshape_complex_vec(two_data) iq_data = np.concatenate((zero_data_reshaped, one_data_reshaped, two_data_reshaped)) # construct vector w/ 0's, 1's and 2's (for testing) state_012 = np.zeros(1024) # shots gives number of experiments state_012 = np.concatenate((state_012, np.ones(1024))) state_012 = np.concatenate((state_012, 2*np.ones(1024))) # Shuffle and split data into training and test sets iq_012_train, iq_012_test, state_012_train, state_012_test = train_test_split(iq_data, state_012, test_size=0.5) classifier_lda_012 = LinearDiscriminantAnalysis() classifier_lda_012.fit(iq_012_train, state_012_train) score_012 = classifier_lda_012.score(iq_012_test, state_012_test) if verbose: print('The accuracy score of the discriminator is: ', score_012) self._state_discriminator_012 = classifier_lda_012 if visual: self._separatrix_plot(classifier_lda_012, x_min, x_max, y_min, y_max, 1024) return self._state_discriminator_012 @staticmethod def _separatrix_plot(lda, x_min, x_max, y_min, y_max, shots): """Returns a sepratrix plot for the classifier.""" # pylint: disable=too-many-arguments num_x, num_y = shots, shots xvals, vals = np.meshgrid(np.linspace(x_min, x_max, num_x), np.linspace(y_min, y_max, num_y)) predict_prob = lda.predict_proba(np.c_[xvals.ravel(), vals.ravel()]) predict_prob = predict_prob[:, 1].reshape(xvals.shape) plt.contour(xvals, vals, predict_prob, [0.5], linewidths=2., colors='black') def get_qubit_freq_ground(self): """Returns the set 0->1 transition frequency.""" return self._qubit_freq_ground def get_qubit_freq_excited(self): """Returns the set 1->2 transition frequency.""" return self._qubit_freq_excited def get_pi_amp_ground(self): """Returns the set 0->1 transition pi pulse amplitude.""" return self._pi_amp_ground def get_pi_amp_excited(self): """Returns the set 1->2 transition pi pulse amplitude.""" return self._pi_amp_excited def get_three_level_discriminator(self): """Returns the set 0-1-2 state discriminator.""" return self._state_discriminator_012 def calibrate_all(self, verbose=False, visual=False): """Calibrates and sets both the ground and excited transition frequencies and corresponding pi pulse amplitudes. Also constructs a 0-1-2 state discriminator.""" ground_freq = self.find_freq_ground(verbose, visual) ground_amp = self.find_pi_amp_ground(verbose, visual) excited_freq = self.find_freq_excited(verbose, visual) excited_amp = self.find_pi_amp_excited(verbose, visual) state_discriminator = self.find_three_level_discriminator(verbose, visual) return ground_freq, ground_amp, excited_freq, excited_amp, state_discriminator def T1_ground(self, verbose=False, visual=False): """Returns the T1 of 1 state""" time_max=600 time_step=8 times=np.arange(1,time_max,time_step)*1e-6 delay_times_dt=times/self._dt t1_gnd_sched=[] for delay in delay_times_dt: this_sched= Schedule(name=f"T1 delay={delay*self._dt/1e-6} us") this_sched+= Play(self.get_pi_pulse_ground(),self._drive_chan) this_sched|=self._measure<<int(delay) t1_gnd_sched.append(this_sched) #sched_idx=0 #t1_gnd_sched[sched_idx] # Execution settings t1_gnd_job = execute(t1_gnd_sched, backend=self._backend, meas_level=1, meas_return='avg', shots=256, schedule_los=[{self._drive_chan: self.get_qubit_freq_ground()}] * len(t1_gnd_sched)) if verbose: job_monitor(t1_gnd_job) t1_gnd_results =self.get_job_data(t1_gnd_job, average=True) t1_gnd_results = np.real(t1_gnd_results) # Fit the data fit_params, y_fit = self._fit_function(times, t1_gnd_results, lambda x, A, C, T1: (A * np.exp(-x / T1) + C),[-6, 8, 100*1e-6]) _, _, T1_gnd = fit_params if visual: plt.scatter(times*1e6, t1_gnd_results, color='black') plt.plot(times*1e6, y_fit, color='red', label=f"T1 = {T1_gnd*1e6:.2f} us") plt.xlim(0, np.max(times)*1e6) plt.title("$T_1$ Experiment", fontsize=15) plt.xlabel('Delay before measurement [$\mu$s]', fontsize=15) plt.ylabel('Signal [a.u.]', fontsize=15) plt.legend() plt.show() return T1_gnd def T1_excited(self, verbose=False, visual=False): """Returns the T1 of 2 state""" time_max=600 time_step=8 times=np.arange(1,time_max,time_step)*1e-6 delay_times_dt=times/self._dt t1_exc_sched=[] for delay in delay_times_dt: this_sched= Schedule(name=f"T1 delay={delay*self._dt/1e-6} us") this_sched+= Play(self.get_pi_pulse_ground(),self._drive_chan) this_sched += Play(self.get_pi_pulse_excited(), self._drive_chan) this_sched|=self._measure<<int(delay) t1_exc_sched.append(this_sched) #sched_idx=0 #t1_gnd_sched[sched_idx] # Execution settings t1_exc_job = execute(t1_exc_sched, backend=self._backend, meas_level=1, meas_return='avg', shots=256, schedule_los=[{self._drive_chan: self.get_qubit_freq_ground()}] * len(t1_exc_sched)) if verbose: job_monitor(t1_exc_job) t1_exc_results =self.get_job_data(t1_exc_job, average=True) t1_exc_results = np.real(t1_exc_results) # Reverse the sign to have a decay behavior. # Fit the data fit_params, y_fit = self._fit_function(times, t1_exc_results, lambda x, A, C, T1: (A * np.exp(-x / T1) + C),[-6, 8, 100*1e-6]) _, _, T1_exc = fit_params if visual: plt.scatter(times*1e6, t1_exc_results, color='black') plt.plot(times*1e6, y_fit, color='red', label=f"T1 = {T1_exc*1e6:.2f} us") plt.xlim(0, np.max(times)*1e6) plt.title("$T_1$ Experiment", fontsize=15) plt.xlabel('Delay before measurement [$\mu$s]', fontsize=15) plt.ylabel('Signal [a.u.]', fontsize=15) plt.legend() plt.show() return T1_exc def T2_ground(self,verbose=False,visual=False): """Returns the T2 of 1 state""" time_max=300 time_step=4 times=np.arange(2,time_max,time_step)*1e-6 delay_times_dt=times/self._dt t2_gnd_sched=[] for delay in delay_times_dt: this_sched= Schedule(name=f"T2 delay={delay*self._dt/1e-6} us") this_sched|= Play(self.get_x90_pulse_ground(),self._drive_chan) this_sched|= Play(self.get_pi_pulse_ground(),self._drive_chan) << int(this_sched.duration+delay) this_sched|= Play(self.get_x90_pulse_ground(),self._drive_chan)<< int(this_sched.duration+delay) this_sched|=self._measure<<int(this_sched.duration) t2_gnd_sched.append(this_sched) #sched_idx=0 #t1_gnd_sched[sched_idx] # Execution settings t2_gnd_job = execute(t2_gnd_sched, backend=self._backend, meas_level=1, meas_return='avg', shots=512, schedule_los=[{self._drive_chan: self.get_qubit_freq_ground()}] * len(t2_gnd_sched)) if verbose: job_monitor(t2_gnd_job) t2_gnd_results =self.get_job_data(t2_gnd_job, average=True) t2_gnd_results = np.real(t2_gnd_results) # Fit the data2 fit_params, y_fit = self._fit_function(2*times, t2_gnd_results, lambda x, A, C, T2: (A * np.exp(-x / T2) + C),[-3, 0, 100*1e-6]) _, _, T2_gnd = fit_params if visual: plt.scatter(2*times*1e6, t2_gnd_results, color='black') plt.plot(2*times*1e6, y_fit, color='red', label=f"T2 = {T2_gnd*1e6:.2f} us") plt.xlim(0, np.max(2*times)*1e6) plt.title("$T_2$ Experiment with Hahn Echo", fontsize=15) plt.xlabel('Delay before measurement [$\mu$s]', fontsize=15) plt.ylabel('Signal [a.u.]', fontsize=15) plt.legend() plt.show() return T2_gnd
https://github.com/mrvee-qC-bee/SCQC23
mrvee-qC-bee
# Automatically appears upon opening a new python notebook in the IBM Quantum Lab # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit_aer import AerSimulator # qiskit-ibmq-provider has been deprecated. # Please see the Migration Guides in https://ibm.biz/provider_migration_guide for more detail. from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Estimator, Session, Options # Loading your IBM Quantum account(s) service = QiskitRuntimeService(channel="ibm_quantum") # Invoke a primitive inside a session. For more details see https://qiskit.org/documentation/partners/qiskit_ibm_runtime/tutorials.html # with Session(backend=service.backend("ibmq_qasm_simulator")): # result = Sampler().run(circuits).result() # Copied from IBM Quantum Composer from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from numpy import pi qreg_q = QuantumRegister(2, 'q') creg_c = ClassicalRegister(2, 'c') circuit = QuantumCircuit(qreg_q, creg_c) circuit.h(qreg_q[0]) # h gate on 1st qubit circuit.cx(qreg_q[0], qreg_q[1]) # control, target circuit.measure(qreg_q[0], creg_c[0]) # measure qubit 1 onto classical bit 1 circuit.measure(qreg_q[1], creg_c[1]) # measure qubit 2 onto bit 2 circuit.draw() # condensed notation circuit = QuantumCircuit(2) circuit.h(0) circuit.cx(0, 1) circuit.measure_all() circuit.draw() # running on a simulator sim = AerSimulator() job = sim.run(circuit) # shots = 1024 is the default result = job.result() counts = result.get_counts() counts plot_histogram(counts) # running on a real device from qiskit_ibm_provider import IBMProvider, least_busy provider = IBMProvider(instance='ibm-q/open/main') # get the least-busy backend real_backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 1 and not b.configuration().simulator and b.status().operational==True)) print(f"The best backend is: {real_backend.name}") # Transpile to a circuit optimized for execution on a real machine backend and Execute it circuit_transpiled = transpile(circuit, real_backend) # submit the job job = real_backend.run(circuit, shots = 1024) # Monitoring our job from qiskit_ibm_provider.job import job_monitor print(f"Job ID: {job.job_id()}") job_monitor(job) results = job.result() counts = results.get_counts() counts plot_histogram(count) # what you will additionally need to run locally IBMProvider.save_account(token="", overwrite=True) # get your token from the dashboard in the IBM Quantum Platform
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
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) # plot using a DensityMatrix state = DensityMatrix(qc) plot_state_city(state)
https://github.com/quantumyatra/quantum_computing
quantumyatra
# Useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np from math import pi from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.tools.visualization import circuit_drawer from qiskit.quantum_info import state_fidelity from qiskit import BasicAer backend = BasicAer.get_backend('unitary_simulator') q = QuantumRegister(3) qc = QuantumCircuit(q) qc.u3(pi/2,pi/2,pi/2,q[0]) qc.draw(output='mpl') job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) q = QuantumRegister(3) qc = QuantumCircuit(q) qc.u3(pi/2,pi/2,pi/2,q[1]) qc.draw(output='mpl') job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) q = QuantumRegister(3) qc = QuantumCircuit(q) qc.u3(pi/2,pi/2,pi/2,q[2]) qc.draw(output='mpl') job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) q = QuantumRegister(3) qc = QuantumCircuit(q) qc.u3(pi/2,pi/2,pi/2,q[0]) qc.u3(pi/2,pi/2,pi/2,q[1]) qc.draw(output='mpl') job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) q = QuantumRegister(3) qc = QuantumCircuit(q) qc.u3(pi/2,pi/2,pi/2,q[0]) qc.u3(pi/2,pi/2,pi/2,q[1]) qc.u3(pi/2,pi/2,pi/2,q[2]) qc.draw(output='mpl') job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) q = QuantumRegister(3) qc = QuantumCircuit(q) qc.u3(pi/2,pi/2,pi/2,q[0]) qc.u3(pi/2,pi/2,pi/2,q[0]) qc.u3(pi/4,pi/4,pi/4,q[1]) qc.u3(3*pi/4,3*pi/4,3*pi/4,q[1]) qc.u3(pi/6,pi/6,pi/6,q[2]) qc.u3(5*pi/6,5*pi/6,5*pi/6,q[2]) qc.draw(output='mpl') job = execute(qc, backend) job.result().get_unitary(qc, decimals=3)
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 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. """Univariate Marginal Distribution Algorithm (Estimation-of-Distribution-Algorithm).""" from __future__ import annotations from collections.abc import Callable from typing import Any import numpy as np from scipy.stats import norm from qiskit.utils import algorithm_globals from .optimizer import OptimizerResult, POINT from .scipy_optimizer import Optimizer, OptimizerSupportLevel class UMDA(Optimizer): """Continuous Univariate Marginal Distribution Algorithm (UMDA). UMDA [1] is a specific type of Estimation of Distribution Algorithm (EDA) where new individuals are sampled from univariate normal distributions and are updated in each iteration of the algorithm by the best individuals found in the previous iteration. .. seealso:: This original implementation of the UDMA optimizer for Qiskit was inspired by my (Vicente P. Soloviev) work on the EDAspy Python package [2]. EDAs are stochastic search algorithms and belong to the family of the evolutionary algorithms. The main difference is that EDAs have a probabilistic model which is updated in each iteration from the best individuals of previous generations (elite selection). Depending on the complexity of the probabilistic model, EDAs can be classified in different ways. In this case, UMDA is a univariate EDA as the embedded probabilistic model is univariate. UMDA has been compared to some of the already implemented algorithms in Qiskit library to optimize the parameters of variational algorithms such as QAOA or VQE and competitive results have been obtained [1]. UMDA seems to provide very good solutions for those circuits in which the number of layers is not big. The optimization process can be personalized depending on the paremeters chosen in the initialization. The main parameter is the population size. The bigger it is, the final result will be better. However, this increases the complexity of the algorithm and the runtime will be much heavier. In the work [1] different experiments have been performed where population size has been set to 20 - 30. .. note:: The UMDA implementation has more parameters but these have default values for the initialization for better understanding of the user. For example, ``\alpha`` parameter has been set to 0.5 and is the percentage of the population which is selected in each iteration to update the probabilistic model. Example: This short example runs UMDA to optimize the parameters of a variational algorithm. Here we will use the same operator as used in the algorithms introduction, which was originally computed by Qiskit Nature for an H2 molecule. The minimum energy of the H2 Hamiltonian can be found quite easily so we are able to set maxiters to a small value. .. code-block:: python from qiskit.opflow import X, Z, I from qiskit import Aer from qiskit_algorithms.optimizers import UMDA from qiskit_algorithms import QAOA from qiskit.utils import QuantumInstance H2_op = (-1.052373245772859 * I ^ I) + \ (0.39793742484318045 * I ^ Z) + \ (-0.39793742484318045 * Z ^ I) + \ (-0.01128010425623538 * Z ^ Z) + \ (0.18093119978423156 * X ^ X) p = 2 # Toy example: 2 layers with 2 parameters in each layer: 4 variables opt = UMDA(maxiter=100, size_gen=20) backend = Aer.get_backend('statevector_simulator') vqe = QAOA(opt, quantum_instance=QuantumInstance(backend=backend), reps=p) result = vqe.compute_minimum_eigenvalue(operator=H2_op) If it is desired to modify the percentage of individuals considered to update the probabilistic model, then this code can be used. Here for example we set the 60% instead of the 50% predefined. .. code-block:: python opt = UMDA(maxiter=100, size_gen=20, alpha = 0.6) backend = Aer.get_backend('statevector_simulator') vqe = QAOA(opt, quantum_instance=QuantumInstance(backend=backend), reps=p) result = vqe.compute_minimum_eigenvalue(operator=qubit_op) References: [1]: Vicente P. Soloviev, Pedro Larrañaga and Concha Bielza (2022, July). Quantum Parametric Circuit Optimization with Estimation of Distribution Algorithms. In 2022 The Genetic and Evolutionary Computation Conference (GECCO). DOI: https://doi.org/10.1145/3520304.3533963 [2]: Vicente P. Soloviev. Python package EDAspy. https://github.com/VicentePerezSoloviev/EDAspy. """ ELITE_FACTOR = 0.4 STD_BOUND = 0.3 def __init__( self, maxiter: int = 100, size_gen: int = 20, alpha: float = 0.5, callback: Callable[[int, np.array, float], None] | None = None, ) -> None: r""" Args: maxiter: Maximum number of iterations. size_gen: Population size of each generation. alpha: Percentage (0, 1] of the population to be selected as elite selection. callback: A callback function passed information in each iteration step. The information is, in this order: the number of function evaluations, the parameters, the best function value in this iteration. """ self.size_gen = size_gen self.maxiter = maxiter self.alpha = alpha self._vector: np.ndarray | None = None # initialization of generation self._generation: np.ndarray | None = None self._dead_iter = int(self._maxiter / 5) self._truncation_length = int(size_gen * alpha) super().__init__() self._best_cost_global: float | None = None self._best_ind_global: int | None = None self._evaluations: np.ndarray | None = None self._n_variables: int | None = None self.callback = callback def _initialization(self) -> np.ndarray: vector = np.zeros((4, self._n_variables)) vector[0, :] = np.pi # mu vector[1, :] = 0.5 # std return vector # build a generation of size SIZE_GEN from prob vector def _new_generation(self): """Build a new generation sampled from the vector of probabilities. Updates the generation pandas dataframe """ gen = algorithm_globals.random.normal( self._vector[0, :], self._vector[1, :], [self._size_gen, self._n_variables] ) self._generation = self._generation[: int(self.ELITE_FACTOR * len(self._generation))] self._generation = np.vstack((self._generation, gen)) # truncate the generation at alpha percent def _truncation(self): """Selection of the best individuals of the actual generation. Updates the generation by selecting the best individuals. """ best_indices = self._evaluations.argsort()[: self._truncation_length] self._generation = self._generation[best_indices, :] self._evaluations = np.take(self._evaluations, best_indices) # check each individual of the generation def _check_generation(self, objective_function): """Check the cost of each individual in the cost function implemented by the user.""" self._evaluations = np.apply_along_axis(objective_function, 1, self._generation) # update the probability vector def _update_vector(self): """From the best individuals update the vector of normal distributions in order to the next generation can sample from it. Update the vector of normal distributions """ for i in range(self._n_variables): self._vector[0, i], self._vector[1, i] = norm.fit(self._generation[:, i]) if self._vector[1, i] < self.STD_BOUND: self._vector[1, i] = self.STD_BOUND def minimize( self, fun: Callable[[POINT], float], x0: POINT, jac: Callable[[POINT], POINT] | None = None, bounds: list[tuple[float, float]] | None = None, ) -> OptimizerResult: not_better_count = 0 result = OptimizerResult() if isinstance(x0, float): x0 = [x0] self._n_variables = len(x0) self._best_cost_global = 999999999999 self._best_ind_global = 9999999 history = [] self._evaluations = np.array(0) self._vector = self._initialization() # initialization of generation self._generation = algorithm_globals.random.normal( self._vector[0, :], self._vector[1, :], [self._size_gen, self._n_variables] ) for _ in range(self._maxiter): self._check_generation(fun) self._truncation() self._update_vector() best_mae_local: float = min(self._evaluations) history.append(best_mae_local) best_ind_local = np.where(self._evaluations == best_mae_local)[0][0] best_ind_local = self._generation[best_ind_local] # update the best values ever if best_mae_local < self._best_cost_global: self._best_cost_global = best_mae_local self._best_ind_global = best_ind_local not_better_count = 0 else: not_better_count += 1 if not_better_count >= self._dead_iter: break if self.callback is not None: self.callback( len(history) * self._size_gen, self._best_ind_global, self._best_cost_global ) self._new_generation() result.x = self._best_ind_global result.fun = self._best_cost_global result.nfev = len(history) * self._size_gen return result @property def size_gen(self) -> int: """Returns the size of the generations (number of individuals per generation)""" return self._size_gen @size_gen.setter def size_gen(self, value: int): """ Sets the size of the generations of the algorithm. Args: value: Size of the generations (number of individuals per generation). Raises: ValueError: If `value` is lower than 1. """ if value <= 0: raise ValueError("The size of the generation should be greater than 0.") self._size_gen = value @property def maxiter(self) -> int: """Returns the maximum number of iterations""" return self._maxiter @maxiter.setter def maxiter(self, value: int): """ Sets the maximum number of iterations of the algorithm. Args: value: Maximum number of iterations of the algorithm. Raises: ValueError: If `value` is lower than 1. """ if value <= 0: raise ValueError("The maximum number of iterations should be greater than 0.") self._maxiter = value @property def alpha(self) -> float: """Returns the alpha parameter value (percentage of population selected to update probabilistic model)""" return self._alpha @alpha.setter def alpha(self, value: float): """ Sets the alpha parameter (percentage of individuals selected to update the probabilistic model) Args: value: Percentage (0,1] of generation selected to update the probabilistic model. Raises: ValueError: If `value` is lower than 0 or greater than 1. """ if (value <= 0) or (value > 1): raise ValueError(f"alpha must be in the range (0, 1], value given was {value}") self._alpha = value @property def settings(self) -> dict[str, Any]: return { "maxiter": self.maxiter, "alpha": self.alpha, "size_gen": self.size_gen, "callback": self.callback, } def get_support_level(self): """Get the support level dictionary.""" return { "gradient": OptimizerSupportLevel.ignored, "bounds": OptimizerSupportLevel.ignored, "initial_point": OptimizerSupportLevel.required, }
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/kanavsetia/qiskitcamp
kanavsetia
import numpy as np from qiskit.chemistry import bksf from qiskit.chemistry.fermionic_operator import FermionicOperator as FO import pdb from collections import OrderedDict from pyscf import gto, scf, ao2mo from pyscf.lib import param from scipy import linalg as scila from pyscf.lib import logger as pylogger # from qiskit.chemistry import AquaChemistryError from qiskit.chemistry import QMolecule from qiskit import QuantumRegister, QuantumCircuit from qiskit.transpiler import PassManager, transpile_dag, transpile from qiskit.aqua import Operator, QuantumInstance from qiskit.aqua.algorithms.adaptive import VQE from qiskit.aqua.algorithms.classical import ExactEigensolver from qiskit.chemistry import FermionicOperator from qiskit.quantum_info import Pauli from qiskit.converters import circuit_to_dag from qiskit.transpiler.passes import CXCancellation, Optimize1qGates from qiskit import BasicAer from qiskit.chemistry.drivers import PySCFDriver, UnitsType import networkx as nx import int_func #initialize one_body matrix and the two_body matrix np.set_printoptions(linewidth=230,suppress=True) ########## Random Test Case ############## two_body = np.zeros([4,4,4,4]) one_body=np.zeros([4,4]) one_body[3,2]=.5 one_body[2,3]=0.5 one_body[0,3]=0.4 one_body[3,0]=0.4 one_body[3,1]=0.3 one_body[1,3]=0.3 one_body[1,2]=0.21 one_body[2,1]=0.21 two_body=np.einsum('ijkl->iljk',two_body) ########### H2O ###################### mol = gto.Mole() mol.atom = [['O',(0.0, 0.0,0.0)],['H',(1, 0, 0)], ['H',(-1.0,0.0,0.0)]] mol.basis = 'sto-3g' _q_=int_func.qmol_func(mol, atomic=True) one_body=_q_.one_body_integrals obs=np.size(one_body,1) two_body=_q_.two_body_integrals ########### NH3 ###################### mol = gto.Mole() mol.atom = [['N', (0.0000, 0.0000, 0.0000)], ['H', (0.0000, -0.9377, -0.3816)], ['H', (0.8121, 0.4689 ,-0.3816)], ['H', (-0.8121, 0.4689 ,-0.3816)]] mol.basis = 'sto-3g' _q_=int_func.qmol_func(mol, atomic=True) one_body=_q_.one_body_integrals obs=np.size(one_body,1) two_body=_q_.two_body_integrals ########### CH4 ###################### mol = gto.Mole() mol.atom=[['C', (2.5369, 0.0000, 0.0000)], ['H', (3.0739, 0.3100, 0.0000)], ['H', (2.0000, -0.3100, 0.0000)], ['H', (2.2269, 0.5369, 0.0000)], ['H', (2.8469, -0.5369, 0.0000)]] mol.basis = 'sto-3g' _q_=int_func.qmol_func(mol, atomic=True) one_body=_q_.one_body_integrals obs=np.size(one_body,1) two_body=_q_.two_body_integrals # def r_mat(one_body, two_body) fer_op1=FO(h1=one_body,h2=two_body) # First step of the algorithm is to get the graph. edge_list=bksf.bravyi_kitaev_fast_edge_list(fer_op1) two_body=np.zeros([obs,obs,obs,obs]) fer_op1=FO(h1=one_body,h2=np.einsum('ijkl->iljk',two_body)) #initialize graph and calculate the degree G=nx.Graph() G.add_edges_from(edge_list.transpose()) degree=np.zeros(np.size(one_body,1)) #print([e for e in G.edges]) for i in range(obs): degree[i]=G.degree(i) # sort_deg=np.argsort(degree) #sort the edges with degree in descending order sort_deg=(-degree).argsort() #calculate r matrix to transform the Hamiltonian for renumbered fermionic modes. rmat=np.zeros([np.size(one_body,1),np.size(one_body,1)]) for i in range(np.size(one_body,1)): rmat[i,np.where(sort_deg==i)]=1 #initialize fermionic operator with the renumbered Hamiltonian fer_op1.transform(rmat) jw_qo=fer_op1.mapping('jordan_wigner') # Checking to make sure everything went correctly. edge_list=bksf.bravyi_kitaev_fast_edge_list(fer_op1) G=nx.Graph() G.add_edges_from(edge_list.transpose()) # degree=np.zeros(4) # print(edge_list) # # jw_qo=Operator(paulis=[[.4,Pauli.from_label('ZZZZ')],[.4,Pauli.from_label('IZZZ')]]) # Separating the x terms and the y terms in the Hamiltonian. X_paulis=[] Y_paulis=[] d=0 for i in jw_qo._paulis: if d%2==0: X_paulis.append(i) else: Y_paulis.append(i) d=d+1 for i in X_paulis: Y_paulis.append(i) # initialize the operator with reordered terms jw_x_qo=Operator(Y_paulis) # print(jw_x_qo.print_operators()) # Generating the circuit from the Operator class q = QuantumRegister(np.size(one_body,1), name='q') q_circ=jw_x_qo.evolve(None, 1, 'circuit', 1,q) # Getting rid of extra gates simulator = BasicAer.get_backend('qasm_simulator') pass_manager = PassManager() # pass_manager.append(CXCancellation()) pass_manager.append(Optimize1qGates()) # q_circ.draw() # print(q_circ.count_ops()) new_circ = transpile(q_circ, simulator, pass_manager=pass_manager) pass_manager=PassManager() pass_manager.append(CXCancellation()) for i in range(np.size(one_body,1)): new_circ = transpile(new_circ, simulator, pass_manager=pass_manager) # new_circ = transpile(new_circ, simulator, pass_manager=pass_manager) print("Gate count using the optimization based on the structure of the fermionic problem") print(new_circ.count_ops()) # q = QuantumRegister(4, name='q') # q_circ=jw_qo.evolve(None, 1, 'circuit', 1,q)
https://github.com/pranavdurai10/quantum-gates
pranavdurai10
''' /////////////////////////////////////////////////////////////////////////// Code written by Pranav Durai for Quantum Computer on 11.06.2023 @ 18:00:01 Component: Controlled-T Gate Framework: Qiskit 0.43.0 /////////////////////////////////////////////////////////////////////////// ''' # Import necessary libraries from qiskit import QuantumCircuit, Aer, execute # Create a quantum circuit with two qubits circuit = QuantumCircuit(2) # Apply the Controlled-T gate using a combination of gates circuit.h(1) circuit.cx(0, 1) circuit.tdg(1) circuit.cx(0, 1) circuit.t(1) circuit.cx(0, 1) # Measure the qubits circuit.measure_all() # Simulate the circuit using the local Aer simulator simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, simulator, shots=1) # Get the result result = job.result() counts = result.get_counts(circuit) # Print the measurement outcome print("Measurement outcome:", list(counts.keys())[0])
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
PabloMartinezAngerosa
from tsp_qaoa import test_solution from qiskit.visualization import plot_histogram import networkx as nx import numpy as np import json import csv # Array of JSON Objects # Sort the JSON data based on the value of the brand key UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["mean"]) # genera las distancias index = -1 for sample in UNIFORM_CONVERGENCE_SAMPLE: mean = sample["mean"] index += 1 distance_p_ground_state = np.max(np.abs(UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"] - sample["probabilities"])) UNIFORM_CONVERGENCE_SAMPLE[index]["distance_pgs"] = distance_p_ground_state header = ['instance', 'iteration', 'distance'] length_instances = 2 with open('qaoa_multiple_distance.csv', 'w', encoding='UTF8') as f: writer = csv.writer(f) # write the header writer.writerow(header) for i in range(length_instances): job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution() iteration = 0 for sample in UNIFORM_CONVERGENCE_SAMPLE: iteration += 1 mean = sample["mean"] distance = sample["distance_pgs"] state = 0 for probability in sample["probabilities"]: state += 1 # write the data data = [iteration, state, probability, mean] writer.writerow(data) writer_q.writerow([iteration, distance])
https://github.com/UST-QuAntiL/nisq-analyzer-content
UST-QuAntiL
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister # https://github.com/Qiskit/qiskit-community-tutorials/blob/master/algorithms/bernstein_vazirani.ipynb def get_circuit(**kwargs): number_of_qubits = kwargs["number_of_qubits"] a = kwargs["a"] a = a % 2**(number_of_qubits) # a = a mod 2^(number_of_qubits) print(a) qr = QuantumRegister(number_of_qubits) cr = ClassicalRegister(number_of_qubits) qc = QuantumCircuit(qr, cr) # hadamard gates for i in range(number_of_qubits): qc.h(qr[i]) qc.barrier() # inner product oracle for i in range(number_of_qubits): if (a & (1 << i)): #if bin(a)[i] = 1 then use Z gate qc.z(qr[i]) else: qc.iden(qr[i]) # else (=0) use identity qc.barrier() # hadamard gates for i in range(number_of_qubits): qc.h(qr[i]) # measurement qc.barrier(qr) qc.measure(qr, cr) return qc
https://github.com/primaryobjects/oracle
primaryobjects
from lib.util import execute from lib.grover import grover from lib.oracles.entangle import oracle from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister # # Superimposed Emotions # # Generates an emoticon from two ASCII binary strings that contain nearly identical bits except for a few. # The differing bits get applied entanglement, resulting in a random selection of either emoticon from the quantum circuit. # The final output simulataneously represents both emoticons. Measuring the output collapses the state, resulting in a single emotion to display. # # Motivated by https://medium.com/qiskit/making-a-quantum-computer-smile-cee86a6fc1de and https://github.com/quantumjim/quantum_emoticon/blob/master/quantum_emoticon.ipynb # See also the IBM Quantum Composer version at https://quantum-computing.ibm.com/composer/files/d363d10d96ff5f1b9000b64c56a9856a3fbe01a5dd0bb91288a12a47c22a76a8 # emoticons = [ ';)', # 00111011 00101001 '8)' # 00111000 00101001 # ^^----- all bits are the same, except for these two. ] def decode_binary_string(s): """ Returns an ASCII string for a binary bit string (1 byte [8 bits] per character). """ #n = int(s, 2) #return n.to_bytes((n.bit_length() + 7) // 8, 'big').decode() return ''.join(chr(int(s[i*8:i*8+8],2)) for i in range(len(s)//8)) def main(): """ Return a random emoticon from ;) or 8) by using entangled qubits and bit strings to represent ASCII characters. """ emoticon1 = ';)' emoticon2 = '8)' # Convert ascii to a binary string. b1 = ''.join(format(ord(i), '08b') for i in emoticon1) b2 = ''.join(format(ord(i), '08b') for i in emoticon2) # Number of qubits, 1 qubit for each bit. n = len(b1) # Create a quantum circuit. var = QuantumRegister(n, 'var') cr = ClassicalRegister(n, 'c') qc = QuantumCircuit(var, cr) # Append the oracle, which encodes the binary values and applies entanglement accordingly. qc.append(oracle(b1, b2, [[8, 9]]), range(n)) # Measure all qubits to force a single result out of superposition. qc.measure(var, cr) print(qc.draw()) # Run the circuit several times to show the difference in superposition state. results = [] for i in range(1000): # Execute the quantum circuit. result = execute(qc) # Get the resulting hit counts. counts = result.get_counts() if i == 0: print(counts) # Find the most frequent hit count. key = max(counts, key=counts.get) # Decode the bits into ASCII characters (8 bits [1 byte] per character). result = decode_binary_string(key) results += result # Print the output, random result of emoticon1 or emotion2! if i > 0 and i % 80 == 0: print(''.join(results)) results.clear() main()
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") # from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open(filename, "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) filename = "job_ids_ibmq_jakarta_100step_20220413_030821_.pkl" # change here with open(filename, "rb") as f: job_ids_dict = pickle.load(f) job_ids = job_ids_dict["job_ids"] cal_job_id = job_ids_dict["cal_job_id"] retrieved_jobs = [] for job_id in job_ids: retrieved_jobs.append(backend.retrieve_job(job_id)) retrieved_cal_job = backend.retrieve_job(cal_job_id) cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids))) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import * from qiskit.circuit import Gate my_gate = Gate(name='my_gate', num_qubits=2, params=[]) qr = QuantumRegister(3, 'q') circ = QuantumCircuit(qr) circ.append(my_gate, [qr[0], qr[1]]) circ.append(my_gate, [qr[1], qr[2]]) circ.draw() # Build a sub-circuit sub_q = QuantumRegister(2) sub_circ = QuantumCircuit(sub_q, name='sub_circ') sub_circ.h(sub_q[0]) sub_circ.crz(1, sub_q[0], sub_q[1]) sub_circ.barrier() sub_circ.id(sub_q[1]) sub_circ.u(1, 2, -2, sub_q[0]) # Convert to a gate and stick it into an arbitrary place in the bigger circuit sub_inst = sub_circ.to_instruction() qr = QuantumRegister(3, 'q') circ = QuantumCircuit(qr) circ.h(qr[0]) circ.cx(qr[0], qr[1]) circ.cx(qr[1], qr[2]) circ.append(sub_inst, [qr[1], qr[2]]) circ.draw() decomposed_circ = circ.decompose() # Does not modify original circuit decomposed_circ.draw() from qiskit.circuit import Parameter theta = Parameter('θ') n = 5 qc = QuantumCircuit(5, 1) qc.h(0) for i in range(n-1): qc.cx(i, i+1) qc.barrier() qc.rz(theta, range(5)) qc.barrier() for i in reversed(range(n-1)): qc.cx(i, i+1) qc.h(0) qc.measure(0, 0) qc.draw('mpl') print(qc.parameters) import numpy as np theta_range = np.linspace(0, 2 * np.pi, 128) circuits = [qc.bind_parameters({theta: theta_val}) for theta_val in theta_range] circuits[-1].draw() backend = BasicAer.get_backend('qasm_simulator') job = backend.run(transpile(circuits, backend)) counts = job.result().get_counts() import matplotlib.pyplot as plt fig = plt.figure(figsize=(8,6)) ax = fig.add_subplot(111) ax.plot(theta_range, list(map(lambda c: c.get('0', 0), counts)), '.-', label='0') ax.plot(theta_range, list(map(lambda c: c.get('1', 0), counts)), '.-', label='1') ax.set_xticks([i * np.pi / 2 for i in range(5)]) ax.set_xticklabels(['0', r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3\pi}{2}$', r'$2\pi$'], fontsize=14) ax.set_xlabel('θ', fontsize=14) ax.set_ylabel('Counts', fontsize=14) ax.legend(fontsize=14) import time from itertools import combinations from qiskit.compiler import assemble from qiskit.test.mock import FakeVigo start = time.time() qcs = [] theta_range = np.linspace(0, 2*np.pi, 32) for n in theta_range: qc = QuantumCircuit(5) for k in range(8): for i,j in combinations(range(5), 2): qc.cx(i,j) qc.rz(n, range(5)) for i,j in combinations(range(5), 2): qc.cx(i,j) qcs.append(qc) compiled_circuits = transpile(qcs, backend=FakeVigo()) qobj = assemble(compiled_circuits, backend=FakeVigo()) end = time.time() print('Time compiling over set of bound circuits: ', end-start) start = time.time() qc = QuantumCircuit(5) theta = Parameter('theta') for k in range(8): for i,j in combinations(range(5), 2): qc.cx(i,j) qc.rz(theta, range(5)) for i,j in combinations(range(5), 2): qc.cx(i,j) transpiled_qc = transpile(qc, backend=FakeVigo()) qobj = assemble([transpiled_qc.bind_parameters({theta: n}) for n in theta_range], backend=FakeVigo()) end = time.time() print('Time compiling over parameterized circuit, then binding: ', end-start) phi = Parameter('phi') sub_circ1 = QuantumCircuit(2, name='sc_1') sub_circ1.rz(phi, 0) sub_circ1.rx(phi, 1) sub_circ2 = QuantumCircuit(2, name='sc_2') sub_circ2.rx(phi, 0) sub_circ2.rz(phi, 1) qc = QuantumCircuit(4) qr = qc.qregs[0] qc.append(sub_circ1.to_instruction(), [qr[0], qr[1]]) qc.append(sub_circ2.to_instruction(), [qr[0], qr[1]]) qc.append(sub_circ2.to_instruction(), [qr[2], qr[3]]) print(qc.draw()) # The following raises an error: "QiskitError: 'Name conflict on adding parameter: phi'" # phi2 = Parameter('phi') # qc.u3(0.1, phi2, 0.3, 0) p = Parameter('p') qc = QuantumCircuit(3, name='oracle') qc.rz(p, 0) qc.cx(0, 1) qc.rz(p, 1) qc.cx(1, 2) qc.rz(p, 2) theta = Parameter('theta') phi = Parameter('phi') gamma = Parameter('gamma') qr = QuantumRegister(9) larger_qc = QuantumCircuit(qr) larger_qc.append(qc.to_instruction({p: theta}), qr[0:3]) larger_qc.append(qc.to_instruction({p: phi}), qr[3:6]) larger_qc.append(qc.to_instruction({p: gamma}), qr[6:9]) print(larger_qc.draw()) print(larger_qc.decompose().draw()) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/quantumjim/qreative
quantumjim
import json import requests from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, IBMQ, execute, compile IBMQ.load_accounts() q = QuantumRegister(5) c = ClassicalRegister(5) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q,c) device = 'ibmqx4' backend = IBMQ.get_backend(device) qobj = compile(qc,backend,shots=8192,memory=True) qobj_dict = qobj.as_dict() print(qobj_dict) print( json.dumps(qobj_dict) ) data_dict = {'qObject': qobj_dict,'backend': {'name':device}} data = json.dumps(data_dict) print(data) token = 'insert your API token here' url = 'https://quantumexperience.ng.bluemix.net/api' response = requests.post(str(url + "/users/loginWithToken"),data={'apiToken': token}) resp_id = response.json()['id'] job_url = url+'/Jobs?access_token='+resp_id job = requests.post(job_url, data=data,headers={'Content-Type': 'application/json'}) job_id = job.json()['id'] results_url = url+'/Jobs/'+job_id+'?access_token='+resp_id result = requests.get(results_url).json() random_hex = result['qObjectResult']['results'][0]['data']['memory']
https://github.com/Sanjay-995/Qiskit-Developer-Prep-Guide
Sanjay-995
import qiskit qiskit.__version__ qiskit.__qiskit_version__ #Import the required packages from qiskit import QuantumCircuit, QuantumRegister,ClassicalRegister,Aer,execute from qiskit.visualization import * from math import sqrt v=[1/sqrt(2),0,0,1/sqrt(2)] v qc_bell=QuantumCircuit(2) v=[1/sqrt(2),0,0,1/sqrt(2)] qc_bell.initialize(v,[0,1]) qc_bell.draw('mpl') backend=Aer.get_backend('statevector_simulator') job=execute(qc_bell,backend) result=job.result() sv=result.get_statevector() print("Statvector :",sv) sv.draw(output="latex") #Create a Quantum Circuit with 2 qubits qc_bell=QuantumCircuit(2) qc_bell.h(0) qc_bell.cx(0,1) qc_bell.draw('mpl') backend=Aer.get_backend('statevector_simulator') job=execute(qc_bell,backend) result=job.result() sv=result.get_statevector() print("Statvector :",sv) sv.draw(output="latex") qc_2=QuantumCircuit(2) v1, v2=[0,1],[1,0] qc_2.initialize(v1,0) qc_2.initialize(v2,1) qc_2.draw('mpl') backend=Aer.get_backend('statevector_simulator') job=execute(qc_2,backend) result=job.result() sv=result.get_statevector() print("Statvector :",sv) sv.draw(output="latex") #Create a Quantum Circuit with 2 qubits qc_3=QuantumCircuit(2) qc_3.x(0) qc_3.draw('mpl',initial_state=True) backend=Aer.get_backend('statevector_simulator') job=execute(qc_3,backend) result=job.result() sv=result.get_statevector() print("Statvector :",sv) sv.draw(output="latex") #Create a Quantum Circuit with 2 qubits qc_4=QuantumCircuit(2) qc_4.cx(0,1) qc_4.draw('mpl') backend=Aer.get_backend('statevector_simulator') job=execute(qc_4,backend) result=job.result() sv=result.get_statevector() print("Statvector :",sv) sv.draw(output="latex") #Create a Quantum Circuit with 2 qubits qc_5=QuantumCircuit(2) qc_5.h(0) qc_5.h(1) qc_5.draw('mpl') backend=Aer.get_backend('statevector_simulator') job=execute(qc_5,backend) result=job.result() sv=result.get_statevector() print("Statvector :",sv) sv.draw(output="latex")
https://github.com/zhangx1923/QISKit_Deve_Challenge
zhangx1923
# -*- coding: utf-8 -*- # # 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. # ============================================================================= """ ---------------> please fill out this section <--------------- Your Name : Zhang xin, Xiang hong, Li yanhong, Shen ruping Your E-Mail :zhang.x@cqu.edu.cn Description of the algorithm : - How does the algorithm work? - Did you use any previously published schemes? Cite relevant papers. - What packages did you use in your code and for what part of the algorithm? - How general is your approach? Does it work for arbitrary coupling layouts (qubit number)? - Are there known situations when the algorithm fails? The optimization scheme we designed is divided into three steps: the whole qubit adjustment, the local qubit adjustment and the mergence of the single qubit gates. In the first, we extracte all the CNOT operations in the current quantum program and sorting them according to the order they perform in the quantum program. Then, traversing the CNOT operations fromfront to back, and conducting qubit ID adjustment to each illegal CNOT encountered, since each adjustment will change all of the qubit ID, so we should make sure that this adjustment does not make the previous CNOT operation illegal. And then, continue to adjust backwards until we have no way to modify the current illegal CNOT operation by adjusting the qubit ID without affecting the previous CNOT operation. Secondly, we do the following design in the algorithm: After switching the state of the qubit by using SWAP gates, it is not necessary to use these SWAP gates to restore it again, instead, we use the Qubit ID that participates in transformation as a mapping to adjust the qubit ID to the subsequent code(This is why we call it local qubit adjustment). In the end, we combine the single qubits which act on a same qubit in possible. In order to write and execute programs more conveniently, we introduced the following three Python modules: 1. re 2. copy 3. sympy It should be noted that all of these Python modules can be installed directly through PIP execution or CONDA instructions, and the code can be successfully executed on Windows and MAC systems. Our method is general and works well for arbitrary coupling layouts and all qubits number. For more details, you can read the IBM Developer challenge code manual. ---------------> please fill out this section <--------------- """ # Include any Python modules needed for your implementation here import re from Optimize import * # The following class is the input and output circuit representation for a # QISKit compiler from qiskit.dagcircuit import DAGCircuit from challenge_evaluation import * def compiler_function(dag_circuit,coupling_map=None,gate_costs=None): #Instantiate an object of that class opt = Optimize(dag_circuit,coupling_map) #print(opt.qasm) #print(dag_circuit.qasm()) #there are two cases: #1. the original qasm code can be exeucted on the platform after adjusted the id of qubit #2. the original qasm can't be exeucted by adjusting the id, then we have to use SWAP gates oriQASM = dag_circuit.qasm() opt.setQASM(oriQASM) #the QASM can be executed on the targat platform tarQASM = opt.qasm if opt.badCnot != []: oriQASM = opt.adjustID() #generate the final qasm code tarQASM = opt.generateQASM(oriQASM) tarQASM = opt.reduceSameGate(tarQASM) #generate the instance of DAGCircuit resCircuit = qasm_to_dag_circuit(tarQASM) return resCircuit # def compiler_function(dag_circuit, coupling_map=None, gate_costs=None): # """ # Modify a DAGCircuit based on a gate cost function. # Instructions: # Your submission involves filling in the implementation # of this function. The function takes as input a DAGCircuit # object, which can be generated from a QASM file by using the # function 'qasm_to_dag_circuit' from the included # 'submission_evaluation.py' module. For more information # on the DAGCircuit object see the or QISKit documentation # (eg. 'help(DAGCircuit)'). # Args: # dag_circuit (DAGCircuit): DAGCircuit object to be compiled. # coupling_circuit (list): Coupling map for device topology. # A coupling map of None corresponds an # all-to-all connected topology. # gate_costs (dict) : dictionary of gate names and costs. # Returns: # A modified DAGCircuit object that satisfies an input coupling_map # and has as low a gate_cost as possible. # """ # ##################### # # Put your code here # ##################### # # Example using mapper passes in Qiskit # import copy # from qiskit.mapper import swap_mapper, direction_mapper, cx_cancellation, optimize_1q_gates, Coupling # from qiskit import qasm, unroll # # initial_layout = None # coupling = Coupling(coupling_map) # #print(coupling) # compiled_dag, final_layout = swap_mapper(copy.deepcopy(dag_circuit), coupling, initial_layout, trials=40, seed=19) # # Expand swaps # basis_gates = "u1,u2,u3,cx,id" # QE target basis # program_node_circuit = qasm.Qasm(data=compiled_dag.qasm()).parse() # unroller_circuit = unroll.Unroller(program_node_circuit, # unroll.DAGBackend( # basis_gates.split(","))) # compiled_dag = unroller_circuit.execute() # # Change cx directions # compiled_dag = direction_mapper(compiled_dag, coupling) # # Simplify cx gates # cx_cancellation(compiled_dag) # # Simplify single qubit gates # compiled_dag = optimize_1q_gates(compiled_dag) # ##################### # # Put your code here # ##################### # # Return the compiled dag circuit # return compiled_dag if __name__ == "__main__": dics = {0:"circle",1:"linear",2:"neighbour",3:"center"} for q in range(9,10): for cm in range(3,4): for d in range(5,15): res = score(d,cm,q,compiler_function,'local_qasm_simulator') name= "d" + str(d) + ".txt" location = "ha/" + str(q) + "-" + dics[cm] + "/" files = open(location+name,"w") strs = "" for k in res[1].keys(): strs += str(res[1][k]) strs += "\n" strs += str(res[0]) files.write(strs) files.close()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_optimization.problems import QuadraticProgram # define a problem qp = QuadraticProgram() qp.binary_var("x") qp.integer_var(name="y", lowerbound=-1, upperbound=4) qp.maximize(quadratic={("x", "y"): 1}) qp.linear_constraint({"x": 1, "y": -1}, "<=", 0) print(qp.prettyprint()) from qiskit_optimization.algorithms import CplexOptimizer, GurobiOptimizer cplex_result = CplexOptimizer().solve(qp) gurobi_result = GurobiOptimizer().solve(qp) print("cplex") print(cplex_result.prettyprint()) print() print("gurobi") print(gurobi_result.prettyprint()) result = CplexOptimizer(disp=True, cplex_parameters={"threads": 1, "timelimit": 0.1}).solve(qp) print(result.prettyprint()) from qiskit_optimization.algorithms import MinimumEigenOptimizer from qiskit_aer import Aer from qiskit.algorithms.minimum_eigensolvers import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler meo = MinimumEigenOptimizer(QAOA(sampler=Sampler(), optimizer=COBYLA(maxiter=100))) result = meo.solve(qp) print(result.prettyprint()) print("\ndisplay the best 5 solution samples") for sample in result.samples[:5]: print(sample) # docplex model from docplex.mp.model import Model docplex_model = Model("docplex") x = docplex_model.binary_var("x") y = docplex_model.integer_var(-1, 4, "y") docplex_model.maximize(x * y) docplex_model.add_constraint(x <= y) docplex_model.prettyprint() # gurobi model import gurobipy as gp gurobipy_model = gp.Model("gurobi") x = gurobipy_model.addVar(vtype=gp.GRB.BINARY, name="x") y = gurobipy_model.addVar(vtype=gp.GRB.INTEGER, lb=-1, ub=4, name="y") gurobipy_model.setObjective(x * y, gp.GRB.MAXIMIZE) gurobipy_model.addConstr(x - y <= 0) gurobipy_model.update() gurobipy_model.display() from qiskit_optimization.translators import from_docplex_mp, from_gurobipy qp = from_docplex_mp(docplex_model) print("QuadraticProgram obtained from docpblex") print(qp.prettyprint()) print("-------------") print("QuadraticProgram obtained from gurobipy") qp2 = from_gurobipy(gurobipy_model) print(qp2.prettyprint()) from qiskit_optimization.translators import to_gurobipy, to_docplex_mp gmod = to_gurobipy(from_docplex_mp(docplex_model)) print("convert docplex to gurobipy via QuadraticProgram") gmod.display() dmod = to_docplex_mp(from_gurobipy(gurobipy_model)) print("\nconvert gurobipy to docplex via QuadraticProgram") print(dmod.export_as_lp_string()) ind_mod = Model("docplex") x = ind_mod.binary_var("x") y = ind_mod.integer_var(-1, 2, "y") z = ind_mod.integer_var(-1, 2, "z") ind_mod.maximize(3 * x + y - z) ind_mod.add_indicator(x, y >= z, 1) print(ind_mod.export_as_lp_string()) qp = from_docplex_mp(ind_mod) result = meo.solve(qp) # apply QAOA to QuadraticProgram print("QAOA") print(result.prettyprint()) print("-----\nCPLEX") print(ind_mod.solve()) # apply CPLEX directly to the Docplex model import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/QuSTaR/kaleidoscope
QuSTaR
# -*- coding: utf-8 -*- # This code is part of Kaleidoscope. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # 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. # The Hamming distance and internal plot histogram data are part of # Qiskit. The latter will be modified at some point. """Interactive histogram from experiment counts""" import functools from collections import Counter, OrderedDict import numpy as np import plotly.graph_objects as go from kaleidoscope.errors import KaleidoscopeError from kaleidoscope.colors import COLORS1, COLORS2, COLORS3, COLORS4, COLORS5, COLORS14 from kaleidoscope.colors.utils import find_text_color from .plotly_wrapper import PlotlyWidget, PlotlyFigure def hamming_distance(str1, str2): """Calculate the Hamming distance between two bit strings Args: str1 (str): First string. str2 (str): Second string. Returns: int: Distance between strings. Raises: ValueError: Strings not same length """ if len(str1) != len(str2): raise ValueError('Strings not same length.') return sum(s1 != s2 for s1, s2 in zip(str1, str2)) VALID_SORTS = ['asc', 'desc', 'hamming'] DIST_MEAS = {'hamming': hamming_distance} def probability_distribution(data, figsize=(None, None), colors=None, scale='linear', number_to_keep=None, sort='asc', target_string=None, legend=None, bar_labels=True, state_labels_kind='bits', state_labels=None, title=None, plot_background_color='#e5e0df', background_color='#ffffff', as_widget=False): """Interactive histogram plot of probability distributions. Parameters: data (list or dict): This is either a list of dictionaries or a single dict containing the values to represent (ex {'001': 130}) figsize (tuple): Figure size in pixels. colors (list or str): String or list of strings for histogram bar colors. scale (str): Probability scale 'linear' (default) or 'log'. number_to_keep (int): The number of terms to plot and rest is made into a single bar called 'rest'. sort (string): Could be 'asc', 'desc', or 'hamming'. target_string (str): Target string if 'sort' is a distance measure. legend(list): A list of strings to use for labels of the data. The number of entries must match the length of data (if data is a list or 1 if it's a dict) bar_labels (bool): Label each bar in histogram with probability value. state_labels_kind (str): 'bits' (default) or 'ints'. state_labels (list): A list of custom state labels. title (str): A string to use for the plot title. plot_background_color (str): Set the background color behind histogram bars. background_color (str): Set the background color for axes. as_widget (bool): Return figure as an ipywidget. Returns: PlotlyFigure or PlotlyWidget: A figure for the rendered histogram. Raises: ValueError: When legend is provided and the length doesn't match the input data. ImportError: When failed to load plotly. KaleidoscopeError: When state labels is not correct length. Example: .. jupyter-execute:: from qiskit import * import kaleidoscope.qiskit from kaleidoscope.qiskit.services import Simulators from kaleidoscope.interactive import probability_distribution sim = Simulators.aer_vigo_simulator qc = QuantumCircuit(3, 3) >> sim qc.h(1) qc.cx(1,0) qc.cx(1,2) qc.measure(range(3), range(3)) counts = qc.transpile().sample().result_when_done() probability_distribution(counts) """ if sort not in VALID_SORTS: raise ValueError("Value of sort option, %s, isn't a " "valid choice. Must be 'asc', " "'desc', or 'hamming'") if sort in DIST_MEAS and target_string is None: err_msg = 'Must define target_string when using distance measure.' raise ValueError(err_msg) if isinstance(data, dict): data = [data] if legend and len(legend) != len(data): raise ValueError("Length of legendL (%s) doesn't match " "number of input executions: %s" % (len(legend), len(data))) text_color = find_text_color(background_color) labels = list(sorted( functools.reduce(lambda x, y: x.union(y.keys()), data, set()))) if number_to_keep is not None: labels.append('rest') if sort in DIST_MEAS: dist = [] for item in labels: dist.append(DIST_MEAS[sort](item, target_string)) labels = [list(x) for x in zip(*sorted(zip(dist, labels), key=lambda pair: pair[0]))][1] # Set bar colors if colors is None: if len(data) == 1: colors = COLORS1 elif len(data) == 2: colors = COLORS2 elif len(data) == 3: colors = COLORS3 elif len(data) == 4: colors = COLORS4 elif len(data) == 5: colors = COLORS5 else: colors = COLORS14 elif isinstance(colors, str): colors = [colors] width = 1/(len(data)+1) # the width of the bars labels_dict, all_pvalues, _ = _plot_histogram_data(data, labels, number_to_keep) fig = go.Figure() for item, _ in enumerate(data): xvals = [] yvals = [] for idx, val in enumerate(all_pvalues[item]): xvals.append(idx+item*width) yvals.append(val) labels = list(labels_dict.keys()) if state_labels_kind == 'ints': labels = [int(label, 2) for label in labels] if state_labels: if len(state_labels) != len(labels): raise KaleidoscopeError('Number of input state labels does not match data.') labels = state_labels hover_template = "<b>{x}</b><br>P = {y}" hover_text = [hover_template.format(x=labels[kk], y=np.round(yvals[kk], 3)) for kk in range(len(yvals))] fig.add_trace(go.Bar(x=xvals, y=yvals, width=width, hoverinfo="text", hovertext=hover_text, marker_color=colors[item % len(colors)], name=legend[item] if legend else '', text=np.round(yvals, 3) if bar_labels else None, textposition='auto' )) xaxes_labels = list(labels_dict.keys()) if state_labels_kind == 'ints': xaxes_labels = [int(label, 2) for label in xaxes_labels] if state_labels: if len(state_labels) != len(xaxes_labels): raise KaleidoscopeError('Number of input state labels does not match data.') xaxes_labels = state_labels fig.update_xaxes(title='Basis state', titlefont_size=16, tickvals=list(range(len(labels_dict.keys()))), ticktext=xaxes_labels, tickfont_size=14, showline=True, linewidth=1, linecolor=text_color if text_color == 'white' else None, ) fig.update_yaxes(title='Probability', titlefont_size=16, tickfont_size=14, showline=True, linewidth=1, linecolor=text_color if text_color == 'white' else None, ) if scale == 'log': lower = np.min([min(item.values())/sum(item.values()) for item in data]) lower = int(np.floor(np.log10(lower))) fig.update_yaxes(type="log", range=[lower, 0]) fig.update_layout(yaxis=dict(tickmode='array', tickvals=[10**k for k in range(lower, 1)], ticktext=["10<sup>{}</sup>".format(k) for k in range(lower, 1)] )) fig.update_layout(xaxis_tickangle=-70, showlegend=(legend is not None), width=figsize[0], height=figsize[1], plot_bgcolor=plot_background_color, paper_bgcolor=background_color, title=dict(text=title, x=0.5), title_font_size=18, font=dict(color=text_color), ) if as_widget: return PlotlyWidget(fig) return PlotlyFigure(fig) def _plot_histogram_data(data, labels, number_to_keep): """Generate the data needed for plotting counts. Parameters: data (list or dict): This is either a list of dictionaries or a single dict containing the values to represent (ex {'001': 130}) labels (list): The list of bitstring labels for the plot. number_to_keep (int): The number of terms to plot and rest is made into a single bar called 'rest'. Returns: tuple: tuple containing: (dict): The labels actually used in the plotting. (list): List of ndarrays for the bars in each experiment. (list): Indices for the locations of the bars for each experiment. """ labels_dict = OrderedDict() all_pvalues = [] all_inds = [] for execution in data: if number_to_keep is not None: data_temp = dict(Counter(execution).most_common(number_to_keep)) data_temp["rest"] = sum(execution.values()) - sum(data_temp.values()) execution = data_temp values = [] for key in labels: if key not in execution: if number_to_keep is None: labels_dict[key] = 1 values.append(0) else: values.append(-1) else: labels_dict[key] = 1 values.append(execution[key]) values = np.array(values, dtype=float) where_idx = np.where(values >= 0)[0] pvalues = values[where_idx] / sum(values[where_idx]) all_pvalues.append(pvalues) numelem = len(values[where_idx]) ind = np.arange(numelem) # the x locations for the groups all_inds.append(ind) return labels_dict, all_pvalues, all_inds
https://github.com/quantumyatra/quantum_computing
quantumyatra
import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, BasicAer, IBMQ from qiskit.visualization import plot_histogram, plot_bloch_multivector from qiskit.extensions import Initialize from qiskit.quantum_info import random_statevector from utility import * qr = QuantumRegister(3) # Protocol uses 3 qubits crz = ClassicalRegister(1) # and 2 classical bits crx = ClassicalRegister(1) # in 2 different registers teleportation_circuit = QuantumCircuit(qr, crz, crx) def create_bell_pair(qc, a, b, print_state_vec=False): "creates a bell pair in qc using qubits a and b" qc.h(a) qc.cx(a,b) if print_state_vec : state = get_state_vector(qc) print (state) def test_bell_pair(): qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = get_state_vector(qc) print (state) test_bell_pair() qr = QuantumRegister(3) crz = ClassicalRegister(1) crx = ClassicalRegister(1) teleportation_circuit = QuantumCircuit(qr, crz, crx) create_bell_pair(teleportation_circuit, 1, 2) teleportation_circuit.draw(output='mpl') def alice_gates(qc, psi, a): qc.cx(psi, a) qc.h(psi) qr = QuantumRegister(3) crz = ClassicalRegister(1) crx = ClassicalRegister(1) teleportation_circuit = QuantumCircuit(qr, crz, crx) create_bell_pair(teleportation_circuit, 1, 2) teleportation_circuit.barrier() alice_gates(teleportation_circuit, 0, 1) teleportation_circuit.draw(output='mpl') def measure_and_send(qc, a, b): """Measures qubits a & b and 'sends' the results to Bob""" qc.barrier() qc.measure(a,0) qc.measure(b,1) #Set up qr = QuantumRegister(3) crz = ClassicalRegister(1) crx = ClassicalRegister(1) teleportation_circuit = QuantumCircuit(qr, crz, crx) # step 1 create_bell_pair(teleportation_circuit, 1, 2) #step 2 teleportation_circuit.barrier() alice_gates(teleportation_circuit, 0, 1) #step 3 measure_and_send(teleportation_circuit, 0, 1) teleportation_circuit.draw(output='mpl') def bob_gates(qc, qubit, crz, crx): # Here we use c_if to control our gates with a classical # bit instead of a qubit qc.x(qubit).c_if(crx, 1) # Apply gates if the registers qc.z(qubit).c_if(crz, 1) # are in the state '1' #Set up qr = QuantumRegister(3) crz = ClassicalRegister(1) crx = ClassicalRegister(1) teleportation_circuit = QuantumCircuit(qr, crz, crx) # step 1 create_bell_pair(teleportation_circuit, 1, 2) #step 2 teleportation_circuit.barrier() alice_gates(teleportation_circuit, 0, 1) #step 3 measure_and_send(teleportation_circuit, 0, 1) # step 4 teleportation_circuit.barrier() bob_gates(teleportation_circuit, 2, crz, crx) teleportation_circuit.draw(output='mpl') from qiskit.quantum_info import random_statevector psi = random_statevector(2).data print (psi) plot_bloch_multivector(psi) from IPython.display import display, Markdown, Latex display(Latex('$\psi$')) init_gate = Initialize(psi) #Set up qr = QuantumRegister(3) crz = ClassicalRegister(1) crx = ClassicalRegister(1) qc = QuantumCircuit(qr, crz, crx) psi = random_statevector(2).data init_gate = Initialize(psi) init_gate.label = "init" # step 0 qc.append(init_gate, [0] ) qc.barrier() # step 1 create_bell_pair(qc, 1, 2) qc.barrier() #step 2 alice_gates(qc, 0, 1) #step 3 measure_and_send(qc, 0, 1) # step 4 #qc.barrier() bob_gates(qc, 2, crz, crx) qc.draw(output='mpl')
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test schedule block subroutine reference mechanism.""" import numpy as np from qiskit import circuit, pulse from qiskit.pulse import builder from qiskit.pulse.transforms import inline_subroutines from qiskit.test import QiskitTestCase class TestReference(QiskitTestCase): """Test for basic behavior of reference mechanism.""" def test_append_schedule(self): """Test appending schedule without calling. Appended schedules are not subroutines. These are directly exposed to the outer block. """ with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0)) with pulse.build() as sched_y1: builder.append_schedule(sched_x1) with pulse.build() as sched_z1: builder.append_schedule(sched_y1) self.assertEqual(len(sched_z1.references), 0) def test_append_schedule_parameter_scope(self): """Test appending schedule without calling. Parameter in the appended schedule has the scope of outer schedule. """ param = circuit.Parameter("name") with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0)) with pulse.build() as sched_y1: builder.append_schedule(sched_x1) with pulse.build() as sched_z1: builder.append_schedule(sched_y1) sched_param = next(iter(sched_z1.scoped_parameters())) self.assertEqual(sched_param.name, "root::name") # object equality self.assertEqual( sched_z1.search_parameters("root::name")[0], param, ) def test_refer_schedule(self): """Test refer to schedule by name. Outer block is only aware of its inner reference. Nested reference is not directly exposed to the most outer block. """ with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0)) with pulse.build() as sched_y1: builder.reference("x1", "d0") with pulse.build() as sched_z1: builder.reference("y1", "d0") sched_y1.assign_references({("x1", "d0"): sched_x1}) sched_z1.assign_references({("y1", "d0"): sched_y1}) self.assertEqual(len(sched_z1.references), 1) self.assertEqual(sched_z1.references[("y1", "d0")], sched_y1) self.assertEqual(len(sched_y1.references), 1) self.assertEqual(sched_y1.references[("x1", "d0")], sched_x1) def test_refer_schedule_parameter_scope(self): """Test refer to schedule by name. Parameter in the called schedule has the scope of called schedule. """ param = circuit.Parameter("name") with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0)) with pulse.build() as sched_y1: builder.reference("x1", "d0") with pulse.build() as sched_z1: builder.reference("y1", "d0") sched_y1.assign_references({("x1", "d0"): sched_x1}) sched_z1.assign_references({("y1", "d0"): sched_y1}) sched_param = next(iter(sched_z1.scoped_parameters())) self.assertEqual(sched_param.name, "root::y1,d0::x1,d0::name") # object equality self.assertEqual( sched_z1.search_parameters("root::y1,d0::x1,d0::name")[0], param, ) # regex self.assertEqual( sched_z1.search_parameters(r"\S::x1,d0::name")[0], param, ) def test_call_schedule(self): """Test call schedule. Outer block is only aware of its inner reference. Nested reference is not directly exposed to the most outer block. """ with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0)) with pulse.build() as sched_y1: builder.call(sched_x1, name="x1") with pulse.build() as sched_z1: builder.call(sched_y1, name="y1") self.assertEqual(len(sched_z1.references), 1) self.assertEqual(sched_z1.references[("y1",)], sched_y1) self.assertEqual(len(sched_y1.references), 1) self.assertEqual(sched_y1.references[("x1",)], sched_x1) def test_call_schedule_parameter_scope(self): """Test call schedule. Parameter in the called schedule has the scope of called schedule. """ param = circuit.Parameter("name") with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0)) with pulse.build() as sched_y1: builder.call(sched_x1, name="x1") with pulse.build() as sched_z1: builder.call(sched_y1, name="y1") sched_param = next(iter(sched_z1.scoped_parameters())) self.assertEqual(sched_param.name, "root::y1::x1::name") # object equality self.assertEqual( sched_z1.search_parameters("root::y1::x1::name")[0], param, ) # regex self.assertEqual( sched_z1.search_parameters(r"\S::x1::name")[0], param, ) def test_append_and_call_schedule(self): """Test call and append schedule. Reference is copied to the outer schedule by appending. Original reference remains unchanged. """ with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0)) with pulse.build() as sched_y1: builder.call(sched_x1, name="x1") with pulse.build() as sched_z1: builder.append_schedule(sched_y1) self.assertEqual(len(sched_z1.references), 1) self.assertEqual(sched_z1.references[("x1",)], sched_x1) # blocks[0] is sched_y1 and its reference is now point to outer block reference self.assertIs(sched_z1.blocks[0].references, sched_z1.references) # however the original program is protected to prevent unexpected mutation self.assertIsNot(sched_y1.references, sched_z1.references) # appended schedule is preserved self.assertEqual(len(sched_y1.references), 1) self.assertEqual(sched_y1.references[("x1",)], sched_x1) def test_calling_similar_schedule(self): """Test calling schedules with the same representation. sched_x1 and sched_y1 are the different subroutines, but same representation. Two references shoud be created. """ param1 = circuit.Parameter("param") param2 = circuit.Parameter("param") with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, param1, name="p"), pulse.DriveChannel(0)) with pulse.build() as sched_y1: pulse.play(pulse.Constant(100, param2, name="p"), pulse.DriveChannel(0)) with pulse.build() as sched_z1: pulse.call(sched_x1) pulse.call(sched_y1) self.assertEqual(len(sched_z1.references), 2) def test_calling_same_schedule(self): """Test calling same schedule twice. Because it calls the same schedule, no duplication should occur in reference table. """ param = circuit.Parameter("param") with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0)) with pulse.build() as sched_z1: pulse.call(sched_x1, name="same_sched") pulse.call(sched_x1, name="same_sched") self.assertEqual(len(sched_z1.references), 1) def test_calling_same_schedule_with_different_assignment(self): """Test calling same schedule twice but with different parameters. Same schedule is called twice but with different assignment. Two references should be created. """ param = circuit.Parameter("param") with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0)) with pulse.build() as sched_z1: pulse.call(sched_x1, param=0.1) pulse.call(sched_x1, param=0.2) self.assertEqual(len(sched_z1.references), 2) def test_alignment_context(self): """Test nested alignment context. Inline alignment is identical to append_schedule operation. Thus scope is not newly generated. """ with pulse.build(name="x1") as sched_x1: with pulse.align_right(): with pulse.align_left(): pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0)) self.assertEqual(len(sched_x1.references), 0) def test_appending_child_block(self): """Test for edge case. User can append blocks which is an element of another schedule block. But this is not standard use case. In this case, references may contain subroutines which don't exist in the context. This is because all references within the program are centrally managed in the most outer block. """ with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0)) with pulse.build() as sched_y1: pulse.play(pulse.Constant(100, 0.2, name="y1"), pulse.DriveChannel(0)) with pulse.build() as sched_x2: builder.call(sched_x1, name="x1") self.assertEqual(list(sched_x2.references.keys()), [("x1",)]) with pulse.build() as sched_y2: builder.call(sched_y1, name="y1") self.assertEqual(list(sched_y2.references.keys()), [("y1",)]) with pulse.build() as sched_z1: builder.append_schedule(sched_x2) builder.append_schedule(sched_y2) self.assertEqual(list(sched_z1.references.keys()), [("x1",), ("y1",)]) # child block references point to its parent, i.e. sched_z1 self.assertIs(sched_z1.blocks[0].references, sched_z1._reference_manager) self.assertIs(sched_z1.blocks[1].references, sched_z1._reference_manager) with pulse.build() as sched_z2: # Append child block # The reference of this block is sched_z1.reference thus it contains both x1 and y1. # However, y1 doesn't exist in the context, so only x1 should be added. # Usually, user will append sched_x2 directly here, rather than sched_z1.blocks[0] # This is why this situation is an edge case. builder.append_schedule(sched_z1.blocks[0]) self.assertEqual(len(sched_z2.references), 1) self.assertEqual(sched_z2.references[("x1",)], sched_x1) def test_replacement(self): """Test nested alignment context. Replacing schedule block with schedule block. Removed block contains own reference, that should be removed with replacement. New block also contains reference, that should be passed to the current reference. """ with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0)) with pulse.build() as sched_y1: pulse.play(pulse.Constant(100, 0.2, name="y1"), pulse.DriveChannel(0)) with pulse.build() as sched_x2: builder.call(sched_x1, name="x1") with pulse.build() as sched_y2: builder.call(sched_y1, name="y1") with pulse.build() as sched_z1: builder.append_schedule(sched_x2) builder.append_schedule(sched_y2) self.assertEqual(len(sched_z1.references), 2) self.assertEqual(sched_z1.references[("x1",)], sched_x1) self.assertEqual(sched_z1.references[("y1",)], sched_y1) # Define schedule to replace with pulse.build() as sched_r1: pulse.play(pulse.Constant(100, 0.1, name="r1"), pulse.DriveChannel(0)) with pulse.build() as sched_r2: pulse.call(sched_r1, name="r1") sched_z2 = sched_z1.replace(sched_x2, sched_r2) self.assertEqual(len(sched_z2.references), 2) self.assertEqual(sched_z2.references[("r1",)], sched_r1) self.assertEqual(sched_z2.references[("y1",)], sched_y1) def test_special_parameter_name(self): """Testcase to guarantee usage of some special symbols in parameter name. These symbols might be often used in user code. No conflict should occur with the default scope delimiter. """ param = circuit.Parameter("my.parameter_object") with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0)) with pulse.build() as sched_y1: pulse.reference("sub", "q0") sched_y1.assign_references({("sub", "q0"): sched_x1}) ret_param = sched_y1.search_parameters(r"\Ssub,q0::my.parameter_object")[0] self.assertEqual(param, ret_param) def test_parameter_in_multiple_scope(self): """Testcase for scope-aware parameter getter. When a single parameter object is used in multiple scopes, the scoped_parameters method must return parameter objects associated to each scope, while parameters property returns a single parameter object. """ param = circuit.Parameter("name") with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, param), pulse.DriveChannel(0)) with pulse.build() as sched_y1: pulse.play(pulse.Constant(100, param), pulse.DriveChannel(1)) with pulse.build() as sched_z1: pulse.call(sched_x1, name="x1") pulse.call(sched_y1, name="y1") self.assertEqual(len(sched_z1.parameters), 1) self.assertEqual(len(sched_z1.scoped_parameters()), 2) self.assertEqual(sched_z1.search_parameters("root::x1::name")[0], param) self.assertEqual(sched_z1.search_parameters("root::y1::name")[0], param) def test_parallel_alignment_equality(self): """Testcase for potential edge case. In parallel alignment context, reference instruction is broadcasted to all channels. When new channel is added after reference, this should be connected with reference node. """ with pulse.build() as subroutine: pulse.reference("unassigned") with pulse.build() as sched1: with pulse.align_left(): pulse.delay(10, pulse.DriveChannel(0)) pulse.call(subroutine) # This should be broadcasted to d1 as well pulse.delay(10, pulse.DriveChannel(1)) with pulse.build() as sched2: with pulse.align_left(): pulse.delay(10, pulse.DriveChannel(0)) pulse.delay(10, pulse.DriveChannel(1)) pulse.call(subroutine) self.assertNotEqual(sched1, sched2) def test_subroutine_conflict(self): """Test for edge case of appending two schedule blocks having the references with conflicting reference key. This operation should fail because one of references will be gone after assignment. """ with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, 0.1), pulse.DriveChannel(0)) with pulse.build() as sched_x2: pulse.call(sched_x1, name="conflict_name") self.assertEqual(sched_x2.references[("conflict_name",)], sched_x1) with pulse.build() as sched_y1: pulse.play(pulse.Constant(100, 0.2), pulse.DriveChannel(0)) with pulse.build() as sched_y2: pulse.call(sched_y1, name="conflict_name") self.assertEqual(sched_y2.references[("conflict_name",)], sched_y1) with self.assertRaises(pulse.exceptions.PulseError): with pulse.build(): builder.append_schedule(sched_x2) builder.append_schedule(sched_y2) def test_assign_existing_reference(self): """Test for explicitly assign existing reference. This operation should fail because overriding reference is not allowed. """ with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, 0.1), pulse.DriveChannel(0)) with pulse.build() as sched_y1: pulse.play(pulse.Constant(100, 0.2), pulse.DriveChannel(0)) with pulse.build() as sched_z1: pulse.call(sched_x1, name="conflict_name") with self.assertRaises(pulse.exceptions.PulseError): sched_z1.assign_references({("conflict_name",): sched_y1}) class TestSubroutineWithCXGate(QiskitTestCase): """Test called program scope with practical example of building fully parametrized CX gate.""" def setUp(self): super().setUp() # parameters of X pulse self.xp_dur = circuit.Parameter("dur") self.xp_amp = circuit.Parameter("amp") self.xp_sigma = circuit.Parameter("sigma") self.xp_beta = circuit.Parameter("beta") # amplitude of SX pulse self.sxp_amp = circuit.Parameter("amp") # parameters of CR pulse self.cr_dur = circuit.Parameter("dur") self.cr_amp = circuit.Parameter("amp") self.cr_sigma = circuit.Parameter("sigma") self.cr_risefall = circuit.Parameter("risefall") # channels self.control_ch = circuit.Parameter("ctrl") self.target_ch = circuit.Parameter("tgt") self.cr_ch = circuit.Parameter("cr") # echo pulse on control qubit with pulse.build(name="xp") as xp_sched_q0: pulse.play( pulse.Drag( duration=self.xp_dur, amp=self.xp_amp, sigma=self.xp_sigma, beta=self.xp_beta, ), channel=pulse.DriveChannel(self.control_ch), ) self.xp_sched = xp_sched_q0 # local rotation on target qubit with pulse.build(name="sx") as sx_sched_q1: pulse.play( pulse.Drag( duration=self.xp_dur, amp=self.sxp_amp, sigma=self.xp_sigma, beta=self.xp_beta, ), channel=pulse.DriveChannel(self.target_ch), ) self.sx_sched = sx_sched_q1 # cross resonance with pulse.build(name="cr") as cr_sched: pulse.play( pulse.GaussianSquare( duration=self.cr_dur, amp=self.cr_amp, sigma=self.cr_sigma, risefall_sigma_ratio=self.cr_risefall, ), channel=pulse.ControlChannel(self.cr_ch), ) self.cr_sched = cr_sched def test_lazy_ecr(self): """Test lazy subroutines through ECR schedule construction.""" with pulse.build(name="lazy_ecr") as sched: with pulse.align_sequential(): pulse.reference("cr", "q0", "q1") pulse.reference("xp", "q0") with pulse.phase_offset(np.pi, pulse.ControlChannel(self.cr_ch)): pulse.reference("cr", "q0", "q1") pulse.reference("xp", "q0") # Schedule has references self.assertTrue(sched.is_referenced()) # Schedule is not schedulable because of unassigned references self.assertFalse(sched.is_schedulable()) # Two references cr and xp are called self.assertEqual(len(sched.references), 2) # Parameters in the current scope are Parameter("cr") which is used in phase_offset # References are not assigned yet. params = {p.name for p in sched.parameters} self.assertSetEqual(params, {"cr"}) # Parameter names are scoepd scoped_params = {p.name for p in sched.scoped_parameters()} self.assertSetEqual(scoped_params, {"root::cr"}) # Assign CR and XP schedule to the empty reference sched.assign_references({("cr", "q0", "q1"): self.cr_sched}) sched.assign_references({("xp", "q0"): self.xp_sched}) # Check updated references assigned_refs = sched.references self.assertEqual(assigned_refs[("cr", "q0", "q1")], self.cr_sched) self.assertEqual(assigned_refs[("xp", "q0")], self.xp_sched) # Parameter added from subroutines scoped_params = {p.name for p in sched.scoped_parameters()} ref_params = { # This is the cr parameter that belongs to phase_offset instruction in the root scope "root::cr", # This is the same cr parameter that belongs to the play instruction in a child scope "root::cr,q0,q1::cr", "root::cr,q0,q1::amp", "root::cr,q0,q1::dur", "root::cr,q0,q1::risefall", "root::cr,q0,q1::sigma", "root::xp,q0::ctrl", "root::xp,q0::amp", "root::xp,q0::beta", "root::xp,q0::dur", "root::xp,q0::sigma", } self.assertSetEqual(scoped_params, ref_params) # Get parameter without scope, cr amp and xp amp are hit. params = sched.get_parameters(parameter_name="amp") self.assertEqual(len(params), 2) # Get parameter with scope, only xp amp params = sched.search_parameters(parameter_regex="root::xp,q0::amp") self.assertEqual(len(params), 1) def test_cnot(self): """Integration test with CNOT schedule construction.""" # echeod cross resonance with pulse.build(name="ecr", default_alignment="sequential") as ecr_sched: pulse.call(self.cr_sched, name="cr") pulse.call(self.xp_sched, name="xp") with pulse.phase_offset(np.pi, pulse.ControlChannel(self.cr_ch)): pulse.call(self.cr_sched, name="cr") pulse.call(self.xp_sched, name="xp") # cnot gate, locally equivalent to ecr with pulse.build(name="cx", default_alignment="sequential") as cx_sched: pulse.shift_phase(np.pi / 2, pulse.DriveChannel(self.control_ch)) pulse.call(self.sx_sched, name="sx") pulse.call(ecr_sched, name="ecr") # get parameter with scope, full scope is not needed xp_amp = cx_sched.search_parameters(r"\S:xp::amp")[0] self.assertEqual(self.xp_amp, xp_amp) # get parameter with scope, of course full scope can be specified xp_amp_full_scoped = cx_sched.search_parameters("root::ecr::xp::amp")[0] self.assertEqual(xp_amp_full_scoped, xp_amp) # assign parameters assigned_cx = cx_sched.assign_parameters( value_dict={ self.cr_ch: 0, self.control_ch: 0, self.target_ch: 1, self.sxp_amp: 0.1, self.xp_amp: 0.2, self.xp_dur: 160, self.xp_sigma: 40, self.xp_beta: 3.0, self.cr_amp: 0.5, self.cr_dur: 800, self.cr_sigma: 64, self.cr_risefall: 2, }, inplace=True, ) flatten_cx = inline_subroutines(assigned_cx) with pulse.build(default_alignment="sequential") as ref_cx: # sz pulse.shift_phase(np.pi / 2, pulse.DriveChannel(0)) with pulse.align_left(): # sx pulse.play( pulse.Drag( duration=160, amp=0.1, sigma=40, beta=3.0, ), channel=pulse.DriveChannel(1), ) with pulse.align_sequential(): # cr with pulse.align_left(): pulse.play( pulse.GaussianSquare( duration=800, amp=0.5, sigma=64, risefall_sigma_ratio=2, ), channel=pulse.ControlChannel(0), ) # xp with pulse.align_left(): pulse.play( pulse.Drag( duration=160, amp=0.2, sigma=40, beta=3.0, ), channel=pulse.DriveChannel(0), ) with pulse.phase_offset(np.pi, pulse.ControlChannel(0)): # cr with pulse.align_left(): pulse.play( pulse.GaussianSquare( duration=800, amp=0.5, sigma=64, risefall_sigma_ratio=2, ), channel=pulse.ControlChannel(0), ) # xp with pulse.align_left(): pulse.play( pulse.Drag( duration=160, amp=0.2, sigma=40, beta=3.0, ), channel=pulse.DriveChannel(0), ) self.assertEqual(flatten_cx, ref_cx)
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
import sys, os sys.path.append(os.path.dirname(os.path.realpath(__file__)) + '/../../') from composer.qs_circuit import QSCircuit from qiskit import execute, BasicAer from math import log2 SIZE = 2 ** 3 for i in range(0, SIZE): a = format(2 ** i, '0' + str(SIZE) + 'b') SIZE_REG = len(a) LOG_SIZE_REG = int(log2(SIZE_REG)) a_indexes = list(range(0, SIZE_REG)) output_indexes = list(range(SIZE_REG, SIZE_REG + LOG_SIZE_REG)) aux_index = SIZE_REG + LOG_SIZE_REG CIRCUIT_SIZE = SIZE_REG + LOG_SIZE_REG + 1 qc = QSCircuit(CIRCUIT_SIZE) qc.set_reg(a[::-1], a_indexes) qc.encoder(a_indexes, output_indexes, aux_index) qc.measure(output_indexes, range(len(output_indexes))) # print(qc) backend = BasicAer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1) counts = job.result().get_counts(qc) print(i, '-', list(counts.keys())[0][-LOG_SIZE_REG:])
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests ClassicalFunction as a gate.""" import unittest from qiskit.test import QiskitTestCase from qiskit import QuantumCircuit from qiskit.circuit.library.standard_gates import XGate from qiskit.utils.optionals import HAS_TWEEDLEDUM if HAS_TWEEDLEDUM: from . import examples from qiskit.circuit.classicalfunction import classical_function as compile_classical_function @unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.") class TestOracleDecomposition(QiskitTestCase): """Tests ClassicalFunction.decomposition.""" def test_grover_oracle(self): """grover_oracle.decomposition""" oracle = compile_classical_function(examples.grover_oracle) quantum_circuit = QuantumCircuit(5) quantum_circuit.append(oracle, [2, 1, 0, 3, 4]) expected = QuantumCircuit(5) expected.append(XGate().control(4, ctrl_state="1010"), [2, 1, 0, 3, 4]) self.assertEqual(quantum_circuit.decompose(), expected)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit.primitives import Sampler from qiskit_optimization.algorithms import GroverOptimizer, MinimumEigenOptimizer from qiskit_optimization.translators import from_docplex_mp from docplex.mp.model import Model model = Model() x0 = model.binary_var(name="x0") x1 = model.binary_var(name="x1") x2 = model.binary_var(name="x2") model.minimize(-x0 + 2 * x1 - 3 * x2 - 2 * x0 * x2 - 1 * x1 * x2) qp = from_docplex_mp(model) print(qp.prettyprint()) grover_optimizer = GroverOptimizer(6, num_iterations=10, sampler=Sampler()) results = grover_optimizer.solve(qp) print(results.prettyprint()) exact_solver = MinimumEigenOptimizer(NumPyMinimumEigensolver()) exact_result = exact_solver.solve(qp) print(exact_result.prettyprint()) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Pahamanx/QETCI-Hackathon-2022
Pahamanx
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 from qiskit.circuit.library import MCXGate import qiskit.tools.jupyter %qiskit_job_watcher # Loading your IBM Quantum account(s) provider = IBMQ.load_account() backend = provider.get_backend('simulator_statevector') #階乘函式 def factorial(num): if num == 0: return 1 else: a = 1 for i in range(1,num+1): a = a*i return a #定義complete graph大小 graphSize = 4 edgeNumbers = (graphSize)*(graphSize-1)//2 answerNumber = factorial(graphSize-1)//2 groverTimes = int(( 3.14/4*(2**edgeNumbers/answerNumber)**(1/2) )//1) print(answerNumber, edgeNumbers) #choosing state def choose(a): oracle = QuantumCircuit(edgeNumbers, name = 'choose state') zGate = MCXGate(edgeNumbers-1) oracle.x(a) oracle.h([edgeNumbers-1]) oracle.append(zGate, [i for i in range(edgeNumbers)]) oracle.h([edgeNumbers-1]) oracle.x(a) oracle.draw(output='mpl') return oracle #define Hamiltonian Cycles hamiltonianCycles = [[1,4], [2,3], [0,5]] #oracle oracle = QuantumCircuit(edgeNumbers, name = 'oracle') for i in range(len(hamiltonianCycles)): oracle.append(choose(hamiltonianCycles[i]), [j for j in range(edgeNumbers)]) oracle.draw(output='mpl') # diffuser def diffuser(nqubits): qc = QuantumCircuit(nqubits) # Apply transformation |s> -> |00..0> (H-gates) for qubit in range(nqubits): qc.h(qubit) # Apply transformation |00..0> -> |11..1> (X-gates) for qubit in range(nqubits): qc.x(qubit) # Do multi-controlled-Z gate qc.h(nqubits-1) qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli qc.h(nqubits-1) # Apply transformation |11..1> -> |00..0> for qubit in range(nqubits): qc.x(qubit) # Apply transformation |00..0> -> |s> for qubit in range(nqubits): qc.h(qubit) # We will return the diffuser as a gate U_s = qc.to_gate() U_s.name = "U$_s$" return U_s #quantum circuit qc = QuantumCircuit(edgeNumbers) for i in range(edgeNumbers): qc.h(i) for j in range(groverTimes): qc.append(oracle, [i for i in range(edgeNumbers)]) qc.append(diffuser(edgeNumbers), [i for i in range(edgeNumbers)]) qc.measure_all() qc.draw(output='mpl') job = backend.run(transpile(qc, backend=backend), shots=90) print(job.job_id())
https://github.com/theflyingrahul/qiskitsummerschool2020
theflyingrahul
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/qBraid/qBraid
qBraid
# Copyright (C) 2024 qBraid # # This file is part of the qBraid-SDK # # The qBraid-SDK is free software released under the GNU General Public License v3 # or later. You can redistribute and/or modify it under the terms of the GPL v3. # See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>. # # THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3. """ Module defining QiskitCircuit Class """ from collections import OrderedDict from typing import TYPE_CHECKING import qiskit from qiskit.circuit import Qubit from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit.quantum_info import Operator from qbraid.programs.exceptions import ProgramTypeError from ._model import GateModelProgram if TYPE_CHECKING: import numpy as np from qbraid.runtime.qiskit import QiskitBackend class QiskitCircuit(GateModelProgram): """Wrapper class for ``qiskit.QuantumCircuit`` objects""" def __init__(self, program: "qiskit.QuantumCircuit"): super().__init__(program) if not isinstance(program, qiskit.QuantumCircuit): raise ProgramTypeError( message=f"Expected 'qiskit.QuantumCircuit' object, got '{type(program)}'." ) @property def qubits(self) -> list[Qubit]: """Return the qubits acted upon by the operations in this circuit""" return self.program.qubits @property def num_qubits(self) -> int: """Return the number of qubits in the circuit.""" return self.program.num_qubits @property def num_clbits(self) -> int: """Return the number of classical bits in the circuit.""" return self.program.num_clbits @property def depth(self) -> int: """Return the circuit depth (i.e., length of critical path).""" return self.program.depth() def _unitary(self) -> "np.ndarray": """Calculate unitary of circuit. Removes measurement gates to perform calculation if necessary.""" circuit = self.program.copy() circuit.remove_final_measurements() return Operator(circuit).data def remove_idle_qubits(self) -> None: """Checks whether the circuit uses contiguous qubits/indices, and if not, reduces dimension accordingly.""" circuit = self.program.copy() dag = circuit_to_dag(circuit) idle_wires = list(dag.idle_wires()) for w in idle_wires: dag._remove_idle_wire(w) dag.qubits.remove(w) dag.qregs = OrderedDict() self._program = dag_to_circuit(dag) def reverse_qubit_order(self) -> None: """Reverse the order of the qubits in the circuit.""" circuit = self.program.copy() reversed_circuit = circuit.reverse_bits() self._program = reversed_circuit def transform(self, device) -> None: """Transform program to according to device target profile.""" device_type = device.profile.get("device_type") if device_type == "LOCAL_SIMULATOR": self.remove_idle_qubits() self._program = qiskit.transpile(self.program, backend=device._backend)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# You can set a color for all the bars. from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_paulivec qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = Statevector(qc) plot_state_paulivec(state, color='midnightblue', title="New PauliVec plot")
https://github.com/msramalho/Teach-Me-Quantum
msramalho
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute # Choose the drawer you like best: from qiskit.tools.visualization import matplotlib_circuit_drawer as draw #from qiskit.tools.visualization import circuit_drawer as draw from qiskit import IBMQ IBMQ.load_accounts() # make sure you have setup your token locally to use this %matplotlib inline import matplotlib.pyplot as plt def show_results(D): # D is a dictionary with classical bits as keys and count as value # example: D = {'000': 497, '001': 527} plt.bar(range(len(D)), list(D.values()), align='center') plt.xticks(range(len(D)), list(D.keys())) plt.show() from qiskit import Aer # See a list of available local simulators print("Aer backends: ", Aer.backends()) # see a list of available remote backends (these are freely given by IBM) print("IBMQ Backends: ", IBMQ.backends()) # execute circuit and either display a histogram of the results def execute_locally(qc, draw_circuit=False): # Compile and run the Quantum circuit on a simulator backend backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) result_sim = job_sim.result() result_counts = result_sim.get_counts(qc) # Print the results print("simulation: ", result_sim, result_counts) if draw_circuit: # draw the circuit draw(qc) else: # or show the results show_results(result_counts) from qiskit.backends.ibmq import least_busy import time # Compile and run on a real device backend def execute_remotely(qc, draw_circuit=False): if draw_circuit: # draw the circuit draw(qc) try: # select least busy available device and execute. least_busy_device = least_busy(IBMQ.backends(simulator=False)) print("Running on current least busy device: ", least_busy_device) # running the job job_exp = execute(qc, backend=least_busy_device, shots=1024, max_credits=10) lapse, interval = 0, 10 while job_exp.status().name != 'DONE': print('Status @ {} seconds'.format(interval * lapse)) print(job_exp.status()) time.sleep(interval) lapse += 1 print(job_exp.status()) exp_result = job_exp.result() result_counts = exp_result.get_counts(qc) # Show the results print("experiment: ", exp_result, result_counts) if not draw_circuit: # show the results show_results(result_counts) except: print("All devices are currently unavailable.") def new_circuit(size): # Create a Quantum Register with size qubits qr = QuantumRegister(size) # Create a Classical Register with size bits cr = ClassicalRegister(size) # Create a Quantum Circuit acting on the qr and cr register return qr, cr, QuantumCircuit(qr, cr) qr, cr, circuit = new_circuit(2) # H gate on qubit 0 circuit.h(qr[0]); circuit.cx(qr[0], qr[1]); # measure the qubits circuit.measure(qr, cr); # Try both commands: execute_locally(circuit,draw_circuit=True) # execute_locally(circuit,draw_circuit=False) print(circuit.qasm()) # create the circuit qr, cr, circuit = new_circuit(2) # H gate on qubit 0 circuit.h(qr[0]); # X gate on qubit 1 circuit.x(qr[1]); circuit.cx(qr[0], qr[1]); # measure the qubits circuit.measure(qr, cr); # Try both commands: execute_locally(circuit,draw_circuit=True) # execute_locally(circuit,draw_circuit=False) # create the circuit qr, cr, circuit = new_circuit(2) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]); circuit.h(qr); circuit.measure(qr, cr) execute_locally(circuit,draw_circuit=True) qr, cr, circuit = new_circuit(2) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.h(qr) circuit.measure(qr, cr); execute_remotely(circuit)
https://github.com/epelaaez/QuantumLibrary
epelaaez
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2021 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Tests for qiskit-terra/qiskit/quantum_info/synthesis/xx_decompose/qiskit.py . """ from statistics import mean import unittest import ddt import numpy as np from scipy.stats import unitary_group import qiskit from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.quantum_info.operators import Operator from qiskit.quantum_info.synthesis.xx_decompose.decomposer import ( XXDecomposer, TwoQubitWeylDecomposition, ) from .utilities import canonical_matrix EPSILON = 1e-8 @ddt.ddt class TestXXDecomposer(unittest.TestCase): """Tests for decomposition of two-qubit unitaries over discrete gates from XX family.""" decomposer = XXDecomposer(euler_basis="PSX") def __init__(self, *args, seed=42, **kwargs): super().__init__(*args, **kwargs) self._random_state = np.random.Generator(np.random.PCG64(seed)) def test_random_compilation(self): """Test that compilation gives correct results.""" for _ in range(100): unitary = unitary_group.rvs(4, random_state=self._random_state) unitary /= np.linalg.det(unitary) ** (1 / 4) # decompose into CX, CX/2, and CX/3 circuit = self.decomposer(unitary, approximate=False) decomposed_unitary = Operator(circuit).data self.assertTrue(np.all(unitary - decomposed_unitary < EPSILON)) def test_compilation_determinism(self): """Test that compilation is stable under multiple calls.""" for _ in range(10): unitary = unitary_group.rvs(4, random_state=self._random_state) unitary /= np.linalg.det(unitary) ** (1 / 4) # decompose into CX, CX/2, and CX/3 circuit1 = self.decomposer(unitary, approximate=False) circuit2 = self.decomposer(unitary, approximate=False) self.assertEqual(circuit1, circuit2) @ddt.data(np.pi / 3, np.pi / 5, np.pi / 2) def test_default_embodiment(self, angle): """Test that _default_embodiment actually does yield XX gates.""" embodiment = self.decomposer._default_embodiment(angle) embodiment_matrix = Operator(embodiment).data self.assertTrue(np.all(canonical_matrix(angle, 0, 0) - embodiment_matrix < EPSILON)) def test_check_embodiment(self): """Test that XXDecomposer._check_embodiments correctly diagnoses il/legal embodiments.""" # build the member of the XX family corresponding to a single CX good_angle = np.pi / 2 good_embodiment = qiskit.QuantumCircuit(2) good_embodiment.h(0) good_embodiment.cx(0, 1) good_embodiment.h(1) good_embodiment.rz(np.pi / 2, 0) good_embodiment.rz(np.pi / 2, 1) good_embodiment.h(1) good_embodiment.h(0) good_embodiment.global_phase += np.pi / 4 # mismatch two members of the XX family bad_angle = np.pi / 10 bad_embodiment = qiskit.QuantumCircuit(2) # "self.assertDoesNotRaise" XXDecomposer(embodiments={good_angle: good_embodiment}) self.assertRaises( qiskit.exceptions.QiskitError, XXDecomposer, embodiments={bad_angle: bad_embodiment} ) def test_compilation_improvement(self): """Test that compilation to CX, CX/2, CX/3 improves over CX alone.""" slope, offset = (64 * 90) / 1000000, 909 / 1000000 + 1 / 1000 strength_table = self.decomposer._strength_to_infidelity( basis_fidelity={ strength: 1 - (slope * strength / (np.pi / 2) + offset) for strength in [np.pi / 2, np.pi / 4, np.pi / 6] }, approximate=True, ) limited_strength_table = {np.pi / 2: strength_table[np.pi / 2]} clever_costs = [] naive_costs = [] for _ in range(200): unitary = unitary_group.rvs(4, random_state=self._random_state) unitary /= np.linalg.det(unitary) ** (1 / 4) weyl_decomposition = TwoQubitWeylDecomposition(unitary) target = [getattr(weyl_decomposition, x) for x in ("a", "b", "c")] if target[-1] < -EPSILON: target = [np.pi / 2 - target[0], target[1], -target[2]] # decompose into CX, CX/2, and CX/3 clever_costs.append(self.decomposer._best_decomposition(target, strength_table)["cost"]) naive_costs.append( self.decomposer._best_decomposition(target, limited_strength_table)["cost"] ) # the following are taken from Fig 14 of the XX synthesis paper self.assertAlmostEqual(mean(clever_costs), 1.445e-2, delta=5e-3) self.assertAlmostEqual(mean(naive_costs), 2.058e-2, delta=5e-3) def test_error_on_empty_basis_fidelity(self): """Test synthesizing entangling gate with no entangling basis fails.""" decomposer = XXDecomposer(basis_fidelity={}) qc = QuantumCircuit(2) qc.cx(0, 1) mat = Operator(qc).to_matrix() with self.assertRaisesRegex( qiskit.exceptions.QiskitError, "Attempting to synthesize entangling gate with no controlled gates in basis set.", ): decomposer(mat) def test_no_error_on_empty_basis_fidelity_trivial_target(self): """Test synthesizing non-entangling gate with no entangling basis succeeds.""" decomposer = XXDecomposer(basis_fidelity={}) qc = QuantumCircuit(2) qc.x(0) qc.y(1) mat = Operator(qc).to_matrix() dqc = decomposer(mat) self.assertTrue(np.allclose(mat, Operator(dqc).to_matrix()))
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/Interlin-q/diskit
Interlin-q
import os from qiskit import * import qiskit.tools.visualization as qt from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from numpy import pi import matplotlib.pyplot as plt %matplotlib inline qreg_q = QuantumRegister(2, 'q') creg_c = ClassicalRegister(2, 'c') circuits = [] for i in range(0, 4): circuits.append(QuantumCircuit(qreg_q, creg_c)) circuits[0].reset(qreg_q[0]) circuits[0].reset(qreg_q[1]) circuits[0].cx(qreg_q[0], qreg_q[1]) circuits[0].measure(qreg_q[0], creg_c[0]) circuits[0].measure(qreg_q[1], creg_c[1]) circuits[0].draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') result00 = execute(circuits[0], backend = simulator, shots = 1).result() counts00 = result00.get_counts() print(counts00) qt.plot_histogram(counts00, title="Histogram with the evaluating of |00> state under CNOT transformation") circuits[1].reset(qreg_q[0]) circuits[1].x(qreg_q[1]) circuits[1].cx(qreg_q[0], qreg_q[1]) circuits[1].measure(qreg_q[0], creg_c[0]) circuits[1].measure(qreg_q[1], creg_c[1]) circuits[1].draw(output="mpl") simulator = Aer.get_backend('qasm_simulator') result01 = execute(circuits[1], backend = simulator, shots = 1).result() counts01 = result01.get_counts() print(counts01) qt.plot_histogram(counts01, title="Histogram with the evaluating of |01> state under CNOT transformation") circuits[2].x(qreg_q[0]) circuits[2].reset(qreg_q[1]) circuits[2].cx(qreg_q[0], qreg_q[1]) circuits[2].measure(qreg_q[0], creg_c[0]) circuits[2].measure(qreg_q[1], creg_c[1]) circuits[2].draw(output="mpl") simulator = Aer.get_backend('qasm_simulator') result10 = execute(circuits[2], backend = simulator, shots = 1).result() counts10 = result10.get_counts() print(counts10) qt.plot_histogram(counts10, title="Histogram with the evaluating of |10> state under CNOT transformation") circuits[3].x(qreg_q[0]) circuits[3].x(qreg_q[1]) circuits[3].cx(qreg_q[0], qreg_q[1]) circuits[3].measure(qreg_q[0], creg_c[0]) circuits[3].measure(qreg_q[1], creg_c[1]) circuits[3].draw(output="mpl") simulator = Aer.get_backend('qasm_simulator') result11 = execute(circuits[3], backend = simulator, shots = 1).result() counts11 = result11.get_counts() print(counts11) qt.plot_histogram(counts11, title="Histogram with the evaluating of |11> state under CNOT transformation")
https://github.com/Axect/QuantumAlgorithms
Axect
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute from qiskit.visualization import plot_histogram import numpy as np import matplotlib.pyplot as plt def circuit(alice): e = QuantumRegister(2, name='e') a = QuantumRegister(1, name='a') b = QuantumRegister(1, name='b') c = ClassicalRegister(2, name='c') qc = QuantumCircuit(e, a, b, c, name='circuit') # Initialize Target qubit qc.initialize(alice / np.linalg.norm(alice), e) qc.barrier() # Create Bell pair qc.h(a) qc.cx(a, b) qc.barrier() # Write target qubit to Bell pair qc.cz(e[0], a) qc.cx(e[1], a) qc.barrier() # Decoding qc.cx(a, b) qc.h(a) qc.measure(a, c[1]) qc.measure(b, c[0]) backend = Aer.get_backend('qasm_simulator') return qc, execute(qc, backend).result().get_counts() qc, counts = circuit([1,0,0,1]) qc.draw(output='mpl', style='iqx') plot_histogram(counts)
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import QuantumCircuit,QuantumRegister,transpile import qiskit.test.mock as fake_backends from qiskit.test.mock import FakeProvider provider = FakeProvider() backends =provider.backends() backends backend=provider.get_backend(name ='fake_vigo') backend from qiskit.test.mock import FakeVigo device_backend = FakeVigo() device_backend device_backend.name() config_details = device_backend.configuration() config_details.backend_name config_details.n_qubits config_details.basis_gates for i in range(len(backends)): backend_details = backends[i] config_details = backend_details.configuration() if config_details.n_qubits <=5: print(backends[i],":",config_details.basis_gates) from qiskit.test.mock import FakeLondon device_backend = FakeLondon() config_details = device_backend.configuration() config_details.backend_name config_details.n_qubits config_details.basis_gates
https://github.com/qiskit-community/prototype-qrao
qiskit-community
# This code is part of Qiskit. # # (C) Copyright IBM 2019, 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Quantum Random Access Encoding module. Contains code dealing with QRACs (quantum random access codes) and preparation of such states. .. autosummary:: :toctree: ../stubs/ z_to_31p_qrac_basis_circuit z_to_21p_qrac_basis_circuit qrac_state_prep_1q qrac_state_prep_multiqubit QuantumRandomAccessEncoding """ from typing import Tuple, List, Dict, Optional, Union from collections import defaultdict from functools import reduce from itertools import chain import numpy as np import rustworkx as rx from qiskit import QuantumCircuit from qiskit.opflow import ( I, X, Y, Z, PauliSumOp, PrimitiveOp, CircuitOp, Zero, One, StateFn, CircuitStateFn, ) from qiskit.quantum_info import SparsePauliOp from qiskit_optimization.problems.quadratic_program import QuadraticProgram def _ceildiv(n: int, d: int) -> int: """Perform ceiling division in integer arithmetic >>> _ceildiv(0, 3) 0 >>> _ceildiv(1, 3) 1 >>> _ceildiv(3, 3) 1 >>> _ceildiv(4, 3) 2 """ return (n - 1) // d + 1 def z_to_31p_qrac_basis_circuit(basis: List[int]) -> QuantumCircuit: """Return the basis rotation corresponding to the (3,1,p)-QRAC Args: basis: 0, 1, 2, or 3 for each qubit Returns: The ``QuantumCircuit`` implementing the rotation. """ circ = QuantumCircuit(len(basis)) BETA = np.arccos(1 / np.sqrt(3)) for i, base in enumerate(reversed(basis)): if base == 0: circ.r(-BETA, -np.pi / 4, i) elif base == 1: circ.r(np.pi - BETA, np.pi / 4, i) elif base == 2: circ.r(np.pi + BETA, np.pi / 4, i) elif base == 3: circ.r(BETA, -np.pi / 4, i) else: raise ValueError(f"Unknown base: {base}") return circ def z_to_21p_qrac_basis_circuit(basis: List[int]) -> QuantumCircuit: """Return the basis rotation corresponding to the (2,1,p)-QRAC Args: basis: 0 or 1 for each qubit Returns: The ``QuantumCircuit`` implementing the rotation. """ circ = QuantumCircuit(len(basis)) for i, base in enumerate(reversed(basis)): if base == 0: circ.r(-1 * np.pi / 4, -np.pi / 2, i) elif base == 1: circ.r(-3 * np.pi / 4, -np.pi / 2, i) else: raise ValueError(f"Unknown base: {base}") return circ def qrac_state_prep_1q(*m: int) -> CircuitStateFn: """Prepare a single qubit QRAC state This function accepts 1, 2, or 3 arguments, in which case it generates a 1-QRAC, 2-QRAC, or 3-QRAC, respectively. Args: m: The data to be encoded. Each argument must be 0 or 1. Returns: The circuit state function. """ if len(m) not in (1, 2, 3): raise TypeError( f"qrac_state_prep_1q requires 1, 2, or 3 arguments, not {len(m)}." ) if not all(mi in (0, 1) for mi in m): raise ValueError("Each argument to qrac_state_prep_1q must be 0 or 1.") if len(m) == 3: # Prepare (3,1,p)-qrac # In the following lines, the input bits are XOR'd to match the # conventions used in the paper. # To understand why this transformation happens, # observe that the two states that define each magic basis # correspond to the same bitstrings but with a global bitflip. # Thus the three bits of information we use to construct these states are: # c0,c1 : two bits to pick one of four magic bases # c2: one bit to indicate which magic basis projector we are interested in. c0 = m[0] ^ m[1] ^ m[2] c1 = m[1] ^ m[2] c2 = m[0] ^ m[2] base = [2 * c1 + c2] cob = z_to_31p_qrac_basis_circuit(base) # This is a convention chosen to be consistent with https://arxiv.org/pdf/2111.03167v2.pdf # See SI:4 second paragraph and observe that π+ = |0X0|, π- = |1X1| sf = One if (c0) else Zero # Apply the z_to_magic_basis circuit to either |0> or |1> logical = CircuitOp(cob) @ sf elif len(m) == 2: # Prepare (2,1,p)-qrac # (00,01) or (10,11) c0 = m[0] # (00,11) or (01,10) c1 = m[0] ^ m[1] base = [c1] cob = z_to_21p_qrac_basis_circuit(base) # This is a convention chosen to be consistent with https://arxiv.org/pdf/2111.03167v2.pdf # See SI:4 second paragraph and observe that π+ = |0X0|, π- = |1X1| sf = One if (c0) else Zero # Apply the z_to_magic_basis circuit to either |0> or |1> logical = CircuitOp(cob) @ sf else: assert len(m) == 1 c0 = m[0] sf = One if (c0) else Zero logical = sf return logical.to_circuit_op() def qrac_state_prep_multiqubit( dvars: Union[Dict[int, int], List[int]], q2vars: List[List[int]], max_vars_per_qubit: int, ) -> CircuitStateFn: """ Prepare a multiqubit QRAC state. Args: dvars: state of each decision variable (0 or 1) """ remaining_dvars = set(dvars if isinstance(dvars, dict) else range(len(dvars))) ordered_bits = [] for qi_vars in q2vars: if len(qi_vars) > max_vars_per_qubit: raise ValueError( "Each qubit is expected to be associated with at most " f"`max_vars_per_qubit` ({max_vars_per_qubit}) variables, " f"not {len(qi_vars)} variables." ) if not qi_vars: # This probably actually doesn't cause any issues, but why support # it (and test this edge case) if we don't have to? raise ValueError( "There is a qubit without any decision variables assigned to it." ) qi_bits: List[int] = [] for dv in qi_vars: try: qi_bits.append(dvars[dv]) except (KeyError, IndexError): raise ValueError( f"Decision variable not included in dvars: {dv}" ) from None try: remaining_dvars.remove(dv) except KeyError: raise ValueError( f"Unused decision variable(s) in dvars: {remaining_dvars}" ) from None # Pad with zeros if there are fewer than `max_vars_per_qubit`. # NOTE: This results in everything being encoded as an n-QRAC, # even if there are fewer than n decision variables encoded in the qubit. # In the future, we plan to make the encoding "adaptive" so that the # optimal encoding is used on each qubit, based on the number of # decision variables assigned to that specific qubit. # However, we cannot do this until magic state rounding supports 2-QRACs. while len(qi_bits) < max_vars_per_qubit: qi_bits.append(0) ordered_bits.append(qi_bits) if remaining_dvars: raise ValueError(f"Not all dvars were included in q2vars: {remaining_dvars}") qracs = [qrac_state_prep_1q(*qi_bits) for qi_bits in ordered_bits] logical = reduce(lambda x, y: x ^ y, qracs) return logical def q2vars_from_var2op(var2op: Dict[int, Tuple[int, PrimitiveOp]]) -> List[List[int]]: """Calculate q2vars given var2op""" num_qubits = max(qubit_index for qubit_index, _ in var2op.values()) + 1 q2vars: List[List[int]] = [[] for i in range(num_qubits)] for var, (q, _) in var2op.items(): q2vars[q].append(var) return q2vars class QuantumRandomAccessEncoding: """This class specifies a Quantum Random Access Code that can be used to encode the binary variables of a QUBO (quadratic unconstrained binary optimization problem). Args: max_vars_per_qubit: maximum possible compression ratio. Supported values are 1, 2, or 3. """ # This defines the convention of the Pauli operators (and their ordering) # for each encoding. OPERATORS = ( (Z,), # (1,1,1) QRAC (X, Z), # (2,1,p) QRAC, p ≈ 0.85 (X, Y, Z), # (3,1,p) QRAC, p ≈ 0.79 ) def __init__(self, max_vars_per_qubit: int = 3): if max_vars_per_qubit not in (1, 2, 3): raise ValueError("max_vars_per_qubit must be 1, 2, or 3") self._ops = self.OPERATORS[max_vars_per_qubit - 1] self._qubit_op: Optional[PauliSumOp] = None self._offset: Optional[float] = None self._problem: Optional[QuadraticProgram] = None self._var2op: Dict[int, Tuple[int, PrimitiveOp]] = {} self._q2vars: List[List[int]] = [] self._frozen = False @property def num_qubits(self) -> int: """Number of qubits""" return len(self._q2vars) @property def num_vars(self) -> int: """Number of decision variables""" return len(self._var2op) @property def max_vars_per_qubit(self) -> int: """Maximum number of variables per qubit This is set in the constructor and controls the maximum compression ratio """ return len(self._ops) @property def var2op(self) -> Dict[int, Tuple[int, PrimitiveOp]]: """Maps each decision variable to ``(qubit_index, operator)``""" return self._var2op @property def q2vars(self) -> List[List[int]]: """Each element contains the list of decision variable indice(s) encoded on that qubit""" return self._q2vars @property def compression_ratio(self) -> float: """Compression ratio Number of decision variables divided by number of qubits """ return self.num_vars / self.num_qubits @property def minimum_recovery_probability(self) -> float: """Minimum recovery probability, as set by ``max_vars_per_qubit``""" n = self.max_vars_per_qubit return (1 + 1 / np.sqrt(n)) / 2 @property def qubit_op(self) -> PauliSumOp: """Relaxed Hamiltonian operator""" if self._qubit_op is None: raise AttributeError( "No objective function has been provided from which a " "qubit Hamiltonian can be constructed. Please use the " "encode method if you wish to manually compile " "this field." ) return self._qubit_op @property def offset(self) -> float: """Relaxed Hamiltonian offset""" if self._offset is None: raise AttributeError( "No objective function has been provided from which a " "qubit Hamiltonian can be constructed. Please use the " "encode method if you wish to manually compile " "this field." ) return self._offset @property def problem(self) -> QuadraticProgram: """The ``QuadraticProgram`` used as basis for the encoding""" if self._problem is None: raise AttributeError( "No quadratic program has been associated with this object. " "Please use the encode method if you wish to do so." ) return self._problem def _add_variables(self, variables: List[int]) -> None: self.ensure_thawed() # NOTE: If this is called multiple times, it *always* adds an # additional qubit (see final line), even if aggregating them into a # single call would have resulted in fewer qubits. if self._qubit_op is not None: raise RuntimeError( "_add_variables() cannot be called once terms have been added " "to the operator, as the number of qubits must thereafter " "remain fixed." ) if not variables: return if len(variables) != len(set(variables)): raise ValueError("Added variables must be unique") for v in variables: if v in self._var2op: raise ValueError("Added variables cannot collide with existing ones") # Modify the object now that error checking is complete. n = len(self._ops) old_num_qubits = len(self._q2vars) num_new_qubits = _ceildiv(len(variables), n) # Populate self._var2op and self._q2vars for _ in range(num_new_qubits): self._q2vars.append([]) for i, v in enumerate(variables): qubit, op = divmod(i, n) qubit_index = old_num_qubits + qubit assert v not in self._var2op # was checked above self._var2op[v] = (qubit_index, self._ops[op]) self._q2vars[qubit_index].append(v) def _add_term(self, w: float, *variables: int) -> None: self.ensure_thawed() # Eq. (31) in https://arxiv.org/abs/2111.03167v2 assumes a weight-2 # Pauli operator. To generalize, we replace the `d` in that equation # with `d_prime`, defined as follows: d_prime = np.sqrt(self.max_vars_per_qubit) ** len(variables) op = self.term2op(*variables).mul(w * d_prime) # We perform the following short-circuit *after* calling term2op so at # least we have confirmed that the user provided a valid variables list. if w == 0.0: return if self._qubit_op is None: self._qubit_op = op else: self._qubit_op += op def term2op(self, *variables: int) -> PauliSumOp: """Construct a ``PauliSumOp`` that is a product of encoded decision ``variable``\\(s). The decision variables provided must all be encoded on different qubits. """ ops = [I] * self.num_qubits done = set() for x in variables: pos, op = self._var2op[x] if pos in done: raise RuntimeError(f"Collision of variables: {variables}") ops[pos] = op done.add(pos) pauli_op = reduce(lambda x, y: x ^ y, ops) # Convert from PauliOp to PauliSumOp return PauliSumOp(SparsePauliOp(pauli_op.primitive, coeffs=[pauli_op.coeff])) @staticmethod def _generate_ising_terms( problem: QuadraticProgram, ) -> Tuple[float, np.ndarray, np.ndarray]: num_vars = problem.get_num_vars() # set a sign corresponding to a maximized or minimized problem: # 1 is for minimized problem, -1 is for maximized problem. sense = problem.objective.sense.value # convert a constant part of the objective function into Hamiltonian. offset = problem.objective.constant * sense # convert linear parts of the objective function into Hamiltonian. linear = np.zeros(num_vars) for idx, coef in problem.objective.linear.to_dict().items(): assert isinstance(idx, int) # hint for mypy weight = coef * sense / 2 linear[idx] -= weight offset += weight # convert quadratic parts of the objective function into Hamiltonian. quad = np.zeros((num_vars, num_vars)) for (i, j), coef in problem.objective.quadratic.to_dict().items(): assert isinstance(i, int) # hint for mypy assert isinstance(j, int) # hint for mypy weight = coef * sense / 4 if i == j: linear[i] -= 2 * weight offset += 2 * weight else: quad[i, j] += weight linear[i] -= weight linear[j] -= weight offset += weight return offset, linear, quad @staticmethod def _find_variable_partition(quad: np.ndarray) -> Dict[int, List[int]]: num_nodes = quad.shape[0] assert quad.shape == (num_nodes, num_nodes) graph = rx.PyGraph() # type: ignore graph.add_nodes_from(range(num_nodes)) graph.add_edges_from_no_data(list(zip(*np.where(quad != 0)))) # type: ignore node2color = rx.graph_greedy_color(graph) # type: ignore color2node: Dict[int, List[int]] = defaultdict(list) for node, color in sorted(node2color.items()): color2node[color].append(node) return color2node def encode(self, problem: QuadraticProgram) -> None: """Encode the (n,1,p) QRAC relaxed Hamiltonian of this problem. We associate to each binary decision variable one bit of a (n,1,p) Quantum Random Access Code. This is done in such a way that the given problem's objective function commutes with the encoding. After being called, the object will have the following attributes: qubit_op: The qubit operator encoding the input QuadraticProgram. offset: The constant value in the encoded Hamiltonian. problem: The ``problem`` used for encoding. Inputs: problem: A QuadraticProgram object encoding a QUBO optimization problem Raises: RuntimeError: if the ``problem`` isn't a QUBO or if the current object has been used already """ # Ensure fresh object if self.num_qubits > 0: raise RuntimeError( "Must call encode() on an Encoding that has not been used already" ) # if problem has variables that are not binary, raise an error if problem.get_num_vars() > problem.get_num_binary_vars(): raise RuntimeError( "The type of all variables must be binary. " "You can use `QuadraticProgramToQubo` converter " "to convert integer variables to binary variables. " "If the problem contains continuous variables, `qrao` " "cannot handle it." ) # if constraints exist, raise an error if problem.linear_constraints or problem.quadratic_constraints: raise RuntimeError( "There must be no constraint in the problem. " "You can use `QuadraticProgramToQubo` converter to convert " "constraints to penalty terms of the objective function." ) num_vars = problem.get_num_vars() # Generate the decision variable terms in terms of Ising variables (+1 or -1) offset, linear, quad = self._generate_ising_terms(problem) # Find variable partition (a graph coloring is sufficient) variable_partition = self._find_variable_partition(quad) # The other methods of the current class allow for the variables to # have arbitrary integer indices [i.e., they need not correspond to # range(num_vars)], and the tests corresponding to this file ensure # that this works. However, the current method is a high-level one # that takes a QuadraticProgram, which always has its variables # numbered sequentially. Furthermore, other portions of the QRAO code # base [most notably the assignment of variable_ops in solve_relaxed() # and the corresponding result objects] assume that the variables are # numbered from 0 to (num_vars - 1). So we enforce that assumption # here, both as a way of documenting it and to make sure # _find_variable_partition() returns a sensible result (in case the # user overrides it). assert sorted(chain.from_iterable(variable_partition.values())) == list( range(num_vars) ) # generate a Hamiltonian for _, v in sorted(variable_partition.items()): self._add_variables(sorted(v)) for i in range(num_vars): w = linear[i] if w != 0: self._add_term(w, i) for i in range(num_vars): for j in range(num_vars): w = quad[i, j] if w != 0: self._add_term(w, i, j) self._offset = offset self._problem = problem # This is technically optional and can wait until the optimizer is # constructed, but there's really no reason not to freeze # immediately. self.freeze() def freeze(self): """Freeze the object to prevent further modification. Once an instance of this class is frozen, ``_add_variables`` and ``_add_term`` can no longer be called. This operation is idempotent. There is no way to undo it, as it exists to allow another object to rely on this one not changing its state going forward without having to make a copy as a distinct object. """ if self._frozen is False: self._qubit_op = self._qubit_op.reduce() self._frozen = True @property def frozen(self) -> bool: """``True`` if the object can no longer be modified, ``False`` otherwise.""" return self._frozen def ensure_thawed(self) -> None: """Raise a ``RuntimeError`` if the object is frozen and thus cannot be modified.""" if self._frozen: raise RuntimeError("Cannot modify an encoding that has been frozen") def state_prep(self, dvars: Union[Dict[int, int], List[int]]) -> CircuitStateFn: """Prepare a multiqubit QRAC state.""" return qrac_state_prep_multiqubit(dvars, self.q2vars, self.max_vars_per_qubit) class EncodingCommutationVerifier: """Class for verifying that the relaxation commutes with the objective function See also the "check encoding problem commutation" how-to notebook. """ def __init__(self, encoding: QuantumRandomAccessEncoding): self._encoding = encoding def __len__(self) -> int: return 2**self._encoding.num_vars def __iter__(self): for i in range(len(self)): yield self[i] def __getitem__(self, i: int) -> Tuple[str, float, float]: if i not in range(len(self)): raise IndexError(f"Index out of range: {i}") encoding = self._encoding str_dvars = ("{0:0" + str(encoding.num_vars) + "b}").format(i) dvars = [int(b) for b in str_dvars] encoded_bitstr = encoding.state_prep(dvars) # Offset accounts for the value of the encoded Hamiltonian's # identity coefficient. This term need not be evaluated directly as # Tr[I•rho] is always 1. offset = encoding.offset # Evaluate Un-encoded Problem # ======================== # `sense` accounts for sign flips depending on whether # we are minimizing or maximizing the objective function problem = encoding.problem sense = problem.objective.sense.value obj_val = problem.objective.evaluate(dvars) * sense # Evaluate Encoded Problem # ======================== encoded_problem = encoding.qubit_op # H encoded_obj_val = ( np.real((~StateFn(encoded_problem) @ encoded_bitstr).eval()) + offset ) return (str_dvars, obj_val, encoded_obj_val)
https://github.com/UST-QuAntiL/nisq-analyzer-content
UST-QuAntiL
from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit qc = QuantumCircuit() q = QuantumRegister(5, 'q') c = ClassicalRegister(5, 'c') qc.add_register(q) qc.add_register(c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) # add identity gates to the circuit to enable replacing the oracle after 2 gates per qubit qc.i(q[0]) qc.i(q[1]) qc.i(q[2]) qc.i(q[3]) # ancilla qubit qc.h(q[4]) qc.z(q[4]) qc.barrier() # searched bit string: s = 00110 (first bit is ancilla and using qiskit's reverse qubit ordering) qc.cx(q[1], q[4]) qc.cx(q[2], q[4]) qc.barrier() qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.i(q[4]) qc.measure([0, 1, 2, 3], [0, 1, 2, 3]) def get_circuit(**kwargs): """Get base circuit of the Bernstein-Vazirani algorithm.""" return qc
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import QuantumCircuit, Aer, assemble import numpy as np from qiskit.visualization import plot_histogram, plot_bloch_multivector from qiskit.visualization import array_to_latex qc = QuantumCircuit(3) # Apply H-gate to each qubit: for qubit in range(3): qc.h(qubit) # See the circuit: qc.draw() # Let's see the result svsim = Aer.get_backend('aer_simulator') qc.save_statevector() qobj = assemble(qc) final_state = svsim.run(qobj).result().get_statevector() # In Jupyter Notebooks we can display this nicely using Latex. # If not using Jupyter Notebooks you may need to remove the # array_to_latex function and use print(final_state) instead. array_to_latex(final_state, prefix="\\text{Statevector} = ") qc = QuantumCircuit(2) qc.x(0) qc.draw() svsim = Aer.get_backend('aer_simulator') qc.save_statevector() qobj = assemble(qc) final_state = svsim.run(qobj).result().get_statevector() array_to_latex(final_state, prefix="\\text{Statevector} = ") qc = QuantumCircuit(2) qc.h(0) qc.draw() svsim = Aer.get_backend('aer_simulator') qc.save_statevector() qobj = assemble(qc) final_state = svsim.run(qobj).result().get_statevector() array_to_latex(final_state, prefix="\\text{Statevector} = ") qc = QuantumCircuit(2) qc.x(0) qc.h(1) qc.draw() svsim = Aer.get_backend('aer_simulator') qc.save_statevector() qobj = assemble(qc) final_state = svsim.run(qobj).result().get_statevector() array_to_latex(final_state, prefix="\\text{Statevector} = ") qc = QuantumCircuit(2) qc.h(0) qc.x(1) qc.h(1) qc.draw() svsim = Aer.get_backend('aer_simulator') qc.save_statevector() qobj = assemble(qc) final_state = svsim.run(qobj).result().get_statevector() array_to_latex(final_state, prefix="\\text{Statevector} = ") qc = QuantumCircuit(2) qc.h(0) qc.x(1) qc.draw() usim = Aer.get_backend('aer_simulator') qc.save_unitary() qobj = assemble(qc) unitary = usim.run(qobj).result().get_unitary() array_to_latex(unitary, prefix="\\text{Circuit = }\n") qc = QuantumCircuit(1) qc.x(0) qc.z(0) qc.h(0) qc.draw() usim = Aer.get_backend('aer_simulator') qc.save_unitary() qobj = assemble(qc) unitary = usim.run(qobj).result().get_unitary() array_to_latex(unitary, prefix="\\text{Circuit = }\n") qc = QuantumCircuit(3) qc.x(2) qc.z(1) qc.h(0) qc.draw() usim = Aer.get_backend('aer_simulator') qc.save_unitary() qobj = assemble(qc) unitary = usim.run(qobj).result().get_unitary() array_to_latex(unitary, prefix="\\text{Circuit = }\n") qc = QuantumCircuit(2) # Apply H-gate to the first: qc.h(0) # Apply a CNOT: qc.cx(0,1) qc.draw() # Let's get the result: qc.save_statevector() qobj = assemble(qc) result = svsim.run(qobj).result() # Print the statevector neatly: final_state = result.get_statevector() array_to_latex(final_state, prefix="\\text{Statevector = }") plot_bloch_multivector(final_state) qc = QuantumCircuit(2) # Apply H-gate to the first: qc.h(0) qc.draw() # Let's get the result: qc.save_statevector() qobj = assemble(qc) result = svsim.run(qobj).result() # Print the statevector neatly: final_state = result.get_statevector() array_to_latex(final_state, prefix="\\text{Statevector = }") plot_bloch_multivector(final_state) qc = QuantumCircuit(2) # Apply H-gate to the first: qc.x(0) qc.h(1) qc.cx(1,0) qc.draw() # Let's get the result: qc.save_statevector() qobj = assemble(qc) result = svsim.run(qobj).result() # Print the statevector neatly: final_state = result.get_statevector() array_to_latex(final_state, prefix="\\text{Statevector = }") qc = QuantumCircuit(2) # Apply H-gate to the first: qc.x(0) qc.h(1) qc.cx(1,0) usim = Aer.get_backend('aer_simulator') qc.save_unitary() qobj = assemble(qc) unitary = usim.run(qobj).result().get_unitary() array_to_latex(unitary, prefix="\\text{Circuit = }\n")
https://github.com/mattalcasabas/quantum-shors-algorithm
mattalcasabas
from qiskit import QuantumCircuit, Aer, execute from qiskit.tools.visualization import plot_histogram from qiskit_ibm_runtime import QiskitRuntimeService import numpy as np # Define a function for creating a controlled unitary operator for a^power mod 15 def c_amod15(a, power): # Create a quantum circuit with 4 qubits U = QuantumCircuit(4) # Apply the controlled swaps and X gates based on the specified power for iteration in range(power): # Apply swaps to create the effect of the controlled modular multiplication U.swap(2, 3) U.swap(1, 2) U.swap(0, 1) # Apply X gate to all qubits for q in range(4): U.x(q) # Convert the circuit to a gate U = U.to_gate() # Set the gate name to indicate the operation being performed U.name = "%i^%i mod 15" % (a, power) # Create the controlled version of the gate c_U = U.control() # Return the controlled gate return c_U qubit_count = 8 # number of qubits we'll be using to count a = 7 # this is our guess # Define a function for creating the inverse Quantum Fourier Transform (QFT) def qft_dagger(n): # Create a quantum circuit with n qubits qc = QuantumCircuit(n) # Apply swaps to reverse the order of qubits for qubit in range(n // 2): qc.swap(qubit, n - qubit - 1) # Apply controlled phase shifts and Hadamard gates for j in range(n): # Iterate over qubits m less than j for m in range(j): # Apply a controlled-phase gate with a decreasing angle qc.cp(-np.pi / float(2**(j - m)), m, j) # Apply Hadamard gate to the j-th qubit qc.h(j) # Set the name of the circuit to indicate that it is the inverse QFT qc.name = "QFT dagger" # Return the quantum circuit return qc # Create a quantum circuit with qubit_count + 4 qubits, and qubit_count classical bits qc = QuantumCircuit(qubit_count + 4, qubit_count) # Apply Hadamard gates to the first qubit_count qubits for q in range(qubit_count): qc.h(q) # Apply X gate to the qubit at position 3 + qubit_count qc.x(3 + qubit_count) # Apply controlled modular exponentiation gates for each qubit in a loop for q in range(qubit_count): qc.append(c_amod15(a, 2**q), [q] + [i + qubit_count for i in range(4)]) # Apply the inverse Quantum Fourier Transform to the first qubit_count qubits qc.append(qft_dagger(qubit_count), range(qubit_count)) # Measure the first qubit_count qubits and map the result to classical bits qc.measure(range(qubit_count), range(qubit_count)) # Draw the quantum circuit in text format qc.draw('text') # Choose the Qiskit Aer backend for simulating quantum computation backend = Aer.get_backend('qasm_simulator') # Execute the quantum circuit on the chosen backend, specifying the number of shots result = execute(qc, backend, shots=2048).result() # Get the counts of different measurement outcomes from the result counts = result.get_counts() # Plot a histogram of the measurement outcomes plot_histogram(counts) # Save account to disk. QiskitRuntimeService.save_account(channel="ibm_quantum", token="1b79f356170deeac5fdf52081b78581d5bc4f5708f124fa04b4f316ac96b16320f037201caf33bc8ab511d7af999dd07c8737051176abacfa5e318edee4e0837", name="mattalcasabas", overwrite=True) service = QiskitRuntimeService(name="mattalcasabas") backend = service.backend("ibm_brisbane") # Execute the quantum circuit on the chosen backend, specifying the number of shots result = execute(qc, backend, shots=2048).result() # Get the counts of different measurement outcomes from the result counts = result.get_counts() # Plot a histogram of the measurement outcomes plot_histogram(counts)
https://github.com/ahkatlio/QHSO_Basics_of_Qiskit
ahkatlio
from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram, visualize_transition qc = QuantumCircuit(1,1) qc.h(0) visualize_transition(qc) qc.measure(0,0) qc.draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') result = execute(qc, backend=simulator, shots=1024).result() counts = result.get_counts() plot_histogram(counts) qc3 = QuantumCircuit(1,1) qc3.x(0) qc3.h(0) qc3.draw(output='mpl') visualize_transition(qc3) qc3.measure(0,0) qc3.draw(output='mpl') result = execute(qc3, backend=simulator, shots=1024).result() counts = result.get_counts() plot_histogram(counts) qc2 = QuantumCircuit(1,1) qc2.h(0) qc2.h(0) qc2.draw(output='mpl') visualize_transition(qc2) qc2.measure(0,0) result = execute(qc2, backend=simulator, shots=1024).result() counts = result.get_counts() plot_histogram(counts) from qiskit.visualization import plot_bloch_multivector qc4 = QuantumCircuit(1,1) qc4.h(0) qc4.measure(0,0) qc4.h(0) qc4.draw(output='mpl') backend = Aer.get_backend('statevector_simulator') result = execute(qc4, backend).result() statevector = result.get_statevector(qc4) plot_bloch_multivector(statevector)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
%run ../version.ipynb
https://github.com/ShabaniLab/q-camp
ShabaniLab
# import numpy library import numpy as np # import pyplot library import matplotlib.pyplot as plt # generate a random number between 0 and 1 np.random.randint(0, 5) np.random.randint(0, 2, size=10) # 1000 coin flips A = np.random.randint(0, 2, size=1000) # make figure fig = plt.figure() # get the axes ax = plt.axes() # plot a histogram of the outcomes plt.hist(A) # calculate how many people share the same birthday def calculate_matches(n): outcome = np.random.randint(1, 366, size=n) number_of_matches = 0 for i in range(n): for j in range(i+1, n): if outcome[i] == outcome[j]: number_of_matches += 1 return number_of_matches party_size = np.arange(10, 2000, 100) matches = np.zeros_like(party_size) # calculate for all different party sizes for i in range(len(party_size)): matches[i] = calculate_matches(party_size[i]) print(party_size) print(matches) plt.plot(party_size, matches) # plot that number vs N # a coin flip with p = 0.8 np.random.choice([0, 1], p=[0.8, 0.2]) # 1000 biased coin flips with p = 0.8 B = np.random.choice([0, 1], size=1000, p=[0.8, 0.2]) plt.hist(B) # 10 coin flips each with success probability p = 0.5 # the output is the number of heads out of 10 total coin flips np.random.binomial(10, 0.5) # we can run the whole binomial experiment for multiple times using the "size" argument # this means that if we flip 10 coins for 5 different iterations # the output would be the number of heads in each iteration np.random.binomial(10, 0.5, size=5) # change the number of iterations (size), what do you observe as you increase the size? C = np.random.binomial(10, 0.5, size=100) plt.hist(C) max_trials = 1000 num_trials = np.arange(max_trials) avg_array = np.zeros_like(num_trials, dtype=np.double) for i in range(max_trials): random_event = np.array(np.random.choice([1, 2, 3, 4, 5, 6], size=i+1)) avg_array[i] = np.average(random_event) plt.plot(num_trials, avg_array)
https://github.com/grossiM/Qiskit_workshop1019
grossiM
# useful additional packages import numpy as np import matplotlib.pyplot as plt %matplotlib inline # importing Qiskit from qiskit import Aer, IBMQ from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister import qiskit as qk #from qiskit.wrapper.jupyter import * # import basic plot tools from qiskit.tools.visualization import circuit_drawer, plot_histogram #IBMQ.save_account('APItoken') # Load our saved IBMQ accounts IBMQ.load_account() n = 2 # n is the length of the first register # Let's choose ranomly the type of oracle. The probability that it is balanced is 50% and that is constant is 50% # In order to do so we will use a function from numpy module oracleType, oracleValue = np.random.randint(2), np.random.randint(2) if oracleType == 0: print("The oracle is constant ", oracleValue) else: print("The oracle is balanced") a = np.random.randint(1,2**n) # let's save an hidden value for the balanced function. # create quantum and classical registers all initialized at zero # 2 qubits for oracle interrogation, and the other one is to save the result qr = QuantumRegister(n+1) # we only need the classical register for the measurement of the first quantum circuit cr = ClassicalRegister(n) circuitName = "DeutschJozsa" djCircuit = QuantumCircuit(qr, cr) # Superpose the first register. for i in range(n): djCircuit.h(qr[i]) # Invert the second register and apply H. djCircuit.x(qr[n]) djCircuit.h(qr[n]) # Let's visualize a barrier of the oracle (this is only for stylistical purpose) djCircuit.barrier() if oracleType == 0:#The function is constant if oracleValue == 1: djCircuit.x(qr[n]) else: djCircuit.iden(qr[n]) else: # The function is balanced, in that case the oracle applies a CNOT on the qubit i controlling the qubit n for i in range(n): if (a & (1 << i)): djCircuit.cx(qr[i], qr[n]) # End of the oracle, let's close the barrier djCircuit.barrier() # Apply H to each qubit for i in range(n): djCircuit.h(qr[i]) # Measure djCircuit.barrier() for i in range(n): djCircuit.measure(qr[i], cr[i]) #draw the circuit circuit_drawer(djCircuit) backend = Aer.get_backend('qasm_simulator') shots = 1024 job = qk.execute(djCircuit, backend=backend, shots=shots) results = job.result() answer = results.get_counts() plot_histogram(answer) from qiskit.tools.monitor import job_monitor backend = IBMQ.get_backend('ibmq_16_melbourne') shots = 1024 job = qk.execute(djCircuit, backend=backend, shots=shots) job_monitor(job, interval=5) results = job.result() answer = results.get_counts() threshold = int(0.03 * shots) # set a threshold for significant measurements filteredAnswer = {k: v for k,v in answer.items() if v >= threshold} # filter for an optimal visualization of the results removedCounts = np.sum([ v for k,v in answer.items() if v < threshold ]) # filteredAnswer['other_bitstring'] = removedCounts # plot_histogram(answer) print(answer)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
u = [-2,-1,0,1] v = [1,2,3] uv = [] vu = [] for i in range(len(u)): # one element of u is picked for j in range(len(v)): # now we iteratively select every element of v uv.append(u[i]*v[j]) # this one element of u is iteratively multiplied with every element of v print("u-tensor-v is",uv) for i in range(len(v)): # one element of v is picked for j in range(len(u)): # now we iteratively select every element of u vu.append(v[i]*u[j]) # this one element of v is iteratively multiplied with every element of u print("v-tensor-u is",vu) A = [ [-1,0,1], [-2,-1,2] ] B = [ [0,2], [3,-1], [-1,1] ] print("A =") for i in range(len(A)): print(A[i]) print() # print a line print("B =") for i in range(len(B)): print(B[i]) # let's define A-tensor-B as a (6x6)-dimensional zero matrix AB = [] for i in range(6): AB.append([]) for j in range(6): AB[i].append(0) # let's find A-tensor-B for i in range(2): for j in range(3): # for each A(i,j) we execute the following codes a = A[i][j] # we access each element of B for m in range(3): for n in range(2): b = B[m][n] # now we put (a*b) in the appropriate index of AB AB[3*i+m][2*j+n] = a * b print() # print a line print("A-tensor-B =") print() # print a line for i in range(6): print(AB[i]) A = [ [-1,0,1], [-2,-1,2] ] B = [ [0,2], [3,-1], [-1,1] ] print() # print a line print("B =") for i in range(len(B)): print(B[i]) print("A =") for i in range(len(A)): print(A[i]) # let's define B-tensor-A as a (6x6)-dimensional zero matrix BA = [] for i in range(6): BA.append([]) for j in range(6): BA[i].append(0) # let's find B-tensor-A for i in range(3): for j in range(2): # for each B(i,j) we execute the following codes b = B[i][j] # we access each element of A for m in range(2): for n in range(3): a = A[m][n] # now we put (a*b) in the appropriate index of AB BA[2*i+m][3*j+n] = b * a print() # print a line print("B-tensor-A =") print() # print a line for i in range(6): print(BA[i])
https://github.com/quantum-melbourne/qiskit-challenge-22
quantum-melbourne
#Let us begin by importing necessary libraries. from qiskit import Aer from qiskit.algorithms import VQE, QAOA, NumPyMinimumEigensolver from qiskit.algorithms.optimizers import * from qiskit.circuit.library import TwoLocal from qiskit.utils import QuantumInstance from qiskit.utils import algorithm_globals from qiskit_finance import QiskitFinanceError from qiskit_finance.applications.optimization import PortfolioOptimization from qiskit_finance.data_providers import * from qiskit_optimization.algorithms import MinimumEigenOptimizer from qiskit_optimization.applications import OptimizationApplication from qiskit_optimization.converters import QuadraticProgramToQubo import numpy as np import matplotlib.pyplot as plt %matplotlib inline import datetime import warnings from sympy.utilities.exceptions import SymPyDeprecationWarning warnings.simplefilter("ignore", SymPyDeprecationWarning) # Set parameters for assets and risk factor num_assets = 4 # set number of assets to 4 q = 0.5 # set risk factor to 0.5 budget = 2 # set budget as defined in the problem seed = 132 # set random seed # Generate time series data stocks = [("STOCK%s" % i) for i in range(num_assets)] data = RandomDataProvider(tickers=stocks, start=datetime.datetime(1955,11,5), end=datetime.datetime(1985,10,26), seed=seed) data.run() # Let's plot our finanical data for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.xlabel('days') plt.ylabel('stock value') plt.show() #Let's calculate the expected return for our problem data mu = data.get_period_return_mean_vector() # Returns a vector containing the mean value of each asset's expected return. print(mu) # Let's plot our covariance matrix Σ(sigma) sigma = data.get_period_return_covariance_matrix() #Returns the covariance matrix of the four assets print(sigma) fig, ax = plt.subplots(1,1) im = plt.imshow(sigma, extent=[-1,1,-1,1]) x_label_list = ['stock3', 'stock2', 'stock1', 'stock0'] y_label_list = ['stock3', 'stock2', 'stock1', 'stock0'] ax.set_xticks([-0.75,-0.25,0.25,0.75]) ax.set_yticks([0.75,0.25,-0.25,-0.75]) ax.set_xticklabels(x_label_list) ax.set_yticklabels(y_label_list) plt.colorbar() plt.clim(-0.000002, 0.00001) plt.show() ############################## # Provide your code here portfolio = qp = ############################## print(qp) # Check your answer and submit using the following code from qc_grader.challenges.unimelb_2022 import grade_ex1a grade_ex1a(qp) exact_mes = NumPyMinimumEigensolver() exact_eigensolver = MinimumEigenOptimizer(exact_mes) result = exact_eigensolver.solve(qp) print(result) optimizer = SLSQP(maxiter=1000) algorithm_globals.random_seed = 1234 backend = Aer.get_backend('statevector_simulator') ############################## # Provide your code here vqe = ############################## vqe_meo = MinimumEigenOptimizer(vqe) #please do not change this code result = vqe_meo.solve(qp) #please do not change this code print(result) #please do not change this code # Check your answer and submit using the following code from qc_grader.challenges.unimelb_2022 import grade_ex1b grade_ex1b(vqe, qp) #Step 1: Let us begin by importing necessary libraries import qiskit from qiskit import Aer from qiskit.algorithms import VQE, QAOA, NumPyMinimumEigensolver from qiskit.algorithms.optimizers import * from qiskit.circuit.library import TwoLocal from qiskit.utils import QuantumInstance from qiskit.utils import algorithm_globals from qiskit_finance import QiskitFinanceError from qiskit_finance.applications.optimization import * from qiskit_finance.data_providers import * from qiskit_optimization.algorithms import MinimumEigenOptimizer from qiskit_optimization.applications import OptimizationApplication from qiskit_optimization.converters import QuadraticProgramToQubo import numpy as np import matplotlib.pyplot as plt %matplotlib inline import datetime import warnings from sympy.utilities.exceptions import SymPyDeprecationWarning warnings.simplefilter("ignore",SymPyDeprecationWarning) # Step 2. Generate time series data for four assets. # Do not change start/end dates specified to generate problem data. seed = 132 num_assets = 4 stocks = [("STOCK%s" % i) for i in range(num_assets)] data = RandomDataProvider(tickers=stocks, start=datetime.datetime(1955,11,5), end=datetime.datetime(1985,10,26), seed=seed) data.run() # Let's plot our finanical data (We are generating the same time series data as in the previous example.) for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.xlabel('days') plt.ylabel('stock value') plt.show() # Step 3. Calculate mu and sigma for this problem mu2 = data.get_period_return_mean_vector() #Returns a vector containing the mean value of each asset. sigma2 = data.get_period_return_covariance_matrix() #Returns the covariance matrix associated with the assets. print(mu2, sigma2) # Step 4. Set parameters and constraints based on this challenge 1c ############################## # Provide your code here q2 = #Set risk factor to 0.5 budget2 = #Set budget to 3 ############################## # Step 5. Complete code to generate the portfolio instance ############################## # Provide your code here portfolio2 = qp2 = ############################## # Step 6. Now let's use QAOA to solve this problem. optimizer = SLSQP(maxiter=1000) algorithm_globals.random_seed = 1234 backend = Aer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed) ############################## # Provide your code here qaoa = ############################## qaoa_meo = MinimumEigenOptimizer(qaoa) #please do not change this code result2 = qaoa_meo.solve(qp2) #please do not change this code print(result2) #please do not change this code # Check your answer and submit using the following code from qc_grader.challenges.unimelb_2022 import grade_ex1c grade_ex1c(qaoa, qp2)
https://github.com/wyqian1027/Qiskit-Fall-Fest-USC-2022
wyqian1027
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer from qiskit.visualization import plot_histogram, plot_bloch_multivector, array_to_latex from qiskit.extensions import Initialize from qiskit.quantum_info import random_statevector from qiskit.quantum_info import Statevector # Creamos 3 registros cuánticos qr = QuantumRegister(3, name="q") # Creamos dos registros clásicos con nombres diferentes crz = ClassicalRegister(1, name="crz") crx = ClassicalRegister(1, name="crx") # Creamos el circuito qc = QuantumCircuit(qr, crz, crx) # O QuantumCircuit(3, 2) qc.draw('mpl') # Creamos un circuito cuántico de dos cúbits phi_plus = QuantumCircuit(2) # Aplicamos la puerta H phi_plus.h(0) # Aplicamos la CNOT phi_plus.cnot(0, 1) phi_plus.draw('mpl') Statevector(phi_plus).draw('latex') # Primero fabricamos un estado aleatorio psi = random_statevector(2) #Esta función nos permite meter el estado en q_{0} init_gate = Initialize(psi) init_gate.label = "psi" # Lo representamos en la esfera de Bloch plot_bloch_multivector(psi) # Lo aplicamos qc qc.append(init_gate, [0]) # Y creamos el estado de bell en los dos últimos cúbits qc.h(1) qc.cnot(1, 2) # Representamos qc.draw('mpl') # Implementamos la acción de alice qc.barrier() qc.cnot(0, 1) qc.h(0) qc.draw('mpl') # Medimos los cúbits de Alice qc.barrier() qc.measure(1,crx) qc.measure(0,crz) qc.draw('mpl') # Aplicamos estas operaciones controladas por los bits clásicos #c_if controla las puertas con un bit clásico en vez de con un cubit qc.x(2).c_if(crx, 1) # Estas dos líneas verifican qc.z(2).c_if(crz, 1) # las acciones vistas arriba. qc.draw('mpl') sim = Aer.get_backend('aer_simulator') qc.save_statevector() out_vector = sim.run(qc).result().get_statevector() plot_bloch_multivector(out_vector)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Transpiler pulse gate pass testing.""" import ddt from qiskit import pulse, circuit, transpile from qiskit.providers.fake_provider import FakeAthens, FakeAthensV2 from qiskit.quantum_info.random import random_unitary from qiskit.test import QiskitTestCase @ddt.ddt class TestPulseGate(QiskitTestCase): """Integration test of pulse gate pass with custom backend.""" def setUp(self): super().setUp() self.sched_param = circuit.Parameter("P0") with pulse.build(name="sx_q0") as custom_sx_q0: pulse.play(pulse.Constant(100, 0.1), pulse.DriveChannel(0)) self.custom_sx_q0 = custom_sx_q0 with pulse.build(name="sx_q1") as custom_sx_q1: pulse.play(pulse.Constant(100, 0.2), pulse.DriveChannel(1)) self.custom_sx_q1 = custom_sx_q1 with pulse.build(name="cx_q01") as custom_cx_q01: pulse.play(pulse.Constant(100, 0.4), pulse.ControlChannel(0)) self.custom_cx_q01 = custom_cx_q01 with pulse.build(name="my_gate_q0") as my_gate_q0: pulse.shift_phase(self.sched_param, pulse.DriveChannel(0)) pulse.play(pulse.Constant(120, 0.1), pulse.DriveChannel(0)) self.my_gate_q0 = my_gate_q0 with pulse.build(name="my_gate_q1") as my_gate_q1: pulse.shift_phase(self.sched_param, pulse.DriveChannel(1)) pulse.play(pulse.Constant(120, 0.2), pulse.DriveChannel(1)) self.my_gate_q1 = my_gate_q1 def test_transpile_with_bare_backend(self): """Test transpile without custom calibrations.""" backend = FakeAthens() qc = circuit.QuantumCircuit(2) qc.sx(0) qc.x(0) qc.rz(0, 0) qc.sx(1) qc.measure_all() transpiled_qc = transpile(qc, backend, initial_layout=[0, 1]) ref_calibration = {} self.assertDictEqual(transpiled_qc.calibrations, ref_calibration) def test_transpile_with_backend_target(self): """Test transpile without custom calibrations from target.""" backend = FakeAthensV2() target = backend.target qc = circuit.QuantumCircuit(2) qc.sx(0) qc.x(0) qc.rz(0, 0) qc.sx(1) qc.measure_all() transpiled_qc = transpile(qc, initial_layout=[0, 1], target=target) ref_calibration = {} self.assertDictEqual(transpiled_qc.calibrations, ref_calibration) def test_transpile_with_custom_basis_gate(self): """Test transpile with custom calibrations.""" backend = FakeAthens() backend.defaults().instruction_schedule_map.add("sx", (0,), self.custom_sx_q0) backend.defaults().instruction_schedule_map.add("sx", (1,), self.custom_sx_q1) qc = circuit.QuantumCircuit(2) qc.sx(0) qc.x(0) qc.rz(0, 0) qc.sx(1) qc.measure_all() transpiled_qc = transpile(qc, backend, initial_layout=[0, 1]) ref_calibration = { "sx": { ((0,), ()): self.custom_sx_q0, ((1,), ()): self.custom_sx_q1, } } self.assertDictEqual(transpiled_qc.calibrations, ref_calibration) def test_transpile_with_custom_basis_gate_in_target(self): """Test transpile with custom calibrations.""" backend = FakeAthensV2() target = backend.target target["sx"][(0,)].calibration = self.custom_sx_q0 target["sx"][(1,)].calibration = self.custom_sx_q1 qc = circuit.QuantumCircuit(2) qc.sx(0) qc.x(0) qc.rz(0, 0) qc.sx(1) qc.measure_all() transpiled_qc = transpile(qc, initial_layout=[0, 1], target=target) ref_calibration = { "sx": { ((0,), ()): self.custom_sx_q0, ((1,), ()): self.custom_sx_q1, } } self.assertDictEqual(transpiled_qc.calibrations, ref_calibration) def test_transpile_with_instmap(self): """Test providing instruction schedule map.""" instmap = FakeAthens().defaults().instruction_schedule_map instmap.add("sx", (0,), self.custom_sx_q0) instmap.add("sx", (1,), self.custom_sx_q1) # Inst map is renewed backend = FakeAthens() qc = circuit.QuantumCircuit(2) qc.sx(0) qc.x(0) qc.rz(0, 0) qc.sx(1) qc.measure_all() transpiled_qc = transpile(qc, backend, inst_map=instmap, initial_layout=[0, 1]) ref_calibration = { "sx": { ((0,), ()): self.custom_sx_q0, ((1,), ()): self.custom_sx_q1, } } self.assertDictEqual(transpiled_qc.calibrations, ref_calibration) def test_transpile_with_custom_gate(self): """Test providing non-basis gate.""" backend = FakeAthens() backend.defaults().instruction_schedule_map.add( "my_gate", (0,), self.my_gate_q0, arguments=["P0"] ) backend.defaults().instruction_schedule_map.add( "my_gate", (1,), self.my_gate_q1, arguments=["P0"] ) qc = circuit.QuantumCircuit(2) qc.append(circuit.Gate("my_gate", 1, [1.0]), [0]) qc.append(circuit.Gate("my_gate", 1, [2.0]), [1]) transpiled_qc = transpile(qc, backend, basis_gates=["my_gate"], initial_layout=[0, 1]) my_gate_q0_1_0 = self.my_gate_q0.assign_parameters({self.sched_param: 1.0}, inplace=False) my_gate_q1_2_0 = self.my_gate_q1.assign_parameters({self.sched_param: 2.0}, inplace=False) ref_calibration = { "my_gate": { ((0,), (1.0,)): my_gate_q0_1_0, ((1,), (2.0,)): my_gate_q1_2_0, } } self.assertDictEqual(transpiled_qc.calibrations, ref_calibration) def test_transpile_with_parameterized_custom_gate(self): """Test providing non-basis gate, which is kept parameterized throughout transpile.""" backend = FakeAthens() backend.defaults().instruction_schedule_map.add( "my_gate", (0,), self.my_gate_q0, arguments=["P0"] ) param = circuit.Parameter("new_P0") qc = circuit.QuantumCircuit(1) qc.append(circuit.Gate("my_gate", 1, [param]), [0]) transpiled_qc = transpile(qc, backend, basis_gates=["my_gate"], initial_layout=[0]) my_gate_q0_p = self.my_gate_q0.assign_parameters({self.sched_param: param}, inplace=False) ref_calibration = { "my_gate": { ((0,), (param,)): my_gate_q0_p, } } self.assertDictEqual(transpiled_qc.calibrations, ref_calibration) def test_transpile_with_multiple_circuits(self): """Test transpile with multiple circuits with custom gate.""" backend = FakeAthens() backend.defaults().instruction_schedule_map.add( "my_gate", (0,), self.my_gate_q0, arguments=["P0"] ) params = [0.0, 1.0, 2.0, 3.0] circs = [] for param in params: qc = circuit.QuantumCircuit(1) qc.append(circuit.Gate("my_gate", 1, [param]), [0]) circs.append(qc) transpiled_qcs = transpile(circs, backend, basis_gates=["my_gate"], initial_layout=[0]) for param, transpiled_qc in zip(params, transpiled_qcs): my_gate_q0_x = self.my_gate_q0.assign_parameters( {self.sched_param: param}, inplace=False ) ref_calibration = {"my_gate": {((0,), (param,)): my_gate_q0_x}} self.assertDictEqual(transpiled_qc.calibrations, ref_calibration) def test_multiple_instructions_with_different_parameters(self): """Test adding many instruction with different parameter binding.""" backend = FakeAthens() backend.defaults().instruction_schedule_map.add( "my_gate", (0,), self.my_gate_q0, arguments=["P0"] ) qc = circuit.QuantumCircuit(1) qc.append(circuit.Gate("my_gate", 1, [1.0]), [0]) qc.append(circuit.Gate("my_gate", 1, [2.0]), [0]) qc.append(circuit.Gate("my_gate", 1, [3.0]), [0]) transpiled_qc = transpile(qc, backend, basis_gates=["my_gate"], initial_layout=[0]) my_gate_q0_1_0 = self.my_gate_q0.assign_parameters({self.sched_param: 1.0}, inplace=False) my_gate_q0_2_0 = self.my_gate_q0.assign_parameters({self.sched_param: 2.0}, inplace=False) my_gate_q0_3_0 = self.my_gate_q0.assign_parameters({self.sched_param: 3.0}, inplace=False) ref_calibration = { "my_gate": { ((0,), (1.0,)): my_gate_q0_1_0, ((0,), (2.0,)): my_gate_q0_2_0, ((0,), (3.0,)): my_gate_q0_3_0, } } self.assertDictEqual(transpiled_qc.calibrations, ref_calibration) def test_transpile_with_different_qubit(self): """Test transpile with qubit without custom gate.""" backend = FakeAthens() backend.defaults().instruction_schedule_map.add("sx", (0,), self.custom_sx_q0) qc = circuit.QuantumCircuit(1) qc.sx(0) qc.measure_all() transpiled_qc = transpile(qc, backend, initial_layout=[3]) self.assertDictEqual(transpiled_qc.calibrations, {}) @ddt.data(0, 1, 2, 3) def test_transpile_with_both_instmap_and_empty_target(self, opt_level): """Test when instmap and target are both provided and only instmap contains custom schedules. Test case from Qiskit/qiskit-terra/#9489 """ instmap = FakeAthens().defaults().instruction_schedule_map instmap.add("sx", (0,), self.custom_sx_q0) instmap.add("sx", (1,), self.custom_sx_q1) instmap.add("cx", (0, 1), self.custom_cx_q01) # This doesn't have custom schedule definition target = FakeAthensV2().target qc = circuit.QuantumCircuit(2) qc.append(random_unitary(4, seed=123), [0, 1]) qc.measure_all() transpiled_qc = transpile( qc, optimization_level=opt_level, basis_gates=["sx", "rz", "x", "cx"], inst_map=instmap, target=target, initial_layout=[0, 1], ) ref_calibration = { "sx": { ((0,), ()): self.custom_sx_q0, ((1,), ()): self.custom_sx_q1, }, "cx": { ((0, 1), ()): self.custom_cx_q01, }, } self.assertDictEqual(transpiled_qc.calibrations, ref_calibration) @ddt.data(0, 1, 2, 3) def test_transpile_with_instmap_with_v2backend(self, opt_level): """Test when instmap is provided with V2 backend. Test case from Qiskit/qiskit-terra/#9489 """ instmap = FakeAthens().defaults().instruction_schedule_map instmap.add("sx", (0,), self.custom_sx_q0) instmap.add("sx", (1,), self.custom_sx_q1) instmap.add("cx", (0, 1), self.custom_cx_q01) qc = circuit.QuantumCircuit(2) qc.append(random_unitary(4, seed=123), [0, 1]) qc.measure_all() transpiled_qc = transpile( qc, FakeAthensV2(), optimization_level=opt_level, inst_map=instmap, initial_layout=[0, 1], ) ref_calibration = { "sx": { ((0,), ()): self.custom_sx_q0, ((1,), ()): self.custom_sx_q1, }, "cx": { ((0, 1), ()): self.custom_cx_q01, }, } self.assertDictEqual(transpiled_qc.calibrations, ref_calibration) @ddt.data(0, 1, 2, 3) def test_transpile_with_instmap_with_v2backend_with_custom_gate(self, opt_level): """Test when instmap is provided with V2 backend. In this test case, instmap contains a custom gate which doesn't belong to Qiskit standard gate. Target must define a custom gete on the fly to reflect user-provided instmap. Test case from Qiskit/qiskit-terra/#9489 """ with pulse.build(name="custom") as rabi12: pulse.play(pulse.Constant(100, 0.4), pulse.DriveChannel(0)) instmap = FakeAthens().defaults().instruction_schedule_map instmap.add("rabi12", (0,), rabi12) gate = circuit.Gate("rabi12", 1, []) qc = circuit.QuantumCircuit(1) qc.append(gate, [0]) qc.measure_all() transpiled_qc = transpile( qc, FakeAthensV2(), optimization_level=opt_level, inst_map=instmap, initial_layout=[0], ) ref_calibration = { "rabi12": { ((0,), ()): rabi12, } } self.assertDictEqual(transpiled_qc.calibrations, ref_calibration) def test_transpile_with_instmap_not_mutate_backend(self): """Do not override default backend target when transpile with inst map. Providing an instmap for the transpile arguments may override target, which might be pulled from the provided backend instance. This should not override the source object since the same backend may be used for future transpile without intention of instruction overriding. """ backend = FakeAthensV2() original_sx0 = backend.target["sx"][(0,)].calibration instmap = FakeAthens().defaults().instruction_schedule_map instmap.add("sx", (0,), self.custom_sx_q0) qc = circuit.QuantumCircuit(1) qc.sx(0) qc.measure_all() transpiled_qc = transpile( qc, FakeAthensV2(), inst_map=instmap, initial_layout=[0], ) self.assertTrue(transpiled_qc.has_calibration_for(transpiled_qc.data[0])) self.assertEqual( backend.target["sx"][(0,)].calibration, original_sx0, )
https://github.com/EusseJhoan/DeutschJosza_algorithm
EusseJhoan
from qiskit import QuantumCircuit, transpile, Aer from qiskit.visualization import plot_histogram import numpy as np sim = Aer.get_backend('aer_simulator') def U_f1(qc): return qc def U_f2(qc): qc.x(1) #Compuerta X al segundo qubit return qc def U_f3(qc): qc.cx(0,1) #Compuerta CNOT entre primer y segundo quibit (el primero es el que controla) return qc def U_f4(qc): qc.cx(0,1) #Compuerta CNOT entre primer y segundo quibit (el primero es el que controla) qc.x(1) #Compuerta X al segundo qubit return qc def Deutsch(U_f): qc=QuantumCircuit(2,1) #Se crea un circuito cuántico con 2 bits cuánticos y 1 canal clásico qc.x(1) #Compuerta X al segundo qubit (inicializar estado |1>) qc.h(0) #Compuerta H al primer qubit qc.h(1) #Compuerta H al segundo qubit qc.barrier() #Barrera (empieza oráculo) qc = U_f(qc) #Agregamos el oráculo qc.barrier() #Barrera (termina oráculo) qc.h(0) #Compuerta H al primer qubit qc.measure(0,0) #Medimos el primer qubit y enviamos señal al canal clásico return qc qc=Deutsch(U_f1) # definición circuito con oráculo usando f_1(x) display(qc.draw()) # visualización del circuito counts = sim.run(qc).result().get_counts() #contando las medidas de simulador cuántico plot_histogram(counts) #histrograma de resultados qc=Deutsch(U_f2) #definición circuito con oráculo usando f_2(x) display(qc.draw()) # visualización del circuito counts = sim.run(qc).result().get_counts() #contando las medidas del simulador cuántico plot_histogram(counts) #histrograma de resultados qc=Deutsch(U_f3) #definición circuito con oráculo usando f_3(x) display(qc.draw()) # visualización del circuito counts = sim.run(qc).result().get_counts() #contando las medidas de simulador cuántico plot_histogram(counts) #histrograma de resultados qc=Deutsch(U_f4) #definición circuito con oráculo usando f_4(x) display(qc.draw()) # visualización del circuito counts = sim.run(qc).result().get_counts() #contando las medidas de simulador cuántico plot_histogram(counts) #histrograma de resultados #oráculo para f(x) constante para un número n de bits en el registro def constant(qc,n): ran=np.random.randint(2) #selección aleatoria de 0 ó 1 if ran == 1: qc.x(n) #si el número aleatorio es 1 se pone compuerta X en el objetivo (se induce fase global -1 al registro) return qc #oráculo para f(x) balanceado para un número n de bits en el registro def balanced(qc,n): for i in range(n): qc.cx(i,n) #se crea una CNOT entre cada qubit del registro y el objetivo (los qubits del registro controlan) ran=np.random.randint(2) #selección aleatoria de 0 ó 1 if ran == 1: qc.x(n) #si el número aleatorio es 1 se pone compuerta X en el objetivo (se induce fase global -1 al registro) return qc def D_J(U_f,n): qc=QuantumCircuit(n+1,n) #Se crea un circuito cuántico con n+1 quibits y n canales clásicos qc.x(n) #Compuerta X al bit del registro for i in range(n+1): qc.h(i) #Compuerta H a todos los bits qc.barrier() #Barrera (empieza oráculo) qc = U_f(qc,n) #Agregamos el oráculo qc.barrier() #Barrera (termina oráculo) for i in range(n): qc.h(i) #Compuerta H a los n bits del registro qc.measure(i,i) #Medición los n bits del registro return qc qc=D_J(constant,3) #definición circuito con oráculo constante y 3 bits en registro display(qc.draw()) #ver circuito counts = sim.run(qc).result().get_counts() #contando las medidas de simulador cuántico plot_histogram(counts) #histrograma de resultados qc=D_J(balanced,3) display(qc.draw()) counts = sim.run(qc).result().get_counts() plot_histogram(counts)
https://github.com/aniket1905-del/Quantum_computation
aniket1905-del
import cirq import numpy as np from qiskit import QuantumCircuit, execute, Aer import seaborn as sns import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = (15,10) q0, q1, q2 = [cirq.LineQubit(i) for i in range(3)] circuit = cirq.Circuit() #entagling the 2 quibits in different laboratories #and preparing the qubit to send circuit.append(cirq.H(q0)) circuit.append(cirq.H(q1)) circuit.append(cirq.CNOT(q1, q2)) #entangling the qubit we want to send to the one in the first laboratory circuit.append(cirq.CNOT(q0, q1)) circuit.append(cirq.H(q0)) #measurements circuit.append(cirq.measure(q0, q1)) #last transformations to obtain the qubit information circuit.append(cirq.CNOT(q1, q2)) circuit.append(cirq.CZ(q0, q2)) #measure of the qubit in the receiving laboratory along z axis circuit.append(cirq.measure(q2, key = 'Z')) circuit #starting simulation sim = cirq.Simulator() results = sim.run(circuit, repetitions=100) sns.histplot(results.measurements['Z'], discrete = True) 100 - np.count_nonzero(results.measurements['Z']), np.count_nonzero(results.measurements['Z']) #in qiskit the qubits are integrated in the circuit qc = QuantumCircuit(3, 1) #entangling qc.h(0) qc.h(1) qc.cx(1, 2) qc.cx(0, 1) #setting for measurment qc.h(0) qc.measure([0,1], [0,0]) #transformation to obtain qubit sent qc.cx(1, 2) qc.cz(0, 2) qc.measure(2, 0) print(qc) #simulation simulator = Aer.get_backend('qasm_simulator') job = execute(qc, simulator, shots=100) res = job.result().get_counts(qc) plt.bar(res.keys(), res.values()) res
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Depth pass testing""" import unittest from qiskit import QuantumCircuit, QuantumRegister from qiskit.converters import circuit_to_dag from qiskit.transpiler.passes import CountOps from qiskit.test import QiskitTestCase class TestCountOpsPass(QiskitTestCase): """Tests for CountOps analysis methods.""" def test_empty_dag(self): """Empty DAG has empty counts.""" circuit = QuantumCircuit() dag = circuit_to_dag(circuit) pass_ = CountOps() _ = pass_.run(dag) self.assertDictEqual(pass_.property_set["count_ops"], {}) def test_just_qubits(self): """A dag with 8 operations (6 CXs and 2 Hs)""" # ┌───┐ ┌───┐┌───┐ # q0_0: ┤ H ├──■────■────■────■──┤ X ├┤ X ├ # ├───┤┌─┴─┐┌─┴─┐┌─┴─┐┌─┴─┐└─┬─┘└─┬─┘ # q0_1: ┤ H ├┤ X ├┤ X ├┤ X ├┤ X ├──■────■── # └───┘└───┘└───┘└───┘└───┘ qr = QuantumRegister(2) circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) circuit.cx(qr[1], qr[0]) dag = circuit_to_dag(circuit) pass_ = CountOps() _ = pass_.run(dag) self.assertDictEqual(pass_.property_set["count_ops"], {"cx": 6, "h": 2}) if __name__ == "__main__": unittest.main()
https://github.com/AbeerVaishnav13/4-qubit-design
AbeerVaishnav13
%load_ext autoreload %autoreload 2 import scqubits as scq from qiskit_metal.analyses.quantization.lumped_capacitive import load_q3d_capacitance_matrix from qiskit_metal.analyses.quantization.lom_core_analysis import CompositeSystem, Cell, Subsystem, QuantumSystemRegistry from scipy.constants import speed_of_light as c_light import matplotlib.pyplot as plt %matplotlib inline QuantumSystemRegistry.registry() # Q1 path1 = "./capacitance_matrices/Q1_cap_matrix.txt" t1_mat, _, _, _ = load_q3d_capacitance_matrix(path1) # Q2 path2 = "./capacitance_matrices/Q2_cap_matrix.txt" t2_mat, _, _, _ = load_q3d_capacitance_matrix(path2) # Q3 path3 = "./capacitance_matrices/Q3_cap_matrix.txt" t3_mat, _, _, _ = load_q3d_capacitance_matrix(path3) # Q4 path4 = "./capacitance_matrices/Q4_cap_matrix.txt" t4_mat, _, _, _ = load_q3d_capacitance_matrix(path4) # Cell 2: Transmon-2 opt2 = dict( node_rename = {'b_connector_pad_Q2': 'coupler23', 'c_connector_pad_Q2': 'readout2'}, cap_mat = t2_mat, ind_dict = {('pad_top_Q2', 'pad_bot_Q2'): 12}, # junction inductance in nH jj_dict = {('pad_top_Q2', 'pad_bot_Q2'): 'j2'}, cj_dict = {('pad_top_Q2', 'pad_bot_Q2'): 1}, # junction capacitance in fF ) cell_2 = Cell(opt2) # Cell 3: Transmon-3 opt3 = dict( node_rename = {'b_connector_pad_Q3': 'coupler23', 'c_connector_pad_Q3': 'readout3'}, cap_mat = t3_mat, ind_dict = {('pad_top_Q3', 'pad_bot_Q3'): 12}, # junction inductance in nH jj_dict = {('pad_top_Q3', 'pad_bot_Q3'): 'j3'}, cj_dict = {('pad_top_Q3', 'pad_bot_Q3'): 1}, # junction capacitance in fF ) cell_3 = Cell(opt3) # subsystem 1: Transmon-2 transmon2 = Subsystem(name='transmon2', sys_type='TRANSMON', nodes=['j2']) # subsystem 2: Transmon-3 transmon3 = Subsystem(name='transmon3', sys_type='TRANSMON', nodes=['j3']) # Resonator Subsystems q_opts = dict( Z0 = 50, # characteristic impedance in Ohm vp = 0.404314 * c_light # phase velocity ) # subsystem 3: Q2 readout resonator ro2 = Subsystem(name='readout2', sys_type='TL_RESONATOR', nodes=['readout2'], q_opts=dict(f_res = 6.96, **q_opts)) # subsystem 4: Q3 readout resonator ro3 = Subsystem(name='readout3', sys_type='TL_RESONATOR', nodes=['readout3'], q_opts=dict(f_res = 6.98, **q_opts)) # subsystem 15: Q2-Q3 coupling resonator coup23 = Subsystem(name='coupler23', sys_type='TL_RESONATOR', nodes=['coupler23'], q_opts=dict(f_res = 7.36, **q_opts)) composite_sys = CompositeSystem( subsystems=[transmon2, transmon3, coup23, ro2, ro3], cells=[cell_2, cell_3], grd_node='ground_main_plane', nodes_force_keep=['readout2', 'readout3', 'coupler23'] ) cg = composite_sys.circuitGraph() print(cg) hilbertspace = composite_sys.create_hilbertspace() print(hilbertspace) # Convert the hilbert space into # "Interaction Picture" hilbertspace = composite_sys.add_interaction() hilbertspace.hamiltonian() hamiltonian_results = composite_sys.hamiltonian_results(hilbertspace, evals_count=30) composite_sys.compute_gs()
https://github.com/qiskit-community/community.qiskit.org
qiskit-community
from qiskit import * from qiskit.tools.visualization import plot_histogram import numpy as np q = QuantumRegister(1) c = ClassicalRegister(1) error = {} for n in range(1,11): # Create a blank circuit qc = QuantumCircuit(q,c) # Implement an approximate Hadamard theta = np.pi # here we incorrectly choose theta=pi for j in range(n): qc.rx(theta/n,q[0]) qc.rz(theta/n,q[0]) # We need to measure how good the above approximation is. Here's a simple way to do this. # Step 1: Use a real hadamard to cancel the above approximation. # For a good approximatuon, the qubit will return to state 0. For a bad one, it will end up as some superposition. qc.h(q[0]) # Step 2: Run the circuit, and see how many times we get the outcome 1. # Since it should return 0 with certainty, the fraction of 1s is a measure of the error. qc.measure(q,c) shots = 20000 job = execute(qc, Aer.get_backend('qasm_simulator'),shots=shots) try: error[n] = (job.result().get_counts()['1']/shots) except: pass plot_histogram(error)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the CX Direction pass""" import unittest from math import pi import ddt from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, pulse from qiskit.circuit import Parameter, Gate from qiskit.circuit.library import ( CXGate, CZGate, ECRGate, RXXGate, RYYGate, RZXGate, RZZGate, SwapGate, ) from qiskit.compiler import transpile from qiskit.transpiler import TranspilerError, CouplingMap, Target from qiskit.transpiler.passes import GateDirection from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase @ddt.ddt class TestGateDirection(QiskitTestCase): """Tests the GateDirection pass.""" def test_no_cnots(self): """Trivial map in a circuit without entanglement qr0:---[H]--- qr1:---[H]--- qr2:---[H]--- CouplingMap map: None """ qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.h(qr) coupling = CouplingMap() dag = circuit_to_dag(circuit) pass_ = GateDirection(coupling) after = pass_.run(dag) self.assertEqual(dag, after) def test_direction_error(self): """The mapping cannot be fixed by direction mapper qr0:--------- qr1:---(+)--- | qr2:----.---- CouplingMap map: [2] <- [0] -> [1] """ qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[2]) coupling = CouplingMap([[0, 1], [0, 2]]) dag = circuit_to_dag(circuit) pass_ = GateDirection(coupling) with self.assertRaises(TranspilerError): pass_.run(dag) def test_direction_correct(self): """The CX is in the right direction qr0:---(+)--- | qr1:----.---- CouplingMap map: [0] -> [1] """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) coupling = CouplingMap([[0, 1]]) dag = circuit_to_dag(circuit) pass_ = GateDirection(coupling) after = pass_.run(dag) self.assertEqual(dag, after) def test_direction_flip(self): """Flip a CX qr0:----.---- | qr1:---(+)--- CouplingMap map: [0] -> [1] qr0:-[H]-(+)-[H]-- | qr1:-[H]--.--[H]-- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) coupling = CouplingMap([[0, 1]]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.h(qr[0]) expected.h(qr[1]) expected.cx(qr[0], qr[1]) expected.h(qr[0]) expected.h(qr[1]) pass_ = GateDirection(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_ecr_flip(self): """Flip a ECR gate. ┌──────┐ q_0: ┤1 ├ │ ECR │ q_1: ┤0 ├ └──────┘ CouplingMap map: [0, 1] """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.ecr(qr[1], qr[0]) coupling = CouplingMap([[0, 1]]) dag = circuit_to_dag(circuit) # ┌─────────┐ ┌──────┐┌───┐ # qr_0: ┤ Ry(π/2) ├─┤0 ├┤ H ├ # ├─────────┴┐│ Ecr │├───┤ # qr_1: ┤ Ry(-π/2) ├┤1 ├┤ H ├ # └──────────┘└──────┘└───┘ expected = QuantumCircuit(qr) expected.ry(pi / 2, qr[0]) expected.ry(-pi / 2, qr[1]) expected.ecr(qr[0], qr[1]) expected.h(qr[0]) expected.h(qr[1]) pass_ = GateDirection(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_flip_with_measure(self): """ qr0: -(+)-[m]- | | qr1: --.---|-- | cr0: ------.-- CouplingMap map: [0] -> [1] qr0: -[H]--.--[H]-[m]- | | qr1: -[H]-(+)-[H]--|-- | cr0: --------------.-- """ qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.cx(qr[1], qr[0]) circuit.measure(qr[0], cr[0]) coupling = CouplingMap([[0, 1]]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr, cr) expected.h(qr[0]) expected.h(qr[1]) expected.cx(qr[0], qr[1]) expected.h(qr[0]) expected.h(qr[1]) expected.measure(qr[0], cr[0]) pass_ = GateDirection(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_preserves_conditions(self): """Verify GateDirection preserves conditional on CX gates. ┌───┐ ┌───┐ q_0: |0>───■────┤ X ├───■──┤ X ├ ┌─┴─┐ └─┬─┘ ┌─┴─┐└─┬─┘ q_1: |0>─┤ X ├────■───┤ X ├──■── └─┬─┘ │ └───┘ ┌──┴──┐┌──┴──┐ c_0: 0 ╡ = 0 ╞╡ = 0 ╞══════════ └─────┘└─────┘ """ qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circuit = QuantumCircuit(qr, cr) circuit.cx(qr[0], qr[1]).c_if(cr, 0) circuit.cx(qr[1], qr[0]).c_if(cr, 0) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) coupling = CouplingMap([[0, 1]]) dag = circuit_to_dag(circuit) # ┌───┐ ┌───┐ ┌───┐ ┌───┐ # q_0: ───■───────────┤ H ├────■───────────┤ H ├───■──┤ H ├──■──┤ H ├ # ┌─┴─┐ ┌───┐ └─╥─┘ ┌─┴─┐ ┌───┐ └─╥─┘ ┌─┴─┐├───┤┌─┴─┐├───┤ # q_1: ─┤ X ├──┤ H ├────╫────┤ X ├──┤ H ├────╫───┤ X ├┤ H ├┤ X ├┤ H ├ # └─╥─┘ └─╥─┘ ║ └─╥─┘ └─╥─┘ ║ └───┘└───┘└───┘└───┘ # ┌──╨──┐┌──╨──┐┌──╨──┐┌──╨──┐┌──╨──┐┌──╨──┐ # c: 1/╡ 0x0 ╞╡ 0x0 ╞╡ 0x0 ╞╡ 0x0 ╞╡ 0x0 ╞╡ 0x0 ╞════════════════════ # └─────┘└─────┘└─────┘└─────┘└─────┘└─────┘ expected = QuantumCircuit(qr, cr) expected.cx(qr[0], qr[1]).c_if(cr, 0) # Order of H gates is important because DAG comparison will consider # different conditional order on a creg to be a different circuit. # See https://github.com/Qiskit/qiskit-terra/issues/3164 expected.h(qr[1]).c_if(cr, 0) expected.h(qr[0]).c_if(cr, 0) expected.cx(qr[0], qr[1]).c_if(cr, 0) expected.h(qr[1]).c_if(cr, 0) expected.h(qr[0]).c_if(cr, 0) expected.cx(qr[0], qr[1]) expected.h(qr[1]) expected.h(qr[0]) expected.cx(qr[0], qr[1]) expected.h(qr[1]) expected.h(qr[0]) pass_ = GateDirection(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_regression_gh_8387(self): """Regression test for flipping of CZ gate""" qc = QuantumCircuit(3) qc.cz(1, 0) qc.barrier() qc.cz(2, 0) coupling_map = CouplingMap([[0, 1], [1, 2]]) _ = transpile( qc, basis_gates=["cz", "cx", "u3", "u2", "u1"], coupling_map=coupling_map, optimization_level=2, ) @ddt.data(CXGate(), CZGate(), ECRGate()) def test_target_static(self, gate): """Test that static 2q gates are swapped correctly both if available and not available.""" circuit = QuantumCircuit(2) circuit.append(gate, [0, 1], []) matching = Target(num_qubits=2) matching.add_instruction(gate, {(0, 1): None}) self.assertEqual(GateDirection(None, target=matching)(circuit), circuit) swapped = Target(num_qubits=2) swapped.add_instruction(gate, {(1, 0): None}) self.assertNotEqual(GateDirection(None, target=swapped)(circuit), circuit) @ddt.data(CZGate(), RZXGate(pi / 3), RXXGate(pi / 3), RYYGate(pi / 3), RZZGate(pi / 3)) def test_target_trivial(self, gate): """Test that trivial 2q gates are swapped correctly both if available and not available.""" circuit = QuantumCircuit(2) circuit.append(gate, [0, 1], []) matching = Target(num_qubits=2) matching.add_instruction(gate, {(0, 1): None}) self.assertEqual(GateDirection(None, target=matching)(circuit), circuit) swapped = Target(num_qubits=2) swapped.add_instruction(gate, {(1, 0): None}) self.assertNotEqual(GateDirection(None, target=swapped)(circuit), circuit) @ddt.data(CZGate(), SwapGate(), RXXGate(pi / 3), RYYGate(pi / 3), RZZGate(pi / 3)) def test_symmetric_gates(self, gate): """Test symmetric gates on single direction coupling map.""" circuit = QuantumCircuit(2) circuit.append(gate, [1, 0], []) expected = QuantumCircuit(2) expected.append(gate, [0, 1], []) coupling = CouplingMap.from_line(2, bidirectional=False) pass_ = GateDirection(coupling) self.assertEqual(pass_(circuit), expected) def test_target_parameter_any(self): """Test that a parametrised 2q gate is replaced correctly both if available and not available.""" circuit = QuantumCircuit(2) circuit.rzx(1.5, 0, 1) matching = Target(num_qubits=2) matching.add_instruction(RZXGate(Parameter("a")), {(0, 1): None}) self.assertEqual(GateDirection(None, target=matching)(circuit), circuit) swapped = Target(num_qubits=2) swapped.add_instruction(RZXGate(Parameter("a")), {(1, 0): None}) self.assertNotEqual(GateDirection(None, target=swapped)(circuit), circuit) def test_target_parameter_exact(self): """Test that a parametrised 2q gate is detected correctly both if available and not available.""" circuit = QuantumCircuit(2) circuit.rzx(1.5, 0, 1) matching = Target(num_qubits=2) matching.add_instruction(RZXGate(1.5), {(0, 1): None}) self.assertEqual(GateDirection(None, target=matching)(circuit), circuit) swapped = Target(num_qubits=2) swapped.add_instruction(RZXGate(1.5), {(1, 0): None}) self.assertNotEqual(GateDirection(None, target=swapped)(circuit), circuit) def test_target_parameter_mismatch(self): """Test that the pass raises if a gate is not supported due to a parameter mismatch.""" circuit = QuantumCircuit(2) circuit.rzx(1.5, 0, 1) matching = Target(num_qubits=2) matching.add_instruction(RZXGate(2.5), {(0, 1): None}) pass_ = GateDirection(None, target=matching) with self.assertRaises(TranspilerError): pass_(circuit) swapped = Target(num_qubits=2) swapped.add_instruction(RZXGate(2.5), {(1, 0): None}) pass_ = GateDirection(None, target=swapped) with self.assertRaises(TranspilerError): pass_(circuit) def test_coupling_map_control_flow(self): """Test that gates are replaced within nested control-flow blocks.""" circuit = QuantumCircuit(4, 1) circuit.h(0) circuit.measure(0, 0) with circuit.for_loop((1, 2)): circuit.cx(1, 0) circuit.cx(0, 1) with circuit.if_test((circuit.clbits[0], True)) as else_: circuit.ecr(3, 2) with else_: with circuit.while_loop((circuit.clbits[0], True)): circuit.rzx(2.3, 2, 1) expected = QuantumCircuit(4, 1) expected.h(0) expected.measure(0, 0) with expected.for_loop((1, 2)): expected.h([0, 1]) expected.cx(0, 1) expected.h([0, 1]) expected.cx(0, 1) with expected.if_test((circuit.clbits[0], True)) as else_: expected.ry(pi / 2, 2) expected.ry(-pi / 2, 3) expected.ecr(2, 3) expected.h([2, 3]) with else_: with expected.while_loop((circuit.clbits[0], True)): expected.h([1, 2]) expected.rzx(2.3, 1, 2) expected.h([1, 2]) coupling = CouplingMap.from_line(4, bidirectional=False) pass_ = GateDirection(coupling) self.assertEqual(pass_(circuit), expected) def test_target_control_flow(self): """Test that gates are replaced within nested control-flow blocks.""" circuit = QuantumCircuit(4, 1) circuit.h(0) circuit.measure(0, 0) with circuit.for_loop((1, 2)): circuit.cx(1, 0) circuit.cx(0, 1) with circuit.if_test((circuit.clbits[0], True)) as else_: circuit.ecr(3, 2) with else_: with circuit.while_loop((circuit.clbits[0], True)): circuit.rzx(2.3, 2, 1) expected = QuantumCircuit(4, 1) expected.h(0) expected.measure(0, 0) with expected.for_loop((1, 2)): expected.h([0, 1]) expected.cx(0, 1) expected.h([0, 1]) expected.cx(0, 1) with expected.if_test((circuit.clbits[0], True)) as else_: expected.ry(pi / 2, 2) expected.ry(-pi / 2, 3) expected.ecr(2, 3) expected.h([2, 3]) with else_: with expected.while_loop((circuit.clbits[0], True)): expected.h([1, 2]) expected.rzx(2.3, 1, 2) expected.h([1, 2]) target = Target(num_qubits=4) target.add_instruction(CXGate(), {(0, 1): None}) target.add_instruction(ECRGate(), {(2, 3): None}) target.add_instruction(RZXGate(Parameter("a")), {(1, 2): None}) pass_ = GateDirection(None, target) self.assertEqual(pass_(circuit), expected) def test_target_cannot_flip_message(self): """A suitable error message should be emitted if the gate would be supported if it were flipped.""" gate = Gate("my_2q_gate", 2, []) target = Target(num_qubits=2) target.add_instruction(gate, properties={(0, 1): None}) circuit = QuantumCircuit(2) circuit.append(gate, (1, 0)) pass_ = GateDirection(None, target) with self.assertRaisesRegex(TranspilerError, "'my_2q_gate' would be supported.*"): pass_(circuit) def test_target_cannot_flip_message_calibrated(self): """A suitable error message should be emitted if the gate would be supported if it were flipped.""" target = Target(num_qubits=2) target.add_instruction(CXGate(), properties={(0, 1): None}) gate = Gate("my_2q_gate", 2, []) circuit = QuantumCircuit(2) circuit.append(gate, (1, 0)) circuit.add_calibration(gate, (0, 1), pulse.ScheduleBlock()) pass_ = GateDirection(None, target) with self.assertRaisesRegex(TranspilerError, "'my_2q_gate' would be supported.*"): pass_(circuit) def test_target_unknown_gate_message(self): """A suitable error message should be emitted if the gate isn't valid in either direction on the target.""" gate = Gate("my_2q_gate", 2, []) target = Target(num_qubits=2) target.add_instruction(CXGate(), properties={(0, 1): None}) circuit = QuantumCircuit(2) circuit.append(gate, (0, 1)) pass_ = GateDirection(None, target) with self.assertRaisesRegex(TranspilerError, "'my_2q_gate'.*not supported on qubits .*"): pass_(circuit) def test_allows_calibrated_gates_coupling_map(self): """Test that the gate direction pass allows a gate that's got a calibration to pass through without error.""" cm = CouplingMap([(1, 0)]) gate = Gate("my_2q_gate", 2, []) circuit = QuantumCircuit(2) circuit.append(gate, (0, 1)) circuit.add_calibration(gate, (0, 1), pulse.ScheduleBlock()) pass_ = GateDirection(cm) self.assertEqual(pass_(circuit), circuit) def test_allows_calibrated_gates_target(self): """Test that the gate direction pass allows a gate that's got a calibration to pass through without error.""" target = Target(num_qubits=2) target.add_instruction(CXGate(), properties={(0, 1): None}) gate = Gate("my_2q_gate", 2, []) circuit = QuantumCircuit(2) circuit.append(gate, (0, 1)) circuit.add_calibration(gate, (0, 1), pulse.ScheduleBlock()) pass_ = GateDirection(None, target) self.assertEqual(pass_(circuit), circuit) if __name__ == "__main__": unittest.main()
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. """Variational Quantum Imaginary Time Evolution algorithm.""" from __future__ import annotations from collections.abc import Mapping, Sequence from typing import Type, Callable import numpy as np from scipy.integrate import OdeSolver from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.primitives import BaseEstimator from .solvers.ode.forward_euler_solver import ForwardEulerSolver from .variational_principles import ImaginaryVariationalPrinciple, ImaginaryMcLachlanPrinciple from .var_qte import VarQTE from ..imaginary_time_evolver import ImaginaryTimeEvolver class VarQITE(VarQTE, ImaginaryTimeEvolver): """Variational Quantum Imaginary Time Evolution algorithm. .. code-block::python import numpy as np from qiskit_algorithms import TimeEvolutionProblem, VarQITE from qiskit_algorithms.time_evolvers.variational import ImaginaryMcLachlanPrinciple from qiskit.circuit.library import EfficientSU2 from qiskit.quantum_info import SparsePauliOp, Pauli from qiskit.primitives import Estimator observable = SparsePauliOp.from_list( [ ("II", 0.2252), ("ZZ", 0.5716), ("IZ", 0.3435), ("ZI", -0.4347), ("YY", 0.091), ("XX", 0.091), ] ) ansatz = EfficientSU2(observable.num_qubits, reps=1) init_param_values = np.ones(len(ansatz.parameters)) * np.pi/2 var_principle = ImaginaryMcLachlanPrinciple() time = 1 # without evaluating auxiliary operators evolution_problem = TimeEvolutionProblem(observable, time) var_qite = VarQITE(ansatz, init_param_values, var_principle) evolution_result = var_qite.evolve(evolution_problem) # evaluating auxiliary operators aux_ops = [Pauli("XX"), Pauli("YZ")] evolution_problem = TimeEvolutionProblem(observable, time, aux_operators=aux_ops) var_qite = VarQITE(ansatz, init_param_values, var_principle, Estimator()) evolution_result = var_qite.evolve(evolution_problem) """ def __init__( self, ansatz: QuantumCircuit, initial_parameters: Mapping[Parameter, float] | Sequence[float], variational_principle: ImaginaryVariationalPrinciple | None = None, estimator: BaseEstimator | None = None, ode_solver: Type[OdeSolver] | str = ForwardEulerSolver, lse_solver: Callable[[np.ndarray, np.ndarray], np.ndarray] | None = None, num_timesteps: int | None = None, imag_part_tol: float = 1e-7, num_instability_tol: float = 1e-7, ) -> None: r""" Args: ansatz: Ansatz to be used for variational time evolution. initial_parameters: Initial parameter values for the ansatz. variational_principle: Variational Principle to be used. Defaults to ``ImaginaryMcLachlanPrinciple``. estimator: An estimator primitive used for calculating expectation values of TimeEvolutionProblem.aux_operators. ode_solver: ODE solver callable that implements a SciPy ``OdeSolver`` interface or a string indicating a valid method offered by SciPy. lse_solver: Linear system of equations solver callable. It accepts ``A`` and ``b`` to solve ``Ax=b`` and returns ``x``. If ``None``, the default ``np.linalg.lstsq`` solver is used. num_timesteps: The number of timesteps to take. If ``None``, it is automatically selected to achieve a timestep of approximately 0.01. Only relevant in case of the ``ForwardEulerSolver``. imag_part_tol: Allowed value of an imaginary part that can be neglected if no imaginary part is expected. num_instability_tol: The amount of negative value that is allowed to be rounded up to 0 for quantities that are expected to be non-negative. """ if variational_principle is None: variational_principle = ImaginaryMcLachlanPrinciple() super().__init__( ansatz, initial_parameters, variational_principle, estimator, ode_solver, lse_solver=lse_solver, num_timesteps=num_timesteps, imag_part_tol=imag_part_tol, num_instability_tol=num_instability_tol, )
https://github.com/tomtuamnuq/compare-qiskit-ocean
tomtuamnuq
import time from dwave.system import DWaveCliqueSampler from qiskit_optimization.algorithms import CplexOptimizer from utilities.helpers import create_dwave_meo, create_quadratic_programs_from_paths DIR = 'TEST_DATA' + "/" + time.strftime("%d_%m_%Y") DIR # select linear programs to solve qps = create_quadratic_programs_from_paths(DIR + "/DENSE/", True) qp_dense = qps['test_80'] qps = create_quadratic_programs_from_paths(DIR + "/SPARSE/", True) qp_sparse = qps['test_100'] # init Optimizers cplex = CplexOptimizer() clique = create_dwave_meo(DWaveCliqueSampler()) clique.min_eigen_solver.sampler.set_label("clique_dense_80") dwave_auto = create_dwave_meo() dwave_auto.min_eigen_solver.sampler.set_label("dwave_sparse_100") # solve classically cplex.solve(qp_dense) cplex.solve(qp_sparse) # solve quantum clique embedding for dense problems res_clique = clique.solve(qp_dense) res_clique # solve quantum: automatically searches for embedding res_dwave = dwave_auto.solve(qp_sparse) res_dwave
https://github.com/hritiksauw199/Optimized-Shor-Algorithm-for-factoring
hritiksauw199
import matplotlib.pyplot as plt import numpy as np from qiskit import IBMQ, QuantumCircuit, Aer, transpile, assemble from qiskit.visualization import plot_histogram from math import gcd from numpy.random import randint import pandas as pd from qiskit.providers.ibmq import least_busy from fractions import Fraction def qft_inv(n): qc = QuantumCircuit(n) for qubit in range(n//2): qc.swap(qubit, n-qubit-1) for j in range(n): for m in range(j): qc.cp(-np.pi/float(2**(j-m)), m, j) qc.h(j) qc.name = "QFT_INV" return qc n_count = 3 n = 5 qc = QuantumCircuit(n_count+2, n_count) for q in range(n_count): qc.h(q) qc.cx(2,4) qc.cx(1,4) qc.cx(4,3) qc.ccx(1,3,4) qc.cx(4,3) qc.x(4) qc.cswap(3,0,4) qc.x(4) qc.cx(4,3) qc.ccx(0,3,4) qc.cx(4,3) qc.barrier() qc.append(qft_inv(n_count), range(n_count)) qc.measure(range(n_count), range(n_count)) qc.draw() aer_sim = Aer.get_backend('aer_simulator') t_qc = transpile(qc, aer_sim) qobj = assemble(t_qc) results = aer_sim.run(qobj).result() counts = results.get_counts() plot_histogram(counts) # Load our saved IBMQ accounts and get the least busy backend device with less than or equal to 5 qubits IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= n and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Execute and monitor the job from qiskit.tools.monitor import job_monitor shots = 1024 transpiled_simon_circuit = transpile(qc, backend, optimization_level=3) qobj = assemble(transpiled_simon_circuit, shots=shots) job = backend.run(qobj) job_monitor(job, interval=2) # Get results and plot counts device_counts = job.result().get_counts() plot_histogram(device_counts) rows, measured_phases = [], [] for output in counts: decimal = int(output, 2) # Convert (base 2) string to decimal phase = decimal/(2**n_count) # Find corresponding eigenvalue measured_phases.append(phase) # Add these values to the rows in our table: rows.append([f"{output}(bin) = {decimal:>3}(dec)", f"{decimal}/{2**n_count} = {phase:.2f}"]) # Print the rows in a table headers=["Register Output", "Phase"] df = pd.DataFrame(rows, columns=headers) print(df) rows = [] for phase in measured_phases: frac = Fraction(phase).limit_denominator(15) rows.append([phase, f"{frac.numerator}/{frac.denominator}", frac.denominator]) # Print as a table headers=["Phase", "Fraction", "Guess for r"] df = pd.DataFrame(rows, columns=headers) print(df) rows, measured_phases = [], [] for output in device_counts: decimal = int(output, 2) # Convert (base 2) string to decimal phase = decimal/(2**n_count) # Find corresponding eigenvalue measured_phases.append(phase) # Add these values to the rows in our table: rows.append([f"{output}(bin) = {decimal:>3}(dec)", f"{decimal}/{2**n_count} = {phase:.2f}"]) # Print the rows in a table headers=["Register Output", "Phase"] df = pd.DataFrame(rows, columns=headers) print(df) rows = [] for phase in measured_phases: frac = Fraction(phase).limit_denominator(15) rows.append([phase, f"{frac.numerator}/{frac.denominator}", frac.denominator]) # Print as a table headers=["Phase", "Fraction", "Guess for r"] df = pd.DataFrame(rows, columns=headers) print(df)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Operator from qiskit.transpiler.passes import UnitarySynthesis circuit = QuantumCircuit(1) circuit.rx(0.8, 0) unitary = Operator(circuit).data unitary_circ = QuantumCircuit(1) unitary_circ.unitary(unitary, [0]) synth = UnitarySynthesis(basis_gates=["h", "s"], method="sk") out = synth(unitary_circ) out.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/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit_aer import AerSimulator from qiskit.visualization import plot_histogram # Use Aer's AerSimulator simulator = AerSimulator() # Create a Quantum Circuit acting on the q register circuit = QuantumCircuit(2, 2) # Add a H gate on qubit 0 circuit.h(0) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1 circuit.cx(0, 1) # Map the quantum measurement to the classical bits circuit.measure([0, 1], [0, 1]) # Compile the circuit for the support instruction set (basis_gates) # and topology (coupling_map) of the backend compiled_circuit = transpile(circuit, simulator) # Execute the circuit on the aer simulator job = simulator.run(compiled_circuit, shots=1000) # Grab results from the job result = job.result() # Returns counts counts = result.get_counts(compiled_circuit) print("\nTotal count for 00 and 11 are:", counts) # Draw the circuit circuit.draw() # Plot a histogram plot_histogram(counts) circuit.draw() simulator = AerSimulator() compiled_circuit = transpile(circuit, simulator) job = simulator.run(compiled_circuit, shots=1000) result = job.result() counts = result.get_counts(circuit) print("\nTotal count for 00 and 11 are:",counts) plot_histogram(counts)
https://github.com/nmoran/qiskit-qdrift-quid19
nmoran
import numpy as np import matplotlib.pyplot as plt import math from qiskit import Aer, IBMQ, QuantumRegister, QuantumCircuit from qiskit.providers.ibmq import least_busy from qiskit.providers.aer import noise # lib from Qiskit Aqua from qiskit.aqua.operators.common import evolution_instruction from qiskit.aqua import Operator, QuantumInstance from qiskit.aqua.algorithms import VQE, ExactEigensolver from qiskit.aqua.components.optimizers import COBYLA, SPSA, L_BFGS_B from qiskit.aqua.components.variational_forms import RY, RYRZ, SwapRZ # lib from Qiskit Aqua Chemistry from qiskit.chemistry import QiskitChemistry from qiskit.chemistry import FermionicOperator from qiskit.chemistry.drivers import PySCFDriver, UnitsType from qiskit.chemistry.aqua_extensions.components.variational_forms import UCCSD from qiskit.chemistry.aqua_extensions.components.initial_states import HartreeFock driver = PySCFDriver(atom='H .0 .0 .0; Li .0 .0 1.6', unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') molecule = driver.run() nuclear_repulsion_energy = molecule.nuclear_repulsion_energy num_particles = molecule.num_alpha + molecule.num_beta num_spin_orbitals = molecule.num_orbitals * 2 print('HF Done') h1 = molecule.one_body_integrals h2 = molecule.two_body_integrals ferOp = FermionicOperator(h1=h1, h2=h2) map_type='jordan_wigner' qubitOp = ferOp.mapping(map_type=map, threshold=10**-10) qubitOp.chop(10**-10) num_terms = len(qubitOp.paulis) max_term = max([np.abs(qubitOp.paulis[i][0]) for i in range(num_terms)]) error=.01 norm = 0 probs = [] for i in range(len(qubitOp.paulis)): norm += np.abs(qubitOp.paulis[i][0]) for i in range(len(qubitOp.paulis)): probs.append(np.abs(qubitOp.paulis[i][0])/norm) runs = 10 print('start of big loop') times = np.linspace(.01,.1,10) qdrift_av_counts=[] trotter_counts=[] #iterate through the list of durations for time_idx in range(len(times)): qdrift_gate_counts = [] num_time_slices = math.ceil((num_terms*max_term*times[time_idx])**2 / 2*error) #Iterate (runs) numbers of time to get average data for run in range(runs): random_pauli_list=[] #the number of steps from the norm, time, and error num_steps = math.ceil((2*norm*times[time_idx])**2 /error) standard_timestep = times[time_idx]*norm/num_steps for i in range(num_steps): idx = np.random.choice(num_terms,p=probs) #form the list keeping track of the sign of the coefficients random_pauli_list.append([np.sign(qubitOp.paulis[idx][0])*standard_timestep,qubitOp.paulis[idx][1]]) instruction_qdrift=evolution_instruction(random_pauli_list, evo_time=1, num_time_slices=1, controlled=False, power=1, use_basis_gates=True, shallow_slicing=False) print('completed {} qdrift evolution_instructions'.format(str(time_idx))) quantum_registers_qdrift = QuantumRegister(qubitOp.num_qubits) qc_qdrift = QuantumCircuit(quantum_registers_qdrift) qc_qdrift.append(instruction_qdrift, quantum_registers_qdrift) qc_qdrift = qc_qdrift.decompose() total_qdrift = 0 try: total_qdrift+=qc_qdrift.count_ops()['cx'] except: pass try: total_qdrift+=qc_qdrift.count_ops()['u1'] except: pass try: total_qdrift+=qc_qdrift.count_ops()['u2'] except: pass try: total_qdrift+=qc_qdrift.count_ops()['u3'] except: pass qdrift_gate_counts.append(total_qdrift) print('start of trotter evolution instruction') instruction_trotter=evolution_instruction(qubitOp.paulis, evo_time=times[time_idx], num_time_slices=num_time_slices, controlled=False, power=1, use_basis_gates=True, shallow_slicing=False) print('end of trotter evolution instruction - on to circuit construction') quantum_registers_trotter = QuantumRegister(qubitOp.num_qubits) qc_trotter = QuantumCircuit(quantum_registers_trotter) qc_trotter.append(instruction_trotter, quantum_registers_trotter) qc_trotter = qc_trotter.decompose() total_trotter = 0 try: total_trotter+=qc_trotter.count_ops()['cx'] except: pass try: total_trotter+=qc_trotter.count_ops()['u1'] except: pass try: total_trotter+=qc_trotter.count_ops()['u2'] except: pass try: total_trotter+=qc_trotter.count_ops()['u3'] except: pass trotter_counts.append(total_trotter) qdrift_av_counts.append(sum(qdrift_gate_counts)/len(qdrift_gate_counts)) print('got through {} iterations'.format(str(time_idx))) plt.plot(times,qdrift_av_counts,label='qdrift_avg_counts') plt.plot(times,trotter_counts,label = 'trotter_counts') plt.title('Gates vs Duration for Time Evol({})'.format(map_type)) plt.xlabel("Duration of evolution") plt.ylabel("Number of Gates") plt.legend(loc=0) plt.yscale('log') plt.savefig("LiH_gates_v_time_{}.png".format(map_type), dpi=600)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_optimization import QuadraticProgram qp = QuadraticProgram() qp.binary_var("x") qp.binary_var("y") qp.integer_var(lowerbound=0, upperbound=7, name="z") qp.maximize(linear={"x": 2, "y": 1, "z": 1}) qp.linear_constraint(linear={"x": 1, "y": 1, "z": 1}, sense="LE", rhs=5.5, name="xyz_leq") qp.linear_constraint(linear={"x": 1, "y": 1, "z": 1}, sense="GE", rhs=2.5, name="xyz_geq") print(qp.prettyprint()) from qiskit_optimization.converters import InequalityToEquality ineq2eq = InequalityToEquality() qp_eq = ineq2eq.convert(qp) print(qp_eq.prettyprint()) print(qp_eq.prettyprint()) from qiskit_optimization.converters import IntegerToBinary int2bin = IntegerToBinary() qp_eq_bin = int2bin.convert(qp_eq) print(qp_eq_bin.prettyprint()) print(qp_eq_bin.prettyprint()) from qiskit_optimization.converters import LinearEqualityToPenalty lineq2penalty = LinearEqualityToPenalty() qubo = lineq2penalty.convert(qp_eq_bin) print(qubo.prettyprint()) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Qiskit/feedback
Qiskit
%load_ext autoreload %autoreload 2 import numpy as np from qiskit.circuit.library import RealAmplitudes from qiskit.opflow import PauliSumOp observable = PauliSumOp.from_list( [ ("II", -1.052373245772859), ("IZ", 0.39793742484318045), ("ZI", -0.39793742484318045), ("ZZ", -0.01128010425623538), ("XX", 0.18093119978423156), ] ) print("observable") print(observable) ansatz = RealAmplitudes(num_qubits=2, reps=2) print("\nansatz") ansatz.decompose().draw("mpl") from qiskit.evaluators import PauliExpectationValue from qiskit.providers.aer import AerSimulator backend = AerSimulator() expval = PauliExpectationValue(ansatz, observable, backend=backend) expval.evaluate([0, 1, 1, 2, 3, 5], shots=1000) # multi prameters expval = PauliExpectationValue(ansatz, observable, backend=backend) expval.evaluate([[0, 1, 1, 2, 3, 5], [1, 1, 2, 3, 5, 8]], shots=3000) from qiskit.evaluators import ExactExpectationValue expval = ExactExpectationValue(ansatz, observable, backend=backend) expval.evaluate([0, 1, 1, 2, 3, 5]) expval = ExactExpectationValue(ansatz, observable, backend=backend) expval.evaluate(np.array([[0, 1, 1, 2, 3, 5], [1, 1, 2, 3, 5, 8]])) from qiskit.test.mock import FakeBogota backend = AerSimulator.from_backend(FakeBogota()) expval = PauliExpectationValue(ansatz, observable, backend=backend) expval.set_transpile_options(initial_layout=[3, 2]) print(expval.evaluate([0, 1, 1, 2, 3, 5])) expval.transpiled_circuits[0].draw("mpl") try: from qiskit import QuantumCircuit, QiskitError qc = QuantumCircuit(1, 1) qc.h(0) qc.measure(0, 0) from qiskit import IBMQ prov = IBMQ.load_account() ibmq_qasm_sim = prov.get_backend('ibmq_qasm_simulator') print(f"max_shots {backend.configuration().max_shots}") ibmq_qasm_sim.run(qc, shots=10000).result().get_counts() except QiskitError as ex: print(ex.message) expval = PauliExpectationValue(ansatz, observable, backend=ibmq_qasm_sim) expval.evaluate([0, 1, 1, 2, 3, 5], shots=10000) from qiskit.evaluators.backends import ReadoutErrorMitigation backend = AerSimulator.from_backend(FakeBogota()) mit_tensored = ReadoutErrorMitigation( backend, mitigation="tensored", refresh=600, shots=2000, mit_pattern=[[0], [1]] ) mit_mthree = ReadoutErrorMitigation( backend, mitigation="mthree", refresh=600, shots=2000, qubits=[0, 1] ) expval_raw = PauliExpectationValue(ansatz, observable, backend=backend) expval_tensored = PauliExpectationValue(ansatz, observable, backend=mit_tensored) expval_mthree = PauliExpectationValue(ansatz, observable, backend=mit_mthree) shots = 4000 print(f"w/o mitigation shots={shots}, result={expval_raw.evaluate([0, 1, 1, 2, 3, 5], shots=shots)}") print(f"w/ tensored mitigation shots={shots}, result={expval_tensored.evaluate([0, 1, 1, 2, 3, 5], shots=shots)}") print(f"w/ M3 mitigation shots={shots}, result={expval_mthree.evaluate([0, 1, 1, 2, 3, 5], shots=shots)}") from qiskit.evaluators.expectation_value.expectation_value_gradient import ( FiniteDiffGradient, ParameterShiftGradient, ) parameters = [0, 1, 1, 2, 3, 5] exact_expval = ExactExpectationValue(ansatz, observable, backend=AerSimulator()) exact_findiff = FiniteDiffGradient(exact_expval, 1e-8) print(f"fin diff of exact {exact_findiff.evaluate(parameters).values}") exact_expval = ExactExpectationValue(ansatz, observable, backend=AerSimulator()) exact_findiff = ParameterShiftGradient(exact_expval) print(f"param shift of exact {exact_findiff.evaluate([0, 1, 1, 2, 3, 5]).values}") shots = 2000 findiff = FiniteDiffGradient(expval_raw, 1e-1) paramshift = ParameterShiftGradient(expval_raw) print(f"fin diff w/o mit {findiff.evaluate(parameters, shots=shots).values}") print(f"param shift w/o mit {paramshift.evaluate(parameters, shots=shots).values}") findiff = FiniteDiffGradient(expval_mthree, 1e-1) paramshift = ParameterShiftGradient(expval_mthree) print(f"fin diff w/ mit {findiff.evaluate([0, 1, 1, 2, 3, 5], shots=shots).values}") print(f"param shift w/ mit {paramshift.evaluate(parameters, shots=shots).values}") from scipy.optimize import minimize shots = 1000 expval = PauliExpectationValue(ansatz, observable, backend=AerSimulator(), append=True) paramshift = ParameterShiftGradient(expval) # this may take a long time... result = minimize( lambda x: expval.evaluate(x, shots=shots, seed_simulator=123).value, np.zeros(6), jac=lambda x: paramshift.evaluate(x, shots=shots, seed_simulator=123).values, ) print(result) import matplotlib.pyplot as plt from qiskit.evaluators.results import ExpectationValueResult plt.figure(figsize=(12, 8)) y = [h.value for h in expval.history if isinstance(h, ExpectationValueResult)] x = list(range(len(y))) yerr = np.array( [tuple(abs(c - h.value) for c in h.confidence_interval) for h in expval.history if isinstance(h, ExpectationValueResult)] ).transpose() plt.plot(y, color="blue") plt.errorbar(x, y, yerr=yerr, capsize=5, fmt="o", markersize=8, ecolor="blue", markeredgecolor="blue", color="w") plt.xlabel("Eval count") plt.ylabel("Energy") plt.show()
https://github.com/unitaryfund/mitiq
unitaryfund
# Copyright (C) Unitary Fund # # This source code is licensed under the GPL license (v3) found in the # LICENSE file in the root directory of this source tree. """Tests for circuit conversions.""" from typing import List import cirq import numpy as np import pennylane as qml import pytest import qibo import qiskit from braket.circuits import Circuit as BKCircuit from braket.circuits import Instruction from braket.circuits import gates as braket_gates from pyquil import Program, gates from mitiq import SUPPORTED_PROGRAM_TYPES from mitiq.interface import ( UnsupportedCircuitError, accept_any_qprogram_as_input, accept_qprogram_and_validate, atomic_one_to_many_converter, convert_from_mitiq, convert_to_mitiq, register_mitiq_converters, ) from mitiq.interface.mitiq_qiskit import from_qasm, to_qasm from mitiq.utils import _equal QASMType = str # Cirq Bell circuit. cirq_qreg = cirq.LineQubit.range(2) cirq_circuit = cirq.Circuit( cirq.ops.H.on(cirq_qreg[0]), cirq.ops.CNOT.on(*cirq_qreg) ) # Qiskit Bell circuit. qiskit_qreg = qiskit.QuantumRegister(2) qiskit_circuit = qiskit.QuantumCircuit(qiskit_qreg) qiskit_circuit.h(qiskit_qreg[0]) qiskit_circuit.cx(*qiskit_qreg) qasm_str = qiskit.qasm2.dumps(qiskit_circuit) # pyQuil Bell circuit. pyquil_circuit = Program(gates.H(0), gates.CNOT(0, 1)) # Braket Bell circuit. braket_circuit = BKCircuit( [ Instruction(braket_gates.H(), 0), Instruction(braket_gates.CNot(), [0, 1]), ] ) circuit_types = { "cirq": cirq.Circuit, "qiskit": qiskit.QuantumCircuit, "pyquil": Program, "braket": BKCircuit, "pennylane": qml.tape.QuantumTape, "qibo": qibo.models.circuit.Circuit, } @accept_qprogram_and_validate def scaling_function(circ: cirq.Circuit, *args, **kwargs) -> cirq.Circuit: return circ def one_to_many_circuit_modifier( circ: cirq.Circuit, *args, **kwargs ) -> List[cirq.Circuit]: return [circ, circ[0:1] + circ] # Apply one-to-many decorator one_to_many_circuit_modifier = accept_qprogram_and_validate( one_to_many_circuit_modifier, one_to_many=True, ) @accept_any_qprogram_as_input def get_wavefunction(circ: cirq.Circuit) -> np.ndarray: return circ.final_state_vector() @atomic_one_to_many_converter def returns_several_circuits(circ: cirq.Circuit, *args, **kwargs): return [circ] * 5 @pytest.mark.parametrize( "circuit", (qiskit_circuit, pyquil_circuit, braket_circuit) ) def test_to_mitiq(circuit): converted_circuit, input_type = convert_to_mitiq(circuit) assert _equal(converted_circuit, cirq_circuit) assert input_type in circuit.__module__ def test_register_from_to_mitiq(): class CircuitStr(str): __module__ = "qasm" qasm_circuit = CircuitStr(qasm_str) register_mitiq_converters( qasm_circuit.__module__, convert_to_function=to_qasm, convert_from_function=from_qasm, ) converted_circuit = convert_from_mitiq(cirq_circuit, "qasm") converted_qasm = CircuitStr(converted_circuit) circuit, input_type = convert_to_mitiq(converted_qasm) assert _equal(circuit, cirq_circuit) assert input_type == qasm_circuit.__module__ @pytest.mark.parametrize("item", ("circuit", 1, None)) def test_to_mitiq_bad_types(item): with pytest.raises( UnsupportedCircuitError, match="Could not determine the package of the input circuit.", ): convert_to_mitiq(item) @pytest.mark.parametrize("to_type", SUPPORTED_PROGRAM_TYPES.keys()) def test_from_mitiq(to_type): converted_circuit = convert_from_mitiq(cirq_circuit, to_type) circuit, input_type = convert_to_mitiq(converted_circuit) assert _equal(circuit, cirq_circuit) assert input_type == to_type def test_unsupported_circuit_error(): class CircuitStr(str): __module__ = "qasm" mock_circuit = CircuitStr("mock") with pytest.raises( UnsupportedCircuitError, match="Conversion to circuit type unsupported_circuit_type", ): convert_from_mitiq(mock_circuit, "unsupported_circuit_type") @pytest.mark.parametrize( "circuit_and_expected", [ (cirq.Circuit(cirq.X.on(cirq.LineQubit(0))), np.array([0, 1])), (cirq_circuit, np.array([1, 0, 0, 1]) / np.sqrt(2)), ], ) @pytest.mark.parametrize("to_type", SUPPORTED_PROGRAM_TYPES.keys()) def test_accept_any_qprogram_as_input(circuit_and_expected, to_type): circuit, expected = circuit_and_expected wavefunction = get_wavefunction(convert_from_mitiq(circuit, to_type)) assert np.allclose(wavefunction, expected) @pytest.mark.parametrize( "circuit_and_type", ( (qiskit_circuit, "qiskit"), (pyquil_circuit, "pyquil"), (braket_circuit, "braket"), ), ) def test_converter(circuit_and_type): circuit, input_type = circuit_and_type # Return the input type scaled = scaling_function(circuit) assert isinstance(scaled, circuit_types[input_type]) # Return a Cirq Circuit cirq_scaled = scaling_function(circuit, return_mitiq=True) assert isinstance(cirq_scaled, cirq.Circuit) assert _equal(cirq_scaled, cirq_circuit) @pytest.mark.parametrize("nbits", [1, 10]) @pytest.mark.parametrize("measure", [True, False]) def test_converter_keeps_register_structure_qiskit(nbits, measure): qreg = qiskit.QuantumRegister(nbits) creg = qiskit.ClassicalRegister(nbits) circ = qiskit.QuantumCircuit(qreg, creg) circ.h(qreg) if measure: circ.measure(qreg, creg) scaled = scaling_function(circ) assert scaled.qregs == circ.qregs assert scaled.cregs == circ.cregs assert scaled == circ @pytest.mark.parametrize("nbits", [1, 10]) @pytest.mark.parametrize("measure", [True, False]) def test_converter_keeps_register_structure_qiskit_one_to_many(nbits, measure): qreg = qiskit.QuantumRegister(nbits) creg = qiskit.ClassicalRegister(nbits) circ = qiskit.QuantumCircuit(qreg, creg) circ.h(qreg) if measure: circ.measure(qreg, creg) out_circuits = one_to_many_circuit_modifier(circ) for out_circ in out_circuits: assert out_circ.qregs == circ.qregs assert out_circ.cregs == circ.cregs print(out_circ) assert out_circuits[0] == circ assert out_circuits[1] != circ @pytest.mark.parametrize("to_type", SUPPORTED_PROGRAM_TYPES.keys()) def test_atomic_one_to_many_converter(to_type): circuit = convert_from_mitiq(cirq_circuit, to_type) circuits = returns_several_circuits(circuit) for circuit in circuits: assert isinstance(circuit, circuit_types[to_type]) circuits = returns_several_circuits(circuit, return_mitiq=True) for circuit in circuits: assert isinstance(circuit, cirq.Circuit) def test_noise_scaling_converter_with_qiskit_idle_qubits_and_barriers(): """Idle qubits must be preserved even if the input has barriers. Test input: ┌───┐ ░ q_0: ┤ X ├─░─ └───┘ ░ q_1: ──────░─ ┌───┐ ░ q_2: ┤ X ├─░─ └───┘ ░ q_3: ──────── Expected output: ┌───┐ q_0: ┤ X ├ └───┘ q_1: ───── ┌───┐ q_2: ┤ X ├ └───┘ q_3: ───── """ test_circuit_qiskit = qiskit.QuantumCircuit(4) test_circuit_qiskit.x(0) test_circuit_qiskit.x(2) test_circuit_qiskit.barrier(0, 1, 2) test_copy = test_circuit_qiskit.copy() scaled = scaling_function(test_circuit_qiskit) # Mitiq is expected to remove qiskit barriers expected = qiskit.QuantumCircuit(4) expected.x(0) expected.x(2) assert scaled == expected # Mitiq should not mutate the input circuit assert test_circuit_qiskit == test_copy
https://github.com/primaryobjects/oracle
primaryobjects
from qiskit import QuantumCircuit from qiskit.circuit.library.standard_gates.z import ZGate def oracle(logic, n): ''' Returns a quantum circuit that recognizes even numbers. We do this by checking if qubit 0 equals 0 (even). Upon starting, all qubits are assumed to have a value of 1. We only need to consider qubit 0, the other qubits may be ignored. Parameters: logic: not used (should be None). n: the number of qubits in the circuit. ''' # We use a circuit of size n+1 to include an output qubit. qc = QuantumCircuit(n+1) # Flip the first qubit to 0, since we want to obtain that value. qc.x(0) # Apply a controlled Z-gate from qubit 0 to each of the other qubits. When qubit 0 is 0, the others are flipped, setting the phase. qc.append(ZGate().control(1), [0,range(1,n+1)]) # qc.append(ZGate().control(1), [0,1]) # qc.append(ZGate().control(1), [0,2]) # qc.append(ZGate().control(1), [0,3]) # Undo the flip of the first qubit. qc.x(0) print(qc.draw()) # Convert the oracle to a gate. gate = qc.to_gate() gate.name = "oracle" return gate
https://github.com/Qiskit/feedback
Qiskit
from qiskit_experiments.library.randomized_benchmarking import RBUtils # Run old function with num_qubits = 2 num_qubits = 2 t1s = [100 for _ in range(num_qubits)] t2s = [100 for _ in range(num_qubits)] gate_length = 5 RBUtils.coherence_limit( nQ=num_qubits, T1_list=t1s, T2_list=t2s, gatelen=gate_length ) # Run old function with num_qubits = 3 num_qubits = 3 t1s = [100 for _ in range(num_qubits)] t2s = [100 for _ in range(num_qubits)] gate_length = 5 RBUtils.coherence_limit( nQ=num_qubits, T1_list=t1s, T2_list=t2s, gatelen=gate_length ) # Run new function with num_qubits = 2 num_qubits = 2 t1s = [100 for _ in range(num_qubits)] t2s = [100 for _ in range(num_qubits)] gate_length = 5 RBUtils.coherence_limit_error( num_qubits=num_qubits, gate_length=gate_length, t1s=t1s, t2s=t2s, ) import numpy as np np.isclose( RBUtils.coherence_limit( nQ=num_qubits, T1_list=t1s, T2_list=t2s, gatelen=gate_length ), RBUtils.coherence_limit_error( num_qubits=num_qubits, gate_length=gate_length, t1s=t1s, t2s=t2s, ), 15 ) # Run new function with num_qubits = 3 num_qubits = 3 t1s = [100 for _ in range(num_qubits)] t2s = [100 for _ in range(num_qubits)] gate_length = 5 RBUtils.coherence_limit_error( num_qubits=num_qubits, gate_length=gate_length, t1s=t1s, t2s=t2s, ) # Run new function with num_qubits = 9 num_qubits = 9 t1s = [100 for _ in range(num_qubits)] t2s = [100 for _ in range(num_qubits)] gate_length = 5 RBUtils.coherence_limit_error( num_qubits=num_qubits, gate_length=gate_length, t1s=t1s, t2s=t2s, ) def coherence_limit(nQ=2, T1_list=None, T2_list=None, gatelen=0.1): T1 = np.array(T1_list) if T2_list is None: T2 = 2 * T1 else: T2 = np.array(T2_list) if len(T1) != nQ or len(T2) != nQ: raise ValueError("T1 and/or T2 not the right length") coherence_limit_err = 0 if nQ == 1: coherence_limit_err = 0.5 * ( 1.0 - 2.0 / 3.0 * np.exp(-gatelen / T2[0]) - 1.0 / 3.0 * np.exp(-gatelen / T1[0]) ) elif nQ == 2: T1factor = 0 T2factor = 0 for i in range(2): T1factor += 1.0 / 15.0 * np.exp(-gatelen / T1[i]) T2factor += ( 2.0 / 15.0 * ( np.exp(-gatelen / T2[i]) + np.exp(-gatelen * (1.0 / T2[i] + 1.0 / T1[1 - i])) ) ) T1factor += 1.0 / 15.0 * np.exp(-gatelen * np.sum(1 / T1)) T2factor += 4.0 / 15.0 * np.exp(-gatelen * np.sum(1 / T2)) coherence_limit_err = 0.75 * (1.0 - T1factor - T2factor) else: raise ValueError("Not a valid number of qubits") return coherence_limit_err def coherence_limit_error( num_qubits: int, gate_length: float, t1s: Sequence, t2s: Optional[Sequence] = None ): t1s = np.array(t1s) if t2s is None: t2s = 2 * t1s else: t2s = np.array([min(t2, 2 * t1) for t1, t2 in zip(t1s, t2s)]) if len(t1s) != num_qubits or len(t2s) != num_qubits: raise ValueError("Length of t1s/t2s must equal num_qubits") def thermal_relaxation_choi(t1, t2, time): # without excitation return qi.Choi( np.array( [ [1, 0, 0, np.exp(-time / t2)], [0, 0, 0, 0], [0, 0, 1 - np.exp(-time / t1), 0], [np.exp(-time / t2), 0, 0, np.exp(-time / t1)], ] ) ) chois = [thermal_relaxation_choi(t1, t2, gate_length) for t1, t2 in zip(t1s, t2s)] traces = [np.real(np.trace(np.array(qi.SuperOp(choi)))) for choi in chois] d = 2**num_qubits return d / (d + 1) * (1 - functools.reduce(operator.mul, traces) / (d * d))