repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit, transpile from qiskit.quantum_info import Kraus, SuperOp from qiskit_aer import AerSimulator from qiskit.tools.visualization import plot_histogram # Import from Qiskit Aer noise module from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError, pauli_error, depolarizing_error, thermal_relaxation_error) # Construct a 1-qubit bit-flip and phase-flip errors p_error = 0.05 bit_flip = pauli_error([('X', p_error), ('I', 1 - p_error)]) phase_flip = pauli_error([('Z', p_error), ('I', 1 - p_error)]) print(bit_flip) print(phase_flip) # Compose two bit-flip and phase-flip errors bitphase_flip = bit_flip.compose(phase_flip) print(bitphase_flip) # Tensor product two bit-flip and phase-flip errors with # bit-flip on qubit-0, phase-flip on qubit-1 error2 = phase_flip.tensor(bit_flip) print(error2) # Convert to Kraus operator bit_flip_kraus = Kraus(bit_flip) print(bit_flip_kraus) # Convert to Superoperator phase_flip_sop = SuperOp(phase_flip) print(phase_flip_sop) # Convert back to a quantum error print(QuantumError(bit_flip_kraus)) # Check conversion is equivalent to original error QuantumError(bit_flip_kraus) == bit_flip # Measurement miss-assignement probabilities p0given1 = 0.1 p1given0 = 0.05 ReadoutError([[1 - p1given0, p1given0], [p0given1, 1 - p0given1]]) # Create an empty noise model noise_model = NoiseModel() # Add depolarizing error to all single qubit u1, u2, u3 gates error = depolarizing_error(0.05, 1) noise_model.add_all_qubit_quantum_error(error, ['u1', 'u2', 'u3']) # Print noise model info print(noise_model) # Create an empty noise model noise_model = NoiseModel() # Add depolarizing error to all single qubit u1, u2, u3 gates on qubit 0 only error = depolarizing_error(0.05, 1) noise_model.add_quantum_error(error, ['u1', 'u2', 'u3'], [0]) # Print noise model info print(noise_model) # System Specification n_qubits = 4 circ = QuantumCircuit(n_qubits) # Test Circuit circ.h(0) for qubit in range(n_qubits - 1): circ.cx(qubit, qubit + 1) circ.measure_all() print(circ) # Ideal simulator and execution sim_ideal = AerSimulator() result_ideal = sim_ideal.run(circ).result() plot_histogram(result_ideal.get_counts(0)) # Example error probabilities p_reset = 0.03 p_meas = 0.1 p_gate1 = 0.05 # QuantumError objects error_reset = pauli_error([('X', p_reset), ('I', 1 - p_reset)]) error_meas = pauli_error([('X',p_meas), ('I', 1 - p_meas)]) error_gate1 = pauli_error([('X',p_gate1), ('I', 1 - p_gate1)]) error_gate2 = error_gate1.tensor(error_gate1) # Add errors to noise model noise_bit_flip = NoiseModel() noise_bit_flip.add_all_qubit_quantum_error(error_reset, "reset") noise_bit_flip.add_all_qubit_quantum_error(error_meas, "measure") noise_bit_flip.add_all_qubit_quantum_error(error_gate1, ["u1", "u2", "u3"]) noise_bit_flip.add_all_qubit_quantum_error(error_gate2, ["cx"]) print(noise_bit_flip) # Create noisy simulator backend sim_noise = AerSimulator(noise_model=noise_bit_flip) # Transpile circuit for noisy basis gates circ_tnoise = transpile(circ, sim_noise) # Run and get counts result_bit_flip = sim_noise.run(circ_tnoise).result() counts_bit_flip = result_bit_flip.get_counts(0) # Plot noisy output plot_histogram(counts_bit_flip) # T1 and T2 values for qubits 0-3 T1s = np.random.normal(50e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec T2s = np.random.normal(70e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec # Truncate random T2s <= T1s T2s = np.array([min(T2s[j], 2 * T1s[j]) for j in range(4)]) # Instruction times (in nanoseconds) time_u1 = 0 # virtual gate time_u2 = 50 # (single X90 pulse) time_u3 = 100 # (two X90 pulses) time_cx = 300 time_reset = 1000 # 1 microsecond time_measure = 1000 # 1 microsecond # QuantumError objects errors_reset = [thermal_relaxation_error(t1, t2, time_reset) for t1, t2 in zip(T1s, T2s)] errors_measure = [thermal_relaxation_error(t1, t2, time_measure) for t1, t2 in zip(T1s, T2s)] errors_u1 = [thermal_relaxation_error(t1, t2, time_u1) for t1, t2 in zip(T1s, T2s)] errors_u2 = [thermal_relaxation_error(t1, t2, time_u2) for t1, t2 in zip(T1s, T2s)] errors_u3 = [thermal_relaxation_error(t1, t2, time_u3) for t1, t2 in zip(T1s, T2s)] errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand( thermal_relaxation_error(t1b, t2b, time_cx)) for t1a, t2a in zip(T1s, T2s)] for t1b, t2b in zip(T1s, T2s)] # Add errors to noise model noise_thermal = NoiseModel() for j in range(4): noise_thermal.add_quantum_error(errors_reset[j], "reset", [j]) noise_thermal.add_quantum_error(errors_measure[j], "measure", [j]) noise_thermal.add_quantum_error(errors_u1[j], "u1", [j]) noise_thermal.add_quantum_error(errors_u2[j], "u2", [j]) noise_thermal.add_quantum_error(errors_u3[j], "u3", [j]) for k in range(4): noise_thermal.add_quantum_error(errors_cx[j][k], "cx", [j, k]) print(noise_thermal) # Run the noisy simulation sim_thermal = AerSimulator(noise_model=noise_thermal) # Transpile circuit for noisy basis gates circ_tthermal = transpile(circ, sim_thermal) # Run and get counts result_thermal = sim_thermal.run(circ_tthermal).result() counts_thermal = result_thermal.get_counts(0) # Plot noisy output plot_histogram(counts_thermal) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits to represent the uncertainty num_uncertainty_qubits = 3 # parameters for considered random distribution S = 2.0 # initial spot price vol = 0.4 # volatility of 40% r = 0.05 # annual interest rate of 4% T = 40 / 365 # 40 days to maturity # resulting parameters for log-normal distribution mu = (r - 0.5 * vol**2) * T + np.log(S) sigma = vol * np.sqrt(T) mean = np.exp(mu + sigma**2 / 2) variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2) stddev = np.sqrt(variance) # lowest and highest value considered for the spot price; in between, an equidistant discretization is considered. low = np.maximum(0, mean - 3 * stddev) high = mean + 3 * stddev # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, high) ) # plot probability distribution x = uncertainty_model.values y = uncertainty_model.probabilities plt.bar(x, y, width=0.2) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.grid() plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15) plt.ylabel("Probability ($\%$)", size=15) plt.show() # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 2.126 # set the approximation scaling for the payoff function rescaling_factor = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [-1, 0] offsets = [strike_price - low, 0] f_min = 0 f_max = strike_price - low european_put_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=rescaling_factor, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective european_put = european_put_objective.compose(uncertainty_model, front=True) # plot exact payoff function (evaluated on the grid of the uncertainty model) x = uncertainty_model.values y = np.maximum(0, strike_price - x) plt.plot(x, y, "ro-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Spot Price", size=15) plt.ylabel("Payoff", size=15) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.show() # evaluate exact expected value (normalized to the [0, 1] interval) exact_value = np.dot(uncertainty_model.probabilities, y) exact_delta = -sum(uncertainty_model.probabilities[x <= strike_price]) print("exact expected value:\t%.4f" % exact_value) print("exact delta value: \t%.4f" % exact_delta) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_put, objective_qubits=[num_uncertainty_qubits], post_processing=european_put_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [0, 0] offsets = [1, 0] f_min = 0 f_max = 1 european_put_delta_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, ) # construct circuit for payoff function european_put_delta = european_put_delta_objective.compose(uncertainty_model, front=True) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_put_delta, objective_qubits=[num_uncertainty_qubits] ) # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) conf_int = -np.array(result_delta.confidence_interval)[::-1] print("Exact delta: \t%.4f" % exact_delta) print("Esimated value: \t%.4f" % -result_delta.estimation) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/urwin419/QiskitChecker
urwin419
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) ### added y gate ### qc.y(0) qc.h(1) return qc
https://github.com/DaisukeIto-ynu/KosakaQ_client
DaisukeIto-ynu
# -*- coding: utf-8 -*- """ Created on Thu Nov 17 15:00:00 2022 @author: Yokohama National University, Kosaka Lab """ import warnings import requests from qiskit import qobj as qobj_mod from qiskit.circuit.parameter import Parameter from qiskit.circuit.library import IGate, XGate, YGate, ZGate, HGate, SGate, SdgGate, SXGate, SXdgGate from qiskit.circuit.measure import Measure from qiskit.providers import BackendV2 as Backend from qiskit.providers import Options from qiskit.transpiler import Target from qiskit.providers.models import BackendConfiguration from qiskit.exceptions import QiskitError import kosakaq_job import circuit_to_kosakaq class KosakaQBackend(Backend): def __init__( self, provider, name, url, version, n_qubits, max_shots=4096, max_experiments=1, ): super().__init__(provider=provider, name=name) self.url = url self.version = version self.n_qubits = n_qubits self.max_shots = max_shots self.max_experiments = max_experiments self._configuration = BackendConfiguration.from_dict({ 'backend_name': name, 'backend_version': version, 'url': self.url, 'simulator': False, 'local': False, 'coupling_map': None, 'description': 'KosakaQ Diamond device', 'basis_gates': ['i', 'x', 'y', 'z', 'h', 's', 'sdg', 'sx', 'sxdg'], #後で修正が必要 'memory': False, 'n_qubits': n_qubits, 'conditional': False, 'max_shots': max_shots, 'max_experiments': max_experiments, 'open_pulse': False, 'gates': [ { 'name': 'TODO', 'parameters': [], 'qasm_def': 'TODO' } ] }) self._target = Target(num_qubits=n_qubits) # theta = Parameter('θ') # phi = Parameter('ϕ') # lam = Parameter('λ') self._target.add_instruction(IGate()) self._target.add_instruction(XGate()) self._target.add_instruction(YGate()) self._target.add_instruction(ZGate()) self._target.add_instruction(HGate()) self._target.add_instruction(SGate()) self._target.add_instruction(SdgGate()) self._target.add_instruction(SXGate()) self._target.add_instruction(SXdgGate()) self._target.add_instruction(Measure()) self.options.set_validator("shots", (1,max_shots)) def configuration(self): 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): warnings.warn("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): return 1 @property def target(self): return self._target @classmethod def _default_options(cls): return Options(shots=4096) def run(self, circuit, **kwargs): if isinstance(circuit, qobj_mod.PulseQobj): raise QiskitError("Pulse jobs are not accepted") for kwarg in kwargs: if kwarg != 'shots': warnings.warn( "Option %s is not used by this backend" % kwarg, UserWarning, stacklevel=2) out_shots = kwargs.get('shots', self.options.shots) if out_shots > self.configuration().max_shots: raise ValueError('Number of shots is larger than maximum ' 'number of shots') kosakaq_json = circuit_to_kosakaq.circuit_to_KosakaQ(circuit, self._provider.access_token, shots=out_shots, backend=self.name)[0] header = { "Authorization": "token " + self._provider.access_token, "SDK": "qiskit" } res = requests.post(self.url+r"/job/", data=kosakaq_json, headers=header) res.raise_for_status() response = res.json() if 'id' not in response: raise Exception job = kosakaq_job.KosakaQJob(self, response['id'], access_token=self.provider.access_token, qobj=circuit) return job
https://github.com/maheshwaripranav/Qiskit-Fall-Fest-Kolkata-Hackathon
maheshwaripranav
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ, QuantumRegister, ClassicalRegister from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator import qiskit import copy import matplotlib.pyplot as plt # Loading your IBM Quantum account(s) provider = IBMQ.load_account() from sklearn import model_selection, datasets, svm linnerrud = datasets.load_linnerrud() X = linnerrud.data[0:100] Y = linnerrud.target[0:100] X_train, X_test, Y_train, Y_test = model_selection.train_test_split(X, Y, test_size = 0.33, random_state = 42) print(Y_train) print(X_train[0]) N = 4 def feature_map(X): q = QuantumRegister(N) c = ClassicalRegister(1) qc = QuantumCircuit(q,c) for i, x in enumerate(X_train[0]): qc.rx(x,i) return qc,c def variational_circuit(qc, theta): for i in range(N-1): qc.cnot(i, i+1) qc.cnot(N-1, 0) for i in range(N): qc.ry(theta[i], i) return qc def quantum_nn(X, theta, simulator = True): qc,c = feature_map(X) qc = variational_circuit(qc, theta) qc.measure(0,c) shots = 1E4 backend = Aer.get_backend('qasm_simulator') if simulator == False: shots = 5000 provider = IBMQ.load_account() backend = provider.get_backend('ibmq_athens') job = qiskit.execute(qc, backend, shots = shots) result = job.result() counts = result.get_counts(qc) print(counts) return(counts['1']/shots) def loss(prediction, target): return (prediction-target)**2 def gradient(X, Y, theta): delta = 0.01 grad = [] for i in range(len(theta)): dtheta = copy.copy(theta) dtheta += delta pred_1 = quantum_nn(X, dtheta) pred_2 = quantum_nn(X, theta) grad.append((loss(pred_1, Y) - loss(pred_2, Y))/delta) return np.array(grad) def accuracy(X, Y, theta): counter = 0 for X_i, Y_i in zip(X, Y): prediction = quantum_nn(X_i, theta) if prediction < 0.5 and Y_i == 0: counter += 1 if prediction >= 0.5 and Y_i == 1: counter += 1 return counter/len(Y) eta = 0.05 loss_list = [] theta = np.ones(N) print('Epoch\t Loss\t Training Accuracy') for i in range(20): loss_tmp = [] for X_i, Y_i in zip(X_train, Y_train): prediction = quantum_nn(X_i, theta) loss_tmp.append(loss(prediction, Y_i)) theta = theta - eta * gradient(X_i, Y_i, theta) loss_list.append(np.mean(loss_tmp)) acc = accuracy(X_train, Y_train, theta) print(f'{i} \t {loss_list[-1]:0.3f} \t {acc:0.3f}') plt.plot(loss_list) plt.xlabel('Epoch') plt.ylabel('Loss') plt.show accuracy(X_test, Y_test, theta) clf = svm.SVC() clf.fit(X_train, Y_train) print(clf.predict(X_test)) print(Y_test) quantum_nn(X_test[6], theta, simulator = False) quantum_nn(X_test[6], theta) Y_test[6]
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# # your solution is here # # let's import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # let's import randrange for random choices from random import randrange # # your code is here #
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver( atom="H 0 0 0; H 0 0 0.72" # Two Hydrogen atoms, 0.72 Angstrom apart ) molecule = driver.run() from qiskit_nature.second_q.mappers import QubitConverter, ParityMapper qubit_converter = QubitConverter(ParityMapper()) hamiltonian = qubit_converter.convert(molecule.second_q_ops()[0]) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver sol = NumPyMinimumEigensolver().compute_minimum_eigenvalue(hamiltonian) real_solution = molecule.interpret(sol) real_solution.groundenergy from qiskit_ibm_runtime import QiskitRuntimeService, Estimator, Session, Options service = QiskitRuntimeService() backend = "ibmq_qasm_simulator" from qiskit.algorithms.minimum_eigensolvers import VQE # Use RealAmplitudes circuit to create trial states from qiskit.circuit.library import RealAmplitudes ansatz = RealAmplitudes(num_qubits=2, reps=2) # Search for better states using SPSA algorithm from qiskit.algorithms.optimizers import SPSA optimizer = SPSA(150) # Set a starting point for reproduceability import numpy as np np.random.seed(6) initial_point = np.random.uniform(-np.pi, np.pi, 12) # Create an object to store intermediate results from dataclasses import dataclass @dataclass class VQELog: values: list parameters: list def update(self, count, parameters, mean, _metadata): self.values.append(mean) self.parameters.append(parameters) print(f"Running circuit {count} of ~350", end="\r", flush=True) log = VQELog([],[]) # Main calculation with Session(service=service, backend=backend) as session: options = Options() options.optimization_level = 3 vqe = VQE(Estimator(session=session, options=options), ansatz, optimizer, callback=log.update, initial_point=initial_point) result = vqe.compute_minimum_eigenvalue(hamiltonian) print("Experiment complete.".ljust(30)) print(f"Raw result: {result.optimal_value}") if 'simulator' not in backend: # Run once with ZNE error mitigation options.resilience_level = 2 vqe = VQE(Estimator(session=session, options=options), ansatz, SPSA(1), initial_point=result.optimal_point) result = vqe.compute_minimum_eigenvalue(hamiltonian) print(f"Mitigated result: {result.optimal_value}") import matplotlib.pyplot as plt plt.rcParams["font.size"] = 14 # Plot energy and reference value plt.figure(figsize=(12, 6)) plt.plot(log.values, label="Estimator VQE") plt.axhline(y=real_solution.groundenergy, color="tab:red", ls="--", label="Target") plt.legend(loc="best") plt.xlabel("Iteration") plt.ylabel("Energy [H]") plt.title("VQE energy") plt.show() import qiskit_ibm_runtime qiskit_ibm_runtime.version.get_version_info() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/pyRiemann/pyRiemann-qiskit
pyRiemann
import logging import numpy as np from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit from qiskit.circuit.library import RealAmplitudes from qiskit.quantum_info import Statevector from qiskit_algorithms.optimizers import SPSA from qiskit_algorithms.utils import algorithm_globals from qiskit_machine_learning.circuit.library import RawFeatureVector from qiskit_machine_learning.neural_networks import SamplerQNN from sklearn.base import TransformerMixin def _ansatz(num_qubits): return RealAmplitudes(num_qubits, reps=5) def _auto_encoder_circuit(num_latent, num_trash): qr = QuantumRegister(num_latent + 2 * num_trash + 1, "q") cr = ClassicalRegister(1, "c") circuit = QuantumCircuit(qr, cr) circuit.compose( _ansatz(num_latent + num_trash), range(0, num_latent + num_trash), inplace=True ) circuit.barrier() auxiliary_qubit = num_latent + 2 * num_trash # swap test circuit.h(auxiliary_qubit) for i in range(num_trash): circuit.cswap(auxiliary_qubit, num_latent + i, num_latent + num_trash + i) circuit.h(auxiliary_qubit) circuit.measure(auxiliary_qubit, cr[0]) return circuit class BasicQnnAutoencoder(TransformerMixin): """Quantum denoising This class implements a quantum auto encoder. The implementation was adapted from [1]_, to be compatible with scikit-learn. Parameters ---------- num_latent : int, default=3 The number of qubits in the latent space. num_trash : int, default=2 The number of qubits in the trash space. opt : Optimizer, default=SPSA(maxiter=100, blocking=True) The classical optimizer to use. callback : Callable[int, double], default=None An additional callback for the optimizer. The first parameter is the number of cost evaluation call. The second parameter is the cost. Notes ----- .. versionadded:: 0.3.0 Attributes ---------- costs_ : list The values of the cost function. fidelities_ : list, shape (n_samples,) fidelities (one fidelity for each sample). References ---------- .. [1] \ https://qiskit-community.github.io/qiskit-machine-learning/tutorials/12_quantum_autoencoder.html .. [2] A. Mostafa et al., 2024 \ ‘Quantum Denoising in the Realm of Brain-Computer Interfaces: A Preliminary Study’, https://hal.science/hal-04501908 """ def __init__( self, num_latent=3, num_trash=2, opt=SPSA(maxiter=100, blocking=True), callback=None, ): self.num_latent = num_latent self.num_trash = num_trash self.opt = opt self.callback = callback def _log(self, msg): logging.info(f"[BasicQnnAutoencoder] {msg}") def _get_transformer(self): # encoder transformer = QuantumCircuit(self.n_qubits) transformer = transformer.compose(self._feature_map) ansatz_qc = _ansatz(self.n_qubits) transformer = transformer.compose(ansatz_qc) transformer.barrier() # trash space for i in range(self.num_trash): transformer.reset(self.num_latent + i) transformer.barrier() # decoder transformer = transformer.compose(ansatz_qc.inverse()) self._transformer = transformer return transformer def _compute_fidelities(self, X): fidelities = [] for x in X: param_values = np.concatenate((x, self._opt_result.x)) output_qc = self._transformer.assign_parameters(param_values) output_state = Statevector(output_qc).data original_qc = self._feature_map.assign_parameters(x) original_state = Statevector(original_qc).data fidelity = np.sqrt(np.dot(original_state.conj(), output_state) ** 2) fidelities.append(fidelity.real) return fidelities @property def n_qubits(self): return self.num_latent + self.num_trash def fit(self, X, _y=None, **kwargs): """Fit the autoencoder. Parameters ---------- X : ndarray, shape (n_samples, n_features) Set of time epochs. n_features must equal 2 ** n_qubits, where n_qubits = num_trash + num_latent. Returns ------- self : BasicQnnAutoencoder The BasicQnnAutoencoder instance. """ _, n_features = X.shape self.costs_ = [] self.fidelities_ = [] self._iter = 0 self._log( f"raw feature size: {2 ** self.n_qubits} and feature size: {n_features}" ) assert 2**self.n_qubits == n_features self._feature_map = RawFeatureVector(2**self.n_qubits) self._auto_encoder = _auto_encoder_circuit(self.num_latent, self.num_trash) qc = QuantumCircuit(self.num_latent + 2 * self.num_trash + 1, 1) qc = qc.compose(self._feature_map, range(self.n_qubits)) qc = qc.compose(self._auto_encoder) qnn = SamplerQNN( circuit=qc, input_params=self._feature_map.parameters, weight_params=self._auto_encoder.parameters, interpret=lambda x: x, output_shape=2, ) def cost_func(params_values): self._iter += 1 if self._iter % 10 == 0: self._log(f"Iteration {self._iter}") probabilities = qnn.forward(X, params_values) cost = np.sum(probabilities[:, 1]) / X.shape[0] self.costs_.append(cost) if self.callback: self.callback(self._iter, cost) return cost initial_point = algorithm_globals.random.random( self._auto_encoder.num_parameters ) self._opt_result = self.opt.minimize(fun=cost_func, x0=initial_point) # encoder/decoder circuit self._transformer = self._get_transformer() # compute fidelity self.fidelities_ = self._compute_fidelities(X) self._log(f"Mean fidelity: {np.mean(self.fidelities_)}") return self def transform(self, X, **kwargs): """Apply the transformer circuit. Parameters ---------- X : ndarray, shape (n_samples, n_features) Set of time epochs. n_features must equal 2 ** n_qubits, where n_qubits = num_trash + num_latent. Returns ------- outputs : ndarray, shape (n_samples, 2 ** n_qubits) The autocoded sample. n_qubits = num_trash + num_latent. """ _, n_features = X.shape outputs = [] for x in X: param_values = np.concatenate((x, self._opt_result.x)) output_qc = self._transformer.assign_parameters(param_values) output_sv = Statevector(output_qc).data output_sv = np.reshape(np.abs(output_sv) ** 2, n_features) outputs.append(output_sv) return np.array(outputs)
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/usamisaori/quantum-expressibility-entangling-capability
usamisaori
from qiskit import * from oracle_generation import generate_oracle get_bin = lambda x, n: format(x, 'b').zfill(n) def gen_circuits(min,max,size): circuits = [] secrets = [] ORACLE_SIZE = size for i in range(min,max+1): cur_str = get_bin(i,ORACLE_SIZE-1) (circuit, secret) = generate_oracle(ORACLE_SIZE,False,3,cur_str) circuits.append(circuit) secrets.append(secret) return (circuits, secrets)
https://github.com/tomtuamnuq/compare-qiskit-ocean
tomtuamnuq
import time from typing import Tuple import dimod from dwave.system import DWaveSampler, EmbeddingComposite, DWaveCliqueSampler from qiskit_optimization import QuadraticProgram from qiskit_optimization.algorithms import CplexOptimizer from qiskit_optimization.converters import LinearEqualityToPenalty from utilities.helpers import create_quadratic_programs_from_paths DIR = 'TEST_DATA' + "/" + '27_04_2021' # select linear programs to solve qps = create_quadratic_programs_from_paths(DIR + "/DENSE/") qp_dense = qps['test_70'] qps = create_quadratic_programs_from_paths(DIR + "/SPARSE/") qp_sparse = qps['test_100'] # init solvers cplex = CplexOptimizer() dwave_dense = DWaveCliqueSampler() dwave_sparse = EmbeddingComposite(DWaveSampler()) # solve classically for qp in (qp_dense, qp_sparse): print(cplex.solve(qp)) def qp_to_bqm(qp: QuadraticProgram) -> dimod.BQM: conv = LinearEqualityToPenalty() qubo = conv.convert(qp) bqm = dimod.as_bqm(qubo.objective.linear.to_array(), qubo.objective.quadratic.to_array(), dimod.BINARY) return bqm solver_parameters = {'num_reads': 1024, 'annealing_time': 3} def solve_bqm(sampler: dimod.Sampler, bqm: dimod.BQM): sampleset = sampler.sample(bqm, **solver_parameters) return sampleset qubo_dense = qp_to_bqm(qp_dense) sampleset_dense = solve_bqm(dwave_dense, qubo_dense) # 44d0d592-9107-4661-a6df-3e65836c1bda sampleset_dense.to_pandas_dataframe() def eval_bqm_sampleset(qp: QuadraticProgram, sampleset) -> Tuple[bool, int, float]: x = sampleset.record.sample[0] feasible = qp.is_feasible(x) num_occur = sampleset.record.num_occurrences[0] energy = sampleset.record.energy[0] return feasible, num_occur, energy res = eval_bqm_sampleset(qp_dense, sampleset_dense) res
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/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from datasets import * from qiskit_aqua.utils import split_dataset_to_data_and_labels, map_label_to_class_name from qiskit_aqua.input import SVMInput from qiskit_aqua import run_algorithm feature_dim = 2 # dimension of each data point training_dataset_size = 20 testing_dataset_size = 10 sample_Total, training_input, test_input, class_labels = ad_hoc_data(training_size=training_dataset_size, test_size=testing_dataset_size, n=feature_dim, gap=0.3, PLOT_DATA=True) datapoints, class_to_label = split_dataset_to_data_and_labels(test_input) print(class_to_label) params = { 'problem': {'name': 'svm_classification'}, 'algorithm': { 'name': 'SVM' } } algo_input = SVMInput(training_input, test_input, datapoints[0]) result = run_algorithm(params, algo_input) print("kernel matrix during the training:") kernel_matrix = result['kernel_matrix_training'] img = plt.imshow(np.asmatrix(kernel_matrix),interpolation='nearest',origin='upper',cmap='bone_r') plt.show() print("testing success ratio: ", result['testing_accuracy']) print("predicted classes:", result['predicted_classes']) sample_Total, training_input, test_input, class_labels = Breast_cancer(training_size=20, test_size=10, n=2, PLOT_DATA=True) # n =2 is the dimension of each data point datapoints, class_to_label = split_dataset_to_data_and_labels(test_input) label_to_class = {label:class_name for class_name, label in class_to_label.items()} print(class_to_label, label_to_class) algo_input = SVMInput(training_input, test_input, datapoints[0]) result = run_algorithm(params, algo_input) # print(result) print("kernel matrix during the training:") kernel_matrix = result['kernel_matrix_training'] img = plt.imshow(np.asmatrix(kernel_matrix),interpolation='nearest',origin='upper',cmap='bone_r') plt.show() print("testing success ratio: ", result['testing_accuracy']) print("ground truth: {}".format(map_label_to_class_name(datapoints[1], label_to_class))) print("predicted: {}".format(result['predicted_classes']))
https://github.com/quantumyatra/quantum_computing
quantumyatra
from qiskit import QuantumCircuit, Aer, execute from math import pi import numpy as np from qiskit.visualization import plot_bloch_multivector, plot_histogram qc = QuantumCircuit(2) qc.h(0) qc.h(1) qc.cx(0,1) qc.draw() # Let's see the result statevector_backend = Aer.get_backend('statevector_simulator') final_state = execute(qc,statevector_backend).result().get_statevector() # In Jupyter Notebooks we can display this nicely using Latex. # If not using Jupyter Notebooks you may need to remove the # array_to_latex function and use print(final_state) instead. from qiskit_textbook.tools import array_to_latex array_to_latex(final_state, pretext="\\text{Statevector} = ", precision=1) plot_bloch_multivector(final_state) qc = QuantumCircuit(2) qc.h(0) qc.h(1) qc.z(1) qc.draw() final_state = execute(qc,statevector_backend).result().get_statevector() array_to_latex(final_state, pretext="\\text{Statevector} = ", precision=1) plot_bloch_multivector(final_state) qc.cx(0,1) qc.draw() final_state = execute(qc,statevector_backend).result().get_statevector() array_to_latex(final_state, pretext="\\text{Statevector} = ", precision=1) plot_bloch_multivector(final_state) qc = QuantumCircuit(2) qc.h(0) qc.h(1) qc.cx(0,1) qc.h(0) qc.h(1) display(qc.draw()) # `display` is an IPython tool, remove if it cases an error unitary_backend = Aer.get_backend('unitary_simulator') unitary = execute(qc,unitary_backend).result().get_unitary() array_to_latex(unitary, pretext="\\text{Circuit = }\n") qc = QuantumCircuit(2) qc.cx(1,0) display(qc.draw()) unitary_backend = Aer.get_backend('unitary_simulator') unitary = execute(qc,unitary_backend).result().get_unitary() array_to_latex(unitary, pretext="\\text{Circuit = }\n") qc = QuantumCircuit(2) qc.cu1(pi/4, 0, 1) qc.draw() unitary_backend = Aer.get_backend('unitary_simulator') unitary = execute(qc,unitary_backend).result().get_unitary() array_to_latex(unitary, pretext="\\text{Controlled-T} = \n") qc = QuantumCircuit(2) qc.h(0) qc.x(1) display(qc.draw()) final_state = execute(qc,statevector_backend).result().get_statevector() plot_bloch_multivector(final_state) qc.cu1(pi/4, 0, 1) display(qc.draw()) final_state = execute(qc,statevector_backend).result().get_statevector() plot_bloch_multivector(final_state) import qiskit qiskit.__qiskit_version__
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# the first and second elements are 1 and 1 F = [1,1] for i in range(2,30): F.append(F[i-1] + F[i-2]) # print the final list print(F) # define an empty list N = [] for i in range(11): N.append([ i , i*i , i*i*i , i*i + i*i*i ]) # a list having four elements is added to the list N # Alternatively: #N.append([i , i**2 , i**3 , i**2 + i**3]) # ** is the exponent operator #N = N + [ [i , i*i , i*i*i , i*i + i*i*i] ] # Why using double brakets? #N = N + [ [i , i**2 , i**3 , i**2 + i**3] ] # Why using double brakets? # In the last two alternative solutions, you may try with a single braket, # and then see why double brakets are needed for the exact solution. # print the final list print(N) # let's print the list element by element for i in range(len(N)): print(N[i]) # let's print the list element by element by using an alternative method for el in N: # el will iteratively takes the values of elements in N print(el)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) ghz.draw(output='mpl')
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 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. """ComposedOp Class""" from functools import partial, reduce from typing import List, Optional, Union, cast, Dict from numbers import Number import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import ParameterExpression from qiskit.opflow.exceptions import OpflowError from qiskit.opflow.list_ops.list_op import ListOp from qiskit.opflow.operator_base import OperatorBase from qiskit.quantum_info import Statevector from qiskit.utils.deprecation import deprecate_func class ComposedOp(ListOp): """Deprecated: A class for lazily representing compositions of Operators. Often Operators cannot be efficiently composed with one another, but may be manipulated further so that they can be composed later. This class holds logic to indicate that the Operators in ``oplist`` are meant to be composed, and therefore if they reach a point in which they can be, such as after conversion to QuantumCircuits or matrices, they can be reduced by composition.""" @deprecate_func( since="0.24.0", additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, oplist: List[OperatorBase], coeff: Union[complex, ParameterExpression] = 1.0, abelian: bool = False, ) -> None: """ Args: oplist: The Operators being composed. coeff: A coefficient multiplying the operator abelian: Indicates whether the Operators in ``oplist`` are known to mutually commute. """ super().__init__(oplist, combo_fn=partial(reduce, np.dot), coeff=coeff, abelian=abelian) @property def num_qubits(self) -> int: return self.oplist[0].num_qubits @property def distributive(self) -> bool: return False @property def settings(self) -> Dict: """Return settings.""" return {"oplist": self._oplist, "coeff": self._coeff, "abelian": self._abelian} # TODO take advantage of the mixed product property, tensorpower each element in the composition # def tensorpower(self, other): # """ Tensor product with Self Multiple Times """ # raise NotImplementedError def to_matrix(self, massive: bool = False) -> np.ndarray: OperatorBase._check_massive("to_matrix", True, self.num_qubits, massive) mat = self.coeff * reduce( np.dot, [np.asarray(op.to_matrix(massive=massive)) for op in self.oplist] ) # Note: As ComposedOp has a combo function of inner product we can end up here not with # a matrix (array) but a scalar. In which case we make a single element array of it. if isinstance(mat, Number): mat = [mat] return np.asarray(mat, dtype=complex) def to_circuit(self) -> QuantumCircuit: """Returns the quantum circuit, representing the composed operator. Returns: The circuit representation of the composed operator. Raises: OpflowError: for operators where a single underlying circuit can not be obtained. """ # pylint: disable=cyclic-import from ..state_fns.circuit_state_fn import CircuitStateFn from ..primitive_ops.primitive_op import PrimitiveOp circuit_op = self.to_circuit_op() if isinstance(circuit_op, (PrimitiveOp, CircuitStateFn)): return circuit_op.to_circuit() raise OpflowError( "Conversion to_circuit supported only for operators, where a single " "underlying circuit can be produced." ) def adjoint(self) -> "ComposedOp": return ComposedOp([op.adjoint() for op in reversed(self.oplist)], coeff=self.coeff) def compose( self, other: OperatorBase, permutation: Optional[List[int]] = None, front: bool = False ) -> OperatorBase: new_self, other = self._expand_shorter_operator_and_permute(other, permutation) new_self = cast(ComposedOp, new_self) if front: return other.compose(new_self) # Try composing with last element in list if isinstance(other, ComposedOp): return ComposedOp(new_self.oplist + other.oplist, coeff=new_self.coeff * other.coeff) # Try composing with last element of oplist. We only try # this if that last element isn't itself an # ComposedOp, so we can tell whether composing the # two elements directly worked. If it doesn't, # continue to the final return statement below, appending other to the oplist. if not isinstance(new_self.oplist[-1], ComposedOp): comp_with_last = new_self.oplist[-1].compose(other) # Attempt successful if not isinstance(comp_with_last, ComposedOp): new_oplist = new_self.oplist[0:-1] + [comp_with_last] return ComposedOp(new_oplist, coeff=new_self.coeff) return ComposedOp(new_self.oplist + [other], coeff=new_self.coeff) def eval( self, front: Optional[Union[str, dict, np.ndarray, OperatorBase, Statevector]] = None ) -> Union[OperatorBase, complex]: if self._is_empty(): return 0.0 # pylint: disable=cyclic-import from ..state_fns.state_fn import StateFn def tree_recursive_eval(r, l_arg): if isinstance(r, list): return [tree_recursive_eval(r_op, l_arg) for r_op in r] else: return l_arg.eval(r) eval_list = self.oplist.copy() # Only one op needs to be multiplied, so just multiply the first. eval_list[0] = eval_list[0] * self.coeff # type: ignore if front and isinstance(front, OperatorBase): eval_list = eval_list + [front] elif front: eval_list = [StateFn(front, is_measurement=True)] + eval_list # type: ignore return reduce(tree_recursive_eval, reversed(eval_list)) # Try collapsing list or trees of compositions into a single <Measurement | Op | State>. def non_distributive_reduce(self) -> OperatorBase: """Reduce without attempting to expand all distributive compositions. Returns: The reduced Operator. """ reduced_ops = [op.reduce() for op in self.oplist] reduced_ops = reduce(lambda x, y: x.compose(y), reduced_ops) * self.coeff if isinstance(reduced_ops, ComposedOp) and len(reduced_ops.oplist) > 1: return reduced_ops else: return reduced_ops[0] def reduce(self) -> OperatorBase: reduced_ops = [op.reduce() for op in self.oplist] if len(reduced_ops) == 0: return self.__class__([], coeff=self.coeff, abelian=self.abelian) def distribute_compose(l_arg, r): if isinstance(l_arg, ListOp) and l_arg.distributive: # Either ListOp or SummedOp, returns correct type return l_arg.__class__( [distribute_compose(l_op * l_arg.coeff, r) for l_op in l_arg.oplist] ) if isinstance(r, ListOp) and r.distributive: return r.__class__([distribute_compose(l_arg, r_op * r.coeff) for r_op in r.oplist]) else: return l_arg.compose(r) reduced_ops = reduce(distribute_compose, reduced_ops) * self.coeff if isinstance(reduced_ops, ListOp) and len(reduced_ops.oplist) == 1: return reduced_ops.oplist[0] else: return cast(OperatorBase, reduced_ops)
https://github.com/soultanis/Quantum-Database-Search
soultanis
from qiskit import IBMQ import sys def get_job_status(backend, job_id): backend = IBMQ.get_backend(backend) print("Backend {0} is operational? {1}".format( backend.name(), backend.status()['operational'])) print("Backend was last updated in {0}".format( backend.properties()['last_update_date'])) print("Backend has {0} pending jobs".format( backend.status()['pending_jobs'])) ibmq_job = backend.retrieve_job(job_id) status = ibmq_job.status() print(status.name) print(ibmq_job.creation_date()) if (status.name == 'DONE'): print("EUREKA") result = ibmq_job.result() count = result.get_counts() print("Result is: {0}".format()) from qiskit.tools.visualization import plot_histogram plot_histogram(counts) else: print("... Work in progress ...") print("Queue position = {0}".format(ibmq_job.queue_position())) print("Error message = {0}".format(ibmq_job.error_message())) IBMQ.load_accounts() print("Account(s) loaded") if (len(sys.argv) > 2): get_job_status(sys.argv[1], sys.argv[2])
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np import copy # Problem modelling imports from docplex.mp.model import Model # Qiskit imports from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit.utils.algorithm_globals import algorithm_globals from qiskit_optimization.algorithms import MinimumEigenOptimizer, CplexOptimizer from qiskit_optimization import QuadraticProgram from qiskit_optimization.problems.variable import VarType from qiskit_optimization.converters.quadratic_program_to_qubo import QuadraticProgramToQubo from qiskit_optimization.translators import from_docplex_mp def create_problem(mu: np.array, sigma: np.array, total: int = 3) -> QuadraticProgram: """Solve the quadratic program using docplex.""" mdl = Model() x = [mdl.binary_var("x%s" % i) for i in range(len(sigma))] objective = mdl.sum([mu[i] * x[i] for i in range(len(mu))]) objective -= 2 * mdl.sum( [sigma[i, j] * x[i] * x[j] for i in range(len(mu)) for j in range(len(mu))] ) mdl.maximize(objective) cost = mdl.sum(x) mdl.add_constraint(cost == total) qp = from_docplex_mp(mdl) return qp def relax_problem(problem) -> QuadraticProgram: """Change all variables to continuous.""" relaxed_problem = copy.deepcopy(problem) for variable in relaxed_problem.variables: variable.vartype = VarType.CONTINUOUS return relaxed_problem mu = np.array([3.418, 2.0913, 6.2415, 4.4436, 10.892, 3.4051]) sigma = np.array( [ [1.07978412, 0.00768914, 0.11227606, -0.06842969, -0.01016793, -0.00839765], [0.00768914, 0.10922887, -0.03043424, -0.0020045, 0.00670929, 0.0147937], [0.11227606, -0.03043424, 0.985353, 0.02307313, -0.05249785, 0.00904119], [-0.06842969, -0.0020045, 0.02307313, 0.6043817, 0.03740115, -0.00945322], [-0.01016793, 0.00670929, -0.05249785, 0.03740115, 0.79839634, 0.07616951], [-0.00839765, 0.0147937, 0.00904119, -0.00945322, 0.07616951, 1.08464544], ] ) qubo = create_problem(mu, sigma) print(qubo.prettyprint()) result = CplexOptimizer().solve(qubo) print(result.prettyprint()) qp = relax_problem(QuadraticProgramToQubo().convert(qubo)) print(qp.prettyprint()) sol = CplexOptimizer().solve(qp) print(sol.prettyprint()) c_stars = sol.samples[0].x print(c_stars) algorithm_globals.random_seed = 12345 qaoa_mes = QAOA(sampler=Sampler(), optimizer=COBYLA(), initial_point=[0.0, 1.0]) exact_mes = NumPyMinimumEigensolver() qaoa = MinimumEigenOptimizer(qaoa_mes) qaoa_result = qaoa.solve(qubo) print(qaoa_result.prettyprint()) from qiskit import QuantumCircuit thetas = [2 * np.arcsin(np.sqrt(c_star)) for c_star in c_stars] init_qc = QuantumCircuit(len(sigma)) for idx, theta in enumerate(thetas): init_qc.ry(theta, idx) init_qc.draw(output="mpl") from qiskit.circuit import Parameter beta = Parameter("β") ws_mixer = QuantumCircuit(len(sigma)) for idx, theta in enumerate(thetas): ws_mixer.ry(-theta, idx) ws_mixer.rz(-2 * beta, idx) ws_mixer.ry(theta, idx) ws_mixer.draw(output="mpl") ws_qaoa_mes = QAOA( sampler=Sampler(), optimizer=COBYLA(), initial_state=init_qc, mixer=ws_mixer, initial_point=[0.0, 1.0], ) ws_qaoa = MinimumEigenOptimizer(ws_qaoa_mes) ws_qaoa_result = ws_qaoa.solve(qubo) print(ws_qaoa_result.prettyprint()) def format_qaoa_samples(samples, max_len: int = 10): qaoa_res = [] for s in samples: if sum(s.x) == 3: qaoa_res.append(("".join([str(int(_)) for _ in s.x]), s.fval, s.probability)) res = sorted(qaoa_res, key=lambda x: -x[1])[0:max_len] return [(_[0] + f": value: {_[1]:.3f}, probability: {1e2*_[2]:.1f}%") for _ in res] format_qaoa_samples(qaoa_result.samples) format_qaoa_samples(ws_qaoa_result.samples) from qiskit_optimization.algorithms import WarmStartQAOAOptimizer qaoa_mes = QAOA(sampler=Sampler(), optimizer=COBYLA(), initial_point=[0.0, 1.0]) ws_qaoa = WarmStartQAOAOptimizer( pre_solver=CplexOptimizer(), relax_for_pre_solver=True, qaoa=qaoa_mes, epsilon=0.0 ) ws_result = ws_qaoa.solve(qubo) print(ws_result.prettyprint()) format_qaoa_samples(ws_result.samples) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# I am a comment in python print("Hello From Quantum World :-)") # please run me from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from random import randrange # Create my circuit and register objects qreg = QuantumRegister(2) # my quantum register creg = ClassicalRegister(2) # my classical register circuit = QuantumCircuit(qreg,creg) # my quantum circuit # let's apply a Hadamard gate to the first qubit circuit.h(qreg[0]) # let's set the second qubit to |1> circuit.x(qreg[1]) # let's apply CNOT(first_qubit,second_qubit) circuit.cx(qreg[0],qreg[1]) # let's measure the both qubits circuit.measure(qreg,creg) print("The execution was completed, and the circuit was created :)") ## execute the circuit 100 times job = execute(circuit,Aer.get_backend('qasm_simulator'),shots=1024) # get the result counts = job.result().get_counts(circuit) print(counts) from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # draw the overall circuit drawer(circuit) # re-execute me if you DO NOT see the circuit diagram from qiskit import IBMQ IBMQ.save_account('write YOUR IBM API TOKEN here') # Then, execute this cell IBMQ.stored_accounts() IBMQ.load_accounts() IBMQ.active_accounts() IBMQ.backends() IBMQ.backends(operational=True, simulator=False) from qiskit.backends.ibmq import least_busy least_busy(IBMQ.backends(simulator=False)) backend = least_busy(IBMQ.backends(simulator=True)) backend.name() from qiskit import compile qobj = compile(circuit, backend=backend, shots=1024) job = backend.run(qobj) result = job.result() counts = result.get_counts() print(counts) backend_real = least_busy(IBMQ.backends(simulator=False)) backend_real.name() backend_real.status() qobj_real = compile(circuit, backend=backend_real, shots=1024) job_real = backend_real.run(qobj_real) job_real.queue_position() result_real = job_real.result() counts_real = result_real.get_counts() print(counts_real)
https://github.com/liyaochong/quantum-algorithm-learning-and-implementation
liyaochong
# 导入相应的运算库 import numpy as np from qiskit import BasicAer, execute from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.tools.visualization import circuit_drawer desired_vector1 = [np.sqrt(3)/2, 1/2, 0, 0] desired_vector2 = [1/2, 1/2, 1/2, 1/2] q0 = QuantumRegister(1,'q0') c0 = ClassicalRegister(1,'c0') q1 = QuantumRegister(2,'q1') c1 = ClassicalRegister(2,'c1') q2 = QuantumRegister(2,'q2') c2 = ClassicalRegister(2,'c2') Circuit = QuantumCircuit() Circuit.add_register(q0,c0) Circuit.add_register(q1,c1) Circuit.add_register(q2,c2) Circuit.initialize(desired_vector1, [q1[0],q1[1]]) Circuit.initialize(desired_vector2, [q2[0],q2[1]]) Circuit.h(q0[0]) Circuit.ccx(q0[0],q1[1],q2[1]) Circuit.ccx(q0[0],q2[1],q1[1]) Circuit.ccx(q0[0],q1[1],q2[1]) Circuit.ccx(q0[0],q1[0],q2[0]) Circuit.ccx(q0[0],q2[0],q1[0]) Circuit.ccx(q0[0],q1[0],q2[0]) Circuit.h(q0[0]) Circuit.draw(output='mpl') # 对寄存器q0进行测量 Circuit.measure(q0,c0) # 测量次数设置为1024次 backend = BasicAer.get_backend('qasm_simulator') job = execute(Circuit, backend,shots=1024) job.result().get_counts(Circuit) Inner_product = np.sum(np.multiply(np.array(desired_vector1),np.array(desired_vector2))) Overlap = Inner_product**2 P_0 = 1/2 + Overlap/2 print(P_0*1024)
https://github.com/alejomonbar/Quantum-Supply-Chain-Manager
alejomonbar
# %pip install qiskit # %pip install docplex # %pip install qiskit_optimization # %pip install networkx # %pip install geopandas # %pip install folium import networkx as nx import geopandas as gpd import folium import numpy as np import pandas as pd import matplotlib.pyplot as plt import itertools import time import random from IPython.display import display from qiskit import IBMQ from qiskit.algorithms import QAOA, VQE from qiskit.circuit.library import TwoLocal from qiskit.algorithms.optimizers import COBYLA, SPSA # Classical simulator from qiskit.providers.aer import AerSimulator from docplex.mp.model import Model from qiskit_optimization.runtime import QAOAClient, VQEClient from qiskit_optimization.converters import QuadraticProgramToQubo from qiskit_optimization.translators import from_docplex_mp from qiskit_optimization.algorithms import CplexOptimizer, MinimumEigenOptimizer path = gpd.datasets.get_path('nybb') df = gpd.read_file(path) m = folium.Map(location=[40.70, -73.94], zoom_start=10, max_zoom=12, tiles='CartoDB positron') # Project to NAD83 projected crs df = df.to_crs(epsg=2263) # Access the centroid attribute of each polygon df['centroid'] = df.centroid # Project to WGS84 geographic crs # geometry (active) column df = df.to_crs(epsg=4326) # Centroid column df['centroid'] = df['centroid'].to_crs(epsg=4326) np.random.seed(7) locations = [] ids = 0 for _, r in df.iterrows(): lat, lon = r['centroid'].y, r['centroid'].x for i in range(2): lat_rand, lon_rand = lat + 0.2 * np.random.rand(), lon +0.1 * np.random.rand() locations.append((lon_rand, lat_rand)) folium.Marker(location=[lat_rand, lon_rand], popup=f'Id: {ids}').add_to(m) ids += 1 center = np.array(locations).mean(axis=0) locations = [(center[0], center[1])] + locations folium.CircleMarker(location=[center[1], center[0]], radius=10, popup="<stong>Warehouse</stong>", color="red",fill=True, fillOpacity=1, fillColor="tab:red").add_to(m) m # Normalizing the results to produce a graph in Graphx companies = np.array(locations) companies -= companies[0] companies /= (np.max(np.abs(companies), axis=0)) r = list(np.sqrt(np.sum(companies ** 2, axis=1))) threshold = 1 # Limit for to not consider the route from company i to j if the distance is larger than a threshold n_companies = len(companies) G = nx.Graph(name="VRP") G.add_nodes_from(range(n_companies)) # G.add_weighted_edges_from([0, i, w] for i, w in zip(range(1, n_companies), r[1:])) np.random.seed(2) count = 0 for i in range(n_companies): for j in range(n_companies): if i != j: rij = np.sqrt(np.sum((companies[i] - companies[j])**2)) if (rij < threshold) or (0 in [i, j]): count +=1 G.add_weighted_edges_from([[i, j, rij]]) r.append(rij) colors = [plt.cm.get_cmap("coolwarm")(x) for x in r[1:]] nx.draw(G, pos=companies, with_labels=True, node_size=500, edge_color=colors, width=1, font_color="white",font_size=14, node_color = ["tab:red"] + (n_companies-1)*["darkblue"]) print(f"The number of edges of this problem is: {len(G.edges)}") mdl = Model(name="VRP") n_trucks = 3 # number of K trucks x = {} for i, j in G.edges(): x[(i, j)] = mdl.binary_var(name=f"x_{i}_{j}") # Adding route from company i to company j as a binary variable x[(j, i)] = mdl.binary_var(name=f"x_{j}_{i}") # Adding route from company j to company i as a binary variable print(f"The number of qubits needed to solve the problem is: {mdl.number_of_binary_variables}") cost_func = mdl.sum(w["weight"] * x[(i, j)] for i, j, w in G.edges(data=True)) + mdl.sum(w["weight"] * x[(j, i)] for i, j, w in G.edges(data=True)) mdl.minimize(cost_func) # Constraint 1a(yellow Fig. above): Only one truck goes out from company i for i in range(1, n_companies): mdl.add_constraint(mdl.sum(x[i, j] for j in range(n_companies) if (i, j) in x.keys()) == 1) # Constraint 1b (yellow Fig. above): Only one truck comes into company j for j in range(1, n_companies): mdl.add_constraint(mdl.sum(x[i, j] for i in range(n_companies) if (i, j) in x.keys()) == 1) # Constraint 2: (orange Fig. above) For the warehouse mdl.add_constraint(mdl.sum(x[i, 0] for i in range(1, n_companies)) == n_trucks) mdl.add_constraint(mdl.sum(x[0, j] for j in range(1, n_companies)) == n_trucks) # Constraint 3: (blue Fig. above) To eliminate sub-routes companies_list = list(range(1, n_companies)) subroute_set = [] for i in range(2, len(companies_list) + 1): for comb in itertools.combinations(companies_list, i): subroute_set.append(list(comb)) #subset points for subroute in subroute_set: constraint_3 = [] for i, j in itertools.permutations(subroute, 2): #iterating over all the subset points if (i, j) in x.keys(): constraint_3.append(x[(i,j)]) elif i == j: pass else: constraint_3 = [] break if len(constraint_3) != 0: mdl.add_constraint(mdl.sum(constraint_3) <= len(subroute) - 1) quadratic_program = from_docplex_mp(mdl) print(quadratic_program.export_as_lp_string()) sol = CplexOptimizer().solve(quadratic_program) print(sol.prettyprint()) solution_cplex = sol.raw_results.as_name_dict() G_sol = nx.Graph() G_sol.add_nodes_from(range(n_companies)) for i in solution_cplex: nodes = i[2:].split("_") G_sol.add_edge(int(nodes[0]), int(nodes[1])) nx.draw(G_sol, pos=companies, with_labels=True, node_size=500, edge_color=colors, width=1, font_color="white",font_size=14, node_color = ["tab:red"] + (n_companies-1)*["darkblue"]) qubo = QuadraticProgramToQubo(penalty=15).convert(quadratic_program) num_vars = qubo.get_num_binary_vars() print(f"To represent the inital problem with {mdl.number_of_binary_variables} variables, the QUBO representation needs {num_vars} variables") new_qubo = qubo.substitute_variables(sol.variables_dict) start = time.time() sol_slack = CplexOptimizer().solve(new_qubo) end = time.time() - start print(f"The solver needs {np.round(end, 3)} seconds to finish.") qubo_no_slack = qubo.substitute_variables(sol_slack.variables_dict) sol_no_slack = CplexOptimizer().solve(qubo_no_slack) solution_slack = sol_no_slack.raw_results.as_name_dict() G_sol_slack = nx.Graph() G_sol_slack.add_nodes_from(range(n_companies)) for i in solution_slack: nodes = i[2:].split("_") G_sol.add_edge(int(nodes[0]), int(nodes[1])) nx.draw(G_sol, pos=companies, with_labels=True, node_size=500, edge_color=colors, width=1, font_color="white",font_size=14, node_color = ["tab:red"] + (n_companies-1)*["darkblue"]) index_1s = [k for k, v in sol_no_slack.variables_dict.items() if v == 1] index_0s = [k for k, v in sol_no_slack.variables_dict.items() if v == 0] def Optimization_QAOA(qubo, reps=1, optimizer=COBYLA(maxiter=1000), backend=None, shots=1024, alpha=1.0, provider=None, local=False, error_mitigation=False): intermediate_info = {'nfev': [], 'parameters': [], 'stddev': [], 'mean': [] } def callback(nfev, parameters, mean, stddev): # display(f"Evaluation: {nfev}, Energy: {mean}, Std: {stddev}") intermediate_info['nfev'].append(nfev) intermediate_info['parameters'].append(parameters) intermediate_info['mean'].append(mean) intermediate_info['stddev'].append(stddev) if local: qaoa_mes = QAOA(optimizer=optimizer, reps=reps, quantum_instance=AerSimulator(), callback=callback) else: qaoa_mes = QAOAClient(provider=provider, backend=backend, reps=reps, alpha=alpha, shots=shots, callback=callback, optimizer=optimizer, optimization_level=3,measurement_error_mitigation=error_mitigation) qaoa = MinimumEigenOptimizer(qaoa_mes) result = qaoa.solve(qubo) return result, intermediate_info def Optimization_VQE(qubo, ansatz, optimizer=SPSA(maxiter=50), backend=None, shots=1024, provider=None, local=False, error_mitigation=False): intermediate_info = {'nfev': [], 'parameters': [], 'stddev': [], 'mean': [] } def callback(nfev, parameters, mean, stddev): # display(f"Evaluation: {nfev}, Energy: {mean}, Std: {stddev}") intermediate_info['nfev'].append(nfev) intermediate_info['parameters'].append(parameters) intermediate_info['mean'].append(mean) intermediate_info['stddev'].append(stddev) if local: vqe_mes = VQE(ansatz=ansatz, quantum_instance=AerSimulator(), callback=callback, optimizer=optimizer) else: vqe_mes = VQEClient(ansatz=ansatz, provider=provider, backend=backend, shots=shots, callback=callback, optimizer=optimizer,measurement_error_mitigation=error_mitigation) vqe = MinimumEigenOptimizer(vqe_mes) result = vqe.solve(qubo) return result, intermediate_info def graph(solution, solution_not_kept): G = nx.Graph() G.add_nodes_from(range(n_companies)) for k, v in solution.items(): if v == 1: nodes = k[2:].split("_") G.add_edge(int(nodes[0]), int(nodes[1])) for k, v in solution_not_kept.items(): if v == 1: nodes = k[2:].split("_") G.add_edge(int(nodes[0]), int(nodes[1])) return G num_1s = 3 num_0s = 4 random.seed(1) keep_1s = random.sample(index_1s, num_1s) keep_0s = random.sample(index_0s, num_0s) sol_qubo = sol.variables_dict solution_not_kept7 = {i:sol_qubo[i] for i in sol_qubo.keys() if i not in keep_1s + keep_0s} qubo_7vars = qubo_no_slack.substitute_variables(solution_not_kept7) print(qubo_7vars.export_as_lp_string()) sol7_local_qaoa_cobyla = Optimization_QAOA(qubo_7vars, reps=2, optimizer=COBYLA(maxiter=100), local=True) sol7_local_qaoa_spsa = Optimization_QAOA(qubo_7vars, reps=2, optimizer=SPSA(maxiter=100), local=True) IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-community', group='cdl-hackathon', project='main') provider2 = IBMQ.get_provider(hub='ibm-q-research', group='guanajuato-1', project='main') sol7_oslo_qaoa_cobyla = Optimization_QAOA(qubo_7vars, reps=2, local=False, backend=provider2.backend.ibm_oslo, provider=provider2, optimizer=COBYLA(maxiter=50)) sol7_oslo_qaoa_spsa = Optimization_QAOA(qubo_7vars, reps=2, local=False, backend=provider2.backend.ibm_oslo, provider=provider2, optimizer=SPSA(maxiter=50)) sol7_oslo_qaoa_spsa_mitig = Optimization_QAOA(qubo_7vars, reps=2, local=False, backend=provider2.backend.ibm_oslo, provider=provider2, optimizer=SPSA(maxiter=50), error_mitigation=True) ansatz = TwoLocal(qubo_7vars.get_num_vars(), rotation_blocks='ry', entanglement_blocks='cz') sol7_local_vqe_spsa = Optimization_VQE(qubo_7vars, ansatz, local=True, optimizer=SPSA(maxiter=200)) sol7_local_vqe_cobyla = Optimization_VQE(qubo_7vars, ansatz, local=True, optimizer=COBYLA(maxiter=200)) sol7_lagos_vqe_cobyla = Optimization_VQE(qubo_7vars, ansatz, local=False, optimizer=COBYLA(maxiter=100), backend=provider2.backend.ibm_lagos, provider=provider2) sol7_lagos_vqe_spsa = Optimization_VQE(qubo_7vars, ansatz, local=False, optimizer=SPSA(maxiter=25), backend=provider2.backend.ibm_lagos, provider=provider2) sol7_lagos_vqe_spsa2 = Optimization_VQE(qubo_7vars, ansatz, local=False, optimizer=SPSA(maxiter=25), backend=provider2.backend.ibm_lagos, provider=provider2, error_mitigation=True) plt.figure() plt.plot(sol7_lagos_vqe_spsa[1]["mean"], linestyle=":", color="seagreen", label="VQE-Lagos-SPSA") plt.plot(sol7_lagos_vqe_spsa2[1]["mean"], linestyle="-.", color="indigo", label="VQE-Lagos-SPSA-Mitig") plt.plot(sol7_lagos_vqe_cobyla[1]["mean"], color="olive", label="VQE-Lagos-COBYLA-Mitig") plt.grid() plt.savefig("./Images/inset.png") plt.figure() plt.plot(sol7_oslo_qaoa_spsa[1]["mean"], linestyle=":", color="seagreen", label="QAOA-Oslo-SPSA") plt.plot(sol7_oslo_qaoa_cobyla[1]["mean"], color="olive", label="QAOA-Oslo-COBYLA") plt.grid() plt.savefig("./Images/inset2.png") sol7 = {"local_qaoa_cobyla":sol7_local_qaoa_cobyla, "local_vqe_cobyla":sol7_local_vqe_cobyla, "local_qaoa_spsa":sol7_local_qaoa_spsa, "local_vqe_spsa":sol7_local_vqe_spsa, "oslo_qaoa_cobyla":sol7_oslo_qaoa_cobyla, "oslo_qaoa_spsa":sol7_oslo_qaoa_spsa, "lagos_vqe_spsa":sol7_lagos_vqe_spsa, "lagos_vqe_cobyla_mitig":sol7_lagos_vqe_cobyla} np.save("./Data/sol7.npy", sol7) sol7 = [sol7_local_qaoa_cobyla, sol7_local_vqe_cobyla, sol7_local_qaoa_spsa, sol7_local_vqe_spsa] q_alg = ["QAOA", "VQE"] fig, ax = plt.subplots(3,2, figsize=(15,18)) ax[0,0].plot(sol7_local_qaoa_cobyla[1]["mean"], color="darkblue", label="QAOA-COBYLA") ax[0,0].plot(sol7_local_qaoa_spsa[1]["mean"], linestyle="--", color="lightcoral", label="QAOA-SPSA") ax[0,0].plot(sol7_oslo_qaoa_spsa[1]["mean"], linestyle=":", color="seagreen", label="QAOA-Oslo-SPSA") ax[0,0].plot(sol7_oslo_qaoa_cobyla[1]["mean"], color="olive", label="QAOA-Oslo-COBYLA") ax[0,1].plot(sol7_local_vqe_cobyla[1]["mean"], color="darkblue", label="VQE-COBYLA") ax[0,1].plot(sol7_local_vqe_spsa[1]["mean"], linestyle="--", color="lightcoral", label="VQE-SPSA") ax[0,1].plot(sol7_lagos_vqe_spsa[1]["mean"], linestyle=":", color="seagreen", label="VQE-Lagos-SPSA") ax[0,1].plot(sol7_lagos_vqe_spsa2[1]["mean"], linestyle="-.", color="indigo", label="VQE-Lagos-SPSA-Mitig") ax[0,1].plot(sol7_lagos_vqe_cobyla[1]["mean"], color="olive", label="VQE-Lagos-COBYLA-Mitig") for i in range(2): ax[0,i].set_xlabel("Iterations", fontsize=14) ax[0,i].set_ylabel("Cost", fontsize=14) ax[0,i].legend() ax[0,i].grid() plt.sca(ax[1,i]) nx.draw(graph(sol7[i][0].variables_dict,solution_not_kept7), pos=companies, with_labels=True, node_size=500, edge_color=colors, width=1, font_color="white",font_size=14, node_color = ["tab:red"] + (n_companies-1)*["darkblue"]) ax[1,i].set_title(f"{q_alg[i]}-COBYLA", fontsize=14) plt.sca(ax[2,i]) nx.draw(graph(sol7[i+2][0].variables_dict,solution_not_kept7), pos=companies, with_labels=True, node_size=500, edge_color=colors, width=1, font_color="white",font_size=14, node_color = ["tab:red"] + (n_companies-1)*["darkblue"]) ax[2,i].set_title(f"{q_alg[i]}-SPSA", fontsize=14) plt.savefig("./Images/Sol7Q.png") num_1s = 5 num_0s = 10 random.seed(1) keep_1s = random.sample(index_1s, num_1s) keep_0s = random.sample(index_0s, num_0s) sol_qubo = sol.variables_dict solution_not_kept = {i:sol_qubo[i] for i in sol_qubo.keys() if i not in keep_1s + keep_0s} qubo_15vars = qubo_no_slack.substitute_variables(solution_not_kept) sol15_qasm_qaoa_cobyla = Optimization_QAOA(qubo_15vars, reps=3, local=False, backend=provider2.backend.ibmq_qasm_simulator, provider=provider2, optimizer=COBYLA(maxiter=100)) solution15_qaoa = sol15_qasm_qaoa_cobyla[0].variables_dict G_sol15_qaoa = nx.Graph() G_sol15_qaoa.add_nodes_from(range(n_companies)) for k, v in solution15_qaoa.items(): if v == 1: nodes = k[2:].split("_") G_sol15_qaoa.add_edge(int(nodes[0]), int(nodes[1])) for k, v in solution_not_kept.items(): if v == 1: nodes = k[2:].split("_") G_sol15_qaoa.add_edge(int(nodes[0]), int(nodes[1])) nx.draw(G_sol15_qaoa, pos=companies, with_labels=True, node_size=500, edge_color=colors, width=1, font_color="white",font_size=14, node_color = ["tab:red"] + (n_companies-1)*["darkblue"]) sol15_qasm_qaoa_spsa = Optimization_QAOA(qubo_15vars, reps=3, local=False, backend=provider2.backend.ibmq_qasm_simulator, provider=provider2, optimizer=SPSA(maxiter=25)) ansatz15 = TwoLocal(qubo_15vars.get_num_vars(), rotation_blocks='ry', entanglement_blocks='cz') sol15_qasm_vqe_cobyla = Optimization_VQE(qubo_15vars,ansatz=ansatz15, local=False, backend=provider2.backend.ibmq_qasm_simulator, provider=provider2, optimizer=COBYLA(maxiter=100)) solution15_vqe = sol15_qasm_vqe_cobyla[0].variables_dict G_sol15_vqe = nx.Graph() G_sol15_vqe.add_nodes_from(range(n_companies)) for k, v in solution15_vqe.items(): if v == 1: nodes = k[2:].split("_") G_sol15_vqe.add_edge(int(nodes[0]), int(nodes[1])) for k, v in solution_not_kept.items(): if v == 1: nodes = k[2:].split("_") G_sol15_vqe.add_edge(int(nodes[0]), int(nodes[1])) nx.draw(G_sol15_vqe, pos=companies, with_labels=True, node_size=500, edge_color=colors, width=1, font_color="white",font_size=14, node_color = ["tab:red"] + (n_companies-1)*["darkblue"]) sol15_qasm = {"qaoa_cobyla":sol15_qasm_qaoa_cobyla, "vqe_cobyla":sol15_qasm_vqe_cobyla} np.save("./Data/sol15_qasm.npy", sol15_qasm) solution15 = [G_sol15_qaoa, G_sol15_vqe] fig, ax = plt.subplots(2,2, figsize=(15,10)) ax[0,0].plot(sol15_qasm_qaoa_cobyla[1]["mean"], color="darkblue", label="QAOA-COBYLA") ax[0,1].plot(sol15_qasm_vqe_cobyla[1]["mean"], color="slateblue", label="VQE-COBYLA") for i in range(2): ax[0,i].grid() ax[0,i].set_xlabel("Iterations", fontsize=14) ax[0,i].set_ylabel("Cost", fontsize=14) ax[0,i].legend() plt.sca(ax[1,i]) nx.draw(solution15[i], pos=companies, with_labels=True, node_size=500, edge_color=colors, width=1, font_color="white",font_size=14, node_color = ["tab:red"] + (n_companies-1)*["darkblue"]) fig.savefig("./Images/Sol15Q.png") num_1s = 8 num_0s = 12 random.seed(1) keep_1s = random.sample(index_1s, num_1s) keep_0s = random.sample(index_0s, num_0s) sol_qubo = sol.variables_dict solution_not_kept = {i:sol_qubo[i] for i in sol_qubo.keys() if i not in keep_1s + keep_0s} qubo_20vars = qubo_no_slack.substitute_variables(solution_not_kept) sol20_qasm_qaoa_cobyla_r1 = Optimization_QAOA(qubo_20vars, reps=1, local=False, backend=provider2.backend.ibmq_qasm_simulator, provider=provider2, optimizer=COBYLA(maxiter=10))
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. """Test RemoveResetInZeroState pass""" import unittest from qiskit import QuantumRegister, QuantumCircuit from qiskit.transpiler import PassManager from qiskit.transpiler.passes import RemoveResetInZeroState, DAGFixedPoint from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase class TestRemoveResetInZeroState(QiskitTestCase): """Test swap-followed-by-measure optimizations.""" def test_optimize_single_reset(self): """Remove a single reset qr0:--|0>-- ==> qr0:---- """ qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.reset(qr) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) pass_ = RemoveResetInZeroState() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_dont_optimize_non_zero_state(self): """Do not remove reset if not in a zero state qr0:--[H]--|0>-- ==> qr0:--[H]--|0>-- """ qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.h(qr) circuit.reset(qr) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.h(qr) expected.reset(qr) pass_ = RemoveResetInZeroState() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_optimize_single_reset_in_diff_qubits(self): """Remove a single reset in different qubits qr0:--|0>-- qr0:---- ==> qr1:--|0>-- qr1:---- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.reset(qr) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) pass_ = RemoveResetInZeroState() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) class TestRemoveResetInZeroStateFixedPoint(QiskitTestCase): """Test RemoveResetInZeroState in a transpiler, using fixed point.""" def test_two_resets(self): """Remove two initial resets qr0:--|0>-|0>-- ==> qr0:---- """ qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.reset(qr[0]) circuit.reset(qr[0]) expected = QuantumCircuit(qr) pass_manager = PassManager() pass_manager.append( [RemoveResetInZeroState(), DAGFixedPoint()], do_while=lambda property_set: not property_set["dag_fixed_point"], ) after = pass_manager.run(circuit) self.assertEqual(expected, after) if __name__ == "__main__": unittest.main()
https://github.com/Qiskit/feedback
Qiskit
import numpy from qiskit.circuit.library import GraphState from qiskit.test.mock import FakeMumbai from qiskit.transpiler import CouplingMap from qiskit.transpiler.passes import VF2Layout, CSPLayout from qiskit.visualization import plot_gate_map, plot_circuit_layout backend = FakeMumbai() config = backend.configuration() cm = config.coupling_map size = config.n_qubits display(plot_gate_map(backend)) rows = [x[0] for x in cm] cols = [x[1] for x in cm] A = numpy.zeros((size, size)) A[rows, cols] = 1 from random import shuffle random_map = list(range(size)) shuffle(random_map) B = numpy.zeros((size, size)) for i in range(size): for j in range(size): B[i][j] = A[random_map[i]][random_map[j]] A = B circuit = GraphState(A).decompose() circuit.draw(fold=-1) vf2_pass = VF2Layout(CouplingMap(cm)) csp_pass = CSPLayout(CouplingMap(cm), time_limit=None, call_limit=None) csp_transpiled = csp_pass(circuit) vf2_transpiled = vf2_pass(circuit) plot_circuit_layout(vf2_transpiled, backend) plot_circuit_layout(csp_transpiled, backend) from qiskit import QuantumCircuit # T-shape interaction map circuit = QuantumCircuit(5) circuit.cx(0,1) circuit.cx(0,2) circuit.cx(0,3) circuit.cx(3,4) # Multiple possible answers. This allows for noise-awareness (ish). vf2_transpiled = vf2_pass(circuit) vf2_transpiled
https://github.com/tanmaybisen31/Quantum-Teleportation
tanmaybisen31
# Do the necessary imports import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import IBMQ, Aer, transpile, assemble from qiskit.visualization import plot_histogram, plot_bloch_multivector, array_to_latex from qiskit.extensions import Initialize from qiskit.ignis.verification import marginal_counts from qiskit.quantum_info import random_statevector # Loading your IBM Quantum account(s) provider = IBMQ.load_account() ## SETUP # Protocol uses 3 qubits and 2 classical bits in 2 different registers qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits crz = ClassicalRegister(1, name="crz") # and 2 classical bits crx = ClassicalRegister(1, name="crx") # in 2 different registers teleportation_circuit = QuantumCircuit(qr, crz, crx) def create_bell_pair(qc, a, b): qc.h(a) qc.cx(a,b) qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) create_bell_pair(teleportation_circuit, 1, 2) teleportation_circuit.draw() def alice_gates(qc, psi, a): qc.cx(psi, a) qc.h(psi) qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) ## STEP 1 create_bell_pair(teleportation_circuit, 1, 2) ## STEP 2 teleportation_circuit.barrier() # Use barrier to separate steps alice_gates(teleportation_circuit, 0, 1) teleportation_circuit.draw() 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) qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) create_bell_pair(teleportation_circuit, 1, 2) teleportation_circuit.barrier() # Use barrier to separate steps alice_gates(teleportation_circuit, 0, 1) measure_and_send(teleportation_circuit, 0 ,1) teleportation_circuit.draw() def bob_gates(qc, qubit, crz, crx): qc.x(qubit).c_if(crx, 1) # Apply gates if the registers qc.z(qubit).c_if(crz, 1) # are in the state '1' qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) ## STEP 1 create_bell_pair(teleportation_circuit, 1, 2) ## STEP 2 teleportation_circuit.barrier() # Use barrier to separate steps alice_gates(teleportation_circuit, 0, 1) ## STEP 3 measure_and_send(teleportation_circuit, 0, 1) ## STEP 4 teleportation_circuit.barrier() # Use barrier to separate steps bob_gates(teleportation_circuit, 2, crz, crx) teleportation_circuit.draw() # Create random 1-qubit state psi = random_statevector(2) # Display it nicely display(array_to_latex(psi, prefix="|\\psi\\rangle =")) # Show it on a Bloch sphere plot_bloch_multivector(psi) init_gate = Initialize(psi) init_gate.label = "init" ## SETUP qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits crz = ClassicalRegister(1, name="crz") # and 2 classical registers crx = ClassicalRegister(1, name="crx") qc = QuantumCircuit(qr, crz, crx) ## STEP 0 # First, let's initialize Alice's q0 qc.append(init_gate, [0]) qc.barrier() ## STEP 1 # Now begins the teleportation protocol create_bell_pair(qc, 1, 2) qc.barrier() ## STEP 2 # Send q1 to Alice and q2 to Bob alice_gates(qc, 0, 1) ## STEP 3 # Alice then sends her classical bits to Bob measure_and_send(qc, 0, 1) ## STEP 4 # Bob decodes qubits bob_gates(qc, 2, crz, crx) # Display the circuit qc.draw() 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/yonahirakawa/qiskit-iniciantes
yonahirakawa
from qiskit.visualization import plot_bloch_vector plot_bloch_vector([1,0,0], title="Esfera de Bloch") from qiskit.visualization import plot_bloch_vector, bloch from matplotlib.pyplot import text from math import pi, cos, sin from qutip import * # angles that represent our state theta = pi/2 phi = 4*pi/3 # calculating the coordinates x = sin(theta)*cos(phi) y = sin(theta)*sin(phi) z = cos(theta) # preparing the sphere sphere = bloch sphere.Bloch b = Bloch() # preparing the lables b.ylpos = [1.1, -1.2] b.xlabel = ['$\\left|0\\right>+\\left|1\\right>$', '$\\left|0\\right>-\\left|1\\right>$'] b.ylabel = ['$\\left|0\\right>+i\\left|1\\right>$', '$\\left|0\\right>-i\\left|1\\right>$'] # first 6 drawn vectors will be blue, the 7th - red b.vector_color = ['b','b','b','b','b','b','r'] # drawing vectors of orthogonal states (most popular bases), note the coordinates of vectors, # they correspond to the according states. b.add_vectors([[0,0,1],[0,0,-1],[0,1,0],[0,-1,0],[1,0,0],[-1,0,0]]) # drawing our state (as 7th vector) b.add_vectors([x,y,z]) # showing the Bloch sphere with all that we have prepared b.show()
https://github.com/harshagarine/QISKIT_INDIA_CHALLENGE
harshagarine
### WRITE YOUR CODE BETWEEN THESE LINES - START # import libraries that are used in the function below. from qiskit import QuantumCircuit import numpy as np from math import sqrt, pi ### WRITE YOUR CODE BETWEEN THESE LINES - END def build_state(): # create a quantum circuit on one qubit circuit = QuantumCircuit(1) ### WRITE YOUR CODE BETWEEN THESE LINES - START init = [1/sqrt(2),0-1j/sqrt(2)] circuit.initialize(init,0) # apply necessary gates circuit.rx(pi/2,0) ### WRITE YOUR CODE BETWEEN THESE LINES - END return circuit
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """ Testing InverseCancellation """ import unittest import numpy as np from qiskit import QuantumCircuit from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.passes import InverseCancellation from qiskit.transpiler import PassManager from qiskit.test import QiskitTestCase from qiskit.circuit.library import RXGate, HGate, CXGate, PhaseGate, XGate, TGate, TdgGate class TestInverseCancellation(QiskitTestCase): """Test the InverseCancellation transpiler pass.""" def test_basic_self_inverse(self): """Test that a single self-inverse gate as input can be cancelled.""" qc = QuantumCircuit(2, 2) qc.h(0) qc.h(0) pass_ = InverseCancellation([HGate()]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertNotIn("h", gates_after) def test_odd_number_self_inverse(self): """Test that an odd number of self-inverse gates leaves one gate remaining.""" qc = QuantumCircuit(2, 2) qc.h(0) qc.h(0) qc.h(0) pass_ = InverseCancellation([HGate()]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertIn("h", gates_after) self.assertEqual(gates_after["h"], 1) def test_basic_cx_self_inverse(self): """Test that a single self-inverse cx gate as input can be cancelled.""" qc = QuantumCircuit(2, 2) qc.cx(0, 1) qc.cx(0, 1) pass_ = InverseCancellation([CXGate()]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertNotIn("cx", gates_after) def test_basic_gate_inverse(self): """Test that a basic pair of gate inverse can be cancelled.""" qc = QuantumCircuit(2, 2) qc.rx(np.pi / 4, 0) qc.rx(-np.pi / 4, 0) pass_ = InverseCancellation([(RXGate(np.pi / 4), RXGate(-np.pi / 4))]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertNotIn("rx", gates_after) def test_non_inverse_do_not_cancel(self): """Test that non-inverse gate pairs do not cancel.""" qc = QuantumCircuit(2, 2) qc.rx(np.pi / 4, 0) qc.rx(np.pi / 4, 0) pass_ = InverseCancellation([(RXGate(np.pi / 4), RXGate(-np.pi / 4))]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertIn("rx", gates_after) self.assertEqual(gates_after["rx"], 2) def test_non_consecutive_gates(self): """Test that only consecutive gates cancel.""" qc = QuantumCircuit(2, 2) qc.h(0) qc.h(0) qc.h(0) qc.cx(0, 1) qc.cx(0, 1) qc.h(0) pass_ = InverseCancellation([HGate(), CXGate()]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertNotIn("cx", gates_after) self.assertEqual(gates_after["h"], 2) def test_gate_inverse_phase_gate(self): """Test that an inverse pair of a PhaseGate can be cancelled.""" qc = QuantumCircuit(2, 2) qc.p(np.pi / 4, 0) qc.p(-np.pi / 4, 0) pass_ = InverseCancellation([(PhaseGate(np.pi / 4), PhaseGate(-np.pi / 4))]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertNotIn("p", gates_after) def test_self_inverse_on_different_qubits(self): """Test that self_inverse gates cancel on the correct qubits.""" qc = QuantumCircuit(2, 2) qc.h(0) qc.h(1) qc.h(0) qc.h(1) pass_ = InverseCancellation([HGate()]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertNotIn("h", gates_after) def test_non_inverse_raise_error(self): """Test that non-inverse gate inputs raise an error.""" qc = QuantumCircuit(2, 2) qc.rx(np.pi / 2, 0) qc.rx(np.pi / 4, 0) with self.assertRaises(TranspilerError): InverseCancellation([RXGate(0.5)]) def test_non_gate_inverse_raise_error(self): """Test that non-inverse gate inputs raise an error.""" qc = QuantumCircuit(2, 2) qc.rx(np.pi / 4, 0) qc.rx(np.pi / 4, 0) with self.assertRaises(TranspilerError): InverseCancellation([(RXGate(np.pi / 4))]) def test_string_gate_error(self): """Test that when gate is passed as a string an error is raised.""" qc = QuantumCircuit(2, 2) qc.h(0) qc.h(0) with self.assertRaises(TranspilerError): InverseCancellation(["h"]) def test_consecutive_self_inverse_h_x_gate(self): """Test that only consecutive self-inverse gates cancel.""" qc = QuantumCircuit(2, 2) qc.h(0) qc.h(0) qc.h(0) qc.x(0) qc.x(0) qc.h(0) pass_ = InverseCancellation([HGate(), XGate()]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertNotIn("x", gates_after) self.assertEqual(gates_after["h"], 2) def test_inverse_with_different_names(self): """Test that inverse gates that have different names.""" qc = QuantumCircuit(2, 2) qc.t(0) qc.tdg(0) pass_ = InverseCancellation([(TGate(), TdgGate())]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertNotIn("t", gates_after) self.assertNotIn("tdg", gates_after) def test_three_alternating_inverse_gates(self): """Test that inverse cancellation works correctly for alternating sequences of inverse gates of odd-length.""" qc = QuantumCircuit(2, 2) qc.p(np.pi / 4, 0) qc.p(-np.pi / 4, 0) qc.p(np.pi / 4, 0) pass_ = InverseCancellation([(PhaseGate(np.pi / 4), PhaseGate(-np.pi / 4))]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertIn("p", gates_after) self.assertEqual(gates_after["p"], 1) def test_four_alternating_inverse_gates(self): """Test that inverse cancellation works correctly for alternating sequences of inverse gates of even-length.""" qc = QuantumCircuit(2, 2) qc.p(np.pi / 4, 0) qc.p(-np.pi / 4, 0) qc.p(np.pi / 4, 0) qc.p(-np.pi / 4, 0) pass_ = InverseCancellation([(PhaseGate(np.pi / 4), PhaseGate(-np.pi / 4))]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertNotIn("p", gates_after) def test_five_alternating_inverse_gates(self): """Test that inverse cancellation works correctly for alternating sequences of inverse gates of odd-length.""" qc = QuantumCircuit(2, 2) qc.p(np.pi / 4, 0) qc.p(-np.pi / 4, 0) qc.p(np.pi / 4, 0) qc.p(-np.pi / 4, 0) qc.p(np.pi / 4, 0) pass_ = InverseCancellation([(PhaseGate(np.pi / 4), PhaseGate(-np.pi / 4))]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertIn("p", gates_after) self.assertEqual(gates_after["p"], 1) def test_sequence_of_inverse_gates_1(self): """Test that inverse cancellation works correctly for more general sequences of inverse gates. In this test two pairs of inverse gates are supposed to cancel out.""" qc = QuantumCircuit(2, 2) qc.p(np.pi / 4, 0) qc.p(-np.pi / 4, 0) qc.p(-np.pi / 4, 0) qc.p(np.pi / 4, 0) qc.p(np.pi / 4, 0) pass_ = InverseCancellation([(PhaseGate(np.pi / 4), PhaseGate(-np.pi / 4))]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertIn("p", gates_after) self.assertEqual(gates_after["p"], 1) def test_sequence_of_inverse_gates_2(self): """Test that inverse cancellation works correctly for more general sequences of inverse gates. In this test, in theory three pairs of inverse gates can cancel out, but in practice only two pairs are back-to-back.""" qc = QuantumCircuit(2, 2) qc.p(np.pi / 4, 0) qc.p(np.pi / 4, 0) qc.p(-np.pi / 4, 0) qc.p(-np.pi / 4, 0) qc.p(-np.pi / 4, 0) qc.p(np.pi / 4, 0) qc.p(np.pi / 4, 0) pass_ = InverseCancellation([(PhaseGate(np.pi / 4), PhaseGate(-np.pi / 4))]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertIn("p", gates_after) self.assertEqual(gates_after["p"] % 2, 1) def test_cx_do_not_wrongly_cancel(self): """Test that CX(0,1) and CX(1, 0) do not cancel out, when (CX, CX) is passed as an inverse pair.""" qc = QuantumCircuit(2, 0) qc.cx(0, 1) qc.cx(1, 0) pass_ = InverseCancellation([(CXGate(), CXGate())]) pm = PassManager(pass_) new_circ = pm.run(qc) gates_after = new_circ.count_ops() self.assertIn("cx", gates_after) self.assertEqual(gates_after["cx"], 2) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
#General imports import numpy as np #Operator Imports from qiskit.opflow import Z, X, I, StateFn, CircuitStateFn, SummedOp from qiskit.opflow.gradients import Gradient, NaturalGradient, QFI, Hessian #Circuit imports from qiskit.circuit import QuantumCircuit, QuantumRegister, Parameter, ParameterVector, ParameterExpression from qiskit.circuit.library import EfficientSU2 # Instantiate the quantum state a = Parameter('a') b = Parameter('b') q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.rz(a, q[0]) qc.rx(b, q[0]) # Instantiate the Hamiltonian observable H = (2 * X) + Z # Combine the Hamiltonian observable and the state op = ~StateFn(H) @ CircuitStateFn(primitive=qc, coeff=1.) # Print the operator corresponding to the expectation value print(op) params = [a, b] # Define the values to be assigned to the parameters value_dict = {a: np.pi / 4, b: np.pi} # Convert the operator and the gradient target params into the respective operator grad = Gradient().convert(operator = op, params = params) # Print the operator corresponding to the Gradient print(grad) # Assign the parameters and evaluate the gradient grad_result = grad.assign_parameters(value_dict).eval() print('Gradient', grad_result) # Define the Hamiltonian with fixed coefficients H = 0.5 * X - 1 * Z # Define the parameters w.r.t. we want to compute the gradients params = [a, b] # Define the values to be assigned to the parameters value_dict = { a: np.pi / 4, b: np.pi} # Combine the Hamiltonian observable and the state into an expectation value operator op = ~StateFn(H) @ CircuitStateFn(primitive=qc, coeff=1.) print(op) # Convert the expectation value into an operator corresponding to the gradient w.r.t. the state parameters using # the parameter shift method. state_grad = Gradient(grad_method='param_shift').convert(operator=op, params=params) # Print the operator corresponding to the gradient print(state_grad) # Assign the parameters and evaluate the gradient state_grad_result = state_grad.assign_parameters(value_dict).eval() print('State gradient computed with parameter shift', state_grad_result) # Convert the expectation value into an operator corresponding to the gradient w.r.t. the state parameter using # the linear combination of unitaries method. state_grad = Gradient(grad_method='lin_comb').convert(operator=op, params=params) # Print the operator corresponding to the gradient print(state_grad) # Assign the parameters and evaluate the gradient state_grad_result = state_grad.assign_parameters(value_dict).eval() print('State gradient computed with the linear combination method', state_grad_result) # Convert the expectation value into an operator corresponding to the gradient w.r.t. the state parameter using # the finite difference method. state_grad = Gradient(grad_method='fin_diff').convert(operator=op, params=params) # Print the operator corresponding to the gradient print(state_grad) # Assign the parameters and evaluate the gradient state_grad_result = state_grad.assign_parameters(value_dict).eval() print('State gradient computed with finite difference', state_grad_result) # Besides the method to compute the circuit gradients resp. QFI, a regularization method can be chosen: # `ridge` or `lasso` with automatic parameter search or `perturb_diag_elements` or `perturb_diag` # which perturb the diagonal elements of the QFI. nat_grad = NaturalGradient(grad_method='lin_comb', qfi_method='lin_comb_full', regularization='ridge').convert( operator=op, params=params) # Assign the parameters and evaluate the gradient nat_grad_result = nat_grad.assign_parameters(value_dict).eval() print('Natural gradient computed with linear combination of unitaries', nat_grad_result) # Instantiate the Hamiltonian observable H = X # Instantiate the quantum state with two parameters a = Parameter('a') b = Parameter('b') q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.rz(a, q[0]) qc.rx(b, q[0]) # Combine the Hamiltonian observable and the state op = ~StateFn(H) @ CircuitStateFn(primitive=qc, coeff=1.) # Convert the operator and the hessian target coefficients into the respective operator hessian = Hessian().convert(operator = op, params = [a, b]) # Define the values to be assigned to the parameters value_dict = {a: np.pi / 4, b: np.pi/4} # Assign the parameters and evaluate the Hessian w.r.t. the Hamiltonian coefficients hessian_result = hessian.assign_parameters(value_dict).eval() print('Hessian \n', np.real(np.array(hessian_result))) # Define parameters params = [a, b] # Get the operator object representing the Hessian state_hess = Hessian(hess_method='param_shift').convert(operator=op, params=params) # Assign the parameters and evaluate the Hessian hessian_result = state_hess.assign_parameters(value_dict).eval() print('Hessian computed using the parameter shift method\n', (np.array(hessian_result))) # Get the operator object representing the Hessian state_hess = Hessian(hess_method='lin_comb').convert(operator=op, params=params) # Assign the parameters and evaluate the Hessian hessian_result = state_hess.assign_parameters(value_dict).eval() print('Hessian computed using the linear combination of unitaries method\n', (np.array(hessian_result))) # Get the operator object representing the Hessian using finite difference state_hess = Hessian(hess_method='fin_diff').convert(operator=op, params=params) # Assign the parameters and evaluate the Hessian hessian_result = state_hess.assign_parameters(value_dict).eval() print('Hessian computed with finite difference\n', (np.array(hessian_result))) # Wrap the quantum circuit into a CircuitStateFn state = CircuitStateFn(primitive=qc, coeff=1.) # Convert the state and the parameters into the operator object that represents the QFI qfi = QFI(qfi_method='lin_comb_full').convert(operator=state, params=params) # Define the values for which the QFI is to be computed values_dict = {a: np.pi / 4, b: 0.1} # Assign the parameters and evaluate the QFI qfi_result = qfi.assign_parameters(values_dict).eval() print('full QFI \n', np.real(np.array(qfi_result))) # Convert the state and the parameters into the operator object that represents the QFI # and set the approximation to 'block_diagonal' qfi = QFI('overlap_block_diag').convert(operator=state, params=params) # Assign the parameters and evaluate the QFI qfi_result = qfi.assign_parameters(values_dict).eval() print('Block-diagonal QFI \n', np.real(np.array(qfi_result))) # Convert the state and the parameters into the operator object that represents the QFI # and set the approximation to 'diagonal' qfi = QFI('overlap_diag').convert(operator=state, params=params) # Assign the parameters and evaluate the QFI qfi_result = qfi.assign_parameters(values_dict).eval() print('Diagonal QFI \n', np.real(np.array(qfi_result))) # Execution Imports from qiskit import Aer from qiskit.utils import QuantumInstance # Algorithm Imports from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import CG from qiskit.opflow import I, X, Z from qiskit.circuit import QuantumCircuit, ParameterVector from scipy.optimize import minimize # Instantiate the system Hamiltonian h2_hamiltonian = -1.05 * (I ^ I) + 0.39 * (I ^ Z) - 0.39 * (Z ^ I) - 0.01 * (Z ^ Z) + 0.18 * (X ^ X) # This is the target energy h2_energy = -1.85727503 # Define the Ansatz wavefunction = QuantumCircuit(2) params = ParameterVector('theta', length=8) it = iter(params) wavefunction.ry(next(it), 0) wavefunction.ry(next(it), 1) wavefunction.rz(next(it), 0) wavefunction.rz(next(it), 1) wavefunction.cx(0, 1) wavefunction.ry(next(it), 0) wavefunction.ry(next(it), 1) wavefunction.rz(next(it), 0) wavefunction.rz(next(it), 1) # Define the expectation value corresponding to the energy op = ~StateFn(h2_hamiltonian) @ StateFn(wavefunction) grad = Gradient(grad_method='lin_comb') qi_sv = QuantumInstance(Aer.get_backend('aer_simulator_statevector'), shots=1, seed_simulator=2, seed_transpiler=2) #Conjugate Gradient algorithm optimizer = CG(maxiter=50) # Gradient callable vqe = VQE(wavefunction, optimizer=optimizer, gradient=grad, quantum_instance=qi_sv) result = vqe.compute_minimum_eigenvalue(h2_hamiltonian) print('Result:', result.optimal_value, 'Reference:', h2_energy) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 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. # pylint: disable=invalid-name """Tests for error mitigation routines.""" import unittest from collections import Counter import numpy as np from qiskit import QiskitError, QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.result import ( CorrelatedReadoutMitigator, Counts, LocalReadoutMitigator, ) from qiskit.result.mitigation.utils import ( counts_probability_vector, expval_with_stddev, stddev, str2diag, ) from qiskit.result.utils import marginal_counts from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeYorktown class TestReadoutMitigation(QiskitTestCase): """Tests for correlated and local readout mitigation.""" @classmethod def setUpClass(cls): super().setUpClass() cls.rng = np.random.default_rng(42) @staticmethod def compare_results(res1, res2): """Compare the results between two runs""" res1_total_shots = sum(res1.values()) res2_total_shots = sum(res2.values()) keys = set(res1.keys()).union(set(res2.keys())) total = 0 for key in keys: val1 = res1.get(key, 0) / res1_total_shots val2 = res2.get(key, 0) / res2_total_shots total += abs(val1 - val2) ** 2 return total @staticmethod def mitigators(assignment_matrices, qubits=None): """Generates the mitigators to test for given assignment matrices""" full_assignment_matrix = assignment_matrices[0] for m in assignment_matrices[1:]: full_assignment_matrix = np.kron(full_assignment_matrix, m) CRM = CorrelatedReadoutMitigator(full_assignment_matrix, qubits) LRM = LocalReadoutMitigator(assignment_matrices, qubits) mitigators = [CRM, LRM] return mitigators @staticmethod def simulate_circuit(circuit, assignment_matrix, num_qubits, shots=1024): """Simulates the given circuit under the given readout noise""" probs = Statevector.from_instruction(circuit).probabilities() noisy_probs = assignment_matrix @ probs labels = [bin(a)[2:].zfill(num_qubits) for a in range(2**num_qubits)] results = TestReadoutMitigation.rng.choice(labels, size=shots, p=noisy_probs) return Counts(dict(Counter(results))) @staticmethod def ghz_3_circuit(): """A 3-qubit circuit generating |000>+|111>""" c = QuantumCircuit(3) c.h(0) c.cx(0, 1) c.cx(1, 2) return (c, "ghz_3_ciruit", 3) @staticmethod def first_qubit_h_3_circuit(): """A 3-qubit circuit generating |000>+|001>""" c = QuantumCircuit(3) c.h(0) return (c, "first_qubit_h_3_circuit", 3) @staticmethod def assignment_matrices(): """A 3-qubit readout noise assignment matrices""" return LocalReadoutMitigator(backend=FakeYorktown())._assignment_mats[0:3] @staticmethod def counts_data(circuit, assignment_matrices, shots=1024): """Generates count data for the noisy and noiseless versions of the circuit simulation""" full_assignment_matrix = assignment_matrices[0] for m in assignment_matrices[1:]: full_assignment_matrix = np.kron(full_assignment_matrix, m) num_qubits = len(assignment_matrices) ideal_assignment_matrix = np.eye(2**num_qubits) counts_ideal = TestReadoutMitigation.simulate_circuit( circuit, ideal_assignment_matrix, num_qubits, shots ) counts_noise = TestReadoutMitigation.simulate_circuit( circuit, full_assignment_matrix, num_qubits, shots ) probs_noise = {key: value / shots for key, value in counts_noise.items()} return counts_ideal, counts_noise, probs_noise def test_mitigation_improvement(self): """Test whether readout mitigation led to more accurate results""" shots = 1024 assignment_matrices = self.assignment_matrices() num_qubits = len(assignment_matrices) mitigators = self.mitigators(assignment_matrices) circuit, circuit_name, num_qubits = self.ghz_3_circuit() counts_ideal, counts_noise, probs_noise = self.counts_data( circuit, assignment_matrices, shots ) unmitigated_error = self.compare_results(counts_ideal, counts_noise) unmitigated_stddev = stddev(probs_noise, shots) for mitigator in mitigators: mitigated_quasi_probs = mitigator.quasi_probabilities(counts_noise) mitigated_probs = ( mitigated_quasi_probs.nearest_probability_distribution().binary_probabilities( num_bits=num_qubits ) ) mitigated_error = self.compare_results(counts_ideal, mitigated_probs) self.assertLess( mitigated_error, unmitigated_error * 0.8, "Mitigator {} did not improve circuit {} measurements".format( mitigator, circuit_name ), ) mitigated_stddev_upper_bound = mitigated_quasi_probs._stddev_upper_bound max_unmitigated_stddev = max(unmitigated_stddev.values()) self.assertGreaterEqual( mitigated_stddev_upper_bound, max_unmitigated_stddev, "Mitigator {} on circuit {} gave stddev upper bound {} " "while unmitigated stddev maximum is {}".format( mitigator, circuit_name, mitigated_stddev_upper_bound, max_unmitigated_stddev, ), ) def test_expectation_improvement(self): """Test whether readout mitigation led to more accurate results and that its standard deviation is increased""" shots = 1024 assignment_matrices = self.assignment_matrices() mitigators = self.mitigators(assignment_matrices) num_qubits = len(assignment_matrices) diagonals = [] diagonals.append("IZ0") diagonals.append("101") diagonals.append("IZZ") qubit_index = {i: i for i in range(num_qubits)} circuit, circuit_name, num_qubits = self.ghz_3_circuit() counts_ideal, counts_noise, _ = self.counts_data(circuit, assignment_matrices, shots) probs_ideal, _ = counts_probability_vector(counts_ideal, qubit_index=qubit_index) probs_noise, _ = counts_probability_vector(counts_noise, qubit_index=qubit_index) for diagonal in diagonals: if isinstance(diagonal, str): diagonal = str2diag(diagonal) unmitigated_expectation, unmitigated_stddev = expval_with_stddev( diagonal, probs_noise, shots=counts_noise.shots() ) ideal_expectation = np.dot(probs_ideal, diagonal) unmitigated_error = np.abs(ideal_expectation - unmitigated_expectation) for mitigator in mitigators: mitigated_expectation, mitigated_stddev = mitigator.expectation_value( counts_noise, diagonal ) mitigated_error = np.abs(ideal_expectation - mitigated_expectation) self.assertLess( mitigated_error, unmitigated_error, "Mitigator {} did not improve circuit {} expectation computation for diagonal {} " "ideal: {}, unmitigated: {} mitigated: {}".format( mitigator, circuit_name, diagonal, ideal_expectation, unmitigated_expectation, mitigated_expectation, ), ) self.assertGreaterEqual( mitigated_stddev, unmitigated_stddev, "Mitigator {} did not increase circuit {} the standard deviation".format( mitigator, circuit_name ), ) def test_clbits_parameter(self): """Test whether the clbits parameter is handled correctly""" shots = 10000 assignment_matrices = self.assignment_matrices() mitigators = self.mitigators(assignment_matrices) circuit, _, _ = self.first_qubit_h_3_circuit() counts_ideal, counts_noise, _ = self.counts_data(circuit, assignment_matrices, shots) counts_ideal_12 = marginal_counts(counts_ideal, [1, 2]) counts_ideal_02 = marginal_counts(counts_ideal, [0, 2]) for mitigator in mitigators: mitigated_probs_12 = ( mitigator.quasi_probabilities(counts_noise, qubits=[1, 2], clbits=[1, 2]) .nearest_probability_distribution() .binary_probabilities(num_bits=2) ) mitigated_error = self.compare_results(counts_ideal_12, mitigated_probs_12) self.assertLess( mitigated_error, 0.001, "Mitigator {} did not correctly marganalize for qubits 1,2".format(mitigator), ) mitigated_probs_02 = ( mitigator.quasi_probabilities(counts_noise, qubits=[0, 2], clbits=[0, 2]) .nearest_probability_distribution() .binary_probabilities(num_bits=2) ) mitigated_error = self.compare_results(counts_ideal_02, mitigated_probs_02) self.assertLess( mitigated_error, 0.001, "Mitigator {} did not correctly marganalize for qubits 0,2".format(mitigator), ) def test_qubits_parameter(self): """Test whether the qubits parameter is handled correctly""" shots = 10000 assignment_matrices = self.assignment_matrices() mitigators = self.mitigators(assignment_matrices) circuit, _, _ = self.first_qubit_h_3_circuit() counts_ideal, counts_noise, _ = self.counts_data(circuit, assignment_matrices, shots) counts_ideal_012 = counts_ideal counts_ideal_210 = Counts({"000": counts_ideal["000"], "100": counts_ideal["001"]}) counts_ideal_102 = Counts({"000": counts_ideal["000"], "010": counts_ideal["001"]}) for mitigator in mitigators: mitigated_probs_012 = ( mitigator.quasi_probabilities(counts_noise, qubits=[0, 1, 2]) .nearest_probability_distribution() .binary_probabilities(num_bits=3) ) mitigated_error = self.compare_results(counts_ideal_012, mitigated_probs_012) self.assertLess( mitigated_error, 0.001, "Mitigator {} did not correctly handle qubit order 0, 1, 2".format(mitigator), ) mitigated_probs_210 = ( mitigator.quasi_probabilities(counts_noise, qubits=[2, 1, 0]) .nearest_probability_distribution() .binary_probabilities(num_bits=3) ) mitigated_error = self.compare_results(counts_ideal_210, mitigated_probs_210) self.assertLess( mitigated_error, 0.001, "Mitigator {} did not correctly handle qubit order 2, 1, 0".format(mitigator), ) mitigated_probs_102 = ( mitigator.quasi_probabilities(counts_noise, qubits=[1, 0, 2]) .nearest_probability_distribution() .binary_probabilities(num_bits=3) ) mitigated_error = self.compare_results(counts_ideal_102, mitigated_probs_102) self.assertLess( mitigated_error, 0.001, "Mitigator {} did not correctly handle qubit order 1, 0, 2".format(mitigator), ) def test_repeated_qubits_parameter(self): """Tests the order of mitigated qubits.""" shots = 10000 assignment_matrices = self.assignment_matrices() mitigators = self.mitigators(assignment_matrices, qubits=[0, 1, 2]) circuit, _, _ = self.first_qubit_h_3_circuit() counts_ideal, counts_noise, _ = self.counts_data(circuit, assignment_matrices, shots) counts_ideal_012 = counts_ideal counts_ideal_210 = Counts({"000": counts_ideal["000"], "100": counts_ideal["001"]}) for mitigator in mitigators: mitigated_probs_210 = ( mitigator.quasi_probabilities(counts_noise, qubits=[2, 1, 0]) .nearest_probability_distribution() .binary_probabilities(num_bits=3) ) mitigated_error = self.compare_results(counts_ideal_210, mitigated_probs_210) self.assertLess( mitigated_error, 0.001, "Mitigator {} did not correctly handle qubit order 2,1,0".format(mitigator), ) # checking qubit order 2,1,0 should not "overwrite" the default 0,1,2 mitigated_probs_012 = ( mitigator.quasi_probabilities(counts_noise) .nearest_probability_distribution() .binary_probabilities(num_bits=3) ) mitigated_error = self.compare_results(counts_ideal_012, mitigated_probs_012) self.assertLess( mitigated_error, 0.001, "Mitigator {} did not correctly handle qubit order 0,1,2 (the expected default)".format( mitigator ), ) def test_qubits_subset_parameter(self): """Tests mitigation on a subset of the initial set of qubits.""" shots = 10000 assignment_matrices = self.assignment_matrices() mitigators = self.mitigators(assignment_matrices, qubits=[2, 4, 6]) circuit, _, _ = self.first_qubit_h_3_circuit() counts_ideal, counts_noise, _ = self.counts_data(circuit, assignment_matrices, shots) counts_ideal_2 = marginal_counts(counts_ideal, [0]) counts_ideal_6 = marginal_counts(counts_ideal, [2]) for mitigator in mitigators: mitigated_probs_2 = ( mitigator.quasi_probabilities(counts_noise, qubits=[2]) .nearest_probability_distribution() .binary_probabilities(num_bits=1) ) mitigated_error = self.compare_results(counts_ideal_2, mitigated_probs_2) self.assertLess( mitigated_error, 0.001, "Mitigator {} did not correctly handle qubit subset".format(mitigator), ) mitigated_probs_6 = ( mitigator.quasi_probabilities(counts_noise, qubits=[6]) .nearest_probability_distribution() .binary_probabilities(num_bits=1) ) mitigated_error = self.compare_results(counts_ideal_6, mitigated_probs_6) self.assertLess( mitigated_error, 0.001, "Mitigator {} did not correctly handle qubit subset".format(mitigator), ) diagonal = str2diag("ZZ") ideal_expectation = 0 mitigated_expectation, _ = mitigator.expectation_value( counts_noise, diagonal, qubits=[2, 6] ) mitigated_error = np.abs(ideal_expectation - mitigated_expectation) self.assertLess( mitigated_error, 0.1, "Mitigator {} did not improve circuit expectation".format(mitigator), ) def test_from_backend(self): """Test whether a local mitigator can be created directly from backend properties""" backend = FakeYorktown() num_qubits = len(backend.properties().qubits) probs = TestReadoutMitigation.rng.random((num_qubits, 2)) for qubit_idx, qubit_prop in enumerate(backend.properties().qubits): for prop in qubit_prop: if prop.name == "prob_meas1_prep0": prop.value = probs[qubit_idx][0] if prop.name == "prob_meas0_prep1": prop.value = probs[qubit_idx][1] LRM_from_backend = LocalReadoutMitigator(backend=backend) mats = [] for qubit_idx in range(num_qubits): mat = np.array( [ [1 - probs[qubit_idx][0], probs[qubit_idx][1]], [probs[qubit_idx][0], 1 - probs[qubit_idx][1]], ] ) mats.append(mat) LRM_from_matrices = LocalReadoutMitigator(assignment_matrices=mats) self.assertTrue( matrix_equal( LRM_from_backend.assignment_matrix(), LRM_from_matrices.assignment_matrix() ) ) def test_error_handling(self): """Test that the assignment matrices are valid.""" bad_matrix_A = np.array([[-0.3, 1], [1.3, 0]]) # negative indices bad_matrix_B = np.array([[0.2, 1], [0.7, 0]]) # columns not summing to 1 good_matrix_A = np.array([[0.2, 1], [0.8, 0]]) for bad_matrix in [bad_matrix_A, bad_matrix_B]: with self.assertRaises(QiskitError) as cm: CorrelatedReadoutMitigator(bad_matrix) self.assertEqual( cm.exception.message, "Assignment matrix columns must be valid probability distributions", ) with self.assertRaises(QiskitError) as cm: amats = [good_matrix_A, bad_matrix_A] LocalReadoutMitigator(amats) self.assertEqual( cm.exception.message, "Assignment matrix columns must be valid probability distributions", ) with self.assertRaises(QiskitError) as cm: amats = [bad_matrix_B, good_matrix_A] LocalReadoutMitigator(amats) self.assertEqual( cm.exception.message, "Assignment matrix columns must be valid probability distributions", ) def test_expectation_value_endian(self): """Test that endian for expval is little.""" mitigators = self.mitigators(self.assignment_matrices()) counts = Counts({"10": 3, "11": 24, "00": 74, "01": 923}) for mitigator in mitigators: expval, _ = mitigator.expectation_value(counts, diagonal="IZ", qubits=[0, 1]) self.assertAlmostEqual(expval, -1.0, places=0) def test_quasi_probabilities_shots_passing(self): """Test output of LocalReadoutMitigator.quasi_probabilities We require the number of shots to be set in the output. """ mitigator = LocalReadoutMitigator([np.array([[0.9, 0.1], [0.1, 0.9]])], qubits=[0]) counts = Counts({"10": 3, "11": 24, "00": 74, "01": 923}) quasi_dist = mitigator.quasi_probabilities(counts) self.assertEqual(quasi_dist.shots, sum(counts.values())) # custom number of shots quasi_dist = mitigator.quasi_probabilities(counts, shots=1025) self.assertEqual(quasi_dist.shots, 1025) class TestLocalReadoutMitigation(QiskitTestCase): """Tests specific to the local readout mitigator""" def test_assignment_matrix(self): """Tests that the local mitigator generates the full assignment matrix correctly""" qubits = [7, 2, 3] assignment_matrices = LocalReadoutMitigator(backend=FakeYorktown())._assignment_mats[0:3] expected_assignment_matrix = np.kron( np.kron(assignment_matrices[2], assignment_matrices[1]), assignment_matrices[0] ) expected_mitigation_matrix = np.linalg.inv(expected_assignment_matrix) LRM = LocalReadoutMitigator(assignment_matrices, qubits) self.assertTrue(matrix_equal(expected_mitigation_matrix, LRM.mitigation_matrix())) self.assertTrue(matrix_equal(expected_assignment_matrix, LRM.assignment_matrix())) if __name__ == "__main__": unittest.main()
https://github.com/TheGupta2012/QPE-Algorithms
TheGupta2012
from qiskit import QuantumCircuit, execute, transpile, Aer from qiskit.extensions import UnitaryGate, Initialize from qiskit.quantum_info import Statevector from qiskit.tools.monitor import job_monitor from qiskit.compiler import assemble 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 from scipy.stats import unitary_group import matplotlib.pyplot as plt x = np.linspace(0.05, 1, 200) c = np.cos(x) c2 = (np.cos(x))**2 ex = np.exp(-x) ex2 = np.exp(-x**2) x_inv = (1/x) x_inv2 = (1/x**2) plt.figure(dpi=120) plt.title("Cost Function plots", fontsize=20) plt.xlabel("Theta values", fontsize=16) plt.ylabel("Metric values", fontsize=16) plt.plot(x, c, label="$cos(x)$") plt.plot(x, c2, label="$cos^{2}(x)$") plt.plot(x, ex, label="$e^{-x}$") plt.plot(x, ex2, label="$e^{-x^{2}}$") plt.grid() plt.legend() plt.figure(dpi=120) plt.title("Cost Function plots", fontsize=20) plt.xlabel("Theta values", fontsize=16) plt.ylabel("Metric values", fontsize=16) plt.plot(x, x_inv, label="$\\frac{1}{x}$") plt.plot(x, x_inv2, label="$\\frac{1}{x^{2}}$") plt.grid() plt.legend() class global_max_SPEA(): def __init__(self, unitary, cost_function, max_metric_val, resolution=100, 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 metric if not isinstance(max_metric_val, int) and not isinstance(max_metric_val, float): raise TypeError( "The required metric value should be provided as an int or a float.") elif max_metric_val <= 0: raise ValueError( "The required metric must be finite and greater than 0.") elif cost_function in ['cos', 'cos2', 'exp', 'exp2'] and max_metric_val > 1: raise ValueError( "Maximum metric can't be greater than 1 in case of given cost function") self.max_metric = max_metric_val # 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 cost_fns = ['cos', 'cos2', 'exp', 'exp2', 'inv', 'inv2'] # handle cost function if cost_function not in cost_fns: raise ValueError( "Cost function must be one of [cos, cos2, exp, exp2, inv, inv2]") self.cost_function = cost_function self.basis = [] def __get_basis_vectors(self, randomize=True): # get the d dimensional basis for the unitary provided 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 ''' 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() 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 circuit that is generated with inverse rotation ''' # 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() 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]) # qc = assemble(qc,shots = shots) 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 state is a normalized state in ndarray form''' 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) # 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 state is a normalized state in ndarray form''' result = {'cost': -1, 'theta': -1} # all theta values are iterated over for the same state # run the circuit once 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 = (np.sin(np.pi*theta))**2 # 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* 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_metric_val(self, cost, theta): '''Generate optimization metric value based on the given cost function ''' func = self.cost_function if func == 'cos': return cost*(np.cos(theta)) elif func == 'cos2': return cost*((np.cos(theta))**2) elif func == 'exp': return cost*(np.exp(-theta)) elif func == 'exp2': return cost*(np.exp(-theta**2)) elif func == 'inv': try: return cost/theta except: return 1e7 elif func == 'inv2': try: return cost/(theta**2) except: return 1e7 def get_eigen_pair(self, backend, algo='alternate', theta_left=0, theta_right=1, progress=False, basis=None, basis_ind=None, randomize=True, target_metric=None, shots=512 ): '''Finding the eigenstate pair for the unitary''' # handle algorithm... self.unitary_circuit = self.__get_unitary_circuit(backend) # handle theta bounds 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].") # handle algorithm 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 target_metric is not None: if (target_metric <= 0): raise ValueError("Target metric must be a real value > 0") # handle progress... 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") 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 # new if target_metric is None: max_metric = self.max_metric else: if self.cost_function in ['cos','cos2','exp','exp2']: assert target_metric <= 1 , "For given cost function, target cost can't be greater than 1" max_metric = target_metric 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 = result['cost'] theta_max = result['theta'] best_phi = phi global_metric = self.__get_metric_val(cost, theta_max) # 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 global_metric < max_metric: # 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, "...") # generate a cost dict for each of the iterations thetas, costs, states, metrics = [], [], [], [] 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 * \ (max_metric - global_metric)*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'] # new curr_metric = self.__get_metric_val(curr_cost, curr_theta) # append these parameters if curr_metric > global_metric: # then only add this cost in the cost and states list thetas.append(float(curr_theta)) costs.append(float(curr_cost)) states.append(curr_phi) # new metrics.append(curr_metric) found = True # now each iteration would see the same state as the best phi # is updated once at the end of the iteration # also, the cost is also updated only once at the end of the iteration if progress: sys.stdout.write('\r') sys.stdout.write("%f %%completed" % (100*(i+1)/(2*self.dims))) sys.stdout.flush() # 1 iteration completes if found == False: # phi was not updated , change a a = a/2 if progress: print("\nNo change, updating a...") else: # if found is actually true, then only update # new # we need to update the best phi , theta max and cost on # the basis of cost / theta_max value index = np.argmax(metrics) # update the parameters of the model cost = costs[index] theta_max = thetas[index] best_phi = states[index] global_metric = metrics[index] angle_range /= 2 # updated phi and thus theta too -> refine theta range # update the iterations iters += 1 if progress: print("Best Phi is :", best_phi) print("Theta estimate :", theta_max) print("Current cost :", cost) print("Current Metric :", global_metric) if iters >= self.iterations: print( "Maximum iterations reached for the estimation.\nTerminating algorithm...") break # add cost, eigenvector and theta to the dict results['cost'] = cost results['theta'] = theta_max results['state'] = best_phi results['metric'] = global_metric return results unit = unitary_group.rvs(8) unit # get the eigenvalues and eigenstates eig_v, eig_vect = np.linalg.eig(unit) eig_v = np.angle(eig_v) eig = [] for k in eig_v: if k < 0: e = (k+2*np.pi)/(2*np.pi) else: e = (k)/(2*np.pi) eig.append(e) eig_v = np.array(eig) # print("Eigenvalues :", eig_v) # print("Eigenstates :", eig_vect) def generate_plot1(actual_E, returned_E, experiments,function): colors = ['blue', 'orange', 'red', 'green', 'brown', 'magenta', 'pink'] plt.figure(figsize=(9, 7)) plt.scatter(range(experiments), returned_E, marker='o', edgecolors='grey', color=np.random.choice(colors), alpha=0.8,) for i, k in enumerate(actual_E): if i == 0: plt.plot([0, experiments], [k, k], color='black', linewidth=2, label='Actual Values') else: plt.plot([0, experiments], [k, k], color='black', linewidth=2) plt.xlabel("Experiment Number", fontsize=14) plt.ylabel("Eigenvalues", fontsize=14) plt.title("Scatter plot for returned eigenvalues with cost function "+str(function), fontsize=17) plt.legend() plt.grid() spea1 = global_max_SPEA(unit, resolution=30, max_metric_val=0.92,cost_function='cos', max_iters=15) simulator = Aer.get_backend('qasm_simulator') eigen_vals_ret1 = [] while len(eigen_vals_ret1) != 40: res = spea1.get_eigen_pair( backend=simulator, algo='alternate') if res['metric'] < 0.8: continue print("Result :", res) eigen_vals_ret1.append(res['theta']) generate_plot1(eig_v, eigen_vals_ret1, 40, "cos") spea1 = global_max_SPEA(unit, resolution=30, max_metric_val=0.92,cost_function='cos2', max_iters=15) simulator = Aer.get_backend('qasm_simulator') eigen_vals_ret1 = [] while len(eigen_vals_ret1) != 40: res = spea1.get_eigen_pair( backend=simulator, algo='alternate') if res['metric'] < 0.8: continue # print("Result :", res) eigen_vals_ret1.append(res['theta']) generate_plot1(eig_v, eigen_vals_ret1, 40, "cos2") spea1 = global_max_SPEA(unit, resolution=30, max_metric_val=0.92,cost_function='exp', max_iters=15) simulator = Aer.get_backend('qasm_simulator') eigen_vals_ret1 = [] while len(eigen_vals_ret1) != 40: res = spea1.get_eigen_pair( backend=simulator, algo='alternate') if res['metric'] < 0.8: continue # print("Result :", res) eigen_vals_ret1.append(res['theta']) generate_plot1(eig_v, eigen_vals_ret1, 40, "exp") spea1 = global_max_SPEA(unit, resolution=30, max_metric_val=0.92,cost_function='exp2', max_iters=15) simulator = Aer.get_backend('qasm_simulator') eigen_vals_ret1 = [] while len(eigen_vals_ret1) != 40: res = spea1.get_eigen_pair( backend=simulator, algo='alternate') if res['metric'] < 0.8: continue print("Result :", res) eigen_vals_ret1.append(res['theta']) generate_plot1(eig_v, eigen_vals_ret1, 40, "exp2") spea1 = global_max_SPEA(unit, resolution=30, max_metric_val=4,cost_function='inv', max_iters=15) simulator = Aer.get_backend('qasm_simulator') eigen_vals_ret1 = [] while len(eigen_vals_ret1) != 40: res = spea1.get_eigen_pair( backend=simulator, algo='alternate') if res['metric'] < 3: continue print("Result :", res) eigen_vals_ret1.append(res['theta']) generate_plot1(eig_v, eigen_vals_ret1, 40, "inv") spea1 = global_max_SPEA(unit, resolution=30, max_metric_val=20,cost_function='inv2', max_iters=15) simulator = Aer.get_backend('qasm_simulator') eigen_vals_ret1 = [] while len(eigen_vals_ret1) != 40: res = spea1.get_eigen_pair( backend=simulator, algo='alternate') if res['metric'] < 15: continue print("Result :", res) eigen_vals_ret1.append(res['theta']) generate_plot1(eig_v, eigen_vals_ret1, 40, "inv2")
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/jenglick/scipy22-qiskit-runtime-tutorial
jenglick
# import functionality from qiskit for building and running circuits from qiskit import QuantumCircuit, BasicAer, transpile import numpy as np # define a quantum circuit with a single "X" gate circuit = QuantumCircuit(1) circuit.x(0) circuit.measure_all() circuit.draw() # select a quantum backend and run the circuit backend = BasicAer.get_backend('qasm_simulator') shots = 2**13 job = backend.run(circuit, shots=shots) result = job.result() # get the measurement counts from the circuit counts = result.get_counts() print(counts) print('probability to measure state 0: {}%'.format(counts.get('0', 0) / shots * 100)) print('probability to measure state 1: {}%'.format(counts.get('1', 0) / shots * 100)) # define a quantum circuit with a single Hadamard gate circuit = QuantumCircuit(1) circuit.h(0) circuit.measure_all() circuit.draw() job = backend.run(transpile(circuit, backend), shots=shots) result = job.result() counts = result.get_counts() print(counts) print('probability to measure state 0: {}%'.format(counts.get('0', 0) / shots * 100)) print('probability to measure state 1: {}%'.format(counts.get('1', 0) / shots * 100)) # define the state |1> a = 0 b = 1 state = np.array([a,b]) norm = np.linalg.norm(state) normalized_state_ONE = state/norm print(normalized_state_ONE) # then, initialize this state as a quantum circuit and measure in computational (Z) basis circuit = QuantumCircuit(1) circuit.initialize(normalized_state_ONE) circuit.measure_all() print(circuit) # run the circuit and then subtract the two probabilities p(0)-p(1) job = backend.run(transpile(circuit, backend), shots=shots) result = job.result() counts = result.get_counts() print(counts) expval = (counts.get('0',0)-counts.get('1',0)) / shots print('expectation value: {}'.format(expval)) # define the state |+> a = 0.70710678 # 1/sqrt(2) b = 0.70710678 state = np.array([a,b]) norm = np.linalg.norm(state) normalized_state_PLUS = state/norm print(normalized_state_PLUS) # initialize as a quantum circuit and measure circuit = QuantumCircuit(1) circuit.initialize(normalized_state_PLUS) circuit.measure_all() print(circuit) # run the circuit and then subtract the two probabilities p(0)-p(1) job = backend.run(transpile(circuit, backend), shots=shots) result = job.result() counts = result.get_counts() print(counts) expval = (counts.get('0',0)-counts.get('1',0)) / shots print('expectation value: {}'.format(expval)) # define the Pauli Z operator z = np.array([[1, 0], [0, -1]]) # what are the eigenvectors of this operator? from qiskit.visualization import plot_state_city, plot_bloch_multivector z_eigenvals, z_eigenvecs = np.linalg.eigh(z) print('Eigensystem of Z:') print(z_eigenvals) print(z_eigenvecs) plot_bloch_multivector(z_eigenvecs[:,0]) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/arnavdas88/QuGlassyIsing
arnavdas88
!pip install qiskit J = 4.0 B_x = 0.0 B_z = 0.0 import numpy as np from qiskit.providers.aer import AerSimulator, QasmSimulator from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit.aqua.operators import * from qiskit.aqua import set_qiskit_aqua_logging, QuantumInstance from qiskit.aqua.algorithms import NumPyMinimumEigensolver, VQE, NumPyEigensolver from qiskit.circuit import QuantumCircuit, ParameterVector from qiskit.visualization import plot_histogram Hamiltonian = J * (Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z) - B_z * (( Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ) ) - B_x * ( ( X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X )) ansatz = TwoLocal(num_qubits=36, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True) print(ansatz) backend = AerSimulator(method='matrix_product_state') quantum_instance = QuantumInstance(backend, shots = 8192, initial_layout = None, optimization_level = 3) optimizer = COBYLA(maxiter=10000, tol=0.000000001) vqe = VQE(Hamiltonian, ansatz, optimizer, include_custom = False) print('We are using:', quantum_instance.backend) vqe_result = vqe.run(quantum_instance) print(vqe['result']) plot_histogram(vqe_result['eigenstate']) import pickle filename = "2D_Ising_Model_CountsAF1.pkl" a = {'vqe_result': vqe_result} #This saves the data with open(filename, 'wb') as handle: pickle.dump(a, handle, protocol=pickle.HIGHEST_PROTOCOL) # This loads the data with open(filename, 'rb') as handle: b = pickle.load(handle)
https://github.com/urwin419/QiskitChecker
urwin419
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) ### removed cx gate ### return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) ### removed h gate ### return qc
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Piecewise polynomial Chebyshev approximation to a given f(x).""" from __future__ import annotations from typing import Callable import numpy as np from numpy.polynomial.chebyshev import Chebyshev from qiskit.circuit import QuantumRegister, AncillaRegister from qiskit.circuit.library.blueprintcircuit import BlueprintCircuit from qiskit.circuit.exceptions import CircuitError from .piecewise_polynomial_pauli_rotations import PiecewisePolynomialPauliRotations class PiecewiseChebyshev(BlueprintCircuit): r"""Piecewise Chebyshev approximation to an input function. For a given function :math:`f(x)` and degree :math:`d`, this class implements a piecewise polynomial Chebyshev approximation on :math:`n` qubits to :math:`f(x)` on the given intervals. All the polynomials in the approximation are of degree :math:`d`. The values of the parameters are calculated according to [1] and see [2] for a more detailed explanation of the circuit construction and how it acts on the qubits. Examples: .. plot:: :include-source: import numpy as np from qiskit import QuantumCircuit from qiskit.circuit.library.arithmetic.piecewise_chebyshev import PiecewiseChebyshev f_x, degree, breakpoints, num_state_qubits = lambda x: np.arcsin(1 / x), 2, [2, 4], 2 pw_approximation = PiecewiseChebyshev(f_x, degree, breakpoints, num_state_qubits) pw_approximation._build() qc = QuantumCircuit(pw_approximation.num_qubits) qc.h(list(range(num_state_qubits))) qc.append(pw_approximation.to_instruction(), qc.qubits) qc.draw(output='mpl') References: [1]: Haener, T., Roetteler, M., & Svore, K. M. (2018). Optimizing Quantum Circuits for Arithmetic. `arXiv:1805.12445 <http://arxiv.org/abs/1805.12445>`_ [2]: Carrera Vazquez, A., Hiptmair, H., & Woerner, S. (2022). Enhancing the Quantum Linear Systems Algorithm Using Richardson Extrapolation. `ACM Transactions on Quantum Computing 3, 1, Article 2 <https://doi.org/10.1145/3490631>`_ """ def __init__( self, f_x: float | Callable[[int], float], degree: int | None = None, breakpoints: list[int] | None = None, num_state_qubits: int | None = None, name: str = "pw_cheb", ) -> None: r""" Args: f_x: the function to be approximated. Constant functions should be specified as f_x = constant. degree: the degree of the polynomials. Defaults to ``1``. breakpoints: the breakpoints to define the piecewise-linear function. Defaults to the full interval. num_state_qubits: number of qubits representing the state. name: The name of the circuit object. """ super().__init__(name=name) # define internal parameters self._num_state_qubits = None # Store parameters self._f_x = f_x self._degree = degree if degree is not None else 1 self._breakpoints = breakpoints if breakpoints is not None else [0] self._polynomials: list[list[float]] | None = None self.num_state_qubits = num_state_qubits def _check_configuration(self, raise_on_failure: bool = True) -> bool: """Check if the current configuration is valid.""" valid = True if self._f_x is None: valid = False if raise_on_failure: raise AttributeError("The function to be approximated has not been set.") if self._degree is None: valid = False if raise_on_failure: raise AttributeError("The degree of the polynomials has not been set.") if self._breakpoints is None: valid = False if raise_on_failure: raise AttributeError("The breakpoints have not been set.") if self.num_state_qubits is None: valid = False if raise_on_failure: raise AttributeError("The number of qubits has not been set.") if self.num_qubits < self.num_state_qubits + 1: valid = False if raise_on_failure: raise CircuitError( "Not enough qubits in the circuit, need at least " "{}.".format(self.num_state_qubits + 1) ) return valid @property def f_x(self) -> float | Callable[[int], float]: """The function to be approximated. Returns: The function to be approximated. """ return self._f_x @f_x.setter def f_x(self, f_x: float | Callable[[int], float] | None) -> None: """Set the function to be approximated. Note that this may change the underlying quantum register, if the number of state qubits changes. Args: f_x: The new function to be approximated. """ if self._f_x is None or f_x != self._f_x: self._invalidate() self._f_x = f_x self._reset_registers(self.num_state_qubits) @property def degree(self) -> int: """The degree of the polynomials. Returns: The degree of the polynomials. """ return self._degree @degree.setter def degree(self, degree: int | None) -> None: """Set the error tolerance. Note that this may change the underlying quantum register, if the number of state qubits changes. Args: degree: The new degree. """ if self._degree is None or degree != self._degree: self._invalidate() self._degree = degree self._reset_registers(self.num_state_qubits) @property def breakpoints(self) -> list[int]: """The breakpoints for the piecewise approximation. Returns: The breakpoints for the piecewise approximation. """ breakpoints = self._breakpoints # it the state qubits are set ensure that the breakpoints match beginning and end if self.num_state_qubits is not None: num_states = 2**self.num_state_qubits # If the last breakpoint is < num_states, add the identity polynomial if breakpoints[-1] < num_states: breakpoints = breakpoints + [num_states] # If the first breakpoint is > 0, add the identity polynomial if breakpoints[0] > 0: breakpoints = [0] + breakpoints return breakpoints @breakpoints.setter def breakpoints(self, breakpoints: list[int] | None) -> None: """Set the breakpoints for the piecewise approximation. Note that this may change the underlying quantum register, if the number of state qubits changes. Args: breakpoints: The new breakpoints for the piecewise approximation. """ if self._breakpoints is None or breakpoints != self._breakpoints: self._invalidate() self._breakpoints = breakpoints if breakpoints is not None else [0] self._reset_registers(self.num_state_qubits) @property def polynomials(self) -> list[list[float]]: """The polynomials for the piecewise approximation. Returns: The polynomials for the piecewise approximation. Raises: TypeError: If the input function is not in the correct format. """ if self.num_state_qubits is None: return [[]] # note this must be the private attribute since we handle missing breakpoints at # 0 and 2 ^ num_qubits here (e.g. if the function we approximate is not defined at 0 # and the user takes that into account we just add an identity) breakpoints = self._breakpoints # Need to take into account the case in which no breakpoints were provided in first place if breakpoints == [0]: breakpoints = [0, 2**self.num_state_qubits] num_intervals = len(breakpoints) # Calculate the polynomials polynomials = [] for i in range(0, num_intervals - 1): # Calculate the polynomial approximating the function on the current interval try: # If the function is constant don't call Chebyshev (not necessary and gives errors) if isinstance(self.f_x, (float, int)): # Append directly to list of polynomials polynomials.append([self.f_x]) else: poly = Chebyshev.interpolate( self.f_x, self.degree, domain=[breakpoints[i], breakpoints[i + 1]] ) # Convert polynomial to the standard basis and rescale it for the rotation gates poly = 2 * poly.convert(kind=np.polynomial.Polynomial).coef # Convert to list and append polynomials.append(poly.tolist()) except ValueError as err: raise TypeError( " <lambda>() missing 1 required positional argument: '" + self.f_x.__code__.co_varnames[0] + "'." + " Constant functions should be specified as 'f_x = constant'." ) from err # If the last breakpoint is < 2 ** num_qubits, add the identity polynomial if breakpoints[-1] < 2**self.num_state_qubits: polynomials = polynomials + [[2 * np.arcsin(1)]] # If the first breakpoint is > 0, add the identity polynomial if breakpoints[0] > 0: polynomials = [[2 * np.arcsin(1)]] + polynomials return polynomials @polynomials.setter def polynomials(self, polynomials: list[list[float]] | None) -> None: """Set the polynomials for the piecewise approximation. Note that this may change the underlying quantum register, if the number of state qubits changes. Args: polynomials: The new breakpoints for the piecewise approximation. """ if self._polynomials is None or polynomials != self._polynomials: self._invalidate() self._polynomials = polynomials self._reset_registers(self.num_state_qubits) @property def num_state_qubits(self) -> int: r"""The number of state qubits representing the state :math:`|x\rangle`. Returns: The number of state qubits. """ return self._num_state_qubits @num_state_qubits.setter def num_state_qubits(self, num_state_qubits: int | None) -> None: """Set the number of state qubits. Note that this may change the underlying quantum register, if the number of state qubits changes. Args: num_state_qubits: The new number of qubits. """ if self._num_state_qubits is None or num_state_qubits != self._num_state_qubits: self._invalidate() self._num_state_qubits = num_state_qubits # Set breakpoints if they haven't been set if num_state_qubits is not None and self._breakpoints is None: self.breakpoints = [0, 2**num_state_qubits] self._reset_registers(num_state_qubits) def _reset_registers(self, num_state_qubits: int | None) -> None: """Reset the registers.""" self.qregs = [] if num_state_qubits is not None: qr_state = QuantumRegister(num_state_qubits, "state") qr_target = QuantumRegister(1, "target") self.qregs = [qr_state, qr_target] num_ancillas = num_state_qubits if num_ancillas > 0: qr_ancilla = AncillaRegister(num_ancillas) self.add_register(qr_ancilla) def _build(self): """Build the circuit if not already build. The operation is considered successful when q_objective is :math:`|1>`""" if self._is_built: return super()._build() poly_r = PiecewisePolynomialPauliRotations( self.num_state_qubits, self.breakpoints, self.polynomials, name=self.name ) # qr_state = self.qubits[: self.num_state_qubits] # qr_target = [self.qubits[self.num_state_qubits]] # qr_ancillas = self.qubits[self.num_state_qubits + 1 :] # Apply polynomial approximation self.append(poly_r.to_gate(), self.qubits)
https://github.com/jaykomarraju/Quantum-Optimization-for-Solar-Farm
jaykomarraju
import numpy as np import networkx as nx from qiskit import Aer from qiskit.algorithms import QAOA, NumPyMinimumEigensolver from qiskit.algorithms.optimizers import COBYLA from qiskit.utils import QuantumInstance from qiskit_optimization import QuadraticProgram from qiskit_optimization.algorithms import MinimumEigenOptimizer num_time_slots = 24 # Define the QUBO problem qubo = QuadraticProgram() # Add binary variables for charging (c) and discharging (d) states for t in range(num_time_slots): qubo.binary_var(f'c_{t}') qubo.binary_var(f'd_{t}') # Define the objective function # (In practice, you need to calculate Jij and hi based on the solar farm data) Jij = np.random.rand(num_time_slots, num_time_slots) * 0.5 hi_c = -1 + np.random.rand(num_time_slots) hi_d = 1 - np.random.rand(num_time_slots) # Set linear and quadratic terms of the objective function linear_terms = {} quadratic_terms = {} for t in range(num_time_slots): linear_terms[f'c_{t}'] = hi_c[t] linear_terms[f'd_{t}'] = hi_d[t] for s in range(num_time_slots): if t != s: quadratic_terms[(f'c_{t}', f'c_{s}')] = Jij[t, s] quadratic_terms[(f'd_{t}', f'd_{s}')] = Jij[t, s] qubo.minimize(linear=linear_terms, quadratic=quadratic_terms) # Set up the quantum instance backend = Aer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, seed_simulator=42, seed_transpiler=42, shots=10000) # Set up the QAOA algorithm and optimizer optimizer = COBYLA(maxiter=500) qaoa = QAOA(optimizer=optimizer, reps=5, quantum_instance=quantum_instance) # Set up the minimum eigen optimizer min_eig_optimizer = MinimumEigenOptimizer(qaoa) # Solve the problem result = min_eig_optimizer.solve(qubo) print("QAOA result:", result) # Solve the problem using a classical solver (NumPyMinimumEigensolver) exact_solver = MinimumEigenOptimizer(NumPyMinimumEigensolver()) exact_result = exact_solver.solve(qubo) print("Classical result:", exact_result)
https://github.com/shell-raiser/Qiskit-Developer-Certification-Notes-and-Code
shell-raiser
from qiskit import * %matplotlib inline from qiskit.tools.visualization import plot_histogram secretNumber = '101001' circuit = QuantumCircuit(6+1, 6) circuit.h((0,1,2,3,4,5)) circuit.x(6) circuit.h(6) circuit.barrier() circuit.cx(5, 6) circuit.cx(3, 6) circuit.cx(0, 6) circuit.barrier() circuit.h((0,1,2,3,4,5)) circuit.draw() circuit.barrier() circuit.measure([0,1,2,3,4,5], [0,1,2,3,4,5]) circuit.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=simulator, shots = 1).result() counts = result.get_counts() print(counts) circuit = QuantumCircuit(len(secretNumber)+1, len(secretNumber)) #circuit.h((0,1,2,3,4,5)) circuit.h(range(len(secretNumber))) #circuit.x(6) circuit.x(len(secretNumber)) #circuit.h(6) circuit.x(len(secretNumber)) circuit.barrier() for ii, yesno in enumerate(reversed(secretNumber)): if yesno == '1': circuit.cx (ii, len(secretNumber)) #circuit.cx(5, 6) #circuit.cx(3, 6) #circuit.cx(0, 6) circuit.barrier() #circuit.h((0,1,2,3,4,5)) circuit.h(range(len(secretNumber))) circuit.barrier() circuit.measure(range(len(secretNumber)), range(len(secretNumber))) circuit.draw()
https://github.com/jayeshparashar/Bloch-sphere-
jayeshparashar
#Let's start with importing packages from qiskit import QuantumRegister, ClassicalRegister,QuantumCircuit, Aer, assemble, execute from qiskit.visualization import plot_histogram, plot_bloch_vector, plot_bloch_multivector import numpy as np # import random_statevector to get a random two state quantum system from qiskit.quantum_info import random_statevector, Statevector # Use random_statevector method to get a valid random statevector representing a qubit in superposition of two states rand_sv = random_statevector(2).data print(rand_sv) plot_bloch_multivector(rand_sv) # Define a function to calculate and return the expectation values of X, Y and Z coordinates of a qubit vector situated # on a blochsphere, since qiskit measurement operation is set to measure in default 'Z' axis, in order to measure qubit # in 'X' and 'Y' direction/axis we have to rotate/adjust the final vector as it is measured in X and Y axis while performing # a default Z measurement. def Exp_Value(axis): shots=10000 qc = QuantumCircuit(1,1) qc.initialize(rand_sv,0) if (axis == 'Y') : qc.sdg(0) if (axis == 'X' or axis == 'Y') : qc.h(0) qc.measure(0,0) bkend = Aer.get_backend('qasm_simulator') cnts = execute(qc,bkend,shots=shots).result().get_counts() exp_val = (cnts['0'] * 1 + cnts['1']* -1 )/shots print('counts and exp. value for qubit system for', axis,' measurement ', cnts['0'], cnts['1'], exp_val) return exp_val # The expectation values of X, Y and Z on same initial state is an indicator of average energy which is calculated with # the help of eigenvalues (discrete energy states) obtained during the measurement in same repeated experiment. ev_X = Exp_Value('X') ev_Y = Exp_Value('Y') ev_Z = Exp_Value('Z') print(ev_X, ev_Y, ev_Z) # let's plot the vector on blochsphere with help of cartesian coordinates and see if we get same representation as # rand_sv plot_bloch_vector([ev_X, ev_Y, ev_Z]) # lets calculate the spherical coordinates theta and phi as radius is 1 # since x = sin(θ)cos(φ), y = sin(θ)sin(φ) and z = cos(θ) theta = np.arccos(ev_Z) phi = np.arcsin(ev_Y/np.sin(theta)) print('theta, phi ', theta, phi) plot_bloch_vector([1, theta, phi], coord_type='spherical') #lets calculate the vector associated with this value of theta and phi using standard qubit's representation # on blochsphere amp_zero = np.cos(theta/2) amp_one = np.cos(phi)*np.sin(theta/2) + (np.sin(phi)*np.sin(theta/2)) * complex(0, 1) q_sv = [amp_zero, amp_one] print(q_sv) plot_bloch_multivector(q_sv) # lets measure the state_fidelity to check if both the states (rand_sv and q_sv) are in-fact same from qiskit.quantum_info import state_fidelity print(rand_sv, q_sv) state_fidelity(rand_sv, q_sv) # End of program #
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit_nature.second_q.hamiltonians import QuadraticHamiltonian # create Hamiltonian hermitian_part = np.array( [ [1.0, 2.0, 0.0, 0.0], [2.0, 1.0, 2.0, 0.0], [0.0, 2.0, 1.0, 2.0], [0.0, 0.0, 2.0, 1.0], ] ) antisymmetric_part = np.array( [ [0.0, 3.0, 0.0, 0.0], [-3.0, 0.0, 3.0, 0.0], [0.0, -3.0, 0.0, 3.0], [0.0, 0.0, -3.0, 0.0], ] ) constant = 4.0 hamiltonian = QuadraticHamiltonian( hermitian_part=hermitian_part, antisymmetric_part=antisymmetric_part, constant=constant, ) # convert it to a FermionicOp and print it hamiltonian_ferm = hamiltonian.second_q_op() print(hamiltonian_ferm) # get the transformation matrix W and orbital energies {epsilon_j} ( transformation_matrix, orbital_energies, transformed_constant, ) = hamiltonian.diagonalizing_bogoliubov_transform() print(f"Shape of matrix W: {transformation_matrix.shape}") print(f"Orbital energies: {orbital_energies}") print(f"Transformed constant: {transformed_constant}") from qiskit_nature.second_q.circuit.library import FermionicGaussianState occupied_orbitals = (0, 2) eig = np.sum(orbital_energies[list(occupied_orbitals)]) + transformed_constant print(f"Eigenvalue: {eig}") circuit = FermionicGaussianState(transformation_matrix, occupied_orbitals=occupied_orbitals) circuit.draw("mpl") from qiskit.quantum_info import Statevector from qiskit_nature.second_q.mappers import JordanWignerMapper # simulate the circuit to get the final state state = np.array(Statevector(circuit)) # convert the Hamiltonian to a matrix hamiltonian_jw = JordanWignerMapper().map(hamiltonian_ferm).to_matrix() # check that the state is an eigenvector with the expected eigenvalue np.testing.assert_allclose(hamiltonian_jw @ state, eig * state, atol=1e-8) # create Hamiltonian hermitian_part = np.array( [ [1.0, 2.0, 0.0, 0.0], [2.0, 1.0, 2.0, 0.0], [0.0, 2.0, 1.0, 2.0], [0.0, 0.0, 2.0, 1.0], ] ) constant = 4.0 hamiltonian = QuadraticHamiltonian( hermitian_part=hermitian_part, constant=constant, ) print(f"Hamiltonian conserves particle number: {hamiltonian.conserves_particle_number()}") # get the transformation matrix W and orbital energies {epsilon_j} ( transformation_matrix, orbital_energies, transformed_constant, ) = hamiltonian.diagonalizing_bogoliubov_transform() print(f"Shape of matrix W: {transformation_matrix.shape}") print(f"Orbital energies: {orbital_energies}") print(f"Transformed constant: {transformed_constant}") from qiskit_nature.second_q.circuit.library import SlaterDeterminant occupied_orbitals = (0, 2) eig = np.sum(orbital_energies[list(occupied_orbitals)]) + transformed_constant print(f"Eigenvalue: {eig}") circuit = SlaterDeterminant(transformation_matrix[list(occupied_orbitals)]) circuit.draw("mpl") from qiskit_nature.second_q.circuit.library import BogoliubovTransform from qiskit import QuantumCircuit, QuantumRegister from qiskit.quantum_info import random_hermitian, random_statevector, state_fidelity from scipy.linalg import expm # create Hamiltonian n_modes = 5 hermitian_part = np.array(random_hermitian(n_modes)) hamiltonian = QuadraticHamiltonian(hermitian_part=hermitian_part) # diagonalize Hamiltonian ( transformation_matrix, orbital_energies, _, ) = hamiltonian.diagonalizing_bogoliubov_transform() # set simulation time and construct time evolution circuit time = 1.0 register = QuantumRegister(n_modes) circuit = QuantumCircuit(register) bog_circuit = BogoliubovTransform(transformation_matrix) # change to the diagonal basis of the Hamiltonian circuit.append(bog_circuit.inverse(), register) # perform time evolution by applying z rotations for q, energy in zip(register, orbital_energies): circuit.rz(-energy * time, q) # change back to the original basis circuit.append(bog_circuit, register) # simulate the circuit initial_state = random_statevector(2**n_modes) final_state = initial_state.evolve(circuit) # compute the correct state by direct exponentiation hamiltonian_jw = JordanWignerMapper().map(hamiltonian.second_q_op()).to_matrix() exact_evolution_op = expm(-1j * time * hamiltonian_jw) expected_state = exact_evolution_op @ np.array(initial_state) # check that the simulated state is correct fidelity = state_fidelity(final_state, expected_state) np.testing.assert_allclose(fidelity, 1.0, atol=1e-8) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from sklearn.datasets import make_blobs # example dataset features, labels = make_blobs(n_samples=20, n_features=2, centers=2, random_state=3, shuffle=True) import numpy as np from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler features = MinMaxScaler(feature_range=(0, np.pi)).fit_transform(features) train_features, test_features, train_labels, test_labels = train_test_split( features, labels, train_size=15, shuffle=False ) # number of qubits is equal to the number of features num_qubits = 2 # number of steps performed during the training procedure tau = 100 # regularization parameter C = 1000 from qiskit import BasicAer from qiskit.circuit.library import ZFeatureMap from qiskit.utils import algorithm_globals from qiskit_machine_learning.kernels import FidelityQuantumKernel algorithm_globals.random_seed = 12345 feature_map = ZFeatureMap(feature_dimension=num_qubits, reps=1) qkernel = FidelityQuantumKernel(feature_map=feature_map) from qiskit_machine_learning.algorithms import PegasosQSVC pegasos_qsvc = PegasosQSVC(quantum_kernel=qkernel, C=C, num_steps=tau) # training pegasos_qsvc.fit(train_features, train_labels) # testing pegasos_score = pegasos_qsvc.score(test_features, test_labels) print(f"PegasosQSVC classification test score: {pegasos_score}") grid_step = 0.2 margin = 0.2 grid_x, grid_y = np.meshgrid( np.arange(-margin, np.pi + margin, grid_step), np.arange(-margin, np.pi + margin, grid_step) ) meshgrid_features = np.column_stack((grid_x.ravel(), grid_y.ravel())) meshgrid_colors = pegasos_qsvc.predict(meshgrid_features) import matplotlib.pyplot as plt plt.figure(figsize=(5, 5)) meshgrid_colors = meshgrid_colors.reshape(grid_x.shape) plt.pcolormesh(grid_x, grid_y, meshgrid_colors, cmap="RdBu", shading="auto") plt.scatter( train_features[:, 0][train_labels == 0], train_features[:, 1][train_labels == 0], marker="s", facecolors="w", edgecolors="r", label="A train", ) plt.scatter( train_features[:, 0][train_labels == 1], train_features[:, 1][train_labels == 1], marker="o", facecolors="w", edgecolors="b", label="B train", ) plt.scatter( test_features[:, 0][test_labels == 0], test_features[:, 1][test_labels == 0], marker="s", facecolors="r", edgecolors="r", label="A test", ) plt.scatter( test_features[:, 0][test_labels == 1], test_features[:, 1][test_labels == 1], marker="o", facecolors="b", edgecolors="b", label="B test", ) plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0) plt.title("Pegasos Classification") plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/RedHatParichay/qiskit-lancasterleipzig-2023
RedHatParichay
## Blank Code Cell ## Use only if you need to install the grader and/or Qiskit ## If you are running this notebook in the IBM Quantum Lab - you can ignore this cell !pip install qiskit !pip install 'qc-grader[qiskit] @ git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git' ## Run this cell to make sure your grader is setup correctly %set_env QC_GRADE_ONLY=true %set_env QC_GRADING_ENDPOINT=https://qac-grading.quantum-computing.ibm.com from qiskit import QuantumCircuit qc = QuantumCircuit(3, 3) ## Write your code below this line ## ## Do not change the code below here ## answer1 = qc qc.draw() # Grader Cell: Run this to submit your answer from qc_grader.challenges.fall_fest23 import grade_ex2a grade_ex2a(answer1) from qiskit import QuantumCircuit qc = QuantumCircuit(3, 3) qc.barrier(0, 1, 2) ## Write your code below this line ## ## Do not change the code below this line ## answer2 = qc qc.draw() # Grader Cell: Run this to submit your answer from qc_grader.challenges.fall_fest23 import grade_ex2b grade_ex2b(answer2) answer3: bool ## Quiz: evaluate the results and decide if the following statement is True or False q0 = 1 q1 = 0 q2 = 1 ## Based on this, is it TRUE or FALSE that the Guard on the left is a liar? ## Assign your answer, either True or False, to answer3 below answer3 = from qc_grader.challenges.fall_fest23 import grade_ex2c grade_ex2c(answer3) ## Quiz: Fill in the correct numbers to make the following statement true: ## The treasure is on the right, and the Guard on the left is the liar q0 = q1 = q2 = ## HINT - Remember that Qiskit uses little-endian ordering answer4 = [q0, q1, q2] # Grader Cell: Run this to submit your answer from qc_grader.challenges.fall_fest23 import grade_ex2d grade_ex2d(answer4) from qiskit import QuantumCircuit qc = QuantumCircuit(3) ## in the code below, fill in the missing gates. Run the cell to see a drawing of the current circuit ## qc.h(0) qc.barrier(0, 1, 2) qc.x(2) qc.cx(2, 0) qc.barrier(0, 1, 2) qc.cx(2, 1) qc.x(0) ## Do not change any of the code below this line ## answer5 = qc qc.draw(output="mpl") # Grader Cell: Run this to submit your answer from qc_grader.challenges.fall_fest23 import grade_ex2e grade_ex2e(answer5) from qiskit import QuantumCircuit, Aer, transpile from qiskit.visualization import plot_histogram ## This is the full version of the circuit. Run it to see the results ## quantCirc = QuantumCircuit(3) quantCirc.h(0), quantCirc.h(2), quantCirc.cx(0, 1), quantCirc.barrier(0, 1, 2), quantCirc.cx(2, 1), quantCirc.x(2), quantCirc.cx(2, 0), quantCirc.x(2) quantCirc.barrier(0, 1, 2), quantCirc.swap(0, 1), quantCirc.x(1), quantCirc.cx(2, 1), quantCirc.x(0), quantCirc.x(2), quantCirc.cx(2, 0), quantCirc.x(2) # Execute the circuit and draw the histogram measured_qc = quantCirc.measure_all(inplace=False) backend = Aer.get_backend('qasm_simulator') # the device to run on result = backend.run(transpile(measured_qc, backend), shots=1000).result() counts = result.get_counts(measured_qc) plot_histogram(counts) from qiskit.primitives import Sampler from qiskit.visualization import plot_distribution sampler = Sampler() result = sampler.run(measured_qc, shots=1000).result() probs = result.quasi_dists[0].binary_probabilities() plot_distribution(probs)
https://github.com/abbarreto/qiskit2
abbarreto
%run init.ipynb from qiskit import * nshots = 8192 IBMQ.load_account() provider = IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main') simulator = Aer.get_backend('qasm_simulator') device = provider.get_backend('ibm_nairobi') from qiskit.tools.visualization import plot_histogram from qiskit.tools.monitor import job_monitor, backend_overview, backend_monitor qr = QuantumRegister(4); cr = ClassicalRegister(4); qc = QuantumCircuit(qr,cr) qc.h([0,1]) qc.barrier() qc.cx(0,2); qc.cx(0,3); qc.cx(1,2); qc.cx(1,3) # oraculo qc.barrier() qc.measure([2,3],[2,3]) qc.barrier() qc.h([0,1]); qc.measure([0,1],[0,1]) qc.draw(output='mpl') jobS = execute(qc, backend = simulator, shots = nshots) jobE = execute(qc, backend = device, shots = nshots) job_monitor(jobE) plot_histogram([jobS.result().get_counts(0), jobE.result().get_counts(0)], bar_labels = False, legend = ['sim', 'exp'])
https://github.com/vandnaChaturvedi/Qauntum_algorithms_Qiskit
vandnaChaturvedi
from qiskit import QuantumCircuit, Aer, transpile, assemble from qiskit.visualization import plot_histogram, plot_bloch_multivector from numpy.random import randint import numpy as np print("Imports Successful") qc = QuantumCircuit(1,1) # Alice prepares qubit in state |+> qc.h(0) qc.barrier() # Alice now sends the qubit to Bob # who measures it in the X-basis qc.h(0) qc.measure(0,0) # Draw and simulate circuit display(qc.draw()) aer_sim = Aer.get_backend('aer_simulator') job = aer_sim.run(assemble(qc)) plot_histogram(job.result().get_counts()) qc = QuantumCircuit(1,1) # Alice prepares qubit in state |+> qc.h(0) # Alice now sends the qubit to Bob # but Eve intercepts and tries to read it qc.measure(0, 0) qc.barrier() # Eve then passes this on to Bob # who measures it in the X-basis qc.h(0) qc.measure(0,0) # Draw and simulate circuit display(qc.draw()) aer_sim = Aer.get_backend('aer_simulator') job = aer_sim.run(assemble(qc)) plot_histogram(job.result().get_counts()) np.random.seed(seed=0) n = 100 np.random.seed(seed=0) n = 100 ## Step 1 # Alice generates bits alice_bits = randint(2, size=n) print(alice_bits) np.random.seed(seed=0) n = 100 ## Step 1 #Alice generates bits alice_bits = randint(2, size=n) ## Step 2 # Create an array to tell us which qubits # are encoded in which bases alice_bases = randint(2, size=n) print(alice_bases) def encode_message(bits, bases): message = [] for i in range(n): qc = QuantumCircuit(1,1) if bases[i] == 0: # Prepare qubit in Z-basis if bits[i] == 0: pass else: qc.x(0) else: # Prepare qubit in X-basis if bits[i] == 0: qc.h(0) else: qc.x(0) qc.h(0) qc.barrier() message.append(qc) return message np.random.seed(seed=0) n = 100 ## Step 1 # Alice generates bits alice_bits = randint(2, size=n) ## Step 2 # Create an array to tell us which qubits # are encoded in which bases alice_bases = randint(2, size=n) message = encode_message(alice_bits, alice_bases) print('bit = %i' % alice_bits[0]) print('basis = %i' % alice_bases[0]) message[0].draw() print('bit = %i' % alice_bits[4]) print('basis = %i' % alice_bases[4]) message[4].draw() np.random.seed(seed=0) n = 100 ## Step 1 # Alice generates bits alice_bits = randint(2, size=n) ## Step 2 # Create an array to tell us which qubits # are encoded in which bases alice_bases = randint(2, size=n) message = encode_message(alice_bits, alice_bases) ## Step 3 # Decide which basis to measure in: bob_bases = randint(2, size=n) print(bob_bases) def measure_message(message, bases): backend = Aer.get_backend('aer_simulator') measurements = [] for q in range(n): if bases[q] == 0: # measuring in Z-basis message[q].measure(0,0) if bases[q] == 1: # measuring in X-basis message[q].h(0) message[q].measure(0,0) aer_sim = Aer.get_backend('aer_simulator') qobj = assemble(message[q], shots=1, memory=True) result = aer_sim.run(qobj).result() measured_bit = int(result.get_memory()[0]) measurements.append(measured_bit) return measurements np.random.seed(seed=0) n = 100 ## Step 1 # Alice generates bits alice_bits = randint(2, size=n) ## Step 2 # Create an array to tell us which qubits # are encoded in which bases alice_bases = randint(2, size=n) message = encode_message(alice_bits, alice_bases) ## Step 3 # Decide which basis to measure in: bob_bases = randint(2, size=n) bob_results = measure_message(message, bob_bases) message[0].draw() message[6].draw() print(bob_results) def remove_garbage(a_bases, b_bases, bits): good_bits = [] for q in range(n): if a_bases[q] == b_bases[q]: # If both used the same basis, add # this to the list of 'good' bits good_bits.append(bits[q]) return good_bits np.random.seed(seed=0) n = 100 ## Step 1 # Alice generates bits alice_bits = randint(2, size=n) ## Step 2 # Create an array to tell us which qubits # are encoded in which bases alice_bases = randint(2, size=n) message = encode_message(alice_bits, alice_bases) ## Step 3 # Decide which basis to measure in: bob_bases = randint(2, size=n) bob_results = measure_message(message, bob_bases) ## Step 4 alice_key = remove_garbage(alice_bases, bob_bases, alice_bits) print(alice_key) np.random.seed(seed=0) n = 100 ## Step 1 # Alice generates bits alice_bits = randint(2, size=n) ## Step 2 # Create an array to tell us which qubits # are encoded in which bases alice_bases = randint(2, size=n) message = encode_message(alice_bits, alice_bases) ## Step 3 # Decide which basis to measure in: bob_bases = randint(2, size=n) bob_results = measure_message(message, bob_bases) ## Step 4 alice_key = remove_garbage(alice_bases, bob_bases, alice_bits) bob_key = remove_garbage(alice_bases, bob_bases, bob_results) print(bob_key) def sample_bits(bits, selection): sample = [] for i in selection: # use np.mod to make sure the # bit we sample is always in # the list range i = np.mod(i, len(bits)) # pop(i) removes the element of the # list at index 'i' sample.append(bits.pop(i)) return sample np.random.seed(seed=0) n = 100 ## Step 1 # Alice generates bits alice_bits = randint(2, size=n) ## Step 2 # Create an array to tell us which qubits # are encoded in which bases alice_bases = randint(2, size=n) message = encode_message(alice_bits, alice_bases) ## Step 3 # Decide which basis to measure in: bob_bases = randint(2, size=n) bob_results = measure_message(message, bob_bases) ## Step 4 alice_key = remove_garbage(alice_bases, bob_bases, alice_bits) bob_key = remove_garbage(alice_bases, bob_bases, bob_results) ## Step 5 sample_size = 15 bit_selection = randint(n, size=sample_size) bob_sample = sample_bits(bob_key, bit_selection) print(" bob_sample = " + str(bob_sample)) alice_sample = sample_bits(alice_key, bit_selection) print("alice_sample = "+ str(alice_sample)) bob_sample == alice_sample print(bob_key) print(alice_key) print("key length = %i" % len(alice_key)) np.random.seed(seed=3) np.random.seed(seed=3) ## Step 1 alice_bits = randint(2, size=n) print(alice_bits) np.random.seed(seed=3) ## Step 1 alice_bits = randint(2, size=n) ## Step 2 alice_bases = randint(2, size=n) message = encode_message(alice_bits, alice_bases) print(alice_bases) message[0].draw() np.random.seed(seed=3) ## Step 1 alice_bits = randint(2, size=n) ## Step 2 alice_bases = randint(2, size=n) message = encode_message(alice_bits, alice_bases) ## Interception!! eve_bases = randint(2, size=n) intercepted_message = measure_message(message, eve_bases) print(intercepted_message) message[0].draw() np.random.seed(seed=3) ## Step 1 alice_bits = randint(2, size=n) ## Step 2 alice_bases = randint(2, size=n) message = encode_message(alice_bits, alice_bases) ## Interception!! eve_bases = randint(2, size=n) intercepted_message = measure_message(message, eve_bases) ## Step 3 bob_bases = randint(2, size=n) bob_results = measure_message(message, bob_bases) message[0].draw() np.random.seed(seed=3) ## Step 1 alice_bits = randint(2, size=n) ## Step 2 alice_bases = randint(2, size=n) message = encode_message(alice_bits, alice_bases) ## Interception!! eve_bases = randint(2, size=n) intercepted_message = measure_message(message, eve_bases) ## Step 3 bob_bases = randint(2, size=n) bob_results = measure_message(message, bob_bases) ## Step 4 bob_key = remove_garbage(alice_bases, bob_bases, bob_results) alice_key = remove_garbage(alice_bases, bob_bases, alice_bits) np.random.seed(seed=3) ## Step 1 alice_bits = randint(2, size=n) ## Step 2 alice_bases = randint(2, size=n) message = encode_message(alice_bits, alice_bases) ## Interception!! eve_bases = randint(2, size=n) intercepted_message = measure_message(message, eve_bases) ## Step 3 bob_bases = randint(2, size=n) bob_results = measure_message(message, bob_bases) ## Step 4 bob_key = remove_garbage(alice_bases, bob_bases, bob_results) alice_key = remove_garbage(alice_bases, bob_bases, alice_bits) ## Step 5 sample_size = 15 bit_selection = randint(n, size=sample_size) bob_sample = sample_bits(bob_key, bit_selection) print(" bob_sample = " + str(bob_sample)) alice_sample = sample_bits(alice_key, bit_selection) print("alice_sample = "+ str(alice_sample)) bob_sample == alice_sample n = 100 # Step 1 alice_bits = randint(2, size=n) alice_bases = randint(2, size=n) # Step 2 message = encode_message(alice_bits, alice_bases) # Interception! eve_bases = randint(2, size=n) intercepted_message = measure_message(message, eve_bases) # Step 3 bob_bases = randint(2, size=n) bob_results = measure_message(message, bob_bases) # Step 4 bob_key = remove_garbage(alice_bases, bob_bases, bob_results) alice_key = remove_garbage(alice_bases, bob_bases, alice_bits) # Step 5 sample_size = 15 # Change this to something lower and see if # Eve can intercept the message without Alice # and Bob finding out bit_selection = randint(n, size=sample_size) bob_sample = sample_bits(bob_key, bit_selection) alice_sample = sample_bits(alice_key, bit_selection) if bob_sample != alice_sample: print("Eve's interference was detected.") else: print("Eve went undetected!") import qiskit.tools.jupyter %qiskit_version_table
https://github.com/yh08037/quantum-neural-network
yh08037
# !pip install qiskit-aer-gpu import numpy as np import matplotlib.pyplot as plt %matplotlib inline import torch from torch.autograd import Function from torchvision import datasets, transforms import torch.optim as optim import torch.nn as nn import torch.nn.functional as F # from torchsummary import summary import qiskit from qiskit.visualization import * from qiskit.circuit.random import random_circuit from itertools import combinations if torch.cuda.is_available(): DEVICE = torch.device('cuda') else: DEVICE = torch.device('cpu') print('Using PyTorch version:', torch.__version__, ' Device:', DEVICE) print('cuda index:', torch.cuda.current_device()) print('GPU 이름:', torch.cuda.get_device_name()) BATCH_SIZE = 10 EPOCHS = 10 # Number of optimization epochs n_layers = 1 # Number of random layers n_train = 50 # Size of the train dataset n_test = 30 # Size of the test dataset SAVE_PATH = "quanvolution/" # Data saving folder PREPROCESS = True # If False, skip quantum processing and load data from SAVE_PATH seed = 47 np.random.seed(seed) # Seed for NumPy random number generator torch.manual_seed(seed) # Seed for TensorFlow random number generator train_dataset = datasets.MNIST(root = "./data", train = True, download = True, transform = transforms.ToTensor()) train_dataset.data = train_dataset.data[:n_train] train_dataset.targets = train_dataset.targets[:n_train] test_dataset = datasets.MNIST(root = "./data", train = False, transform = transforms.ToTensor()) test_dataset.data = test_dataset.data[:n_test] test_dataset.targets = test_dataset.targets[:n_test] train_loader = torch.utils.data.DataLoader(dataset = train_dataset, batch_size = BATCH_SIZE, shuffle = True) test_loader = torch.utils.data.DataLoader(dataset = test_dataset, batch_size = BATCH_SIZE, shuffle = False) for (X_train, y_train) in train_loader: print('X_train:', X_train.size(), 'type:', X_train.type()) print('y_train:', y_train.size(), 'type:', y_train.type()) break pltsize = 1 plt.figure(figsize=(10 * pltsize, pltsize)) for i in range(10): plt.subplot(1, 10, i + 1) plt.axis('off') plt.imshow(X_train[i, :, :, :].numpy().reshape(28, 28), cmap = "gray_r") plt.title('Class: ' + str(y_train[i].item())) class QuanvCircuit: """ This class defines filter circuit of Quanvolution layer """ def __init__(self, kernel_size, backend, shots, threshold): # --- Circuit definition start --- self.n_qubits = kernel_size ** 2 self._circuit = qiskit.QuantumCircuit(self.n_qubits) self.theta = [qiskit.circuit.Parameter('theta{}'.format(i)) for i in range(self.n_qubits)] for i in range(self.n_qubits): self._circuit.rx(self.theta[i], i) self._circuit.barrier() self._circuit += random_circuit(self.n_qubits, 2) self._circuit.measure_all() # ---- Circuit definition end ---- self.backend = backend self.shots = shots self.threshold = threshold def run(self, data): # data shape: tensor (1, 5, 5) # val > self.threshold : |1> - rx(pi) # val <= self.threshold : |0> - rx(0) # reshape input data # [1, kernel_size, kernel_size] -> [1, self.n_qubits] data = torch.reshape(data, (1, self.n_qubits)) # encoding data to parameters thetas = [] for dat in data: theta = [] for val in dat: if val > self.threshold: theta.append(np.pi) else: theta.append(0) thetas.append(theta) param_dict = dict() for theta in thetas: for i in range(self.n_qubits): param_dict[self.theta[i]] = theta[i] param_binds = [param_dict] # execute random quantum circuit job = qiskit.execute(self._circuit, self.backend, shots = self.shots, parameter_binds = param_binds) result = job.result().get_counts(self._circuit) # decoding the result counts = 0 for key, val in result.items(): cnt = sum([int(char) for char in key]) counts += cnt * val # Compute probabilities for each state probabilities = counts / (self.shots * self.n_qubits) # probabilities = counts / self.shots return probabilities # backend = qiskit.Aer.get_backend('qasm_simulator') backend = qiskit.providers.aer.QasmSimulator(method = "statevector_gpu") filter_size = 2 circ = QuanvCircuit(filter_size, backend, 100, 127) data = torch.tensor([[0, 200], [100, 255]]) # data = torch.tensor([[0, 200, 128, 192,168], [100, 255,53,47,29],[100, 255,53,47,29],[0, 200, 128, 192,168],[0, 200, 128, 192,168]]) print(data.size()) print(circ.run(data)) circ._circuit.draw(output='mpl') ''' def quanv_feed(image): """ Convolves the input image with many applications of the same quantum circuit. In the standard language of CNN, this would correspond to a convolution with a 5×5 kernel and a stride equal to 1. """ out = np.zeros((24, 24, 25)) # Loop over the coordinates of the top-left pixel of 5X5 squares for j in range(24): for k in range(24): # Process a squared 5x5 region of the image with a quantum circuit circuit_input = [] for a in range(5): for b in range(5): circuit_input.append(image[j + a, k + b, 0]) q_results = circuit(circuit_input) # Assign expectation values to different channels of the output pixel (j/2, k/2) for c in range(25): out[24, 24, c] = q_results[c] return out ''' class QuanvFunction(Function): """ Quanv function definition """ @staticmethod def forward(ctx, inputs, in_channels, out_channels, kernel_size, quantum_circuits, shift): """ Forward pass computation """ # input shape : (-1, 1, 28, 28) # otuput shape : (-1, 6, 24, 24) ctx.in_channels = in_channels ctx.out_channels = out_channels ctx.kernel_size = kernel_size ctx.quantum_circuits = quantum_circuits ctx.shift = shift _, _, len_x, len_y = inputs.size() len_x = len_x - kernel_size + 1 len_y = len_y - kernel_size + 1 outputs = torch.zeros((len(inputs), len(quantum_circuits), len_x, len_y)).to(DEVICE) for i in range(len(inputs)): print(f"batch{i}") input = inputs[i] for c in range(len(quantum_circuits)): circuit = quantum_circuits[c] print(f"channel{c}") for h in range(len_y): for w in range(len_x): data = input[0, h:h+kernel_size, w:w+kernel_size] outputs[i, c, h, w] = circuit.run(data) # print(f"({h},{w})") ctx.save_for_backward(inputs, outputs) return outputs ''' features = [] for input in inputs: feature = [] for circuit in quantum_circuits: xys = [] for x in range(len_x): ys = [] for y in range(len_y): data = input[0, x:x+kernel_size, y:y+kernel_size] ys.append(circuit.run(data)) xys.append(ys) feature.append(xys) features.append(feature) result = torch.tensor(features) ctx.save_for_backward(inputs, result) return result ''' @staticmethod def backward(ctx, grad_output): # 확인 필요(검증 x) """ Backward pass computation """ input, expectation_z = ctx.saved_tensors input_list = np.array(input.tolist()) shift_right = input_list + np.ones(input_list.shape) * ctx.shift shift_left = input_list - np.ones(input_list.shape) * ctx.shift gradients = [] for i in range(len(input_list)): expectation_right = ctx.quantum_circuit.run(shift_right[i]) expectation_left = ctx.quantum_circuit.run(shift_left[i]) gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left]) gradients.append(gradient) gradients = np.array([gradients]).T return torch.tensor([gradients]).float() * grad_output.float(), None, None class Quanv(nn.Module): """ Quanvolution(Quantum convolution) layer definition """ def __init__(self, in_channels, out_channels, kernel_size, backend=qiskit.providers.aer.QasmSimulator(method="statevector_gpu"), shots=100, shift=np.pi/2): super(Quanv, self).__init__() self.quantum_circuits = [QuanvCircuit(kernel_size=kernel_size, backend=backend, shots=shots, threshold=127) for i in range(out_channels)] self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = kernel_size self.shift = shift def forward(self, inputs): return QuanvFunction.apply(inputs, self.in_channels, self.out_channels, self.kernel_size, self.quantum_circuits, self.shift) class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.quanv = Quanv(in_channels=1, out_channels=1, kernel_size = 3) # <- Quanv!!!! self.conv = nn.Conv2d(1, 16, kernel_size=5) self.dropout = nn.Dropout2d() self.fc1 = nn.Linear(256, 64) self.fc2 = nn.Linear(64, 10) def forward(self, x): x = F.relu(self.quanv(x)) x = F.max_pool2d(x, 2) x = F.relu(self.conv(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) # x = x.view(-1, 256) x = torch.flatten(x, start_dim=1) x = F.relu(self.fc1(x)) x = self.fc2(x) return F.softmax(x) model = Net().to(DEVICE) optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.CrossEntropyLoss() epochs = 20 loss_list = [] model.train().to(DEVICE) for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): target = target.to(DEVICE) optimizer.zero_grad() # Forward pass output = model(data).to(DEVICE) # Calculating loss loss = loss_func(output, target).to(DEVICE) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format( 100. * (epoch + 1) / epochs, loss_list[-1])) model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): data = data.cuda() target = target.cuda() output = model(data).cuda() pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100 / batch_size) )
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.visualization.timeline import draw as timeline_draw from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeBoeblingen backend = FakeBoeblingen() ghz = QuantumCircuit(5) ghz.h(0) ghz.cx(0,range(1,5)) circ = transpile(ghz, backend, scheduling_method="asap") timeline_draw(circ)
https://github.com/nielsaNTNU/qiskit_utilities
nielsaNTNU
import numpy as np import pylab as pl import qiskit.tools.jupyter from qiskit import execute, QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.quantum_info import Kraus, SuperOp from qiskit.providers.aer import QasmSimulator from qiskit.tools.visualization import plot_histogram # Import from Qiskit Aer noise module from qiskit import * from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise import QuantumError, ReadoutError from qiskit.providers.aer.noise import depolarizing_error from qiskit.providers.aer.noise import thermal_relaxation_error backendname_sim = Aer.get_backend('qasm_simulator') circ = QuantumCircuit(2,2) circ.h(0) circ.cx(0,1) circ.measure(0,0) circ.measure(1,1) circ.draw(output='mpl') circs=[] for i in range(1024): circs.append(circ) job_clean = execute(circs, backendname_sim, shots=1024) results_clean=job_clean.result().results # counts_clean=job.result().get_counts() # plot_histogram(counts_clean) # T1 and T2 values for qubits 0-4 T1s = np.random.normal(50e2, 10e2, 5) # Sampled from normal distribution mean 50 microsec T2s = np.random.normal(70e2, 10e2, 5) # Sampled from normal distribution mean 50 microsec # Truncate random T2s <= T1s T2s = np.array([min(T2s[j], 2 * T1s[j]) for j in range(5)]) # Instruction times (in nanoseconds) time_u1 = 0 # virtual gate time_u2 = 50 # (single X90 pulse) time_u3 = 100 # (two X90 pulses) time_cx = 300 time_reset = 1000 # 1 microsecond time_measure = 1000 # 1 microsecond # QuantumError objects errors_reset = [thermal_relaxation_error(t1, t2, time_reset) for t1, t2 in zip(T1s, T2s)] errors_measure = [thermal_relaxation_error(t1, t2, time_measure) for t1, t2 in zip(T1s, T2s)] errors_u1 = [thermal_relaxation_error(t1, t2, time_u1) for t1, t2 in zip(T1s, T2s)] errors_u2 = [thermal_relaxation_error(t1, t2, time_u2) for t1, t2 in zip(T1s, T2s)] errors_u3 = [thermal_relaxation_error(t1, t2, time_u3) for t1, t2 in zip(T1s, T2s)] errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand( thermal_relaxation_error(t1b, t2b, time_cx)) for t1a, t2a in zip(T1s, T2s)] for t1b, t2b in zip(T1s, T2s)] # Add errors to noise model noise_thermal = NoiseModel() for j in range(5): noise_thermal.add_quantum_error(errors_reset[j], "reset", [j]) noise_thermal.add_quantum_error(errors_measure[j], "measure", [j]) noise_thermal.add_quantum_error(errors_u1[j], "u1", [j]) noise_thermal.add_quantum_error(errors_u2[j], "u2", [j]) noise_thermal.add_quantum_error(errors_u3[j], "u3", [j]) for k in range(5): noise_thermal.add_quantum_error(errors_cx[j][k], "cx", [j, k]) print(noise_thermal) job_thermal = execute(circs, backendname_sim, basis_gates=noise_thermal.basis_gates, noise_model=noise_thermal,shots=1024) results_thermal=job_thermal.result().results # result_thermal = job.result() counts_clean = job_clean.result().get_counts(0) counts_thermal = job_thermal.result().get_counts(0) # Plot noisy output plot_histogram([counts_thermal,counts_clean],legend=['thermal','clean']) numones=np.zeros((2**5,1)) for i in range(2**5): numones[i]=bin(i).count("1") def expectationValue(results): #num_qubits = results[0].header.n_qubits E=np.zeros((len(results),1)) for item in range(0,len(results)): shots = results[item].shots counts = results[item].data.counts for key in list(counts.__dict__.keys()): c=getattr(counts, key)#number of counts E[item] += numones[int(key,0)]*c/shots E_conv = np.zeros_like(E) for j in range(1,len(results)+1): E_conv[j-1] = sum(E[0:j])/j return E, E_conv E_clean, E_conv_clean = expectationValue(job_clean.result().results) E_thermal, E_conv_thermal = expectationValue(job_thermal.result().results) pl.plot(E_conv_clean) pl.plot(E_conv_thermal)
https://github.com/hephaex/Quantum-Computing-Awesome-List
hephaex
from qiskit import * from math import pi import numpy as np from qiskit.visualization import plot_bloch_multivector, plot_histogram qc = QuantumCircuit(3) for qubit in range(3): qc.h(qubit) qc.draw() backend = Aer.get_backend('statevector_simulator') final_state = execute(qc, backend).result().get_statevector() print(final_state) qc = QuantumCircuit(2) qc.h(0) qc.x(1) qc.draw() backend = Aer.get_backend('unitary_simulator') unitary = execute(qc, backend).result().get_unitary() print(unitary) qiskit.__qiskit_version__ qc = QuantumCircuit(3) qc.x(0) qc.z(1) qc.h(2) qc.draw() unitary = execute(qc, backend).result().get_unitary() print(unitary) qc = QuantumCircuit(2) # Apply H-gate to the first: qc.h(0) qc.draw() backend = Aer.get_backend('statevector_simulator') final_state = execute(qc,backend).result().get_statevector() print(final_state) qc = QuantumCircuit(2) # Apply H-gate to the first: qc.h(0) # Apply a CNOT: qc.cx(0,1) qc.draw() final_state = Aer.get_backend('statevector_simulator') final_state = execute(qc, backend).result().get_statevector() print(final_state) results = execute(qc,backend).result().get_counts() plot_histogram(results) qc = QuantumCircuit(2) qc.h(0) qc.x(1) qc.cx(0,1) qc.draw() backend = Aer.get_backend('statevector_simulator') result = execute(qc, backend).result().get_statevector() print(result) result = execute(qc, backend).result().get_counts() plot_histogram(result) unitary = execute(qc, backend).result().get_unitary() print(unitary)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import BasicAer, transpile, QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.h(0) qc.measure(0, 0) qc.x(0).c_if(cr, 0) qc.measure(0, 0) qc.draw('mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit.visualization import plot_circuit_layout from qiskit.providers.fake_provider import FakeVigo backend = FakeVigo() ghz = QuantumCircuit(3, 3) ghz.h(0) ghz.cx(0,range(1,3)) ghz.barrier() ghz.measure(range(3), range(3)) new_circ_lv0 = transpile(ghz, backend=backend, optimization_level=0) plot_circuit_layout(new_circ_lv0, backend)
https://github.com/martynscn/Masters-Thesis-on-Quantum-Cryptography
martynscn
# This code has been adapted and modified from IBM Qiskit 2021 and also from https://github.com/ttlion/ShorAlgQiskit. # It uses the implementation as contained in the work of Stephane Beauregard (https://arxiv.org/abs/quant-ph/0205095) # Many thanks to IBM Qiskit team, Tiago Miguel (ttlion), Qubit by Qubit, Peter Shor and Stephane Beauregard. from typing import Optional, Union, Tuple, List import math import array import fractions import logging import numpy as np from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister, execute, IBMQ, transpile,BasicAer, Aer, assemble from qiskit.circuit import Gate, Instruction, ParameterVector from qiskit.circuit.library import QFT from qiskit.providers import BaseBackend, Backend from qiskit.quantum_info import partial_trace from qiskit.utils import summarize_circuits from qiskit.utils.arithmetic import is_power from qiskit.utils.validation import validate_min from qiskit.utils.quantum_instance import QuantumInstance import qiskit.visualization from qiskit.providers.aer import QasmSimulator from datetime import datetime import csv # provider = IBMQ.enable_account("PUT TOKEN HERE") backend = QasmSimulator() from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" #"last_expr" or "all" # """ Function to check if N is of type q^p""" def check_if_power(N): # """ Check if N is a perfect power in O(n^3) time, n=ceil(logN) """ b=2 while (2**b) <= N: a = 1 c = N while (c-a) >= 2: m = int( (a+c)/2 ) if (m**b) < (N+1): p = int( (m**b) ) else: p = int(N+1) if int(p) == int(N): print('N is {0}^{1}'.format(int(m),int(b)) ) return True if p<N: a = int(m) else: c = int(m) b=b+1 return False def egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) def modinv(a, m): g, x, y = egcd(a, m) if g != 1: raise Exception('modular inverse does not exist') else: return x % m def create_QFT(circuit,up_reg,n,with_swaps): i=n-1 while i>=0: circuit.h(up_reg[i]) j=i-1 while j>=0: if (np.pi)/(pow(2,(i-j))) > 0: circuit.cu1( (np.pi)/(pow(2,(i-j))) , up_reg[i] , up_reg[j] ) j=j-1 i=i-1 if with_swaps==1: i=0 while i < ((n-1)/2): circuit.swap(up_reg[i], up_reg[n-1-i]) i=i+1 def create_inverse_QFT(circuit,up_reg,n,with_swaps): if with_swaps==1: i=0 while i < ((n-1)/2): circuit.swap(up_reg[i], up_reg[n-1-i]) i=i+1 i=0 while i<n: circuit.h(up_reg[i]) if i != n-1: j=i+1 y=i while y>=0: if (np.pi)/(pow(2,(j-y))) > 0: circuit.cu1( - (np.pi)/(pow(2,(j-y))) , up_reg[j] , up_reg[y] ) y=y-1 i=i+1 def getAngle(a, N): s=bin(int(a))[2:].zfill(N) angle = 0 for i in range(0, N): if s[N-1-i] == '1': angle += math.pow(2, -(N-i)) angle *= np.pi return angle def getAngles(a,N): s=bin(int(a))[2:].zfill(N) angles=np.zeros([N]) for i in range(0, N): for j in range(i,N): if s[j]=='1': angles[N-i-1]+=math.pow(2, -(j-i)) angles[N-i-1]*=np.pi return angles def ccphase(circuit, angle, ctl1, ctl2, tgt): circuit.cu1(angle/2,ctl1,tgt) circuit.cx(ctl2,ctl1) circuit.cu1(-angle/2,ctl1,tgt) circuit.cx(ctl2,ctl1) circuit.cu1(angle/2,ctl2,tgt) def phiADD(circuit, q, a, N, inv): angle=getAngles(a,N) for i in range(0,N): if inv==0: circuit.u1(angle[i],q[i]) else: circuit.u1(-angle[i],q[i]) def cphiADD(circuit, q, ctl, a, n, inv): angle=getAngles(a,n) for i in range(0,n): if inv==0: circuit.cu1(angle[i],ctl,q[i]) else: circuit.cu1(-angle[i],ctl,q[i]) def ccphiADD(circuit,q,ctl1,ctl2,a,n,inv): angle=getAngles(a,n) for i in range(0,n): if inv==0: ccphase(circuit,angle[i],ctl1,ctl2,q[i]) else: ccphase(circuit,-angle[i],ctl1,ctl2,q[i]) def ccphiADDmodN(circuit, q, ctl1, ctl2, aux, a, N, n): ccphiADD(circuit, q, ctl1, ctl2, a, n, 0) phiADD(circuit, q, N, n, 1) # phiADD(circuit, q, a,N, 1) create_inverse_QFT(circuit, q, n, 0) circuit.cx(q[n-1],aux) create_QFT(circuit,q,n,0) cphiADD(circuit, q, aux, N, n, 0) # cphiADD(circuit, q, aux, a, n, 0) ccphiADD(circuit, q, ctl1, ctl2, a, n, 1) create_inverse_QFT(circuit, q, n, 0) circuit.x(q[n-1]) circuit.cx(q[n-1], aux) circuit.x(q[n-1]) create_QFT(circuit,q,n,0) ccphiADD(circuit, q, ctl1, ctl2, a, n, 0) def ccphiADDmodN_inv(circuit, q, ctl1, ctl2, aux, a, N, n): ccphiADD(circuit, q, ctl1, ctl2, a, n, 1) create_inverse_QFT(circuit, q, n, 0) circuit.x(q[n-1]) circuit.cx(q[n-1],aux) circuit.x(q[n-1]) create_QFT(circuit, q, n, 0) ccphiADD(circuit, q, ctl1, ctl2, a, n, 0) cphiADD(circuit, q, aux, N, n, 1) # cphiADD(circuit, q, aux, a, n, 1) create_inverse_QFT(circuit, q, n, 0) circuit.cx(q[n-1], aux) create_QFT(circuit, q, n, 0) phiADD(circuit, q, N, n, 0) # phiADD(circuit, q, a, N, 0) ccphiADD(circuit, q, ctl1, ctl2, a, n, 1) def cMULTmodN(circuit, ctl, q, aux, a, N, n): # up_reg = QuantumRegister(1, name = "up_reg") # down_reg = QuantumRegister(n, name = "down_reg") # up_classic = ClassicalRegister(2*n, name="up_classic") # c_aux = ClassicalRegister(1, name = "aux_classic") # cMULTmodN_circuit = QuantumCircuit( # up_reg ,down_reg , aux,up_classic, c_aux, # name=r"${0}^{{{1}^{{{2}}}}} mod{3}$".format(2,2,int(math.log(math.log(a,2),2)), N) # ) # create_QFT(cMULTmodN_circuit,aux,n+1,0) # for i in range(0, n): # ccphiADDmodN(cMULTmodN_circuit, aux, q[i], ctl, aux[n+1], (2**i)*a % N, N, n+1) # create_inverse_QFT(cMULTmodN_circuit, aux, n+1, 0) # for i in range(0, n): # circuit.cswap(ctl,q[i],aux[i]) # cMULTmodN_circuit.cswap(ctl,q[i],aux[i]) # create_QFT(cMULTmodN_circuit, aux, n+1, 0) # ccphiADDmodN_inv(cMULTmodN_circuit, aux, q[i], ctl, aux[n+1], math.pow(2,i)*a_inv % N, N, n+1) # create_inverse_QFT(cMULTmodN_circuit, aux, n+1, 0) # cMULTmodN_circuit_instruction = cMULTmodN_circuit.to_instruction() # circuit.append(cMULTmodN_circuit_instruction, [ctl, *down_reg, *aux]) create_QFT(circuit,aux,n+1,0) for i in range(0, n): ccphiADDmodN(circuit, aux, q[i], ctl, aux[n+1], (2**i)*a % N, N, n+1) create_inverse_QFT(circuit, aux, n+1, 0) for i in range(0, n): circuit.cswap(ctl,q[i],aux[i]) a_inv = modinv(a, N) create_QFT(circuit, aux, n+1, 0) i = n-1 while i >= 0: ccphiADDmodN_inv(circuit, aux, q[i], ctl, aux[n+1], math.pow(2,i)*a_inv % N, N, n+1) i -= 1 create_inverse_QFT(circuit, aux, n+1, 0) def calculate_continued_fraction(b: array.array) -> int: # """Calculate the continued fraction of x/T from the current terms of expansion b.""" x_over_T = 0 for i in reversed(range(len(b) - 1)): x_over_T = 1 / (b[i + 1] + x_over_T) x_over_T += b[0] frac = fractions.Fraction(x_over_T).limit_denominator() return frac.denominator def get_factors(N: int, a: int, measurement: str) -> Optional[List[int]]: # """Apply the continued fractions to find r and the gcd to find the desired factors.""" x_final = int(measurement, 2) #print('In decimal, x_final value for this result is: {}.'.format(x_final)) if x_final <= 0: fail_reason = 'x_final value is <= 0, there are no continued fractions.' else: fail_reason = None #print('Running continued fractions for this case.') # Calculate T and x/T T_upper = len(measurement) T = pow(2, T_upper) x_over_T = x_final / T ## this is our theta # Cycle in which each iteration corresponds to putting one more term in the # calculation of the Continued Fraction (CF) of x/T # Initialize the first values according to CF rule i = 0 b = array.array('i') t = array.array('f') b.append(math.floor(x_over_T)) t.append(x_over_T - b[i]) exponential = 0.0 while i < N and fail_reason is None: # From the 2nd iteration onwards, calculate the new terms of the CF based on the previous terms as the rule suggests if i > 0: try: b_temp = math.floor(1 / t[i - 1]) except ZeroDivisionError as err: b_temp = 0 b.append(b_temp) try: t_temp = (1 / t[i - 1]) - b[i] except ZeroDivisionError as err: t_temp = 0 t.append(t_temp) # type: ignore # Calculate the denominator of the CF using the known terms denominator = calculate_continued_fraction(b) # Increment i for next iteration i += 1 if denominator % 2 == 1: #print('Odd denominator, will try next iteration of continued fractions.') continue # Denominator is even, try to get factors of N. Get the exponential a^(r/2) if denominator < 1000: try: exponential = pow(a, denominator / 2) except OverflowError as err: exponential = 999999999 # Check if the value is too big or not if exponential > 1000000: if exponential == 999999999: fail_reason = 'OverflowError' else: fail_reason = 'denominator of continued fraction is too big (> 10^3).' else: # The value is not too big, get the right values and do the proper gcd() putting_plus = int(exponential + 1) putting_minus = int(exponential - 1) one_factor = math.gcd(putting_plus, N) other_factor = math.gcd(putting_minus, N) # Check if the factors found are trivial factors or are the desired factors if any(factor in {1, N} for factor in (one_factor, other_factor)): #print('Found just trivial factors, not good enough.') # Check if the number has already been found, (use i - 1 because i was already incremented) if t[i - 1] == 0: fail_reason = 'the continued fractions found exactly x_final/(2^(2n)).' else: return sorted((one_factor, other_factor)) return None def process_results(sim_result, circuit, shots, N, a, n): counts_result = sim_result.get_counts(circuit) total_counts = len(counts_result) counts_result_sorted = sorted(counts_result.items(), key=lambda x: x[1], reverse=True) counts_result_keys = list(counts_result.keys()) counts_result_values = list(counts_result.values()) prob_success=0 prob_failure=0 result_successful_counts = 0 result_failure_counts = 0 for initial_undesired_measurement, frequency in counts_result_sorted: measurement = initial_undesired_measurement.split(" ")[1] x_value = int(measurement, 2) prob_this_result = 100 * frequency/shots factors = get_factors(N, a, measurement) if factors: prob_success = prob_success + prob_this_result result_successful_counts = result_successful_counts + 1 if factors not in result_factors: result_factors.append(factors) elif not factors: prob_failure = prob_failure + prob_this_result result_failure_counts = result_failure_counts + 1 return [result_factors, prob_success, prob_failure, total_counts, result_successful_counts,result_failure_counts] def my_shor(a,N,shots): start_time_number = datetime.now() start_time = start_time_number.strftime("%H:%M:%S") summary_result = dict() validate_min('N', N, 3) validate_min('a', a, 2) if N < 1 or N % 2 == 0: raise ValueError('The input needs to be an odd integer greater than 1.') if a >= N or math.gcd(a, N) != 1: raise ValueError('The integer a needs to satisfy a < N and gcd(a, N) = 1.') n = math.ceil(math.log(N,2)) global result_factors result_factors = [] tf, b, p = is_power(N, return_decomposition=True) if tf: print('The input integer is a power: {0}={1}^{2}.'.format(N, b, p)) result_factors.append(b) # """auxilliary quantum register used in addition and multiplication""" aux = QuantumRegister(size = n+2, name="aux_reg") # """single qubit where the sequential QFT is performed""" up_reg = QuantumRegister(1, name = "up_reg") down_reg = QuantumRegister(n, name = "down_reg") # """classical register where the measured values of the sequential QFT are stored""" up_classic = ClassicalRegister(2*n, name="up_classic") # """classical bit used to reset the state of the top qubit to 0 if the previous measurement was 1""" c_aux = ClassicalRegister(1, name = "aux_classic") # """ Create Quantum Circuit """ circuit = QuantumCircuit(up_reg ,down_reg , aux,up_classic, c_aux) circuit.x(down_reg[0]) # circuit.draw(filename = "shor_semiclassical_QFT_initialization") for i in range(0, 2*n): circuit.x(up_reg).c_if(c_aux, 1) circuit.h(up_reg) cMULTmodN(circuit, up_reg[0], down_reg, aux, a**(2**(2*n-1-i)), N, n) # later confirm if this should be up_reg[i] instead of up_reg[0] for j in range(0, 2**i): circuit.u1(getAngle(j, i), up_reg[0]).c_if(up_classic, j) circuit.h(up_reg) circuit.measure(up_reg[0], up_classic[i]) circuit.measure(up_reg[0], c_aux[0]) # circuit.draw(filename = "shor_semiclassical_QFT_final_circuit") circuit.draw() qc_compiled = transpile(circuit, backend, optimization_level = 3) job_sim_1 = backend.run(qc_compiled, shots=shots) sim_result=job_sim_1.result() # counts_result = sim_result.get_counts(circuit) # len(counts_result) # measurement_plot = qiskit.visualization.plot_histogram(counts_result,figsize=(20, 12) ,number_to_keep = 30,bar_labels=True, title = "Measurement results from shor_standard_QFT circuit variant" ) # measurement_plot.savefig("shor_semiclassical_QFT_measurement_result") # measurement_plot processed_result = process_results(sim_result, circuit, shots, N, a, n) end_time_number = datetime.now() end_time = end_time_number.strftime("%H:%M:%S") duration = end_time_number - start_time_number print("Current Start Time =", start_time) print(processed_result) print("Current End Time =", end_time) circuit_count_ops = circuit.count_ops() circuit_decomposed = circuit.decompose() circuit_decomposed_count_ops = circuit_decomposed.count_ops() qc_compiled_count_ops = qc_compiled.count_ops() summary_result["num_qubits"] = n summary_result["Number(N)"] = N summary_result["a"] = a summary_result["start_time"] = start_time summary_result["end_time"] = end_time summary_result["duration"] = duration summary_result["result_factors"] = processed_result[0] summary_result["prob_success"] = processed_result[1] summary_result["prob_failure"] = processed_result[2] summary_result["total_counts"] = processed_result[3] summary_result["result_successful_counts"] = processed_result[4] summary_result["result_failure_counts"] = processed_result[5] summary_result["circuit_width"] = circuit.width() summary_result["circuit_depth"] = circuit.depth() summary_result["circuit_size"] = circuit.size() summary_result["circuit_num_nonlocal_gates"] = circuit.num_nonlocal_gates() summary_result["circuit_num_ancillas"] = circuit.num_ancillas summary_result["circuit_num_clbits"] = circuit.num_clbits summary_result["circuit_num_qubits"] = circuit.num_qubits summary_result["circuit_num_ancillas"] = circuit.num_ancillas summary_result["circuit_num_of_count_ops"] = len(circuit_count_ops) summary_result["circuit_num_of_x"] = circuit_count_ops.get('x') summary_result["circuit_num_of_measure"] = circuit_count_ops.get('measure') summary_result["circuit_num_of_h"] = circuit_count_ops.get('h') summary_result["circuit_num_of_cswap"] = circuit_count_ops.get('cswap') summary_result["circuit_num_of_swap"] = circuit_count_ops.get('swap') summary_result["circuit_num_of_cx"] = circuit_count_ops.get('cx') summary_result["circuit_num_of_toffoli"] = circuit_count_ops.get('toffoli') summary_result["circuit_num_of_p"] = circuit_count_ops.get('p') summary_result["circuit_num_of_t"] = circuit_count_ops.get('t') summary_result["circuit_decomposed_width"] = circuit_decomposed.width() summary_result["circuit_decomposed_depth"] = circuit_decomposed.depth() summary_result["circuit_decomposed_size"] = circuit_decomposed.size() summary_result["circuit_decomposed_num_nonlocal_gates"] = circuit_decomposed.num_nonlocal_gates() summary_result["circuit_decomposed_num_ancillas"] = circuit_decomposed.num_ancillas summary_result["circuit_decomposed_num_clbits"] = circuit_decomposed.num_clbits summary_result["circuit_decomposed_num_qubits"] = circuit_decomposed.num_qubits summary_result["circuit_decomposed_num_ancillas"] = circuit_decomposed.num_ancillas summary_result["circuit_decomposed_num_of_count_ops"] = len(circuit_decomposed_count_ops) summary_result["circuit_decomposed_num_of_x"] = circuit_decomposed_count_ops.get('x') summary_result["circuit_decomposed_num_of_measure"] = circuit_decomposed_count_ops.get('measure') summary_result["circuit_decomposed_num_of_h"] = circuit_decomposed_count_ops.get('h') summary_result["circuit_decomposed_num_of_cswap"] = circuit_decomposed_count_ops.get('cswap') summary_result["circuit_decomposed_num_of_swap"] = circuit_decomposed_count_ops.get('swap') summary_result["circuit_decomposed_num_of_cx"] = circuit_decomposed_count_ops.get('cx') summary_result["circuit_decomposed_num_of_toffoli"] = circuit_decomposed_count_ops.get('toffoli') summary_result["circuit_decomposed_num_of_p"] = circuit_decomposed_count_ops.get('p') summary_result["circuit_decomposed_num_of_t"] = circuit_decomposed_count_ops.get('t') summary_result["qc_compiled_width"] = qc_compiled.width() summary_result["qc_compiled_depth"] = qc_compiled.depth() summary_result["qc_compiled_size"] = qc_compiled.size() summary_result["qc_compiled_num_nonlocal_gates"] = qc_compiled.num_nonlocal_gates() summary_result["qc_compiled_num_ancillas"] = qc_compiled.num_ancillas summary_result["qc_compiled_num_clbits"] = qc_compiled.num_clbits summary_result["qc_compiled_num_qubits"] = qc_compiled.num_qubits summary_result["qc_compiled_num_ancillas"] = qc_compiled.num_ancillas summary_result["qc_compiled_num_of_count_ops"] = len(qc_compiled_count_ops) summary_result["qc_compiled_num_of_x"] = qc_compiled_count_ops.get('x') summary_result["qc_compiled_num_of_measure"] = qc_compiled_count_ops.get('measure') summary_result["qc_compiled_num_of_h"] = qc_compiled_count_ops.get('h') summary_result["qc_compiled_num_of_cswap"] = qc_compiled_count_ops.get('cswap') summary_result["qc_compiled_num_of_swap"] = qc_compiled_count_ops.get('swap') summary_result["qc_compiled_num_of_cx"] = qc_compiled_count_ops.get('cx') summary_result["qc_compiled_num_of_toffoli"] = qc_compiled_count_ops.get('toffoli') summary_result["qc_compiled_num_of_p"] = qc_compiled_count_ops.get('p') summary_result["qc_compiled_num_of_t"] = qc_compiled_count_ops.get('t') return summary_result # Run for just a single number N %%time N = 21 shots = 1024 global result_factors all_summary_result_temp = [] for random_a in range(2, N): if math.gcd(random_a,N) > 1: continue a = random_a summary_result = my_shor(a,N,shots) print("Finished running for a = {} and N = {}\n".format(a, N)) all_summary_result_temp.append(summary_result) summary_result_list = [] for key, value in summary_result.items(): summary_result_list.append([key,value]) summary_result_list with open("a({0})_N({1})_semiclassical.csv".format(a, N), 'a') as myfile: write = csv.writer(myfile) #write.writerow(fields) write.writerows(summary_result_list) all_summary_result_temp # Run for many numbers N. %%time shots = 1024 global result_factors all_summary_result = [] for N in [15, 21, 33, 35, 39, 51, 55, 57]: for a in range(2, N): if math.gcd(a,N) > 1: continue print("Beginning running for a = {} and N = {}".format(a, N)) summary_result = my_shor(a,N,shots) print("Finished running for a = {} and N = {}\n\n".format(a, N)) all_summary_result.append(summary_result) all_summary_result %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.providers.fake_provider import FakeHanoi backend = FakeHanoi() config = backend.configuration() # Basic Features print("This backend is called {0}, and is on version {1}. It has {2} qubit{3}. It " "{4} OpenPulse programs. The basis gates supported on this device are {5}." "".format(config.backend_name, config.backend_version, config.n_qubits, '' if config.n_qubits == 1 else 's', 'supports' if config.open_pulse else 'does not support', config.basis_gates)) config.dt # units of seconds config.meas_levels config.dtm config.meas_map config.drive(0) config.measure(0) config.acquire(0) props = backend.properties() def describe_qubit(qubit, properties): """Print a string describing some of reported properties of the given qubit.""" # Conversion factors from standard SI units us = 1e6 ns = 1e9 GHz = 1e-9 print("Qubit {0} has a \n" " - T1 time of {1} microseconds\n" " - T2 time of {2} microseconds\n" " - U2 gate error of {3}\n" " - U2 gate duration of {4} nanoseconds\n" " - resonant frequency of {5} GHz".format( qubit, properties.t1(qubit) * us, properties.t2(qubit) * us, properties.gate_error('sx', qubit), properties.gate_length('sx', qubit) * ns, properties.frequency(qubit) * GHz)) describe_qubit(0, props) defaults = backend.defaults() q0_freq = defaults.qubit_freq_est[0] # Hz q0_meas_freq = defaults.meas_freq_est[0] # Hz GHz = 1e-9 print("DriveChannel(0) defaults to a modulation frequency of {} GHz.".format(q0_freq * GHz)) print("MeasureChannel(0) defaults to a modulation frequency of {} GHz.".format(q0_meas_freq * GHz)) calibrations = defaults.instruction_schedule_map print(calibrations) measure_schedule = calibrations.get('measure', range(config.n_qubits)) measure_schedule.draw(backend=backend) # You can use `has` to see if an operation is defined. Ex: Does qubit 3 have an x gate defined? calibrations.has('x', 3) # Some circuit operations take parameters. U1 takes a rotation angle: calibrations.get('u1', 0, P0=3.1415) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/sohamch08/Qiskit-Quantum-Algo
sohamch08
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister import numpy as np def step_1_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit: # qr is a quantum register with 2 qubits # cr is a classical register with 2 bits qc = QuantumCircuit(qr, cr) ########## your code goes here ####### ##1 Initialization q0, q1 = qr # apply Hadamard on the auxiliary qubit qc.h(q0) # put the system qubit into the |1> state qc.x(q1) ##2 Apply control-U operator as many times as needed to get the least significant phase bit # controlled-S is equivalent to CPhase with angle pi / 2 s_angle = np.pi / 2 # we want to apply controlled-S 2^k times k = 1 # calculate the angle of CPhase corresponding to 2^k applications of controlled-S cphase_angle = s_angle * 2**k # apply the controlled phase gate qc.cp(cphase_angle, q0, q1) ##3 Measure the auxiliary qubit in x-basis into the first classical bit # apply Hadamard to change to the X basis qc.h(q0) # measure the auxiliary qubit into the first classical bit c0, _ = cr qc.measure(q0, c0) return qc qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") qc = QuantumCircuit(qr, cr) qc = step_1_circuit(qr, cr) qc.draw("mpl") # Submit your circuit from qc_grader.challenges.spring_2023 import grade_ex3a grade_ex3a(qc) def step_2_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit: # qr is a quantum register with 2 qubits # cr is a classical register with 2 bits # begin with the circuit from Step 1 qc = step_1_circuit(qr, cr) ########## your code goes here ####### ##1 Reset and re-initialize the auxiliary qubit q0, q1 = qr # reset the auxiliary qubit qc.reset(q0) # apply Hadamard on the auxiiliary qubit qc.h(q0) ##2 Apply phase correction conditioned on the first classical bit c0, c1 = cr with qc.if_test((c0, 1)): qc.p(-np.pi / 2, q0) ##3 Apply control-U operator as many times as needed to get the next phase bit # controlled-S is equivalent to CPhase with angle pi / 2 s_angle = np.pi / 2 # we want to apply controlled-S 2^k times k = 0 # calculate the angle of CPhase corresponding to 2^k applications of controlled-S cphase_angle = s_angle * 2**k # apply the controlled phase gate qc.cp(cphase_angle, q0, q1) ##4 Measure the auxiliary qubit in x-basis into the second classical bit # apply Hadamard to change to the X basis qc.h(q0) # measure the auxiliary qubit into the first classical bit qc.measure(q0, c1) return qc qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") qc = QuantumCircuit(qr, cr) qc = step_2_circuit(qr, cr) qc.draw("mpl") # Submit your circuit from qc_grader.challenges.spring_2023 import grade_ex3b grade_ex3b(qc) from qiskit_aer import AerSimulator sim = AerSimulator() job = sim.run(qc, shots=1000) result = job.result() counts = result.get_counts() counts from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister import numpy as np def t_gate_ipe_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit: # qr is a quantum register with 2 qubits # cr is a classical register with 3 bits qc = QuantumCircuit(qr, cr) ########## your code goes here ####### # Initialization q0, q1 = qr qc.h(q0) qc.x(q1) # Apply control-U operator as many times as needed to get the least significant phase bit t_angle = np.pi / 4 k = 2 cphase_angle = t_angle * 2**k qc.cp(cphase_angle, q0, q1) # Measure the auxiliary qubit in x-basis into the first classical bit qc.h(q0) c0, c1, c2 = cr qc.measure(q0, c0) # Reset and re-initialize the auxiliary qubit qc.reset(q0) qc.h(q0) # Apply phase correction conditioned on the first classical bit with qc.if_test((c0, 1)): qc.p(-np.pi / 2, q0) # Apply control-U operator as many times as needed to get the next phase bit k = 1 cphase_angle = t_angle * 2**k qc.cp(cphase_angle, q0, q1) # Measure the auxiliary qubit in x-basis into the second classical bit qc.h(q0) qc.measure(q0, c1) # Reset and re-initialize the auxiliary qubit qc.reset(q0) qc.h(q0) # Apply phase correction conditioned on the first and second classical bits with qc.if_test((c0, 1)): qc.p(-np.pi / 4, q0) with qc.if_test((c1, 1)): qc.p(-np.pi / 2, q0) # Apply control-U operator as many times as needed to get the next phase bit k = 0 cphase_angle = t_angle * 2**k qc.cp(cphase_angle, q0, q1) # Measure the auxiliary qubit in x-basis into the third classical bit qc.h(q0) qc.measure(q0, c2) return qc qr = QuantumRegister(2, "q") cr = ClassicalRegister(3, "c") qc = QuantumCircuit(qr, cr) qc = t_gate_ipe_circuit(qr, cr) qc.draw("mpl") from qiskit_aer import AerSimulator sim = AerSimulator() job = sim.run(qc, shots=1000) result = job.result() counts = result.get_counts() counts # Submit your circuit from qc_grader.challenges.spring_2023 import grade_ex3c grade_ex3c(qc) from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister import numpy as np def u_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit: # qr is a quantum register with 2 qubits # cr is a classical register with 2 bits qc = QuantumCircuit(qr, cr) # Initialization q0, q1 = qr qc.h(q0) qc.x(q1) # Apply control-U operator as many times as needed to get the least significant phase bit u_angle = 2 * np.pi / 3 k = 1 cphase_angle = u_angle * 2**k qc.cp(cphase_angle, q0, q1) # Measure the auxiliary qubit in x-basis into the first classical bit qc.h(q0) c0, c1 = cr qc.measure(q0, c0) # Reset and re-initialize the auxiliary qubit qc.reset(q0) qc.h(q0) # Apply phase correction conditioned on the first classical bit with qc.if_test((c0, 1)): qc.p(-np.pi / 2, q0) # Apply control-U operator as many times as needed to get the next phase bit k = 0 cphase_angle = u_angle * 2**k qc.cp(cphase_angle, q0, q1) # Measure the auxiliary qubit in x-basis into the second classical bit qc.h(q0) qc.measure(q0, c1) return qc qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") qc = QuantumCircuit(qr, cr) qc = u_circuit(qr, cr) qc.draw("mpl") from qiskit_aer import AerSimulator sim = AerSimulator() job = sim.run(qc, shots=1000) result = job.result() counts = result.get_counts() print(counts) success_probability = counts["01"] / counts.shots() print(f"Success probability: {success_probability}") from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister import numpy as np def u_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit: # qr is a quantum register with 2 qubits # cr is a classical register with 1 bits qc = QuantumCircuit(qr, cr) # Initialization q0, q1 = qr qc.h(q0) qc.x(q1) # Apply control-U operator as many times as needed to get the least significant phase bit u_angle = 2 * np.pi / 3 k = 1 cphase_angle = u_angle * 2**k qc.cp(cphase_angle, q0, q1) # Measure the auxiliary qubit in x-basis qc.h(q0) (c0,) = cr qc.measure(q0, c0) return qc qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") qc = QuantumCircuit(qr, cr) qc = u_circuit(qr, cr) qc.draw("mpl") job = sim.run(qc, shots=15) result = job.result() counts = result.get_counts() print(counts) step1_bit = 1 ####### your code goes here ####### print(step1_bit) # Submit your result from qc_grader.challenges.spring_2023 import grade_ex3d grade_ex3d(step1_bit) from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister import numpy as np def u_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit: # qr is a quantum register with 2 qubits # cr is a classical register with 2 bits qc = QuantumCircuit(qr, cr) ########## your code goes here ####### # Initialization q0, q1 = qr if step1_bit: qc.x(q0) qc.x(q1) # Measure the auxiliary qubit c0, c1 = cr qc.measure(q0, c0) # Reset and re-initialize the auxiliary qubit qc.reset(q0) qc.h(q0) # Apply phase correction conditioned on the first classical bit with qc.if_test((c0, 1)): qc.p(-np.pi / 2, q0) # Apply control-U operator as many times as needed to get the next phase bit u_angle = 2 * np.pi / 3 k = 0 cphase_angle = u_angle * 2**k qc.cp(cphase_angle, q0, q1) # Measure the auxiliary qubit in x-basis into the second classical bit qc.h(q0) qc.measure(q0, c1) return qc qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") qc = QuantumCircuit(qr, cr) qc = u_circuit(qr, cr) qc.draw("mpl") # Submit your result from qc_grader.challenges.spring_2023 import grade_ex3e grade_ex3e(qc) from qiskit_aer import AerSimulator sim = AerSimulator() job = sim.run(qc, shots=1000) result = job.result() counts = result.get_counts() print(counts) success_probability = counts["01"] / counts.shots() print(f"Success probability: {success_probability}") from qiskit_ibm_provider import IBMProvider provider = IBMProvider() hub = "qc-spring-23-1" group = "group-1" project = "recIvcxUcc27LvvSh" backend_name = "ibm_peekskill" backend = provider.get_backend(backend_name, instance=f"{hub}/{group}/{project}") from qiskit import transpile qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") qc = QuantumCircuit(qr, cr) qc = step_2_circuit(qr, cr) qc_transpiled = transpile(qc, backend) job = backend.run(qc_transpiled, shots=1000, dynamic=True) job_id = job.job_id() print(job_id) retrieve_job = provider.retrieve_job(job_id) retrieve_job.status() from qiskit.tools.visualization import plot_histogram counts = retrieve_job.result().get_counts() plot_histogram(counts)
https://github.com/arian-code/nptel_quantum_assignments
arian-code
from sympy import * import numpy as np init_printing(use_unicode=True) a, b, d, f = symbols('alpha beta theta phi') a, b, d, f p1=exp(I*f) H=Matrix([[1/sqrt(2), 1/sqrt(2)],[1/sqrt(2), -1/sqrt(2)]]) S=Matrix([[0, 1],[1, I]]) X=Matrix([[0, 1],[1, 0]]) Y=Matrix([[0, -I],[I, 0]]) Z=Matrix([[1, 0],[0, -1]]) H, S, X, Y, Z #option A lhs=H*X*H rhs=-1*Z print (lhs) print (rhs) if (lhs==rhs): print ("It is true") else: print ("It is false") #option B lhs=H*Y*H rhs=-1*Y print (lhs) print (rhs) if (lhs==rhs): print ("It is true") else: print ("It is false") #option C lhs=H rhs=1/sqrt(2)*(X+Z) print (lhs) print (rhs) if (lhs==rhs): print ("It is true") else: print ("It is false") #option D lhs=H*Z*H rhs=X print (lhs) print (rhs) if (lhs==rhs): print ("It is true") else: print ("It is false")
https://github.com/sergiogh/qpirates-qiskit-notebooks
sergiogh
#initialization import matplotlib.pyplot as plt %matplotlib inline import numpy as np import math # importing Qiskit from qiskit import IBMQ, Aer from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute # import basic plot tools from qiskit.visualization import plot_histogram from qiskit.circuit.library import QFT def qft_dagger(circ, qubits, n): circ.append(QFT(n).inverse(), qubits) # Add UROTx based on CU1 gates def apply_crot(circ, control_qubit, target_qubit, theta, exponent): circ.cu1(2*math.pi*theta*exponent, control_qubit, target_qubit) def prepare_circuit(n, theta): qpe = QuantumCircuit(n+1,n) qpe.x(n) qpe.h(range(n)) for x in range(n): exponent = 2**(n-x-1) apply_crot(qpe, x, n, theta, exponent) qpe.barrier() qft_dagger(qpe, range(n), n) qpe.barrier() for i in range(n): qpe.measure(i,i) return qpe # The idea is that we are able to estimate theta (the angle) thanks to the QFT Dagger. # The more qubits we apply on top, the more accuracy we get. Take a look import operator backend = Aer.get_backend('qasm_simulator') shots = 2048 theta = 0.24125 for qubits in range(2, 15): circuit = prepare_circuit(qubits, theta) results = execute(circuit, backend=backend, shots=shots).result() counts = results.get_counts(circuit) highest_probability_outcome = max(counts.items(), key=operator.itemgetter(1))[0][::-1] measured_theta = int(highest_probability_outcome, 2)/2**qubits print("Using %d qubits with theta = %.6f, measured_theta = %.6f." % (qubits, theta, measured_theta)) ## Look at the lovely circuit circuit.draw('text')
https://github.com/geduardo/Q-Snake-Qiskitcamp-Europe-2019
geduardo
import pew_tunnel as pew import random import pygame from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer import numpy as np ######################################################################### #FUNCTIONS ######################################################################### simulator = Aer.get_backend('statevector_simulator') ################################################################# ################### #IBMQ real backends ################### from qiskit import IBMQ from qiskit.providers.ibmq import least_busy # Load local account information provider = IBMQ.load_account() def ibmq_qrand(nbits, N): # Get the least busy real quantum system backend = least_busy(provider.backends(simulator=False)) print(backend, backend.status().pending_jobs) circ = QuantumCircuit(1, 1) circ.h(0) circ.measure(0, 0) job = execute(circ, backend, memory=True, shots=int(N*nbits)) res = job.result() val = res.get_memory() print(val) integ = np.zeros(N) for k in range(N): #convert val array into bitstring b and then into integer b = '' shift = int(nbits * k) for i in range(nbits): b += str(val[i+shift]) integ[k] = int(b, 2) return integ def get_rand_from_list(counter, list): return list[counter] ############################################################### def qrand(nbits): """generates nbits real random numbers using quantum state measurements in qiskit.""" circ = QuantumCircuit(1, 1) circ.h(0) circ.measure(0, 0) val = np.zeros(nbits) for i in range(nbits): job=execute(circ, simulator) res = job.result() vec = res.get_statevector() val[i] = vec[0] * 1 + vec[1] * 0 #convert val array into bitstring b and then into integer b = '' for i in range(nbits): b += str(int(val[i])) integ = int(b, 2) return integ def Pt(U0, E, L, betac, gamma_sqc): """return tunneling probability for square barrier""" return 1/ (np.cosh(betac * L)**2 + gamma_sqc * np.sinh(betac * L)**2) def beta(U0, E): """supply function for Pt""" return np.sqrt(2* (U0 - E)) def gamma_sq(U0, E): """supply function for Pt""" return 0.25 * ((1 - E/U0)/(E/U0) + (E/U0)/(1-E/U0) - 2) def theta(p_tunnel): """returns rotation angle corresponding to tunneling prob. p_tunnel""" return 2 * np.arcsin(np.sqrt(p_tunnel)) def tunnelres(U0, length_snake, L, betac, gamma_sqc): """returns 0 if tunnel, returns 1 if no tunnel""" P_t = Pt(U0, length_snake, L, betac, gamma_sqc) #get tunneling prob depending on current snake length theta_rot = theta(P_t) #get rot angle #qcirc qr = QuantumRegister(1) cr = ClassicalRegister(1) circ = QuantumCircuit(qr, cr) circ.rx(theta_rot, qr[0]) circ.measure(qr, cr) job = execute(circ, simulator) res = job.result() vec = res.get_statevector() val = vec[0] * 1 + vec[1] * 0 if val == 1: return 0 else: return 1 #r= random.randint(0, 1) #return round(r) ########################################################################## #MAIN ########################################################################## #initialize pew dis = pew.init() screen = pew.Pix() #set size bits = 3 ds= 2**bits #displazsize #set game starting parameters game_speed = 4 snake = [(2, 4)] dx, dy = 1, 0 apple_x, apple_y = 6, 4 screen.pixel(apple_x, apple_y, 2) howmanyapples = 1 #marker for total number of eaten apples, used for scoring #set graphics for probability display pygame.font.init() #gate backkgorund font1 = pygame.font.Font(None, 33) text = font1.render('Probability for tunneling is', True, (255, 0, 0)) dis.blit(text, (20, 330)) font2 = pygame.font.Font(None, 45) text2 = font2.render('100%', True, (255, 0, 0)) dis.blit(text2, (130, 360)) ima = pygame.image.load('pewblack.jpg') #tunneling parameters U0=37 #max snake length = 6x6 = 36 E=1 L=0.05 #optimal barrier size for nice tunneling probabilities num_list = ibmq_qrand(3, 250) #list of random numbers for ibmq function num_list_x = num_list[:125] num_list_y = num_list[125:] #initialize tunneling tracker tunnel=0 #don't see other side as second barrier snakepos=1 #marker of snakepos, 1=head, increase towards tail headtunnel=0 #let the head tunnel again through other even if tail still in process while True: #snake runs #create barrier bar= [] for i in range(ds): screen.pixel(0, i, 1) screen.pixel(ds-1, i, 1) screen.pixel(i, 0, 1) screen.pixel(i, ds-1, 1) bar.append((0, i)) bar.append((ds-1, i)) bar.append((i, 0)) bar.append((i, ds-1)) #find the head if len(snake) > 1: x, y = snake[-2] screen.pixel(x, y, 1) x, y = snake[-1] screen.pixel(x, y, 3) #color the head yellow pew.show(screen) pew.tick(1 / game_speed) #get commands keys = pew.keys() if headtunnel==0: if keys & pew.K_UP and dy == 0: dx, dy = 0, -1 elif keys & pew.K_LEFT and dx == 0: dx, dy = -1, 0 elif keys & pew.K_RIGHT and dx == 0: dx, dy = 1, 0 elif keys & pew.K_DOWN and dy == 0: dx, dy = 0, 1 x = (x + dx) % 8 y = (y + dy) % 8 elif headtunnel==1: #steering not allowed during tunneling of the head (during two rounds) x = (x + dx) % 8 y = (y + dy) % 8 headtunnel=2 elif headtunnel>=2: x = (x + dx) % 8 y = (y + dy) % 8 headtunnel=0 ##TUNNELING PROCESS #snake tail tunnels if tunnel>0 and snakepos<=len(snake): #get segment for tunneling sx, sy = snake[-snakepos] E=len(snake)/2 #divide by two for lower tunnel prob for tail (lower mass->lower energy) tunnels = tunnelres(U0, E, L, beta(U0, E), gamma_sq(U0, E)) if tunnels==1: #tunnels snakepos+=1 else: #does not tunnel del snake[-snakepos] screen.pixel(sx, sy, 0) #reset if last segment tunneled if tunnel>0 and snakepos==(len(snake)+1): tunnel=0 snakepos=1 #snake head tunnels if headtunnel==0 and (x, y) in bar: E=len(snake) tunnel = tunnelres(U0, E, L, beta(U0, E), gamma_sq(U0, E)) if tunnel==0 and len(snake) != 1: #head doesn't tunnel --> game over break else: snakepos+=1 headtunnel+=1 elif headtunnel==1 and (x, y) in bar: headtunnel=0 #display tunneling prob. E = len(snake) if E > 1: prob = Pt(U0, E, L, beta(U0, E), gamma_sq(U0, E)) text3 = font2.render(str(int(round(prob * 100))) + '%', True, (255, 0, 0)) dis.blit(ima, (130, 360)) dis.blit(text3, (130, 360)) else: #if length of snake ==1 (only head), tunneling prob = 100% dis.blit(ima, (130, 360)) #cover the ultimate prob. display dis.blit(text2, (130, 360)) #text2 = '100%' #####TUNNEL END if (x, y) in snake: #exit, game over condition break snake.append((x, y)) #apple generation if x == apple_x and y == apple_y: screen.pixel(apple_x, apple_y, 0) apple_x, apple_y = snake[0] while (apple_x, apple_y) in snake or (apple_x, apple_y) in bar: apple_x = get_rand_from_list(howmanyapples, num_list_x) #random.getrandbits(3) #use this for pseudo random number gen, no qiskit needed apple_y = get_rand_from_list(howmanyapples, num_list_y) #random.getrandbits(3) screen.pixel(apple_x, apple_y, 2) game_speed += 0.2 #increase game speed howmanyapples += 1 #increase number of eaten apples, score +1 else: x, y = snake.pop(0) screen.pixel(x, y, 0) text = pew.Pix.from_text("Game over!") #Game over message and closing for dx in range(-8, text.width): screen.blit(text, -dx, 1) pew.show(screen) pew.tick(1 / 12) text = pew.Pix.from_text("Score:" + str(int(howmanyapples))) #Score message for dx in range(-8, text.width): screen.blit(text, -dx, 1) pew.show(screen) pew.tick(1 / 12)
https://github.com/hugoecarl/TSP-Problem-Study
hugoecarl
with open('in-exemplo.txt', 'r') as f: print(f.read()) with open('out-exemplo.txt', 'r') as f: print(f.read()) import time import matplotlib.pyplot as plt import pandas as pd import os import subprocess %matplotlib inline #Roda entradas def roda_com_entrada(executavel, arquivo_in, envs = '1', deb = '0'): with open(arquivo_in) as f: start = time.perf_counter() a = f.read() proc = subprocess.run([executavel], input=a, text=True, capture_output=True, env=dict(OMP_NUM_THREADS=envs, DEBUG=deb, **os.environ)) end = time.perf_counter() f.close() ret = '' for i in a: if i == "\n": break ret += i return (proc.stdout, end - start, int(ret)) #retorna tamanho do tour apartir do stdout def tamanho_tour(out): buf = '' for i in out: if i == " ": return float(buf) buf += i #Cria resultados tamanho_entradas = [] tempos = [] tempos_1 = [] tempos_2 = [] resultados1 = [] resultados2 = [] resultados3 = [] #Usando as mesmas entradas for i in range(8): print("Rodando entrada: "+str(i)) a = roda_com_entrada('./busca_local_antigo','busca-exaustiva/in-'+str(i)+'.txt') b = roda_com_entrada('./busca-exaustiva/busca-exaustiva','busca-exaustiva/in-'+str(i)+'.txt') c = roda_com_entrada('./heuristico/heuristico','busca-exaustiva/in-'+str(i)+'.txt') tempos.append(a[1]) tempos_1.append(b[1]) tempos_2.append(c[1]) tamanho_entradas.append(a[2]) resultados1.append(tamanho_tour(a[0])) resultados2.append(tamanho_tour(b[0])) resultados3.append(tamanho_tour(c[0])) #Teste com entrada um pouco maior print("Rodando entrada: 8") tempos.append(roda_com_entrada('./busca_local_antigo','maior.txt')[1]) tempos_1.append(roda_com_entrada('./busca-exaustiva/busca-exaustiva','maior.txt')[1]) tempos_2.append(roda_com_entrada('./heuristico/heuristico','maior.txt')[1]) tamanho_entradas.append(roda_com_entrada('./busca-local/busca-local','maior.txt')[2]) resultados1.append(tamanho_tour(roda_com_entrada('./busca_local_antigo','maior.txt')[0])) resultados2.append(tamanho_tour(roda_com_entrada('./busca-exaustiva/busca-exaustiva','maior.txt')[0])) resultados3.append(tamanho_tour(roda_com_entrada('./heuristico/heuristico','maior.txt')[0])) plt.title("Comparacao Desempenho") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas, tempos_1) plt.plot(tamanho_entradas, tempos) plt.plot(tamanho_entradas, tempos_2) plt.legend(["busca-exaustiva", "busca-local","heuristico"]) plt.show() plt.title("Comparacao Desempenho") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas, tempos) plt.plot(tamanho_entradas, tempos_2) plt.legend(["busca-local","heuristico"]) plt.show() df = pd.DataFrame() df["Tamanho Entrada"] = pd.Series(tamanho_entradas) df["busca-local-tempo"] = pd.Series(tempos) df["busca-exaustiva-tempo"] = pd.Series(tempos_1) df["heuristica-tempo"] = pd.Series(tempos_2) df["busca-local-resultado"] = pd.Series(resultados1) df["busca-exaustiva-resultado"] = pd.Series(resultados2) df["heuristica-resultado"] = pd.Series(resultados3) df df.describe() #Cria resultados tamanho_entradas = [] tempos = [] tempos_1 = [] tempos_2 = [] tempos_3 = [] tempos_4 = [] tempos_5 = [] #Usando as mesmas entradas for i in range(7): print("Rodando entrada: "+str(i)) a = roda_com_entrada('./busca-local/busca-local-paralela','busca-local/in-'+str(i)+'.txt') b = roda_com_entrada('./busca-local/busca-local-paralela','busca-local/in-'+str(i)+'.txt','2') c = roda_com_entrada('./busca-local/busca-local-paralela','busca-local/in-'+str(i)+'.txt','3') d = roda_com_entrada('./busca-local/busca-local-paralela','busca-local/in-'+str(i)+'.txt','4') e = roda_com_entrada('./busca_local_antigo','busca-local/in-'+str(i)+'.txt') f = roda_com_entrada('./busca-local/busca-local-gpu','busca-local/in-'+str(i)+'.txt') tempos.append(a[1]) tempos_1.append(b[1]) tempos_2.append(c[1]) tempos_3.append(d[1]) tempos_4.append(e[1]) tempos_5.append(f[1]) tamanho_entradas.append(a[2]) plt.title("Comparacao Desempenho Busca Local") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas, tempos) plt.plot(tamanho_entradas, tempos_1) plt.plot(tamanho_entradas, tempos_2) plt.plot(tamanho_entradas, tempos_3) plt.legend(["1 thread otimizado", "2 threads otimizado","3 threads otimizado", "4 threads otimizado", "Sem otimizações"]) plt.show() plt.title("Comparacao Desempenho Busca Local") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas, tempos_3) plt.plot(tamanho_entradas, tempos_5) plt.legend(["4 thread otimizado", "GPU"]) plt.show() plt.title("Comparacao Desempenho Busca Local") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas, tempos) plt.plot(tamanho_entradas, tempos_4) plt.legend(["1 thread otimizado", "Sem otimizações"]) plt.show() df = pd.DataFrame() df["Tamanho Entrada"] = pd.Series(tamanho_entradas) df["busca-local-1-thread"] = pd.Series(tempos) df["busca-local-2-threads"] = pd.Series(tempos_1) df["busca-local-3-threads"] = pd.Series(tempos_2) df["busca-local-4-threads"] = pd.Series(tempos_3) df["busca-local-gpu"] = pd.Series(tempos_5) df["busca-local-semopt"] = pd.Series(tempos_4) df #Cria resultados tamanho_entradas = [] tempos = [] tempos_1 = [] #Usando as mesmas entradas for i in range(7): print("Rodando entrada: "+str(i)) a = roda_com_entrada('./busca-exaustiva/busca-exaustiva','busca-exaustiva/in-'+str(i)+'.txt', '1', '1') b = roda_com_entrada('./busca-exaustiva/busca-exaustiva','busca-exaustiva/in-'+str(i)+'.txt', '1', '0') tempos.append(a[1]) tempos_1.append(b[1]) tamanho_entradas.append(a[2]) plt.title("Comparacao Desempenho Busca Exaustiva") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas, tempos) plt.plot(tamanho_entradas, tempos_1) plt.legend(["Exaustivo Simples", "Exaustivo Branch and Bound"]) plt.show() df = pd.DataFrame() df["Tamanho Entrada"] = pd.Series(tamanho_entradas) df["busca-exaustiva-simples"] = pd.Series(tempos) df["busca-exaustiva-branchnbound"] = pd.Series(tempos_1) df
https://github.com/robinsonvs/tcc-information-systems
robinsonvs
from qiskit import QuantumCircuit as qc from qiskit import QuantumRegister as qr from qiskit import transpile from qiskit.providers import Backend from qiskit.quantum_info import DensityMatrix as dm from qiskit.result import Counts from qiskit.visualization import plot_histogram from qiskit_ibm_runtime import QiskitRuntimeService from math import pi, sqrt from heapq import nlargest """Number of qubits.""" N: int = 5 """Set of m nonnegative integers to search for using Grover's algorithm (i.e. TARGETS in base 10).""" SEARCH_VALUES: set[int] = { 11, 9, 0, 3 } """Amount of times to simulate the algorithm.""" SHOTS: int = 10000 """Set of m N-qubit binary strings representing target state(s) (i.e. SEARCH_VALUES in base 2).""" TARGETS: set[str] = { f"{s:0{N}b}" for s in SEARCH_VALUES } """N-qubit quantum register.""" QUBITS: qr = qr(N, "qubit") """Name of backend to run the algorithm on.""" BACKEND_NAME: str = "ibmq_qasm_simulator" """Backend to run the algorithm on.""" BACKEND: Backend = QiskitRuntimeService().backend(BACKEND_NAME) def oracle(targets: set[str] = TARGETS, name: str = "Oracle") -> qc: """Mark target state(s) with negative phase. Args: targets (set[str]): N-qubit binary string(s) representing target state(s). Defaults to TARGETS. name (str, optional): Quantum circuit's name. Defaults to "Oracle". Returns: qc: Quantum circuit representation of oracle. """ # Create N-qubit quantum circuit for oracle oracle = qc(QUBITS, name = name) for target in targets: # Reverse target state since Qiskit uses little-endian for qubit ordering target = target[::-1] # Flip zero qubits in target for i in range(N): if target[i] == "0": oracle.x(i) # Pauli-X gate # Simulate (N - 1)-control Z gate oracle.h(N - 1) # Hadamard gate oracle.mcx(list(range(N - 1)), N - 1) # (N - 1)-control Toffoli gate oracle.h(N - 1) # Hadamard gate # Flip back to original state for i in range(N): if target[i] == "0": oracle.x(i) # Pauli-X gate return oracle # Generate and display quantum circuit for oracle grover_oracle = oracle() grover_oracle.draw("mpl", style = "iqp") def diffuser(name: str = "Diffuser") -> qc: """Amplify target state(s) amplitude, which decreases the amplitudes of other states and increases the probability of getting the correct solution (i.e. target state(s)). Args: name (str, optional): Quantum circuit's name. Defaults to "Diffuser". Returns: qc: Quantum circuit representation of diffuser (i.e. Grover's diffusion operator). """ # Create N-qubit quantum circuit for diffuser diffuser = qc(QUBITS, name = name) diffuser.h(QUBITS) # Hadamard gate diffuser.append(oracle({ "0" * N }), list(range(N))) # Oracle with all zero target state diffuser.h(QUBITS) # Hadamard gate return diffuser # Generate and display quantum circuit for diffuser grover_diffuser = diffuser() grover_diffuser.draw("mpl", style = "iqp") def grover(oracle: qc = oracle(), diffuser: qc = diffuser(), name: str = "Grover Circuit") -> tuple[qc, dm]: """Create quantum circuit representation of Grover's algorithm, which consists of 4 parts: (1) state preparation/initialization, (2) oracle, (3) diffuser, and (4) measurement of resulting state. Steps 2-3 are repeated an optimal number of times (i.e. Grover's iterate) in order to maximize probability of success of Grover's algorithm. Args: oracle (qc, optional): Quantum circuit representation of oracle. Defaults to oracle(). diffuser (qc, optional): Quantum circuit representation of diffuser. Defaults to diffuser(). name (str, optional): Quantum circuit's name. Defaults to "Grover Circuit". Returns: tuple[qc, dm]: Quantum circuit representation of Grover's algorithm and its density matrix. """ # Create N-qubit quantum circuit for Grover's algorithm grover = qc(QUBITS, name = name) # Intialize qubits with Hadamard gate (i.e. uniform superposition) grover.h(QUBITS) # Apply barrier to separate steps grover.barrier() # Apply oracle and diffuser (i.e. Grover operator) optimal number of times for _ in range(int((pi / 4) * sqrt((2 ** N) / len(TARGETS)))): grover.append(oracle, list(range(N))) grover.append(diffuser, list(range(N))) # Generate density matrix representation of Grover's algorithm density_matrix = dm(grover) # Measure all qubits once finished grover.measure_all() return grover, density_matrix # Save density matrix and generate and display quantum circuit for Grover's algorithm grover_circuit, density_matrix = grover(grover_oracle, grover_diffuser) grover_circuit.draw("mpl", style = "iqp") def outcome(winners: list[str], counts: Counts) -> None: """Print top measurement(s) (state(s) with highest frequency) and target state(s) in binary and decimal form, determine if top measurement(s) equals target state(s), then print result. Args: winners (list[str]): State(s) (N-qubit binary string(s)) with highest probability of being measured. counts (Counts): Each state and its respective frequency. """ print("WINNER(S):") print(f"Binary = {winners}\nDecimal = {[ int(key, 2) for key in winners ]}\n") print("TARGET(S):") print(f"Binary = {TARGETS}\nDecimal = {SEARCH_VALUES}\n") if not all(key in TARGETS for key in winners): print ("Target(s) not found...") else: winners_frequency, total = 0, 0 for value, frequency in counts.items(): if value in winners: winners_frequency += frequency total += frequency print(f"Target(s) found with {winners_frequency / total:.2%} accuracy!") # Simulate Grover's algorithm with Qiskit backend and get results with BACKEND.open_session() as session: results = BACKEND.run(transpile(grover_circuit, BACKEND, optimization_level = 2), shots = SHOTS).result() # Get each state's frequency counts = results.get_counts() # Find winner(s) (i.e. state(s) with highest count) winners = nlargest(len(TARGETS), counts, key = counts.get) # Print outcome outcome(winners, counts) # Display simulation results as histogram plot_histogram(data = counts, number_to_keep = len(TARGETS)) # City plot of density_matrix density_matrix.draw("city") # Bloch sphere representation of density_matrix # reverse_bits = True since Qiskit uses little-endian for qubit ordering density_matrix.draw("bloch", reverse_bits = True) # Hinton plot of density_matrix density_matrix.draw("hinton") # Qsphere representation of density_matrix density_matrix.draw("qsphere")
https://github.com/carstenblank/dc-qiskit-algorithms
carstenblank
# Copyright 2018 Carsten Blank # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import unittest from typing import List import numpy as np import qiskit from qiskit.providers import JobV1 from qiskit_aer import Aer, StatevectorSimulator, QasmSimulator from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from ddt import ddt, data as test_data, unpack from qiskit.result import Result import dc_qiskit_algorithms.MottonenStatePreparation logging.basicConfig(format=logging.BASIC_FORMAT, level='INFO') log = logging.getLogger('test_DraperAdder') # noinspection NonAsciiCharacters @ddt class MottonenStatePrepTests(unittest.TestCase): def execute_test(self, vector: List[float]): probability_vector = [np.absolute(e)**2 for e in vector] qubits = int(np.log2(len(vector))) reg = QuantumRegister(qubits, "reg") c = ClassicalRegister(qubits, "c") qc = QuantumCircuit(reg, c, name='state prep') qc.state_prep_möttönen(vector, reg) local_backend: StatevectorSimulator = Aer.get_backend('statevector_simulator') job: JobV1 = qiskit.execute(qc, backend=local_backend, shots=1) result: Result = job.result() # State vector result_state_vector = result.get_statevector('state prep') print(["{0:.2f}".format(e) for e in result_state_vector]) # Try to find a global phase global_phase = set([np.angle(v) - np.angle(rv) for v, rv in zip(vector, result_state_vector) if abs(v) > 1e-3 and abs(rv) > 1e-3]) global_phase = global_phase.pop() or 0.0 result_state_vector = np.exp(1.0j * global_phase) * result_state_vector for expected, actual in zip(vector, result_state_vector): self.assertAlmostEqual(actual.imag, 0.0, places=6) self.assertAlmostEqual(expected, actual.real, places=6) # Probability vector from state vector result_probability_vector = [np.absolute(e)**2 for e in result_state_vector] print(["{0:.3f}".format(e) for e in result_probability_vector]) for expected, actual in zip(probability_vector, result_probability_vector): self.assertAlmostEqual(expected, actual, places=2) # Probability Vector by Measurement qc.measure(reg, c) local_qasm_backend: QasmSimulator = Aer.get_backend('qasm_simulator') shots = 2**12 job: JobV1 = qiskit.execute(qc, backend=local_qasm_backend, shots=shots) result = job.result() # type: Result counts = result.get_counts('state prep') measurement_probability_vector = [0.0 for e in result_state_vector] for binary, count in sorted(counts.items()): index = int(binary, 2) probability = float(count) / float(shots) print("%s (%d): %.3f" % (binary, index, probability)) measurement_probability_vector[index] = probability print(["{0:.3f}".format(e) for e in measurement_probability_vector]) for expected, actual in zip(probability_vector, measurement_probability_vector): self.assertAlmostEqual(expected, actual, delta=0.02) @unpack @test_data( {'vector': [-0.1, 0.2, -0.3, 0.4, -0.5, 0.6, -0.7, 0.8]}, {'vector': [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]}, {'vector': [0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]}, {'vector': [0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]}, {'vector': [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0]}, {'vector': [0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]}, {'vector': [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0]}, {'vector': [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0]}, {'vector': [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]} ) def test_state_preparation(self, vector): vector = np.asarray(vector) vector = (1 / np.linalg.norm(vector)) * vector self.execute_test(list(vector)) def test_instantiation(self): gate = dc_qiskit_algorithms.MottonenStatePreparationGate([1.0, 0.0]) self.assertIsInstance(gate, dc_qiskit_algorithms.MottonenStatePreparationGate) if __name__ == '__main__': unittest.main(verbosity=2)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# load necessary Runtime libraries from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Session backend = "ibmq_qasm_simulator" # use the simulator from qiskit.circuit import Parameter from qiskit.opflow import I, X, Z mu = Parameter('$\\mu$') ham_pauli = mu * X cc = Parameter('$c$') ww = Parameter('$\\omega$') ham_res = -(1/2)*ww*(I^Z) + cc*(X^X) + (ham_pauli^I) tt = Parameter('$t$') U_ham = (tt*ham_res).exp_i() from qiskit import transpile from qiskit.circuit import ClassicalRegister from qiskit.opflow import PauliTrotterEvolution, Suzuki import numpy as np num_trot_steps = 5 total_time = 10 cr = ClassicalRegister(1, 'c') spec_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=2, reps=num_trot_steps)).convert(U_ham) spec_circ = spec_op.to_circuit() spec_circ_t = transpile(spec_circ, basis_gates=['sx', 'rz', 'cx']) spec_circ_t.add_register(cr) spec_circ_t.measure(0, cr[0]) spec_circ_t.draw('mpl') # fixed Parameters fixed_params = { cc: 0.3, mu: 0.7, tt: total_time } # Parameter value for single circuit param_keys = list(spec_circ_t.parameters) # run through all the ww values to create a List of Lists of Parameter value num_pts = 101 wvals = np.linspace(-2, 2, num_pts) param_vals = [] for wval in wvals: all_params = {**fixed_params, **{ww: wval}} param_vals.append([all_params[key] for key in param_keys]) with Session(backend=backend): sampler = Sampler() job = sampler.run( circuits=[spec_circ_t]*num_pts, parameter_values=param_vals, shots=1e5 ) result = job.result() Zexps = [] for dist in result.quasi_dists: if 1 in dist: Zexps.append(1 - 2*dist[1]) else: Zexps.append(1) from qiskit.opflow import PauliExpectation, Zero param_bind = { cc: 0.3, mu: 0.7, tt: total_time } init_state = Zero^2 obsv = I^Z Zexp_exact = (U_ham @ init_state).adjoint() @ obsv @ (U_ham @ init_state) diag_meas_op = PauliExpectation().convert(Zexp_exact) Zexact_values = [] for w_set in wvals: param_bind[ww] = w_set Zexact_values.append(np.real(diag_meas_op.bind_parameters(param_bind).eval())) import matplotlib.pyplot as plt plt.style.use('dark_background') fig, ax = plt.subplots(dpi=100) ax.plot([-param_bind[mu], -param_bind[mu]], [0, 1], ls='--', color='purple') ax.plot([param_bind[mu], param_bind[mu]], [0, 1], ls='--', color='purple') ax.plot(wvals, Zexact_values, label='Exact') ax.plot(wvals, Zexps, label=f"{backend}") ax.set_xlabel(r'$\omega$ (arb)') ax.set_ylabel(r'$\langle Z \rangle$ Expectation') ax.legend() import qiskit_ibm_runtime qiskit_ibm_runtime.version.get_version_info() from qiskit.tools.jupyter import * %qiskit_version_table
https://github.com/yatharth0610/Quantum-Algorithms-qiskit-
yatharth0610
from qiskit import * from qiskit.compiler import * from qiskit.tools.jupyter import * from qiskit.visualization import * import matplotlib.pyplot as plotter import scipy import numpy as np from IPython.display import display, Math, Latex import qiskit.quantum_info as qi %matplotlib inline # Loading your IBM Q account(s) provider = IBMQ.load_account() def qft_rotations(circuit, n): """Performs qft on the first n qubits in circuit (without swaps)""" if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cu1(np.pi/2**(n-qubit), qubit, n) # At the end of our function, we call the same function again on # the next qubits (we reduced n by one earlier in the function) qft_rotations(circuit, n) def swap_registers(circuit, n): for qubit in range(n//2): circuit.swap(qubit, n-qubit-1) return circuit def qft(circuit, n): """QFT on the first n qubits in circuit""" qft_rotations(circuit, n) swap_registers(circuit, n) return circuit # Let's see how it looks: qc = QuantumCircuit(4,4) qft(qc,4) qc.draw(output = 'mpl') def inverse_qft(circuit, n): """Does the inverse QFT on the first n qubits in circuit""" # First we create a QFT circuit of the correct size: qft_circ = qft(QuantumCircuit(n), n) # Then we take the inverse of this circuit invqft_circ = qft_circ.inverse() # And add it to the first n qubits in our existing circuit circuit.append(invqft_circ, circuit.qubits[:n]) return circuit.decompose() # .decompose() allows us to see the individual gates qc = inverse_qft(qc,4) qc.measure(range(4),range(4)) def run_circuit(qc): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qc, backend, shots = 10000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts counts = run_circuit(qc) print(counts) plot_histogram(counts) # we should get the intial state '0000' qc1 = QuantumCircuit(3,3) qc1.x(0) qc1.x(1) qc1.x(2) # try for different initial values for i in range(4):# choose the number of times you want to do qft) qft(qc1,3) qc1.measure(0,0) qc1.measure(1,1) qc1.measure(2,2) def run_circuit(qc1): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qc1, backend, shots = 10000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts counts = run_circuit(qc1) print(counts) plot_histogram(counts) qc2 = QuantumCircuit(2) for i in range(2): qft(qc2, 2) matrix = qi.Operator(qc2).data print(matrix) def Modulo_increment(qc): qft(qc,4) for i in range(4): qc.u1(np.pi/(2**(3-i)), i) qft(qc, 4) return qc # checking for the case of '1000' qc2 = QuantumCircuit(4,4) qc2.x(3) qc2 = Modulo_increment(qc2) qc2.measure(range(4),range(4)) # qc2.draw('mpl') def run_circuit(qc2): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qc2, backend, shots = 10000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts counts = run_circuit(qc2) print(counts) plot_histogram(counts) # checking for the case of '1101' qc3 = QuantumCircuit(4,4) qc3.x(3) qc3.x(2) qc3.x(0) qc3 = Modulo_increment(qc2) qc3.measure(range(4),range(4)) def run_circuit(qc3): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qc3, backend, shots = 10000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts counts = run_circuit(qc3) print(counts) plot_histogram(counts) # checking for the case of '1111' qc4 = QuantumCircuit(4,4) qc4.x(range(4)) qc4 = Modulo_increment(qc4) qc4.measure(range(4),range(4)) def run_circuit(qc4): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qc4, backend, shots = 10000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts counts = run_circuit(qc4) print(counts) plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import BasicAer, transpile, QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.h(0) qc.measure(0, 0) qc.x(0).c_if(cr, 0) qc.measure(0, 0) qc.draw('mpl')
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
from qiskit import * q = QuantumRegister(2,"q") c = ClassicalRegister(2,"c") qc = QuantumCircuit(q,c) qc.x(q[0]) qc.measure(q[0],c[0]) qc.h(q[1]).c_if(c,0) qc.measure(q,c) print(qc) job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1024) counts = job.result().get_counts(qc) print(counts) # counts is a dictionary q2 = QuantumRegister(2,"qreg") c2 = ClassicalRegister(2,"creg") qc2 = QuantumCircuit(q2,c2) qc2.x(q2[1]) qc2.z(q2[1]) qc2.measure(q2,c2) job = execute(qc2,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(qc2) print(counts) # counts is a dictionary from math import pi q = QuantumRegister(1) # quantum register with a single qubit c = ClassicalRegister(1) # classical register with a single bit qc = QuantumCircuit(q,c) # quantum circuit with quantum and classical registers # rotate the qubit with rotation_angle qc.ry(2*(pi/3),q[0]) # measure the qubit qc.measure(q,c) job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1000) counts = job.result().get_counts(qc) print(counts) # counts is a dictionary q2 = QuantumRegister(1,"qreg") c2 = ClassicalRegister(1,"creg") qc2 = QuantumCircuit(q2,c2) #Your code here1 qc2.x(q2[0]) #Your code here2 qc2.h(q2[0]) qc2.measure(q2,c2) job = execute(qc2,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(qc2) print(counts) # counts is a dictionary
https://github.com/rebajram/quantumteleportation
rebajram
from qiskit import * import numpy as np class teleprotocol: def __init__(self,nq,ne0,ne1,input): self.n=n self.input=input self.qubit = QuantumRegister(nq, "Q") self.ebit0 = QuantumRegister(ne0, "Alice") self.ebit1 = QuantumRegister(ne1, "Bob") self.a = ClassicalRegister(nq, "Alice Q") self.b = ClassicalRegister(ne0, "Alice A") self.c = ClassicalRegister(ne1, "Bob B") self.d = ClassicalRegister(ne1, "Spion") def Qcirc(self): qc = QuantumCircuit(self.qubit,self.ebit0,self.ebit1) for i in range(0, self.n): if self.input[i]==1: qc.x(self.qubit[i]) qc.h(self.qubit[i]) if self.input[i]==0: qc.h(self.qubit[i]) # qc.u(np.pi/2,np.pi/4,np.pi/8,self.qubit[i]) return qc def Acirc(self): qc = QuantumCircuit(self.qubit,self.ebit0,self.ebit1) qc.h(self.ebit0) qc.cx(self.ebit0, self.ebit1) qc.barrier() return qc def QAcirc(self): qc = QuantumCircuit(self.qubit,self.ebit0,self.ebit1) qc.cx(self.qubit,self.ebit0) qc.h(self.qubit) qc.barrier() return qc def M0circ(self): qc = QuantumCircuit(self.qubit,self.ebit0,self.ebit1,self.a,self.b,self.c,self.d) qc.measure(self.ebit0, self.a) qc.measure(self.qubit, self.b) qc.barrier() return qc def M1circ(self): qc = QuantumCircuit(self.qubit,self.ebit0,self.ebit1,self.a,self.b,self.c,self.d) for i in range(0, self.n): with qc.if_test((self.a[i], 1)): qc.x(self.ebit1[i]) with qc.if_test((self.b[i], 1)): qc.z(self.ebit1[i]) qc.barrier() return qc,self.a,self.b def SPcirc(self): qc = QuantumCircuit(self.qubit,self.ebit0,self.ebit1,self.a,self.b,self.c,self.d) qc.measure(self.ebit1, self.d) qc.barrier() return qc,self.d def Bobmeasure(self): qc = QuantumCircuit(self.qubit,self.ebit0,self.ebit1,self.a,self.b,self.c,self.d) qc.h(self.ebit1) qc.measure(self.ebit1, self.c) qc.barrier() return qc,self.c n=6 input=[1,0,0,1,1,1] qc=teleprotocol(n,0,0,input).Qcirc() qc.draw('mpl') backend = Aer.get_backend('statevector_simulator') # Create a Quantum Program for execution job = backend.run(qc) result = job.result() qubitstate = result.get_statevector(qc, decimals=3) qubitstate.draw('latex') qc=teleprotocol(0,n,n,input).Acirc() qc.draw('mpl') backend = Aer.get_backend('statevector_simulator') # Create a Quantum Program for execution job = backend.run(qc) result = job.result() qcstate = result.get_statevector(qc, decimals=3) qcstate.draw('latex') qc1=teleprotocol(n,n,n,input).Qcirc() qc2=teleprotocol(n,n,n,input).Acirc() qc3=teleprotocol(n,n,n,input).QAcirc() qcSpion,c=teleprotocol(n,n,n,input).SPcirc() qcnew = qc1.compose(qc2) #qcnew = qcnew.compose(qc3) #qcnew = qcnew.compose(qcSpion) qcnew.draw('mpl') backend = Aer.get_backend('statevector_simulator') # Create a Quantum Program for execution job = backend.run(qcnew) result = job.result() qcstate = result.get_statevector(qcnew, decimals=3) qcstate.draw('latex') qc1=teleprotocol(n,n,n,input).Qcirc() qc2=teleprotocol(n,n,n,input).Acirc() qc3=teleprotocol(n,n,n,input).QAcirc() qc4=teleprotocol(n,n,n,input).M0circ() qc5,a,b=teleprotocol(n,n,n,input).M1circ() qcSpion,c=teleprotocol(n,n,n,input).SPcirc() qc6,d=teleprotocol(n,n,n,input).Bobmeasure() #qcnew = qc1 qcnew = qc1.compose(qc2) qcnew = qcnew.compose(qc3) qcnew = qcnew.compose(qc4) qcnew.draw('mpl') job=backend.run(qcnew,shots=1) result=job.result() qcstate = result.get_statevector(qcnew, decimals=3) qcstate.draw('latex') counts=result.get_counts(qcnew) print(counts) qc1=teleprotocol(n,n,n,input).Qcirc() qc2=teleprotocol(n,n,n,input).Acirc() qc3=teleprotocol(n,n,n,input).QAcirc() qc4=teleprotocol(n,n,n,input).M0circ() qc5,a,b=teleprotocol(n,n,n,input).M1circ() qcSpion,c=teleprotocol(n,n,n,input).SPcirc() qc6,d=teleprotocol(n,n,n,input).Bobmeasure() #qcnew = qc1 qcnew = qc1.compose(qc2) spion = qcnew.compose(qcSpion) #qcnew = qcnew.compose(qcSpion) qcnew = qcnew.compose(qc3) qcnew = qcnew.compose(qc4) qcnew = qcnew.compose(qc5) qcnew.draw('mpl') job=backend.run(qcnew,shots=1) result=job.result() qcstate = result.get_statevector(qcnew, decimals=3) qcstate.draw('latex') qc1=teleprotocol(n,n,n,input).Qcirc() qc2=teleprotocol(n,n,n,input).Acirc() qc3=teleprotocol(n,n,n,input).QAcirc() qc4=teleprotocol(n,n,n,input).M0circ() qc5,a,b=teleprotocol(n,n,n,input).M1circ() qcSpion,c=teleprotocol(n,n,n,input).SPcirc() qc6,d=teleprotocol(n,n,n,input).Bobmeasure() #qcnew = qc1 qcnew = qc1.compose(qc2) spion = qcnew.compose(qcSpion) #qcnew = qcnew.compose(qcSpion) qcnew = qcnew.compose(qc3) qcnew = qcnew.compose(qc4) qcnew = qcnew.compose(qc5) qcnew = qcnew.compose(qc6) qcnew.draw('mpl') job=backend.run(qcnew,shots=1) result=job.result() qcstate = result.get_statevector(qcnew, decimals=3) qcstate.draw('latex') counts=result.get_counts(qcnew) print(counts)
https://github.com/TRSasasusu/qiskit-quantum-zoo
TRSasasusu
from typing import Optional from math import gcd import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, assemble from qiskit.visualization import plot_histogram from sympy import Rational from sympy.ntheory.continued_fraction import continued_fraction, continued_fraction_convergents from qft import qft from elementary import ax_modM from classical_utils import lcm def order_finding(x: int, N: int, show_hist: Optional[bool] = False) -> int: #def order_finding(x: int, N: int, epsilon: Optional[float] = 0.2, show_hist: Optional[bool] = False) -> int: r"""Order-finding algorithm: it finds $r$ of $x^r\equiv 1\pmod N$. It requires Args: x (int): $x$ N (int): $N$ Returns: order $r$ Examples: ``` >>> order_finding(x=3, N=5, show_hist=True) 4 ``` and get below image in `img` directory: ![](../img/order_finding_x3_N5.png) It represents $0/2^6=0$, $2^4/2^6=1/4$, $2^5/2^6=1/2$, and $(2^4+2^5)/2^6=3/4$ from the left. This answer is $r=4$, so $1/2$ looks wrong. However, $\tilde{r}=2$ is a factor of $r$, so we can get correct $r$ by lcm with another $\tilde{r}$. """ L = int(np.ceil(np.log2(N))) t = 2 * L# + 1 + int(np.ceil(np.log2(3 + 1 / (2 * epsilon)))) # epsilon requires too many qubits to run this program... first_register = QuantumRegister(t) second_register = QuantumRegister(2 * t) auxiliary_register_mid = QuantumRegister(t) auxiliary_register_end = QuantumRegister(6 * t - 2) classical_register = ClassicalRegister(len(first_register)) qc = QuantumCircuit(first_register, auxiliary_register_mid, second_register, auxiliary_register_end, classical_register) # qc.add_register(first_register) # qc.add_register(second_register) # qc.add_register(classical_register) qc.h(first_register) #import pdb; pdb.set_trace() #qc.append(ax_modM(a=x, M=N, N_len=len(first_register)), [first_register, auxiliary_register_mid, second_register, auxiliary_register_end]) qc.append(ax_modM(a=x, M=N, N_len=len(first_register)), qc.qubits[:10 * t - 2]) qc.append(qft(n=len(first_register)).inverse(), first_register) qc.measure(first_register, classical_register) backend = Aer.get_backend('aer_simulator_matrix_product_state')#('aer_simulator') qc = transpile(qc, backend) job = backend.run(qc, shots=10000) hist = job.result().get_counts() if show_hist: plot_histogram(hist) plt.savefig(f'img/order_finding_x{x}_N{N}.png', bbox_inches='tight') #plt.savefig(f'img/order_finding_x{x}_N{N}_eps{epsilon}.png', bbox_inches='tight') all_fractions = [] for measured_key, _ in sorted(hist.items(), key=lambda x: x[1], reverse=True): tilde_s_per_r = Rational(int(measured_key[-t:], 2), 2 ** t) if tilde_s_per_r == 0: continue fractions = [] for fraction in continued_fraction_convergents(continued_fraction(tilde_s_per_r)): if pow(x, fraction.denominator, N) == 1: return fraction.denominator fractions.append(fraction) for other_fraction in all_fractions: if math.gcd(fraction.numerator, other_fraction.numerator) == 1: r_candidate = lcm(fraction.denominator, other_fraction.denominator) if pow(x, r_candidate, N) == 1: return r_candidate raise Exception('r is NOT found!') if __name__ == '__main__': #print(order_finding(x=5, N=21, show_hist=True)) print(order_finding(x=3, N=5, show_hist=True))
https://github.com/DRA-chaos/Solutions-to-the-Lab-Exercises---IBM-Qiskit-Summer-School-2021
DRA-chaos
from qiskit.circuit.library import RealAmplitudes ansatz = RealAmplitudes(num_qubits=2, reps=1, entanglement='linear') ansatz.draw('mpl', style='iqx') from qiskit.opflow import Z, I hamiltonian = Z ^ Z from qiskit.opflow import StateFn expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz) import numpy as np point = np.random.random(ansatz.num_parameters) index = 2 from qiskit import Aer from qiskit.utils import QuantumInstance backend = Aer.get_backend('qasm_simulator') q_instance = QuantumInstance(backend, shots = 8192, seed_simulator = 2718, seed_transpiler = 2718) from qiskit.circuit import QuantumCircuit from qiskit.opflow import Z, X H = X ^ X U = QuantumCircuit(2) U.h(0) U.cx(0, 1) # YOUR CODE HERE expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(U) matmult_result =expectation.eval() from qc_grader import grade_lab4_ex1 # Note that the grading function is expecting a complex number grade_lab4_ex1(matmult_result) from qiskit.opflow import CircuitSampler, PauliExpectation sampler = CircuitSampler(q_instance) # YOUR CODE HERE sampler = CircuitSampler(q_instance) # q_instance is the QuantumInstance from the beginning of the notebook expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(U) in_pauli_basis = PauliExpectation().convert(expectation) shots_result = sampler.convert(in_pauli_basis).eval() from qc_grader import grade_lab4_ex2 # Note that the grading function is expecting a complex number grade_lab4_ex2(shots_result) from qiskit.opflow import PauliExpectation, CircuitSampler expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz) in_pauli_basis = PauliExpectation().convert(expectation) sampler = CircuitSampler(q_instance) def evaluate_expectation(x): value_dict = dict(zip(ansatz.parameters, x)) result = sampler.convert(in_pauli_basis, params=value_dict).eval() return np.real(result) eps = 0.2 e_i = np.identity(point.size)[:, index] # identity vector with a 1 at index ``index``, otherwise 0 plus = point + eps * e_i minus = point - eps * e_i finite_difference = (evaluate_expectation(plus) - evaluate_expectation(minus)) / (2 * eps) print(finite_difference) from qiskit.opflow import Gradient expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz) shifter = Gradient('fin_diff', analytic=False, epsilon=eps) grad = shifter.convert(expectation, params=ansatz.parameters[index]) print(grad) value_dict = dict(zip(ansatz.parameters, point)) sampler.convert(grad, value_dict).eval().real eps = np.pi / 2 e_i = np.identity(point.size)[:, index] # identity vector with a 1 at index ``index``, otherwise 0 plus = point + eps * e_i minus = point - eps * e_i finite_difference = (evaluate_expectation(plus) - evaluate_expectation(minus)) / 2 print(finite_difference) expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz) shifter = Gradient() # parameter-shift rule is the default grad = shifter.convert(expectation, params=ansatz.parameters[index]) sampler.convert(grad, value_dict).eval().real expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz) shifter = Gradient('lin_comb') # parameter-shift rule is the default grad = shifter.convert(expectation, params=ansatz.parameters[index]) sampler.convert(grad, value_dict).eval().real # initial_point = np.random.random(ansatz.num_parameters) initial_point = np.array([0.43253681, 0.09507794, 0.42805949, 0.34210341]) expectation = StateFn(hamiltonian, is_measurement=True).compose(StateFn(ansatz)) gradient = Gradient().convert(expectation) gradient_in_pauli_basis = PauliExpectation().convert(gradient) sampler = CircuitSampler(q_instance) def evaluate_gradient(x): value_dict = dict(zip(ansatz.parameters, x)) result = sampler.convert(gradient_in_pauli_basis, params=value_dict).eval() # add parameters in here! return np.real(result) # Note: The GradientDescent class will be released with Qiskit 0.28.0 and can then be imported as: # from qiskit.algorithms.optimizers import GradientDescent from qc_grader.gradient_descent import GradientDescent gd_loss = [] def gd_callback(nfevs, x, fx, stepsize): gd_loss.append(fx) gd = GradientDescent(maxiter=300, learning_rate=0.01, callback=gd_callback) x_opt, fx_opt, nfevs = gd.optimize(initial_point.size, # number of parameters evaluate_expectation, # function to minimize gradient_function=evaluate_gradient, # function to evaluate the gradient initial_point=initial_point) # initial point import matplotlib import matplotlib.pyplot as plt matplotlib.rcParams['font.size'] = 14 plt.figure(figsize=(12, 6)) plt.plot(gd_loss, label='vanilla gradient descent') plt.axhline(-1, ls='--', c='tab:red', label='target') plt.ylabel('loss') plt.xlabel('iterations') plt.legend(); from qiskit.opflow import NaturalGradient expectation = StateFn(hamiltonian, is_measurement=True).compose(StateFn(ansatz)) natural_gradient = NaturalGradient(regularization='ridge').convert(expectation) natural_gradient_in_pauli_basis = PauliExpectation().convert(natural_gradient) sampler = CircuitSampler(q_instance, caching="all") def evaluate_natural_gradient(x): value_dict = dict(zip(ansatz.parameters, x)) result = sampler.convert(natural_gradient, params=value_dict).eval() return np.real(result) print('Vanilla gradient:', evaluate_gradient(initial_point)) print('Natural gradient:', evaluate_natural_gradient(initial_point)) qng_loss = [] def qng_callback(nfevs, x, fx, stepsize): qng_loss.append(fx) qng = GradientDescent(maxiter=300, learning_rate=0.01, callback=qng_callback) x_opt, fx_opt, nfevs = qng.optimize(initial_point.size, evaluate_expectation, gradient_function=evaluate_natural_gradient, initial_point=initial_point) def plot_loss(): plt.figure(figsize=(12, 6)) plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent') plt.plot(qng_loss, 'tab:green', label='quantum natural gradient') plt.axhline(-1, c='tab:red', ls='--', label='target') plt.ylabel('loss') plt.xlabel('iterations') plt.legend() plot_loss() from qc_grader.spsa import SPSA spsa_loss = [] def spsa_callback(nfev, x, fx, stepsize, accepted): spsa_loss.append(fx) spsa = SPSA(maxiter=300, learning_rate=0.01, perturbation=0.01, callback=spsa_callback) x_opt, fx_opt, nfevs = spsa.optimize(initial_point.size, evaluate_expectation, initial_point=initial_point) def plot_loss(): plt.figure(figsize=(12, 6)) plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent') plt.plot(qng_loss, 'tab:green', label='quantum natural gradient') plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA') plt.axhline(-1, c='tab:red', ls='--', label='target') plt.ylabel('loss') plt.xlabel('iterations') plt.legend() plot_loss() # Note: The QNSPSA class will be released with Qiskit 0.28.0 and can then be imported as: # from qiskit.algorithms.optimizers import QNSPSA from qc_grader.qnspsa import QNSPSA qnspsa_loss = [] def qnspsa_callback(nfev, x, fx, stepsize, accepted): qnspsa_loss.append(fx) fidelity = QNSPSA.get_fidelity(ansatz, q_instance, expectation=PauliExpectation()) qnspsa = QNSPSA(fidelity, maxiter=300, learning_rate=0.01, perturbation=0.01, callback=qnspsa_callback) x_opt, fx_opt, nfevs = qnspsa.optimize(initial_point.size, evaluate_expectation, initial_point=initial_point) def plot_loss(): plt.figure(figsize=(12, 6)) plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent') plt.plot(qng_loss, 'tab:green', label='quantum natural gradient') plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA') plt.plot(qnspsa_loss, 'tab:green', ls='--', label='QN-SPSA') plt.axhline(-1, c='tab:red', ls='--', label='target') plt.ylabel('loss') plt.xlabel('iterations') plt.legend() plot_loss() autospsa_loss = [] def autospsa_callback(nfev, x, fx, stepsize, accepted): autospsa_loss.append(fx) autospsa = SPSA(maxiter=300, learning_rate=None, perturbation=None, callback=autospsa_callback) x_opt, fx_opt, nfevs = autospsa.optimize(initial_point.size, evaluate_expectation, initial_point=initial_point) def plot_loss(): plt.figure(figsize=(12, 6)) plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent') plt.plot(qng_loss, 'tab:green', label='quantum natural gradient') plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA') plt.plot(qnspsa_loss, 'tab:green', ls='--', label='QN-SPSA') plt.plot(autospsa_loss, 'tab:red', label='Powerlaw SPSA') plt.axhline(-1, c='tab:red', ls='--', label='target') plt.ylabel('loss') plt.xlabel('iterations') plt.legend() plot_loss() H_tfi = -(Z^Z^I)-(I^Z^Z)-(X^I^I)-(I^X^I)-(I^I^X) from qc_grader import grade_lab4_ex3 # Note that the grading function is expecting a Hamiltonian grade_lab4_ex3(H_tfi) from qiskit.circuit.library import EfficientSU2 efficient_su2 = EfficientSU2(3, entanglement="linear", reps=2) tfi_sampler = CircuitSampler(q_instance) def evaluate_tfi(parameters): exp = StateFn(H_tfi, is_measurement=True).compose(StateFn(efficient_su2)) value_dict = dict(zip(efficient_su2.parameters, parameters)) result = tfi_sampler.convert(PauliExpectation().convert(exp), params=value_dict).eval() return np.real(result) # target energy tfi_target = -3.4939592074349326 # initial point for reproducibility tfi_init = np.array([0.95667807, 0.06192812, 0.47615196, 0.83809827, 0.89022282, 0.27140831, 0.9540853 , 0.41374024, 0.92595507, 0.76150126, 0.8701938 , 0.05096063, 0.25476016, 0.71807858, 0.85661325, 0.48311132, 0.43623886, 0.6371297 ]) tfi_result = SPSA(maxiter=300, learning_rate=None, perturbation=None) tfi_result = tfi_result.optimize(tfi_init.size, evaluate_tfi, initial_point=tfi_init) tfi_minimum = tfi_result[1] print("Error:", np.abs(tfi_result[1] - tfi_target)) from qc_grader import grade_lab4_ex4 # Note that the grading function is expecting a floating point number grade_lab4_ex4(tfi_minimum) from qiskit_machine_learning.datasets import ad_hoc_data training_features, training_labels, test_features, test_labels = ad_hoc_data( training_size=20, test_size=10, n=2, one_hot=False, gap=0.5 ) # the training labels are in {0, 1} but we'll use {-1, 1} as class labels! training_labels = 2 * training_labels - 1 test_labels = 2 * test_labels - 1 def plot_sampled_data(): from matplotlib.patches import Patch from matplotlib.lines import Line2D import matplotlib.pyplot as plt plt.figure(figsize=(12,6)) for feature, label in zip(training_features, training_labels): marker = 'o' color = 'tab:green' if label == -1 else 'tab:blue' plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color) for feature, label in zip(test_features, test_labels): marker = 's' plt.scatter(feature[0], feature[1], marker=marker, s=100, facecolor='none', edgecolor='k') legend_elements = [ Line2D([0], [0], marker='o', c='w', mfc='tab:green', label='A', ms=15), Line2D([0], [0], marker='o', c='w', mfc='tab:blue', label='B', ms=15), Line2D([0], [0], marker='s', c='w', mfc='none', mec='k', label='test features', ms=10) ] plt.legend(handles=legend_elements, bbox_to_anchor=(1, 0.6)) plt.title('Training & test data') plt.xlabel('$x$') plt.ylabel('$y$') plot_sampled_data() from qiskit.circuit.library import ZZFeatureMap dim = 2 feature_map = ZZFeatureMap(dim, reps=1) # let's keep it simple! feature_map.draw('mpl', style='iqx') ansatz = RealAmplitudes(num_qubits=dim, entanglement='linear', reps=1) # also simple here! ansatz.draw('mpl', style='iqx') circuit = feature_map.compose(ansatz) circuit.draw('mpl', style='iqx') hamiltonian = Z ^ Z # global Z operators gd_qnn_loss = [] def gd_qnn_callback(*args): gd_qnn_loss.append(args[2]) gd = GradientDescent(maxiter=100, learning_rate=0.01, callback=gd_qnn_callback) from qiskit_machine_learning.neural_networks import OpflowQNN qnn_expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(circuit) qnn = OpflowQNN(qnn_expectation, input_params=list(feature_map.parameters), weight_params=list(ansatz.parameters), exp_val=PauliExpectation(), gradient=Gradient(), # <-- Parameter-Shift gradients quantum_instance=q_instance) from qiskit_machine_learning.algorithms import NeuralNetworkClassifier #initial_point = np.array([0.2, 0.1, 0.3, 0.4]) classifier = NeuralNetworkClassifier(qnn, optimizer=gd) classifier.fit(training_features, training_labels); predicted = classifier.predict(test_features) def plot_predicted(): from matplotlib.lines import Line2D plt.figure(figsize=(12, 6)) for feature, label in zip(training_features, training_labels): marker = 'o' color = 'tab:green' if label == -1 else 'tab:blue' plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color) for feature, label, pred in zip(test_features, test_labels, predicted): marker = 's' color = 'tab:green' if pred == -1 else 'tab:blue' if label != pred: # mark wrongly classified plt.scatter(feature[0], feature[1], marker='o', s=500, linewidths=2.5, facecolor='none', edgecolor='tab:red') plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color) legend_elements = [ Line2D([0], [0], marker='o', c='w', mfc='tab:green', label='A', ms=15), Line2D([0], [0], marker='o', c='w', mfc='tab:blue', label='B', ms=15), Line2D([0], [0], marker='s', c='w', mfc='tab:green', label='predict A', ms=10), Line2D([0], [0], marker='s', c='w', mfc='tab:blue', label='predict B', ms=10), Line2D([0], [0], marker='o', c='w', mfc='none', mec='tab:red', label='wrongly classified', mew=2, ms=15) ] plt.legend(handles=legend_elements, bbox_to_anchor=(1, 0.7)) plt.title('Training & test data') plt.xlabel('$x$') plt.ylabel('$y$') plot_predicted() qng_qnn_loss = [] def qng_qnn_callback(*args): qng_qnn_loss.append(args[2]) gd = GradientDescent(maxiter=100, learning_rate=0.01, callback=qng_qnn_callback) qnn = OpflowQNN(qnn_expectation, input_params=list(feature_map.parameters), weight_params=list(ansatz.parameters), gradient=NaturalGradient(regularization='ridge'), # <-- using Natural Gradients! quantum_instance=q_instance) classifier = NeuralNetworkClassifier(qnn, optimizer=gd)#, initial_point=initial_point) classifier.fit(training_features, training_labels); def plot_losses(): plt.figure(figsize=(12, 6)) plt.plot(gd_qnn_loss, 'tab:blue', marker='o', label='vanilla gradients') plt.plot(qng_qnn_loss, 'tab:green', marker='o', label='natural gradients') plt.xlabel('iterations') plt.ylabel('loss') plt.legend(loc='best') plot_losses() from qiskit.opflow import I def sample_gradients(num_qubits, reps, local=False): """Sample the gradient of our model for ``num_qubits`` qubits and ``reps`` repetitions. We sample 100 times for random parameters and compute the gradient of the first RY rotation gate. """ index = num_qubits - 1 # you can also exchange this for a local operator and observe the same! if local: operator = Z ^ Z ^ (I ^ (num_qubits - 2)) else: operator = Z ^ num_qubits # real amplitudes ansatz ansatz = RealAmplitudes(num_qubits, entanglement='linear', reps=reps) # construct Gradient we want to evaluate for different values expectation = StateFn(operator, is_measurement=True).compose(StateFn(ansatz)) grad = Gradient().convert(expectation, params=ansatz.parameters[index]) # evaluate for 100 different, random parameter values num_points = 100 grads = [] for _ in range(num_points): # points are uniformly chosen from [0, pi] point = np.random.uniform(0, np.pi, ansatz.num_parameters) value_dict = dict(zip(ansatz.parameters, point)) grads.append(sampler.convert(grad, value_dict).eval()) return grads num_qubits = list(range(2, 13)) reps = num_qubits # number of layers = numbers of qubits gradients = [sample_gradients(n, r) for n, r in zip(num_qubits, reps)] fit = np.polyfit(num_qubits, np.log(np.var(gradients, axis=1)), deg=1) x = np.linspace(num_qubits[0], num_qubits[-1], 200) plt.figure(figsize=(12, 6)) plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='measured variance') plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}') plt.xlabel('number of qubits') plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$') plt.legend(loc='best'); from qiskit.opflow import NaturalGradient def sample_natural_gradients(num_qubits, reps): index = num_qubits - 1 operator = Z ^ num_qubits ansatz = RealAmplitudes(num_qubits, entanglement='linear', reps=reps) expectation = StateFn(operator, is_measurement=True).compose(StateFn(ansatz)) grad = # TODO: ``grad`` should be the natural gradient for the parameter at index ``index``. # Hint: Check the ``sample_gradients`` function, this one is almost the same. grad = NaturalGradient().convert(expectation, params=ansatz.parameters[index]) num_points = 100 grads = [] for _ in range(num_points): point = np.random.uniform(0, np.pi, ansatz.num_parameters) value_dict = dict(zip(ansatz.parameters, point)) grads.append(sampler.convert(grad, value_dict).eval()) return grads num_qubits = list(range(2, 13)) reps = num_qubits # number of layers = numbers of qubits natural_gradients = [sample_natural_gradients(n, r) for n, r in zip(num_qubits, reps)] fit = np.polyfit(num_qubits, np.log(np.var(natural_gradients, axis=1)), deg=1) x = np.linspace(num_qubits[0], num_qubits[-1], 200) plt.figure(figsize=(12, 6)) plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='vanilla gradients') plt.semilogy(num_qubits, np.var(natural_gradients, axis=1), 's-', label='natural gradients') plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {float(fit[0]):.2f}') plt.xlabel('number of qubits') plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$') plt.legend(loc='best'); num_qubits = list(range(2, 13)) fixed_depth_global_gradients = [sample_gradients(n, 1) for n in num_qubits] fit = np.polyfit(num_qubits, np.log(np.var(fixed_depth_global_gradients, axis=1)), deg=1) x = np.linspace(num_qubits[0], num_qubits[-1], 200) plt.figure(figsize=(12, 6)) plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth') plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth') plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}') plt.xlabel('number of qubits') plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$') plt.legend(loc='best'); num_qubits = list(range(2, 13)) linear_depth_local_gradients = [sample_gradients(n, n, local=True) for n in num_qubits] fit = np.polyfit(num_qubits, np.log(np.var(linear_depth_local_gradients, axis=1)), deg=1) x = np.linspace(num_qubits[0], num_qubits[-1], 200) plt.figure(figsize=(12, 6)) plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth') plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth') plt.semilogy(num_qubits, np.var(linear_depth_local_gradients, axis=1), 'o-', label='local cost, linear depth') plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}') plt.xlabel('number of qubits') plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$') plt.legend(loc='best'); num_qubits = list(range(2, 13)) fixed_depth_local_gradients = [sample_gradients(n, 1, local=True) for n in num_qubits] fit = np.polyfit(num_qubits, np.log(np.var(fixed_depth_local_gradients, axis=1)), deg=1) x = np.linspace(num_qubits[0], num_qubits[-1], 200) plt.figure(figsize=(12, 6)) plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth') plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth') plt.semilogy(num_qubits, np.var(linear_depth_local_gradients, axis=1), 'o-', label='local cost, linear depth') plt.semilogy(num_qubits, np.var(fixed_depth_local_gradients, axis=1), 'o-', label='local cost, constant depth') plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}') plt.xlabel('number of qubits') plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$') plt.legend(loc='best'); num_qubits = 6 operator = Z ^ Z ^ (I ^ (num_qubits - 4)) def minimize(circuit, optimizer): initial_point = np.random.random(circuit.num_parameters) exp = StateFn(operator, is_measurement=True) @ StateFn(circuit) grad = Gradient().convert(exp) # pauli basis exp = PauliExpectation().convert(exp) grad = PauliExpectation().convert(grad) sampler = CircuitSampler(q_instance, caching="all") def loss(x): values_dict = dict(zip(circuit.parameters, x)) return np.real(sampler.convert(exp, values_dict).eval()) def gradient(x): values_dict = dict(zip(circuit.parameters, x)) return np.real(sampler.convert(grad, values_dict).eval()) return optimizer.optimize(circuit.num_parameters, loss, gradient, initial_point=initial_point) circuit = RealAmplitudes(4, reps=1, entanglement='linear') circuit.draw('mpl', style='iqx') circuit.reps = 5 circuit.draw('mpl', style='iqx') def layerwise_training(ansatz, max_num_layers, optimizer): optimal_parameters = [] fopt = None for reps in range(1, max_num_layers): ansatz.reps = reps # bind already optimized parameters values_dict = dict(zip(ansatz.parameters, optimal_parameters)) partially_bound = ansatz.bind_parameters(values_dict) xopt, fopt, _ = minimize(partially_bound, optimizer) print('Circuit depth:', ansatz.depth(), 'best value:', fopt) optimal_parameters += list(xopt) return fopt, optimal_parameters ansatz = RealAmplitudes(4, entanglement='linear') optimizer = GradientDescent(maxiter=50) np.random.seed(12) fopt, optimal_parameters = layerwise_training(ansatz, 4, optimizer)
https://github.com/jacobwatkins1/rodeo-algorithm
jacobwatkins1
import numpy as np from sympy import * from qiskit import * from qiskit.quantum_info import Kraus, SuperOp from qiskit.providers.aer import AerSimulator from qiskit.tools.visualization import plot_histogram # Import from Qiskit Aer noise module from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise import QuantumError, ReadoutError from qiskit.providers.aer.noise import pauli_error from qiskit.providers.aer.noise import depolarizing_error from qiskit.providers.aer.noise import thermal_relaxation_error from numpy import linalg as la Id = np.matrix([[1,0],[0,1]],dtype=complex) X = np.matrix([[0,1],[1,0]],dtype=complex) Y = np.matrix([[0,-1j],[1j,0]],dtype=complex) Z = np.matrix([[1,0],[0,-1]],dtype=complex) # The values used in our paper. a= -0.08496099317164885 b= -0.8913449722923625 c= 0.2653567873681286 d= 0.5720506205204723 # The values used in our paper. c_i= -0.8453688208879107 c_x= 0.006726766902514836 c_y= -0.29354208134440296 c_z= 0.18477436355081123 # The Hamiltonian. H = a*Id+b*X+c*Y+d*Z print(H) # Find the exact eigenstates and eigenvalues. Awh, Avh = la.eig(H) Aeval0h = float(re(Awh[0])) Aeval1h = float(re(Awh[1])) Aevec0h = Avh[:,0] Aevec1h = Avh[:,1] print('The energy eigenvalues of H are:',Aeval0h, 'and', Aeval1h) print('The corresponding eigenvectors are:', '\n', Aevec0h,'\n', 'and','\n', Aevec1h) N = 3 Aevec0h1 = [0.8729044694074841+0j, -0.4676094626792474+0.13920911500783384j] def qc1(E_targ,tstep,phi): ao = a + phi*c_i bo = b + phi*c_x co = c + phi*c_y do = d + phi*c_z sigo = Matrix([[bo],[co],[do]]) n_hato = np.dot(1/sqrt(bo**2+co**2+do**2),sigo) nxo, nyo, nzo = [float(i.item()) for i in n_hato] theta = 2*tstep*sqrt(bo**2+co**2+do**2) % (4*pi) delta = float(re(atan(nzo*tan(theta/2))+atan(nxo/nyo))) beta = float(re(atan(nzo*tan(theta/2))-atan(nxo/nyo))) gamma = float(2*re(acos(cos(theta/2)/cos((delta+beta)/2)))) if nyo > 0 and theta > 2*pi: gamma *= (-1) elif nyo < 0 and theta <= 2*pi: gamma *= (-1) quanc1t = QuantumCircuit(2) quanc1t.h(1) quanc1t.cu(gamma,beta,delta,0,1,0) quanc1t.p(tstep*(E_targ-ao)-0.5*(delta+beta),1) # The Energy Sensor. quanc1t.h(1) quanc1t.barrier() return quanc1t def qct(E_targ,sigma,phi): qrz = QuantumRegister(2,'q') crz = ClassicalRegister(N,'c') qc = QuantumCircuit(qrz,crz) t = np.random.normal(0, sigma, N).tolist() qc.initialize(Aevec0h1, 0) for i in range (N): # sub_inst = qc1(E_targ,t[i],epsilon).to_instruction() # qc.append(sub_inst,[obj,arena]) qc.append(qc1(E_targ,t[i],phi),[0,1]) # 0:Obj, 1:Arena. qc.measure(1,i) # Mid-circuit measurement, arena is measured. qc.barrier() # qc = transpile(qc,backend=backend,optimization_level=2,initial_layout = [obj,arena]) # qc = transpile(qc,backend=backend,optimization_level=2,layout_method = "noise_adaptive") # qc.barrier() return qc def depolarizing_noise(one_qubit_noise, two_qubit_noise): depolarizing_model = NoiseModel() error_1 = depolarizing_error(one_qubit_noise, 1) error_2 = depolarizing_error(two_qubit_noise, 2) depolarizing_model.add_all_qubit_quantum_error(error_1, ['u1', 'u2', 'u3']) depolarizing_model.add_all_qubit_quantum_error(error_2, ['cx']) print(depolarizing_model) return depolarizing_model test_circuit = qct(Aeval0h,3,0) test_circuit.draw('mpl') # Create noisy simulator backend sim_noise = AerSimulator(noise_model = depolarizing_noise(0.9,0.9)) # Transpile circuit for noisy basis gates circ_tnoise = transpile(test_circuit, sim_noise) # Run and get counts result_bit_flip = sim_noise.run(circ_tnoise).result() counts_bit_flip = result_bit_flip.get_counts(0) # Plot noisy output plot_histogram(counts_bit_flip) def numsli_expc (L,rang1,rang2,nuni,nshots,sigma,k,phi): val0, val1,_,_,_,_ = H_obj(phi) EW = np.linspace(rang1,rang2,L) # The energy spectrum we're interested in. circuits = [] # The 'circuit matrix'. for i in range(L): circuitsi = [] for j in range (nuni): circuit = qct(EW[i],sigma,phi) circuitsi.append(circuit) circuits.append(circuitsi) all_circuits = [] for i in range(L): all_circuits += circuits[i][:] MExperiments = job_manager.run(all_circuits, backend=backend, shots = nshots) results = MExperiments.results() # cresults = results.combine_results() # We are not doing read-out error mitigation here. # mitigated_results = meas_filter.apply(cresults) probsu = [] succs = '0'*N for i in range (L): probsui = [] for j in range (nuni): # counts = mitigated_results.get_counts((nuni*i)+j) counts = results.get_counts((nuni*i)+j) if succs in counts: prob = counts[succs]/sum(counts.values()) else: prob = 0 probsui.append(prob) probsu.append(np.average(probsui)) spec = dict(zip(EW,probsu)) plt.figure(figsize=(16.18,10)) plt.xlabel(r'$Energy\ Spectrum\ (E_{target})$',fontsize = 15) plt.ylabel('Probability to measure the success state',fontsize = 15) hist = plt.bar(spec.keys(), spec.values(), width=np.abs((rang2-rang1)/L), color='lightseagreen',alpha = 0.7) plt.legend([hist],['Results from qasm']) plt.grid() plt.show() # Weighted avg based on the highest bins. #Larg = dict(sorted(spec.items(), key = itemgetter(1), reverse = True)[:Hisk]) #Wavg = np.average(list(Larg.keys()), weights=list(Larg.values())) # Weighted avg of the highest consecutive bins. keys = np.fromiter(spec.keys(), float, count=len(spec)) vals = np.fromiter(spec.values(), float, count=len(spec)) idx = np.convolve(vals, np.ones(k), 'valid').argmax() Wavg = np.average(keys[idx:idx + k], weights=vals[idx:idx + k]) print('Range for the next scan', keys[idx:idx + k]) print('The estimated Eigenvalue is', Wavg) print('The precise values are',val0,'and',val1) return spec
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from sklearn.datasets import make_blobs # example dataset features, labels = make_blobs(n_samples=20, n_features=2, centers=2, random_state=3, shuffle=True) import numpy as np from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler features = MinMaxScaler(feature_range=(0, np.pi)).fit_transform(features) train_features, test_features, train_labels, test_labels = train_test_split( features, labels, train_size=15, shuffle=False ) # number of qubits is equal to the number of features num_qubits = 2 # number of steps performed during the training procedure tau = 100 # regularization parameter C = 1000 from qiskit import BasicAer from qiskit.circuit.library import ZFeatureMap from qiskit.utils import algorithm_globals from qiskit_machine_learning.kernels import FidelityQuantumKernel algorithm_globals.random_seed = 12345 feature_map = ZFeatureMap(feature_dimension=num_qubits, reps=1) qkernel = FidelityQuantumKernel(feature_map=feature_map) from qiskit_machine_learning.algorithms import PegasosQSVC pegasos_qsvc = PegasosQSVC(quantum_kernel=qkernel, C=C, num_steps=tau) # training pegasos_qsvc.fit(train_features, train_labels) # testing pegasos_score = pegasos_qsvc.score(test_features, test_labels) print(f"PegasosQSVC classification test score: {pegasos_score}") grid_step = 0.2 margin = 0.2 grid_x, grid_y = np.meshgrid( np.arange(-margin, np.pi + margin, grid_step), np.arange(-margin, np.pi + margin, grid_step) ) meshgrid_features = np.column_stack((grid_x.ravel(), grid_y.ravel())) meshgrid_colors = pegasos_qsvc.predict(meshgrid_features) import matplotlib.pyplot as plt plt.figure(figsize=(5, 5)) meshgrid_colors = meshgrid_colors.reshape(grid_x.shape) plt.pcolormesh(grid_x, grid_y, meshgrid_colors, cmap="RdBu", shading="auto") plt.scatter( train_features[:, 0][train_labels == 0], train_features[:, 1][train_labels == 0], marker="s", facecolors="w", edgecolors="r", label="A train", ) plt.scatter( train_features[:, 0][train_labels == 1], train_features[:, 1][train_labels == 1], marker="o", facecolors="w", edgecolors="b", label="B train", ) plt.scatter( test_features[:, 0][test_labels == 0], test_features[:, 1][test_labels == 0], marker="s", facecolors="r", edgecolors="r", label="A test", ) plt.scatter( test_features[:, 0][test_labels == 1], test_features[:, 1][test_labels == 1], marker="o", facecolors="b", edgecolors="b", label="B test", ) plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0) plt.title("Pegasos Classification") plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/abhishekchak52/quantum-computing-course
abhishekchak52
%matplotlib inline import numpy as np import matplotlib.pyplot as plt # Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute from qiskit.providers.aer import QasmSimulator from qiskit.visualization import * num_qubits = 32 alice_basis = np.random.randint(2, size=num_qubits) alice_state = np.random.randint(2, size=num_qubits) bob_basis = np.random.randint(2, size=num_qubits) oscar_basis = np.random.randint(2, size=num_qubits) print(f"Alice's State:\t {np.array2string(alice_state, separator='')}") print(f"Alice's Bases:\t {np.array2string(alice_basis, separator='')}") print(f"Oscar's Bases:\t {np.array2string(oscar_basis, separator='')}") print(f"Bob's Bases:\t {np.array2string(bob_basis, separator='')}") def make_bb84_circ(enc_state, enc_basis, meas_basis): ''' enc_state: array of 0s and 1s denoting the state to be encoded enc_basis: array of 0s and 1s denoting the basis to be used for encoding 0 -> Computational Basis 1 -> Hadamard Basis meas_basis: array of 0s and 1s denoting the basis to be used for measurement 0 -> Computational Basis 1 -> Hadamard Basis ''' num_qubits = len(enc_state) bb84_circ = QuantumCircuit(num_qubits) # Sender prepares qubits for index in range(len(enc_basis)): if enc_state[index] == 1: bb84_circ.x(index) if enc_basis[index] == 1: bb84_circ.h(index) bb84_circ.barrier() # Receiver measures the received qubits for index in range(len(meas_basis)): if meas_basis[index] == 1: bb84_circ.h(index) bb84_circ.measure_all() return bb84_circ bb84_AO = make_bb84_circ(alice_state, alice_basis, oscar_basis) oscar_result = execute(bb84_AO.reverse_bits(), backend=QasmSimulator(), shots=1).result().get_counts().most_frequent() print(f"Oscar's results:\t {oscar_result}") # Converting string to array oscar_state = np.array(list(oscar_result), dtype=int) print(f"Oscar's State:\t\t{np.array2string(oscar_state, separator='')}") bb84_OB = make_bb84_circ(oscar_state, oscar_basis, bob_basis) temp_key = execute(bb84_OB.reverse_bits(), backend=QasmSimulator(), shots=1).result().get_counts().most_frequent() print(f"Bob's results:\t\t {temp_key}") alice_key = '' bob_key = '' oscar_key = '' for i in range(num_qubits): if alice_basis[i] == bob_basis[i]: # Only choose bits where Alice and Bob chose the same basis alice_key += str(alice_state[i]) bob_key += str(temp_key[i]) oscar_key += str(oscar_result[i]) print(f"The length of the key is {len(bob_key)}") print(f"Alice's key contains\t {(alice_key).count('0')} zeroes and {(alice_key).count('1')} ones") print(f"Bob's key contains\t {(bob_key).count('0')} zeroes and {(bob_key).count('1')} ones") print(f"Oscar's key contains\t {(oscar_key).count('0')} zeroes and {(oscar_key).count('1')} ones") print(f"Alice's Key:\t {alice_key}") print(f"Bob's Key:\t {bob_key}") print(f"Oscar's Key:\t {oscar_key}")
https://github.com/idriss-hamadi/Qiskit-Quantaum-codes-
idriss-hamadi
from qiskit import * #qiskit framework # Quantum_Register=QuantumRegister(2) # classical_Register=ClassicalRegister(2) # circut=QuantumCircuit(Quantum_Register,classical_Register) #those 3 lines are the same as the next line circut=QuantumCircuit(2,2) circut.draw(output='mpl') #drawing function circut.h(0) #handmard function circut.cx(0,1) #Cnot function circut.measure([0,1],[0,1]) #measuring between the qubits and calssical bits circut.draw(output='mpl') #drawing simulator=Aer.get_backend('qasm_simulator') #using simulator of quantaum comuter called qasm resault=execute(circut,backend=simulator).result() #storing the resault of computation from qiskit.visualization import plot_histogram #importing function of ploting histogram plot_histogram(resault.get_counts()) #plot from qiskit import * # IBMQ.save_account(open("token.txt","r").read()) #signing in using my token in my txt file IBMQ.load_account() #lading account provider=IBMQ.get_provider("ibm-q") quantaum_computer=provider.get_backend('ibmq_quito') import qiskit.tools.jupyter %qiskit_job_watcher job =execute(circut,backend=quantaum_computer) from qiskit.tools.monitor import job_monitor job_monitor(job) quantaum_resault=job.result() plot_histogram(quantaum_resault.get_counts(circut)) %qiskit_disable_job_watcher
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/qiskit-community/qiskit-translations-staging
qiskit-community
import random from qiskit.quantum_info import Statevector secret = random.randint(0,7) # the owner is randomly picked secret_string = format(secret, '03b') # format the owner in 3-bit string oracle = Statevector.from_label(secret_string) # let the oracle know the owner from qiskit.algorithms import AmplificationProblem problem = AmplificationProblem(oracle, is_good_state=secret_string) from qiskit.algorithms import Grover grover_circuits = [] for iteration in range(1,3): grover = Grover(iterations=iteration) circuit = grover.construct_circuit(problem) circuit.measure_all() grover_circuits.append(circuit) # Grover's circuit with 1 iteration grover_circuits[0].draw() # Grover's circuit with 2 iterations grover_circuits[1].draw() from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService() backend = "ibmq_qasm_simulator" # use the simulator from qiskit_ibm_runtime import Sampler, Session with Session(service=service, backend=backend): sampler = Sampler() job = sampler.run(circuits=grover_circuits, shots=1000) result = job.result() print(result) from qiskit.tools.visualization import plot_histogram # Extract bit string with highest probability from results as the answer result_dict = result.quasi_dists[1].binary_probabilities() answer = max(result_dict, key=result_dict.get) print(f"As you can see, the quantum computer returned '{answer}' as the answer with highest probability.\n" "And the results with 2 iterations have higher probability than the results with 1 iteration." ) # Plot the results plot_histogram(result.quasi_dists, legend=['1 iteration', '2 iterations']) # Print the results and the correct answer. print(f"Quantum answer: {answer}") print(f"Correct answer: {secret_string}") print('Success!' if answer == secret_string else 'Failure!') import qiskit_ibm_runtime qiskit_ibm_runtime.version.get_version_info() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.units import DistanceUnit from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver( atom="H 0 0 0; H 0 0 0.735", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) es_problem = driver.run() from qiskit_nature.second_q.mappers import JordanWignerMapper mapper = JordanWignerMapper() from qiskit.algorithms.eigensolvers import NumPyEigensolver numpy_solver = NumPyEigensolver(filter_criterion=es_problem.get_default_filter_criterion()) from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.algorithms.optimizers import SLSQP from qiskit.primitives import Estimator from qiskit_nature.second_q.algorithms import GroundStateEigensolver, QEOM from qiskit_nature.second_q.circuit.library import HartreeFock, UCCSD ansatz = UCCSD( es_problem.num_spatial_orbitals, es_problem.num_particles, mapper, initial_state=HartreeFock( es_problem.num_spatial_orbitals, es_problem.num_particles, mapper, ), ) estimator = Estimator() # This first part sets the ground state solver # see more about this part in the ground state calculation tutorial solver = VQE(estimator, ansatz, SLSQP()) solver.initial_point = [0.0] * ansatz.num_parameters gse = GroundStateEigensolver(mapper, solver) # The qEOM algorithm is simply instantiated with the chosen ground state solver and Estimator primitive qeom_excited_states_solver = QEOM(gse, estimator, "sd") from qiskit_nature.second_q.algorithms import ExcitedStatesEigensolver numpy_excited_states_solver = ExcitedStatesEigensolver(mapper, numpy_solver) numpy_results = numpy_excited_states_solver.solve(es_problem) qeom_results = qeom_excited_states_solver.solve(es_problem) print(numpy_results) print("\n\n") print(qeom_results) import numpy as np def filter_criterion(eigenstate, eigenvalue, aux_values): return np.isclose(aux_values["ParticleNumber"][0], 2.0) new_numpy_solver = NumPyEigensolver(filter_criterion=filter_criterion) new_numpy_excited_states_solver = ExcitedStatesEigensolver(mapper, new_numpy_solver) new_numpy_results = new_numpy_excited_states_solver.solve(es_problem) print(new_numpy_results) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Functions used for the analysis of randomized benchmarking results. """ from scipy.optimize import curve_fit import numpy as np from qiskit import QiskitError from ..tomography import marginal_counts from ...characterization.fitters import build_counts_dict_from_list try: from matplotlib import pyplot as plt HAS_MATPLOTLIB = True except ImportError: HAS_MATPLOTLIB = False class RBFitter: """ Class for fitters for randomized benchmarking """ def __init__(self, backend_result, cliff_lengths, rb_pattern=None): """ Args: backend_result: list of results (qiskit.Result). cliff_lengths: the Clifford lengths, 2D list i x j where i is the number of patterns, j is the number of cliffords lengths rb_pattern: the pattern for the rb sequences. """ if rb_pattern is None: rb_pattern = [[0]] self._cliff_lengths = cliff_lengths self._rb_pattern = rb_pattern self._raw_data = [] self._ydata = [] self._fit = [] self._nseeds = 0 self._result_list = [] self.add_data(backend_result) @property def raw_data(self): """Return raw data.""" return self._raw_data @property def cliff_lengths(self): """Return clifford lengths.""" return self.cliff_lengths @property def ydata(self): """Return ydata (means and std devs).""" return self._ydata @property def fit(self): """Return fit.""" return self._fit @property def seeds(self): """Return the number of loaded seeds.""" return self._nseeds @property def results(self): """Return all the results.""" return self._result_list def add_data(self, new_backend_result, rerun_fit=True): """ Add a new result. Re calculate the raw data, means and fit. Args: new_backend_result: list of rb results rerun_fit: re caculate the means and fit the result Additional information: Assumes that 'result' was executed is the output of circuits generated by randomized_becnhmarking_seq, """ if new_backend_result is None: return if not isinstance(new_backend_result, list): new_backend_result = [new_backend_result] for result in new_backend_result: self._result_list.append(result) # update the number of seeds *if* new ones # added. Note, no checking if we've done all the # cliffords for rbcirc in result.results: nseeds_circ = int(rbcirc.header.name.split('_')[-1]) if (nseeds_circ+1) > self._nseeds: self._nseeds = nseeds_circ+1 for result in self._result_list: if not len(result.results) == len(self._cliff_lengths[0]): raise ValueError( "The number of clifford lengths must match the number of " "results") if rerun_fit: self.calc_data() self.calc_statistics() self.fit_data() @staticmethod def _rb_fit_fun(x, a, alpha, b): """Function used to fit rb.""" # pylint: disable=invalid-name return a * alpha ** x + b def calc_data(self): """ Retrieve probabilities of success from execution results. Outputs results into an internal variable _raw_data which is a 3-dimensional list, where item (i,j,k) is the probability to measure the ground state for the set of qubits in pattern "i" for seed no. j and vector length self._cliff_lengths[i][k]. Additional information: Assumes that 'result' was executed is the output of circuits generated by randomized_becnhmarking_seq, """ circ_counts = {} circ_shots = {} for seedidx in range(self._nseeds): for circ, _ in enumerate(self._cliff_lengths[0]): circ_name = 'rb_length_%d_seed_%d' % (circ, seedidx) count_list = [] for result in self._result_list: try: count_list.append(result.get_counts(circ_name)) except (QiskitError, KeyError): pass circ_counts[circ_name] = \ build_counts_dict_from_list(count_list) circ_shots[circ_name] = sum(circ_counts[circ_name].values()) self._raw_data = [] startind = 0 for patt_ind in range(len(self._rb_pattern)): string_of_0s = '' string_of_0s = string_of_0s.zfill(len(self._rb_pattern[patt_ind])) self._raw_data.append([]) endind = startind+len(self._rb_pattern[patt_ind]) for i in range(self._nseeds): self._raw_data[-1].append([]) for k, _ in enumerate(self._cliff_lengths[patt_ind]): circ_name = 'rb_length_%d_seed_%d' % (k, i) counts_subspace = marginal_counts( circ_counts[circ_name], np.arange(startind, endind)) self._raw_data[-1][i].append( counts_subspace.get(string_of_0s, 0) / circ_shots[circ_name]) startind += (endind) def calc_statistics(self): """ Extract averages and std dev from the raw data (self._raw_data). Assumes that self._calc_data has been run. Output into internal _ydata variable: ydata is a list of dictionaries (length number of patterns). Dictionary ydata[i]: ydata[i]['mean'] is a numpy_array of length n; entry j of this array contains the mean probability of success over seeds, for vector length self._cliff_lengths[i][j]. And ydata[i]['std'] is a numpy_array of length n; entry j of this array contains the std of the probability of success over seeds, for vector length self._cliff_lengths[i][j]. """ self._ydata = [] for patt_ind in range(len(self._rb_pattern)): self._ydata.append({}) self._ydata[-1]['mean'] = np.mean(self._raw_data[patt_ind], 0) if len(self._raw_data[patt_ind]) == 1: # 1 seed self._ydata[-1]['std'] = None else: self._ydata[-1]['std'] = np.std(self._raw_data[patt_ind], 0) def fit_data(self): """ Fit the RB results to an exponential curve. Fit each of the patterns Puts the results into a list of fit dictionaries: where each dictionary corresponds to a pattern and has fields: 'params' - three parameters of rb_fit_fun. The middle one is the exponent. 'err' - the error limits of the parameters. 'epc' - error per Clifford """ self._fit = [] for patt_ind, (lens, qubits) in enumerate(zip(self._cliff_lengths, self._rb_pattern)): # if at least one of the std values is zero, then sigma is replaced # by None if not self._ydata[patt_ind]['std'] is None: sigma = self._ydata[patt_ind]['std'].copy() if len(sigma) - np.count_nonzero(sigma) > 0: sigma = None else: sigma = None params, pcov = curve_fit(self._rb_fit_fun, lens, self._ydata[patt_ind]['mean'], sigma=sigma, p0=(1.0, 0.95, 0.0), bounds=([-2, 0, -2], [2, 1, 2])) alpha = params[1] # exponent params_err = np.sqrt(np.diag(pcov)) alpha_err = params_err[1] nrb = 2 ** len(qubits) epc = (nrb-1)/nrb*(1-alpha) epc_err = epc*alpha_err/alpha self._fit.append({'params': params, 'params_err': params_err, 'epc': epc, 'epc_err': epc_err}) def plot_rb_data(self, pattern_index=0, ax=None, add_label=True, show_plt=True): """ Plot randomized benchmarking data of a single pattern. Args: pattern_index: which RB pattern to plot ax (Axes or None): plot axis (if passed in). add_label (bool): Add an EPC label show_plt (bool): display the plot. Raises: ImportError: If matplotlib is not installed. """ fit_function = self._rb_fit_fun if not HAS_MATPLOTLIB: raise ImportError('The function plot_rb_data needs matplotlib. ' 'Run "pip install matplotlib" before.') if ax is None: plt.figure() ax = plt.gca() xdata = self._cliff_lengths[pattern_index] # Plot the result for each sequence for one_seed_data in self._raw_data[pattern_index]: ax.plot(xdata, one_seed_data, color='gray', linestyle='none', marker='x') # Plot the mean with error bars ax.errorbar(xdata, self._ydata[pattern_index]['mean'], yerr=self._ydata[pattern_index]['std'], color='r', linestyle='--', linewidth=3) # Plot the fit ax.plot(xdata, fit_function(xdata, *self._fit[pattern_index]['params']), color='blue', linestyle='-', linewidth=2) ax.tick_params(labelsize=14) ax.set_xlabel('Clifford Length', fontsize=16) ax.set_ylabel('Ground State Population', fontsize=16) ax.grid(True) if add_label: bbox_props = dict(boxstyle="round,pad=0.3", fc="white", ec="black", lw=2) ax.text(0.6, 0.9, "alpha: %.3f(%.1e) EPC: %.3e(%.1e)" % (self._fit[pattern_index]['params'][1], self._fit[pattern_index]['params_err'][1], self._fit[pattern_index]['epc'], self._fit[pattern_index]['epc_err']), ha="center", va="center", size=14, bbox=bbox_props, transform=ax.transAxes) if show_plt: plt.show()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests preset pass manager API""" import unittest from test import combine from ddt import ddt, data import numpy as np import qiskit from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit.circuit import Qubit, Gate, ControlFlowOp, ForLoopOp from qiskit.compiler import transpile, assemble from qiskit.transpiler import CouplingMap, Layout, PassManager, TranspilerError, Target from qiskit.circuit.library import U2Gate, U3Gate, QuantumVolume, CXGate, CZGate, XGate from qiskit.transpiler.passes import ( ALAPScheduleAnalysis, PadDynamicalDecoupling, RemoveResetInZeroState, ) from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import ( FakeBelem, FakeTenerife, FakeMelbourne, FakeJohannesburg, FakeRueschlikon, FakeTokyo, FakePoughkeepsie, FakeLagosV2, ) from qiskit.converters import circuit_to_dag from qiskit.circuit.library import GraphState from qiskit.quantum_info import random_unitary from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit.transpiler.preset_passmanagers import level0, level1, level2, level3 from qiskit.transpiler.passes import Collect2qBlocks, GatesInBasis from qiskit.transpiler.preset_passmanagers.builtin_plugins import OptimizationPassManager def mock_get_passmanager_stage( stage_name, plugin_name, pm_config, optimization_level=None, # pylint: disable=unused-argument ) -> PassManager: """Mock function for get_passmanager_stage.""" if stage_name == "translation" and plugin_name == "custom_stage_for_test": pm = PassManager([RemoveResetInZeroState()]) return pm elif stage_name == "scheduling" and plugin_name == "custom_stage_for_test": dd_sequence = [XGate(), XGate()] pm = PassManager( [ ALAPScheduleAnalysis(pm_config.instruction_durations), PadDynamicalDecoupling(pm_config.instruction_durations, dd_sequence), ] ) return pm elif stage_name == "init": return PassManager([]) elif stage_name == "routing": return PassManager([]) elif stage_name == "optimization": return OptimizationPassManager().pass_manager(pm_config, optimization_level) elif stage_name == "layout": return PassManager([]) else: raise Exception("Failure, unexpected stage plugin combo for test") def emptycircuit(): """Empty circuit""" return QuantumCircuit() def circuit_2532(): """See https://github.com/Qiskit/qiskit-terra/issues/2532""" circuit = QuantumCircuit(5) circuit.cx(2, 4) return circuit @ddt class TestPresetPassManager(QiskitTestCase): """Test preset passmanagers work as expected.""" @combine(level=[0, 1, 2, 3], name="level{level}") def test_no_coupling_map_with_sabre(self, level): """Test that coupling_map can be None with Sabre (level={level})""" q = QuantumRegister(2, name="q") circuit = QuantumCircuit(q) circuit.cz(q[0], q[1]) result = transpile( circuit, coupling_map=None, layout_method="sabre", routing_method="sabre", optimization_level=level, ) self.assertEqual(result, circuit) @combine(level=[0, 1, 2, 3], name="level{level}") def test_no_coupling_map(self, level): """Test that coupling_map can be None (level={level})""" q = QuantumRegister(2, name="q") circuit = QuantumCircuit(q) circuit.cz(q[0], q[1]) result = transpile(circuit, basis_gates=["u1", "u2", "u3", "cx"], optimization_level=level) self.assertIsInstance(result, QuantumCircuit) def test_layout_3239(self, level=3): """Test final layout after preset level3 passmanager does not include diagonal gates See: https://github.com/Qiskit/qiskit-terra/issues/3239 """ qc = QuantumCircuit(5, 5) qc.h(0) qc.cx(range(3), range(1, 4)) qc.z(range(4)) qc.measure(range(4), range(4)) result = transpile( qc, basis_gates=["u1", "u2", "u3", "cx"], layout_method="trivial", optimization_level=level, ) dag = circuit_to_dag(result) op_nodes = [node.name for node in dag.topological_op_nodes()] self.assertNotIn("u1", op_nodes) # Check if the diagonal Z-Gates (u1) were removed @combine(level=[0, 1, 2, 3], name="level{level}") def test_no_basis_gates(self, level): """Test that basis_gates can be None (level={level})""" q = QuantumRegister(2, name="q") circuit = QuantumCircuit(q) circuit.h(q[0]) circuit.cz(q[0], q[1]) result = transpile(circuit, basis_gates=None, optimization_level=level) self.assertEqual(result, circuit) def test_level0_keeps_reset(self): """Test level 0 should keep the reset instructions""" q = QuantumRegister(2, name="q") circuit = QuantumCircuit(q) circuit.reset(q[0]) circuit.reset(q[0]) result = transpile(circuit, basis_gates=None, optimization_level=0) self.assertEqual(result, circuit) @combine(level=[0, 1, 2, 3], name="level{level}") def test_unitary_is_preserved_if_in_basis(self, level): """Test that a unitary is not synthesized if in the basis.""" qc = QuantumCircuit(2) qc.unitary(random_unitary(4, seed=42), [0, 1]) qc.measure_all() result = transpile(qc, basis_gates=["cx", "u", "unitary"], optimization_level=level) self.assertEqual(result, qc) @combine(level=[0, 1, 2, 3], name="level{level}") def test_unitary_is_preserved_if_basis_is_None(self, level): """Test that a unitary is not synthesized if basis is None.""" qc = QuantumCircuit(2) qc.unitary(random_unitary(4, seed=4242), [0, 1]) qc.measure_all() result = transpile(qc, basis_gates=None, optimization_level=level) self.assertEqual(result, qc) @combine(level=[0, 1, 2, 3], name="level{level}") def test_unitary_is_preserved_if_in_basis_synthesis_translation(self, level): """Test that a unitary is not synthesized if in the basis with synthesis translation.""" qc = QuantumCircuit(2) qc.unitary(random_unitary(4, seed=424242), [0, 1]) qc.measure_all() result = transpile( qc, basis_gates=["cx", "u", "unitary"], optimization_level=level, translation_method="synthesis", ) self.assertEqual(result, qc) @combine(level=[0, 1, 2, 3], name="level{level}") def test_unitary_is_preserved_if_basis_is_None_synthesis_transltion(self, level): """Test that a unitary is not synthesized if basis is None with synthesis translation.""" qc = QuantumCircuit(2) qc.unitary(random_unitary(4, seed=42424242), [0, 1]) qc.measure_all() result = transpile( qc, basis_gates=None, optimization_level=level, translation_method="synthesis" ) self.assertEqual(result, qc) @combine(level=[0, 1, 2, 3], name="level{level}") def test_respect_basis(self, level): """Test that all levels respect basis""" qc = QuantumCircuit(3) qc.h(0) qc.h(1) qc.cp(np.pi / 8, 0, 1) qc.cp(np.pi / 4, 0, 2) basis_gates = ["id", "rz", "sx", "x", "cx"] result = transpile( qc, basis_gates=basis_gates, coupling_map=[[0, 1], [2, 1]], optimization_level=level ) dag = circuit_to_dag(result) circuit_ops = {node.name for node in dag.topological_op_nodes()} self.assertEqual(circuit_ops.union(set(basis_gates)), set(basis_gates)) @combine(level=[0, 1, 2, 3], name="level{level}") def test_alignment_constraints_called_with_by_default(self, level): """Test that TimeUnitConversion is not called if there is no delay in the circuit.""" q = QuantumRegister(2, name="q") circuit = QuantumCircuit(q) circuit.h(q[0]) circuit.cz(q[0], q[1]) with unittest.mock.patch("qiskit.transpiler.passes.TimeUnitConversion.run") as mock: transpile(circuit, backend=FakeJohannesburg(), optimization_level=level) mock.assert_not_called() @combine(level=[0, 1, 2, 3], name="level{level}") def test_alignment_constraints_called_with_delay_in_circuit(self, level): """Test that TimeUnitConversion is called if there is a delay in the circuit.""" q = QuantumRegister(2, name="q") circuit = QuantumCircuit(q) circuit.h(q[0]) circuit.cz(q[0], q[1]) circuit.delay(9.5, unit="ns") with unittest.mock.patch( "qiskit.transpiler.passes.TimeUnitConversion.run", return_value=circuit_to_dag(circuit) ) as mock: transpile(circuit, backend=FakeJohannesburg(), optimization_level=level) mock.assert_called_once() def test_unroll_only_if_not_gates_in_basis(self): """Test that the list of passes _unroll only runs if a gate is not in the basis.""" qcomp = FakeBelem() qv_circuit = QuantumVolume(3) gates_in_basis_true_count = 0 collect_2q_blocks_count = 0 # pylint: disable=unused-argument def counting_callback_func(pass_, dag, time, property_set, count): nonlocal gates_in_basis_true_count nonlocal collect_2q_blocks_count if isinstance(pass_, GatesInBasis) and property_set["all_gates_in_basis"]: gates_in_basis_true_count += 1 if isinstance(pass_, Collect2qBlocks): collect_2q_blocks_count += 1 transpile( qv_circuit, backend=qcomp, optimization_level=3, callback=counting_callback_func, translation_method="synthesis", ) self.assertEqual(gates_in_basis_true_count + 1, collect_2q_blocks_count) def test_get_vf2_call_limit_deprecated(self): """Test that calling test_get_vf2_call_limit emits deprecation warning.""" with self.assertWarns(DeprecationWarning): qiskit.transpiler.preset_passmanagers.common.get_vf2_call_limit(optimization_level=3) @ddt class TestTranspileLevels(QiskitTestCase): """Test transpiler on fake backend""" @combine( circuit=[emptycircuit, circuit_2532], level=[0, 1, 2, 3], backend=[ FakeTenerife(), FakeMelbourne(), FakeRueschlikon(), FakeTokyo(), FakePoughkeepsie(), None, ], dsc="Transpiler {circuit.__name__} on {backend} backend at level {level}", name="{circuit.__name__}_{backend}_level{level}", ) def test(self, circuit, level, backend): """All the levels with all the backends""" result = transpile(circuit(), backend=backend, optimization_level=level, seed_transpiler=42) self.assertIsInstance(result, QuantumCircuit) @ddt class TestPassesInspection(QiskitTestCase): """Test run passes under different conditions""" def setUp(self): """Sets self.callback to set self.passes with the passes that have been executed""" super().setUp() self.passes = [] def callback(**kwargs): self.passes.append(kwargs["pass_"].__class__.__name__) self.callback = callback @data(0, 1, 2, 3) def test_no_coupling_map(self, level): """Without coupling map, no layout selection nor swapper""" qr = QuantumRegister(3, "q") qc = QuantumCircuit(qr) qc.cx(qr[2], qr[1]) qc.cx(qr[2], qr[0]) _ = transpile(qc, optimization_level=level, callback=self.callback) self.assertNotIn("SetLayout", self.passes) self.assertNotIn("TrivialLayout", self.passes) self.assertNotIn("ApplyLayout", self.passes) self.assertNotIn("StochasticSwap", self.passes) self.assertNotIn("SabreSwap", self.passes) self.assertNotIn("CheckGateDirection", self.passes) @data(0, 1, 2, 3) def test_backend(self, level): """With backend a layout and a swapper is run""" qr = QuantumRegister(5, "q") qc = QuantumCircuit(qr) qc.cx(qr[2], qr[4]) backend = FakeMelbourne() _ = transpile(qc, backend, optimization_level=level, callback=self.callback) self.assertIn("SetLayout", self.passes) self.assertIn("ApplyLayout", self.passes) self.assertIn("CheckGateDirection", self.passes) @data(0, 1, 2, 3) def test_5409(self, level): """The parameter layout_method='noise_adaptive' should be honored See: https://github.com/Qiskit/qiskit-terra/issues/5409 """ qr = QuantumRegister(5, "q") qc = QuantumCircuit(qr) qc.cx(qr[2], qr[4]) backend = FakeMelbourne() _ = transpile( qc, backend, layout_method="noise_adaptive", optimization_level=level, callback=self.callback, ) self.assertIn("SetLayout", self.passes) self.assertIn("ApplyLayout", self.passes) self.assertIn("NoiseAdaptiveLayout", self.passes) @data(0, 1, 2, 3) def test_symmetric_coupling_map(self, level): """Symmetric coupling map does not run CheckGateDirection""" qr = QuantumRegister(2, "q") qc = QuantumCircuit(qr) qc.cx(qr[0], qr[1]) coupling_map = [[0, 1], [1, 0]] _ = transpile( qc, coupling_map=coupling_map, initial_layout=[0, 1], optimization_level=level, callback=self.callback, ) self.assertIn("SetLayout", self.passes) self.assertIn("ApplyLayout", self.passes) self.assertNotIn("CheckGateDirection", self.passes) @data(0, 1, 2, 3) def test_initial_layout_fully_connected_cm(self, level): """Honor initial_layout when coupling_map=None See: https://github.com/Qiskit/qiskit-terra/issues/5345 """ qr = QuantumRegister(2, "q") qc = QuantumCircuit(qr) qc.h(qr[0]) qc.cx(qr[0], qr[1]) transpiled = transpile( qc, initial_layout=[0, 1], optimization_level=level, callback=self.callback ) self.assertIn("SetLayout", self.passes) self.assertIn("ApplyLayout", self.passes) self.assertEqual(transpiled._layout.initial_layout, Layout.from_qubit_list([qr[0], qr[1]])) @data(0, 1, 2, 3) def test_partial_layout_fully_connected_cm(self, level): """Honor initial_layout (partially defined) when coupling_map=None See: https://github.com/Qiskit/qiskit-terra/issues/5345 """ qr = QuantumRegister(2, "q") qc = QuantumCircuit(qr) qc.h(qr[0]) qc.cx(qr[0], qr[1]) transpiled = transpile( qc, initial_layout=[4, 2], optimization_level=level, callback=self.callback ) self.assertIn("SetLayout", self.passes) self.assertIn("ApplyLayout", self.passes) ancilla = QuantumRegister(3, "ancilla") self.assertEqual( transpiled._layout.initial_layout, Layout.from_qubit_list([ancilla[0], ancilla[1], qr[1], ancilla[2], qr[0]]), ) @unittest.mock.patch.object( level0.PassManagerStagePluginManager, "get_passmanager_stage", wraps=mock_get_passmanager_stage, ) def test_backend_with_custom_stages(self, _plugin_manager_mock): """Test transpile() executes backend specific custom stage.""" optimization_level = 1 class TargetBackend(FakeLagosV2): """Fake lagos subclass with custom transpiler stages.""" def get_scheduling_stage_plugin(self): """Custom scheduling stage.""" return "custom_stage_for_test" def get_translation_stage_plugin(self): """Custom post translation stage.""" return "custom_stage_for_test" target = TargetBackend() qr = QuantumRegister(2, "q") qc = QuantumCircuit(qr) qc.h(qr[0]) qc.cx(qr[0], qr[1]) _ = transpile(qc, target, optimization_level=optimization_level, callback=self.callback) self.assertIn("ALAPScheduleAnalysis", self.passes) self.assertIn("PadDynamicalDecoupling", self.passes) self.assertIn("RemoveResetInZeroState", self.passes) def test_level1_runs_vf2post_layout_when_routing_required(self): """Test that if we run routing as part of sabre layout VF2PostLayout runs.""" target = FakeLagosV2() qc = QuantumCircuit(5) qc.h(0) qc.cy(0, 1) qc.cy(0, 2) qc.cy(0, 3) qc.cy(0, 4) qc.measure_all() _ = transpile(qc, target, optimization_level=1, callback=self.callback) # Expected call path for layout and routing is: # 1. TrivialLayout (no perfect match) # 2. VF2Layout (no perfect match) # 3. SabreLayout (heuristic layout and also runs routing) # 4. VF2PostLayout (applies a better layout) self.assertIn("TrivialLayout", self.passes) self.assertIn("VF2Layout", self.passes) self.assertIn("SabreLayout", self.passes) self.assertIn("VF2PostLayout", self.passes) # Assert we don't run standalone sabre swap self.assertNotIn("SabreSwap", self.passes) def test_level1_runs_vf2post_layout_when_routing_method_set_and_required(self): """Test that if we run routing as part of sabre layout VF2PostLayout runs.""" target = FakeLagosV2() qc = QuantumCircuit(5) qc.h(0) qc.cy(0, 1) qc.cy(0, 2) qc.cy(0, 3) qc.cy(0, 4) qc.measure_all() _ = transpile( qc, target, optimization_level=1, routing_method="stochastic", callback=self.callback ) # Expected call path for layout and routing is: # 1. TrivialLayout (no perfect match) # 2. VF2Layout (no perfect match) # 3. SabreLayout (heuristic layout and also runs routing) # 4. VF2PostLayout (applies a better layout) self.assertIn("TrivialLayout", self.passes) self.assertIn("VF2Layout", self.passes) self.assertIn("SabreLayout", self.passes) self.assertIn("VF2PostLayout", self.passes) self.assertIn("StochasticSwap", self.passes) def test_level1_not_runs_vf2post_layout_when_layout_method_set(self): """Test that if we don't run VF2PostLayout with custom layout_method.""" target = FakeLagosV2() qc = QuantumCircuit(5) qc.h(0) qc.cy(0, 1) qc.cy(0, 2) qc.cy(0, 3) qc.cy(0, 4) qc.measure_all() _ = transpile( qc, target, optimization_level=1, layout_method="dense", callback=self.callback ) self.assertNotIn("TrivialLayout", self.passes) self.assertNotIn("VF2Layout", self.passes) self.assertNotIn("SabreLayout", self.passes) self.assertNotIn("VF2PostLayout", self.passes) self.assertIn("DenseLayout", self.passes) self.assertIn("SabreSwap", self.passes) def test_level1_not_run_vf2post_layout_when_trivial_is_perfect(self): """Test that if we find a trivial perfect layout we don't run vf2post.""" target = FakeLagosV2() qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() _ = transpile(qc, target, optimization_level=1, callback=self.callback) self.assertIn("TrivialLayout", self.passes) self.assertNotIn("VF2Layout", self.passes) self.assertNotIn("SabreLayout", self.passes) self.assertNotIn("VF2PostLayout", self.passes) # Assert we don't run standalone sabre swap self.assertNotIn("SabreSwap", self.passes) def test_level1_not_run_vf2post_layout_when_vf2layout_is_perfect(self): """Test that if we find a vf2 perfect layout we don't run vf2post.""" target = FakeLagosV2() qc = QuantumCircuit(4) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.measure_all() _ = transpile(qc, target, optimization_level=1, callback=self.callback) self.assertIn("TrivialLayout", self.passes) self.assertIn("VF2Layout", self.passes) self.assertNotIn("SabreLayout", self.passes) self.assertNotIn("VF2PostLayout", self.passes) # Assert we don't run standalone sabre swap self.assertNotIn("SabreSwap", self.passes) def test_level1_runs_vf2post_layout_when_routing_required_control_flow(self): """Test that if we run routing as part of sabre layout VF2PostLayout runs.""" target = FakeLagosV2() _target = target.target target._target.add_instruction(ForLoopOp, name="for_loop") qc = QuantumCircuit(5) qc.h(0) qc.cy(0, 1) qc.cy(0, 2) qc.cy(0, 3) qc.cy(0, 4) with qc.for_loop((1,)): qc.cx(0, 1) qc.measure_all() _ = transpile(qc, target, optimization_level=1, callback=self.callback) # Expected call path for layout and routing is: # 1. TrivialLayout (no perfect match) # 2. VF2Layout (no perfect match) # 3. SabreLayout (heuristic layout) # 4. VF2PostLayout (applies a better layout) self.assertIn("TrivialLayout", self.passes) self.assertIn("VF2Layout", self.passes) self.assertIn("SabreLayout", self.passes) self.assertIn("VF2PostLayout", self.passes) def test_level1_not_runs_vf2post_layout_when_layout_method_set_control_flow(self): """Test that if we don't run VF2PostLayout with custom layout_method.""" target = FakeLagosV2() _target = target.target target._target.add_instruction(ForLoopOp, name="for_loop") qc = QuantumCircuit(5) qc.h(0) qc.cy(0, 1) qc.cy(0, 2) qc.cy(0, 3) qc.cy(0, 4) with qc.for_loop((1,)): qc.cx(0, 1) qc.measure_all() _ = transpile( qc, target, optimization_level=1, layout_method="dense", callback=self.callback ) self.assertNotIn("TrivialLayout", self.passes) self.assertNotIn("VF2Layout", self.passes) self.assertNotIn("SabreLayout", self.passes) self.assertNotIn("VF2PostLayout", self.passes) self.assertIn("DenseLayout", self.passes) self.assertIn("SabreSwap", self.passes) def test_level1_not_run_vf2post_layout_when_trivial_is_perfect_control_flow(self): """Test that if we find a trivial perfect layout we don't run vf2post.""" target = FakeLagosV2() _target = target.target target._target.add_instruction(ForLoopOp, name="for_loop") qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) with qc.for_loop((1,)): qc.cx(0, 1) qc.measure_all() _ = transpile(qc, target, optimization_level=1, callback=self.callback) self.assertIn("TrivialLayout", self.passes) self.assertNotIn("VF2Layout", self.passes) self.assertNotIn("SabreLayout", self.passes) self.assertNotIn("SabreSwap", self.passes) self.assertNotIn("VF2PostLayout", self.passes) def test_level1_not_run_vf2post_layout_when_vf2layout_is_perfect_control_flow(self): """Test that if we find a vf2 perfect layout we don't run vf2post.""" target = FakeLagosV2() _target = target.target target._target.add_instruction(ForLoopOp, name="for_loop") qc = QuantumCircuit(4) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) with qc.for_loop((1,)): qc.cx(0, 1) qc.measure_all() _ = transpile(qc, target, optimization_level=1, callback=self.callback) self.assertIn("TrivialLayout", self.passes) self.assertIn("VF2Layout", self.passes) self.assertNotIn("SabreLayout", self.passes) self.assertNotIn("VF2PostLayout", self.passes) self.assertNotIn("SabreSwap", self.passes) @ddt class TestInitialLayouts(QiskitTestCase): """Test transpiling with different layouts""" @data(0, 1, 2, 3) def test_layout_1711(self, level): """Test that a user-given initial layout is respected, in the qobj. See: https://github.com/Qiskit/qiskit-terra/issues/1711 """ # build a circuit which works as-is on the coupling map, using the initial layout qr = QuantumRegister(3, "q") cr = ClassicalRegister(3) ancilla = QuantumRegister(13, "ancilla") qc = QuantumCircuit(qr, cr) qc.cx(qr[2], qr[1]) qc.cx(qr[2], qr[0]) initial_layout = {0: qr[1], 2: qr[0], 15: qr[2]} final_layout = { 0: qr[1], 1: ancilla[0], 2: qr[0], 3: ancilla[1], 4: ancilla[2], 5: ancilla[3], 6: ancilla[4], 7: ancilla[5], 8: ancilla[6], 9: ancilla[7], 10: ancilla[8], 11: ancilla[9], 12: ancilla[10], 13: ancilla[11], 14: ancilla[12], 15: qr[2], } backend = FakeRueschlikon() qc_b = transpile(qc, backend, initial_layout=initial_layout, optimization_level=level) qobj = assemble(qc_b) self.assertEqual(qc_b._layout.initial_layout._p2v, final_layout) compiled_ops = qobj.experiments[0].instructions for operation in compiled_ops: if operation.name == "cx": self.assertIn(operation.qubits, backend.configuration().coupling_map) self.assertIn(operation.qubits, [[15, 0], [15, 2]]) @data(0, 1, 2, 3) def test_layout_2532(self, level): """Test that a user-given initial layout is respected, in the transpiled circuit. See: https://github.com/Qiskit/qiskit-terra/issues/2532 """ # build a circuit which works as-is on the coupling map, using the initial layout qr = QuantumRegister(5, "q") cr = ClassicalRegister(2) ancilla = QuantumRegister(9, "ancilla") qc = QuantumCircuit(qr, cr) qc.cx(qr[2], qr[4]) initial_layout = { qr[2]: 11, qr[4]: 3, # map to [11, 3] connection qr[0]: 1, qr[1]: 5, qr[3]: 9, } final_layout = { 0: ancilla[0], 1: qr[0], 2: ancilla[1], 3: qr[4], 4: ancilla[2], 5: qr[1], 6: ancilla[3], 7: ancilla[4], 8: ancilla[5], 9: qr[3], 10: ancilla[6], 11: qr[2], 12: ancilla[7], 13: ancilla[8], } backend = FakeMelbourne() qc_b = transpile(qc, backend, initial_layout=initial_layout, optimization_level=level) self.assertEqual(qc_b._layout.initial_layout._p2v, final_layout) output_qr = qc_b.qregs[0] for instruction in qc_b: if instruction.operation.name == "cx": for qubit in instruction.qubits: self.assertIn(qubit, [output_qr[11], output_qr[3]]) @data(0, 1, 2, 3) def test_layout_2503(self, level): """Test that a user-given initial layout is respected, even if cnots are not in the coupling map. See: https://github.com/Qiskit/qiskit-terra/issues/2503 """ # build a circuit which works as-is on the coupling map, using the initial layout qr = QuantumRegister(3, "q") cr = ClassicalRegister(2) ancilla = QuantumRegister(17, "ancilla") qc = QuantumCircuit(qr, cr) qc.append(U3Gate(0.1, 0.2, 0.3), [qr[0]]) qc.append(U2Gate(0.4, 0.5), [qr[2]]) qc.barrier() qc.cx(qr[0], qr[2]) initial_layout = [6, 7, 12] final_layout = { 0: ancilla[0], 1: ancilla[1], 2: ancilla[2], 3: ancilla[3], 4: ancilla[4], 5: ancilla[5], 6: qr[0], 7: qr[1], 8: ancilla[6], 9: ancilla[7], 10: ancilla[8], 11: ancilla[9], 12: qr[2], 13: ancilla[10], 14: ancilla[11], 15: ancilla[12], 16: ancilla[13], 17: ancilla[14], 18: ancilla[15], 19: ancilla[16], } backend = FakePoughkeepsie() qc_b = transpile(qc, backend, initial_layout=initial_layout, optimization_level=level) self.assertEqual(qc_b._layout.initial_layout._p2v, final_layout) output_qr = qc_b.qregs[0] self.assertIsInstance(qc_b[0].operation, U3Gate) self.assertEqual(qc_b[0].qubits[0], output_qr[6]) self.assertIsInstance(qc_b[1].operation, U2Gate) self.assertEqual(qc_b[1].qubits[0], output_qr[12]) @ddt class TestFinalLayouts(QiskitTestCase): """Test final layouts after preset transpilation""" @data(0, 1, 2, 3) def test_layout_tokyo_2845(self, level): """Test that final layout in tokyo #2845 See: https://github.com/Qiskit/qiskit-terra/issues/2845 """ qr1 = QuantumRegister(3, "qr1") qr2 = QuantumRegister(2, "qr2") qc = QuantumCircuit(qr1, qr2) qc.cx(qr1[0], qr1[1]) qc.cx(qr1[1], qr1[2]) qc.cx(qr1[2], qr2[0]) qc.cx(qr2[0], qr2[1]) trivial_layout = { 0: Qubit(QuantumRegister(3, "qr1"), 0), 1: Qubit(QuantumRegister(3, "qr1"), 1), 2: Qubit(QuantumRegister(3, "qr1"), 2), 3: Qubit(QuantumRegister(2, "qr2"), 0), 4: Qubit(QuantumRegister(2, "qr2"), 1), 5: Qubit(QuantumRegister(15, "ancilla"), 0), 6: Qubit(QuantumRegister(15, "ancilla"), 1), 7: Qubit(QuantumRegister(15, "ancilla"), 2), 8: Qubit(QuantumRegister(15, "ancilla"), 3), 9: Qubit(QuantumRegister(15, "ancilla"), 4), 10: Qubit(QuantumRegister(15, "ancilla"), 5), 11: Qubit(QuantumRegister(15, "ancilla"), 6), 12: Qubit(QuantumRegister(15, "ancilla"), 7), 13: Qubit(QuantumRegister(15, "ancilla"), 8), 14: Qubit(QuantumRegister(15, "ancilla"), 9), 15: Qubit(QuantumRegister(15, "ancilla"), 10), 16: Qubit(QuantumRegister(15, "ancilla"), 11), 17: Qubit(QuantumRegister(15, "ancilla"), 12), 18: Qubit(QuantumRegister(15, "ancilla"), 13), 19: Qubit(QuantumRegister(15, "ancilla"), 14), } vf2_layout = { 0: Qubit(QuantumRegister(15, "ancilla"), 0), 1: Qubit(QuantumRegister(15, "ancilla"), 1), 2: Qubit(QuantumRegister(15, "ancilla"), 2), 3: Qubit(QuantumRegister(15, "ancilla"), 3), 4: Qubit(QuantumRegister(15, "ancilla"), 4), 5: Qubit(QuantumRegister(15, "ancilla"), 5), 6: Qubit(QuantumRegister(3, "qr1"), 1), 7: Qubit(QuantumRegister(15, "ancilla"), 6), 8: Qubit(QuantumRegister(15, "ancilla"), 7), 9: Qubit(QuantumRegister(15, "ancilla"), 8), 10: Qubit(QuantumRegister(3, "qr1"), 0), 11: Qubit(QuantumRegister(3, "qr1"), 2), 12: Qubit(QuantumRegister(15, "ancilla"), 9), 13: Qubit(QuantumRegister(15, "ancilla"), 10), 14: Qubit(QuantumRegister(15, "ancilla"), 11), 15: Qubit(QuantumRegister(15, "ancilla"), 12), 16: Qubit(QuantumRegister(2, "qr2"), 0), 17: Qubit(QuantumRegister(2, "qr2"), 1), 18: Qubit(QuantumRegister(15, "ancilla"), 13), 19: Qubit(QuantumRegister(15, "ancilla"), 14), } # Trivial layout expected_layout_level0 = trivial_layout # Dense layout expected_layout_level1 = vf2_layout # CSP layout expected_layout_level2 = vf2_layout expected_layout_level3 = vf2_layout expected_layouts = [ expected_layout_level0, expected_layout_level1, expected_layout_level2, expected_layout_level3, ] backend = FakeTokyo() result = transpile(qc, backend, optimization_level=level, seed_transpiler=42) self.assertEqual(result._layout.initial_layout._p2v, expected_layouts[level]) @data(0, 1, 2, 3) def test_layout_tokyo_fully_connected_cx(self, level): """Test that final layout in tokyo in a fully connected circuit""" qr = QuantumRegister(5, "qr") qc = QuantumCircuit(qr) for qubit_target in qr: for qubit_control in qr: if qubit_control != qubit_target: qc.cx(qubit_control, qubit_target) ancilla = QuantumRegister(15, "ancilla") trivial_layout = { 0: qr[0], 1: qr[1], 2: qr[2], 3: qr[3], 4: qr[4], 5: ancilla[0], 6: ancilla[1], 7: ancilla[2], 8: ancilla[3], 9: ancilla[4], 10: ancilla[5], 11: ancilla[6], 12: ancilla[7], 13: ancilla[8], 14: ancilla[9], 15: ancilla[10], 16: ancilla[11], 17: ancilla[12], 18: ancilla[13], 19: ancilla[14], } sabre_layout = { 0: ancilla[0], 1: qr[4], 2: ancilla[1], 3: ancilla[2], 4: ancilla[3], 5: qr[1], 6: qr[0], 7: ancilla[4], 8: ancilla[5], 9: ancilla[6], 10: qr[2], 11: qr[3], 12: ancilla[7], 13: ancilla[8], 14: ancilla[9], 15: ancilla[10], 16: ancilla[11], 17: ancilla[12], 18: ancilla[13], 19: ancilla[14], } sabre_layout_lvl_2 = { 0: ancilla[0], 1: qr[4], 2: ancilla[1], 3: ancilla[2], 4: ancilla[3], 5: qr[1], 6: qr[0], 7: ancilla[4], 8: ancilla[5], 9: ancilla[6], 10: qr[2], 11: qr[3], 12: ancilla[7], 13: ancilla[8], 14: ancilla[9], 15: ancilla[10], 16: ancilla[11], 17: ancilla[12], 18: ancilla[13], 19: ancilla[14], } sabre_layout_lvl_3 = { 0: ancilla[0], 1: qr[4], 2: ancilla[1], 3: ancilla[2], 4: ancilla[3], 5: qr[1], 6: qr[0], 7: ancilla[4], 8: ancilla[5], 9: ancilla[6], 10: qr[2], 11: qr[3], 12: ancilla[7], 13: ancilla[8], 14: ancilla[9], 15: ancilla[10], 16: ancilla[11], 17: ancilla[12], 18: ancilla[13], 19: ancilla[14], } expected_layout_level0 = trivial_layout expected_layout_level1 = sabre_layout expected_layout_level2 = sabre_layout_lvl_2 expected_layout_level3 = sabre_layout_lvl_3 expected_layouts = [ expected_layout_level0, expected_layout_level1, expected_layout_level2, expected_layout_level3, ] backend = FakeTokyo() result = transpile(qc, backend, optimization_level=level, seed_transpiler=42) self.assertEqual(result._layout.initial_layout._p2v, expected_layouts[level]) @data(0, 1, 2, 3) def test_all_levels_use_trivial_if_perfect(self, level): """Test that we always use trivial if it's a perfect match. See: https://github.com/Qiskit/qiskit-terra/issues/5694 for more details """ backend = FakeTokyo() config = backend.configuration() rows = [x[0] for x in config.coupling_map] cols = [x[1] for x in config.coupling_map] adjacency_matrix = np.zeros((20, 20)) adjacency_matrix[rows, cols] = 1 qc = GraphState(adjacency_matrix) qc.measure_all() expected = { 0: Qubit(QuantumRegister(20, "q"), 0), 1: Qubit(QuantumRegister(20, "q"), 1), 2: Qubit(QuantumRegister(20, "q"), 2), 3: Qubit(QuantumRegister(20, "q"), 3), 4: Qubit(QuantumRegister(20, "q"), 4), 5: Qubit(QuantumRegister(20, "q"), 5), 6: Qubit(QuantumRegister(20, "q"), 6), 7: Qubit(QuantumRegister(20, "q"), 7), 8: Qubit(QuantumRegister(20, "q"), 8), 9: Qubit(QuantumRegister(20, "q"), 9), 10: Qubit(QuantumRegister(20, "q"), 10), 11: Qubit(QuantumRegister(20, "q"), 11), 12: Qubit(QuantumRegister(20, "q"), 12), 13: Qubit(QuantumRegister(20, "q"), 13), 14: Qubit(QuantumRegister(20, "q"), 14), 15: Qubit(QuantumRegister(20, "q"), 15), 16: Qubit(QuantumRegister(20, "q"), 16), 17: Qubit(QuantumRegister(20, "q"), 17), 18: Qubit(QuantumRegister(20, "q"), 18), 19: Qubit(QuantumRegister(20, "q"), 19), } trans_qc = transpile(qc, backend, optimization_level=level, seed_transpiler=42) self.assertEqual(trans_qc._layout.initial_layout._p2v, expected) @data(0) def test_trivial_layout(self, level): """Test that trivial layout is preferred in level 0 See: https://github.com/Qiskit/qiskit-terra/pull/3657#pullrequestreview-342012465 """ qr = QuantumRegister(10, "qr") qc = QuantumCircuit(qr) qc.cx(qr[0], qr[1]) qc.cx(qr[1], qr[2]) qc.cx(qr[2], qr[6]) qc.cx(qr[3], qr[8]) qc.cx(qr[4], qr[9]) qc.cx(qr[9], qr[8]) qc.cx(qr[8], qr[7]) qc.cx(qr[7], qr[6]) qc.cx(qr[6], qr[5]) qc.cx(qr[5], qr[0]) ancilla = QuantumRegister(10, "ancilla") trivial_layout = { 0: qr[0], 1: qr[1], 2: qr[2], 3: qr[3], 4: qr[4], 5: qr[5], 6: qr[6], 7: qr[7], 8: qr[8], 9: qr[9], 10: ancilla[0], 11: ancilla[1], 12: ancilla[2], 13: ancilla[3], 14: ancilla[4], 15: ancilla[5], 16: ancilla[6], 17: ancilla[7], 18: ancilla[8], 19: ancilla[9], } expected_layouts = [trivial_layout, trivial_layout] backend = FakeTokyo() result = transpile(qc, backend, optimization_level=level, seed_transpiler=42) self.assertEqual(result._layout.initial_layout._p2v, expected_layouts[level]) @data(0, 1, 2, 3) def test_initial_layout(self, level): """When a user provides a layout (initial_layout), it should be used.""" qr = QuantumRegister(10, "qr") qc = QuantumCircuit(qr) qc.cx(qr[0], qr[1]) qc.cx(qr[1], qr[2]) qc.cx(qr[2], qr[3]) qc.cx(qr[3], qr[9]) qc.cx(qr[4], qr[9]) qc.cx(qr[9], qr[8]) qc.cx(qr[8], qr[7]) qc.cx(qr[7], qr[6]) qc.cx(qr[6], qr[5]) qc.cx(qr[5], qr[0]) initial_layout = { 0: qr[0], 2: qr[1], 4: qr[2], 6: qr[3], 8: qr[4], 10: qr[5], 12: qr[6], 14: qr[7], 16: qr[8], 18: qr[9], } backend = FakeTokyo() result = transpile( qc, backend, optimization_level=level, initial_layout=initial_layout, seed_transpiler=42 ) for physical, virtual in initial_layout.items(): self.assertEqual(result._layout.initial_layout._p2v[physical], virtual) @ddt class TestTranspileLevelsSwap(QiskitTestCase): """Test if swap is in the basis, do not unroll See https://github.com/Qiskit/qiskit-terra/pull/3963 The circuit in combine should require a swap and that swap should exit at the end for the transpilation""" @combine( circuit=[circuit_2532], level=[0, 1, 2, 3], dsc="circuit: {circuit.__name__}, level: {level}", name="{circuit.__name__}_level{level}", ) def test_1(self, circuit, level): """Simple coupling map (linear 5 qubits).""" basis = ["u1", "u2", "cx", "swap"] coupling_map = CouplingMap([(0, 1), (1, 2), (2, 3), (3, 4)]) result = transpile( circuit(), optimization_level=level, basis_gates=basis, coupling_map=coupling_map, seed_transpiler=42, initial_layout=[0, 1, 2, 3, 4], ) self.assertIsInstance(result, QuantumCircuit) resulting_basis = {node.name for node in circuit_to_dag(result).op_nodes()} self.assertIn("swap", resulting_basis) # Skipping optimization level 3 because the swap gates get absorbed into # a unitary block as part of the KAK decompostion optimization passes and # optimized away. @combine( level=[0, 1, 2], dsc="If swap in basis, do not decompose it. level: {level}", name="level{level}", ) def test_2(self, level): """Simple coupling map (linear 5 qubits). The circuit requires a swap and that swap should exit at the end for the transpilation""" basis = ["u1", "u2", "cx", "swap"] circuit = QuantumCircuit(5) circuit.cx(0, 4) circuit.cx(1, 4) circuit.cx(2, 4) circuit.cx(3, 4) coupling_map = CouplingMap([(0, 1), (1, 2), (2, 3), (3, 4)]) result = transpile( circuit, optimization_level=level, basis_gates=basis, coupling_map=coupling_map, seed_transpiler=421234242, ) self.assertIsInstance(result, QuantumCircuit) resulting_basis = {node.name for node in circuit_to_dag(result).op_nodes()} self.assertIn("swap", resulting_basis) @ddt class TestOptimizationWithCondition(QiskitTestCase): """Test optimization levels with condition in the circuit""" @data(0, 1, 2, 3) def test_optimization_condition(self, level): """Test optimization levels with condition in the circuit""" qr = QuantumRegister(2) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.cx(0, 1).c_if(cr, 1) backend = FakeJohannesburg() circ = transpile(qc, backend, optimization_level=level) self.assertIsInstance(circ, QuantumCircuit) def test_input_dag_copy(self): """Test substitute_node_with_dag input_dag copy on condition""" qc = QuantumCircuit(2, 1) qc.cx(0, 1).c_if(qc.cregs[0], 1) qc.cx(1, 0) circ = transpile(qc, basis_gates=["u3", "cz"]) self.assertIsInstance(circ, QuantumCircuit) @ddt class TestOptimizationOnSize(QiskitTestCase): """Test the optimization levels for optimization based on both size and depth of the circuit. See https://github.com/Qiskit/qiskit-terra/pull/7542 """ @data(2, 3) def test_size_optimization(self, level): """Test the levels for optimization based on size of circuit""" qc = QuantumCircuit(8) qc.cx(1, 2) qc.cx(2, 3) qc.cx(5, 4) qc.cx(6, 5) qc.cx(4, 5) qc.cx(3, 4) qc.cx(5, 6) qc.cx(5, 4) qc.cx(3, 4) qc.cx(2, 3) qc.cx(1, 2) qc.cx(6, 7) qc.cx(6, 5) qc.cx(5, 4) qc.cx(7, 6) qc.cx(6, 7) circ = transpile(qc, optimization_level=level).decompose() circ_data = circ.data free_qubits = {0, 1, 2, 3} # ensure no gates are using qubits - [0,1,2,3] for gate in circ_data: indices = {circ.find_bit(qubit).index for qubit in gate.qubits} common = indices.intersection(free_qubits) for common_qubit in common: self.assertTrue(common_qubit not in free_qubits) self.assertLess(circ.size(), qc.size()) self.assertLessEqual(circ.depth(), qc.depth()) @ddt class TestGeenratePresetPassManagers(QiskitTestCase): """Test generate_preset_pass_manager function.""" @data(0, 1, 2, 3) def test_with_backend(self, optimization_level): """Test a passmanager is constructed when only a backend and optimization level.""" target = FakeTokyo() pm = generate_preset_pass_manager(optimization_level, target) self.assertIsInstance(pm, PassManager) @data(0, 1, 2, 3) def test_with_no_backend(self, optimization_level): """Test a passmanager is constructed with no backend and optimization level.""" target = FakeLagosV2() pm = generate_preset_pass_manager( optimization_level, coupling_map=target.coupling_map, basis_gates=target.operation_names, inst_map=target.instruction_schedule_map, instruction_durations=target.instruction_durations, timing_constraints=target.target.timing_constraints(), target=target.target, ) self.assertIsInstance(pm, PassManager) @data(0, 1, 2, 3) def test_with_no_backend_only_target(self, optimization_level): """Test a passmanager is constructed with a manual target and optimization level.""" target = FakeLagosV2() pm = generate_preset_pass_manager(optimization_level, target=target.target) self.assertIsInstance(pm, PassManager) def test_invalid_optimization_level(self): """Assert we fail with an invalid optimization_level.""" with self.assertRaises(ValueError): generate_preset_pass_manager(42) @unittest.mock.patch.object( level2.PassManagerStagePluginManager, "get_passmanager_stage", wraps=mock_get_passmanager_stage, ) def test_backend_with_custom_stages_level2(self, _plugin_manager_mock): """Test generated preset pass manager includes backend specific custom stages.""" optimization_level = 2 class TargetBackend(FakeLagosV2): """Fake lagos subclass with custom transpiler stages.""" def get_scheduling_stage_plugin(self): """Custom scheduling stage.""" return "custom_stage_for_test" def get_translation_stage_plugin(self): """Custom post translation stage.""" return "custom_stage_for_test" target = TargetBackend() pm = generate_preset_pass_manager(optimization_level, backend=target) self.assertIsInstance(pm, PassManager) pass_list = [y.__class__.__name__ for x in pm.passes() for y in x["passes"]] self.assertIn("PadDynamicalDecoupling", pass_list) self.assertIn("ALAPScheduleAnalysis", pass_list) post_translation_pass_list = [ y.__class__.__name__ for x in pm.translation.passes() # pylint: disable=no-member for y in x["passes"] ] self.assertIn("RemoveResetInZeroState", post_translation_pass_list) @unittest.mock.patch.object( level1.PassManagerStagePluginManager, "get_passmanager_stage", wraps=mock_get_passmanager_stage, ) def test_backend_with_custom_stages_level1(self, _plugin_manager_mock): """Test generated preset pass manager includes backend specific custom stages.""" optimization_level = 1 class TargetBackend(FakeLagosV2): """Fake lagos subclass with custom transpiler stages.""" def get_scheduling_stage_plugin(self): """Custom scheduling stage.""" return "custom_stage_for_test" def get_translation_stage_plugin(self): """Custom post translation stage.""" return "custom_stage_for_test" target = TargetBackend() pm = generate_preset_pass_manager(optimization_level, backend=target) self.assertIsInstance(pm, PassManager) pass_list = [y.__class__.__name__ for x in pm.passes() for y in x["passes"]] self.assertIn("PadDynamicalDecoupling", pass_list) self.assertIn("ALAPScheduleAnalysis", pass_list) post_translation_pass_list = [ y.__class__.__name__ for x in pm.translation.passes() # pylint: disable=no-member for y in x["passes"] ] self.assertIn("RemoveResetInZeroState", post_translation_pass_list) @unittest.mock.patch.object( level3.PassManagerStagePluginManager, "get_passmanager_stage", wraps=mock_get_passmanager_stage, ) def test_backend_with_custom_stages_level3(self, _plugin_manager_mock): """Test generated preset pass manager includes backend specific custom stages.""" optimization_level = 3 class TargetBackend(FakeLagosV2): """Fake lagos subclass with custom transpiler stages.""" def get_scheduling_stage_plugin(self): """Custom scheduling stage.""" return "custom_stage_for_test" def get_translation_stage_plugin(self): """Custom post translation stage.""" return "custom_stage_for_test" target = TargetBackend() pm = generate_preset_pass_manager(optimization_level, backend=target) self.assertIsInstance(pm, PassManager) pass_list = [y.__class__.__name__ for x in pm.passes() for y in x["passes"]] self.assertIn("PadDynamicalDecoupling", pass_list) self.assertIn("ALAPScheduleAnalysis", pass_list) post_translation_pass_list = [ y.__class__.__name__ for x in pm.translation.passes() # pylint: disable=no-member for y in x["passes"] ] self.assertIn("RemoveResetInZeroState", post_translation_pass_list) @unittest.mock.patch.object( level0.PassManagerStagePluginManager, "get_passmanager_stage", wraps=mock_get_passmanager_stage, ) def test_backend_with_custom_stages_level0(self, _plugin_manager_mock): """Test generated preset pass manager includes backend specific custom stages.""" optimization_level = 0 class TargetBackend(FakeLagosV2): """Fake lagos subclass with custom transpiler stages.""" def get_scheduling_stage_plugin(self): """Custom scheduling stage.""" return "custom_stage_for_test" def get_translation_stage_plugin(self): """Custom post translation stage.""" return "custom_stage_for_test" target = TargetBackend() pm = generate_preset_pass_manager(optimization_level, backend=target) self.assertIsInstance(pm, PassManager) pass_list = [y.__class__.__name__ for x in pm.passes() for y in x["passes"]] self.assertIn("PadDynamicalDecoupling", pass_list) self.assertIn("ALAPScheduleAnalysis", pass_list) post_translation_pass_list = [ y.__class__.__name__ for x in pm.translation.passes() # pylint: disable=no-member for y in x["passes"] ] self.assertIn("RemoveResetInZeroState", post_translation_pass_list) @ddt class TestIntegrationControlFlow(QiskitTestCase): """Integration tests for control-flow circuits through the preset pass managers.""" @data(0, 1, 2, 3) def test_default_compilation(self, optimization_level): """Test that a simple circuit with each type of control-flow passes a full transpilation pipeline with the defaults.""" class CustomCX(Gate): """Custom CX""" def __init__(self): super().__init__("custom_cx", 2, []) def _define(self): self._definition = QuantumCircuit(2) self._definition.cx(0, 1) circuit = QuantumCircuit(6, 1) circuit.h(0) circuit.measure(0, 0) circuit.cx(0, 1) circuit.cz(0, 2) circuit.append(CustomCX(), [1, 2], []) with circuit.for_loop((1,)): circuit.cx(0, 1) circuit.cz(0, 2) circuit.append(CustomCX(), [1, 2], []) with circuit.if_test((circuit.clbits[0], True)) as else_: circuit.cx(0, 1) circuit.cz(0, 2) circuit.append(CustomCX(), [1, 2], []) with else_: circuit.cx(3, 4) circuit.cz(3, 5) circuit.append(CustomCX(), [4, 5], []) with circuit.while_loop((circuit.clbits[0], True)): circuit.cx(3, 4) circuit.cz(3, 5) circuit.append(CustomCX(), [4, 5], []) coupling_map = CouplingMap.from_line(6) transpiled = transpile( circuit, basis_gates=["sx", "rz", "cx", "if_else", "for_loop", "while_loop"], coupling_map=coupling_map, optimization_level=optimization_level, seed_transpiler=2022_10_04, ) # Tests of the complete validity of a circuit are mostly done at the indiviual pass level; # here we're just checking that various passes do appear to have run. self.assertIsInstance(transpiled, QuantumCircuit) # Assert layout ran. self.assertIsNot(getattr(transpiled, "_layout", None), None) def _visit_block(circuit, stack=None): """Assert that every block contains at least one swap to imply that routing has run.""" if stack is None: # List of (instruction_index, block_index). stack = () seen_cx = 0 for i, instruction in enumerate(circuit): if isinstance(instruction.operation, ControlFlowOp): for j, block in enumerate(instruction.operation.blocks): _visit_block(block, stack + ((i, j),)) elif isinstance(instruction.operation, CXGate): seen_cx += 1 # Assert unrolling ran. self.assertNotIsInstance(instruction.operation, CustomCX) # Assert translation ran. self.assertNotIsInstance(instruction.operation, CZGate) # There are three "natural" swaps in each block (one for each 2q operation), so if # routing ran, we should see more than that. self.assertGreater(seen_cx, 3, msg=f"no swaps in block at indices: {stack}") # Assert routing ran. _visit_block(transpiled) @data(0, 1, 2, 3) def test_allow_overriding_defaults(self, optimization_level): """Test that the method options can be overridden.""" circuit = QuantumCircuit(3, 1) circuit.h(0) circuit.measure(0, 0) with circuit.for_loop((1,)): circuit.h(0) circuit.cx(0, 1) circuit.cz(0, 2) circuit.cx(1, 2) coupling_map = CouplingMap.from_line(3) calls = set() def callback(pass_, **_): calls.add(pass_.name()) transpiled = transpile( circuit, basis_gates=["u3", "cx", "if_else", "for_loop", "while_loop"], layout_method="trivial", translation_method="unroller", coupling_map=coupling_map, optimization_level=optimization_level, seed_transpiler=2022_10_04, callback=callback, ) self.assertIsInstance(transpiled, QuantumCircuit) self.assertIsNot(getattr(transpiled, "_layout", None), None) self.assertIn("TrivialLayout", calls) self.assertIn("Unroller", calls) self.assertNotIn("DenseLayout", calls) self.assertNotIn("SabreLayout", calls) self.assertNotIn("BasisTranslator", calls) @data(0, 1, 2, 3) def test_invalid_methods_raise_on_control_flow(self, optimization_level): """Test that trying to use an invalid method with control flow fails.""" qc = QuantumCircuit(1) with qc.for_loop((1,)): qc.x(0) with self.assertRaisesRegex(TranspilerError, "Got routing_method="): transpile(qc, routing_method="lookahead", optimization_level=optimization_level) with self.assertRaisesRegex(TranspilerError, "Got scheduling_method="): transpile(qc, scheduling_method="alap", optimization_level=optimization_level) @data(0, 1, 2, 3) def test_unsupported_basis_gates_raise(self, optimization_level): """Test that trying to transpile a control-flow circuit for a backend that doesn't support the necessary operations in its `basis_gates` will raise a sensible error.""" backend = FakeTokyo() qc = QuantumCircuit(1, 1) with qc.for_loop((0,)): pass with self.assertRaisesRegex(TranspilerError, "The control-flow construct.*not supported"): transpile(qc, backend, optimization_level=optimization_level) qc = QuantumCircuit(1, 1) with qc.if_test((qc.clbits[0], False)): pass with self.assertRaisesRegex(TranspilerError, "The control-flow construct.*not supported"): transpile(qc, backend, optimization_level=optimization_level) qc = QuantumCircuit(1, 1) with qc.while_loop((qc.clbits[0], False)): pass with qc.for_loop((0, 1, 2)): pass with self.assertRaisesRegex(TranspilerError, "The control-flow construct.*not supported"): transpile(qc, backend, optimization_level=optimization_level) @data(0, 1, 2, 3) def test_unsupported_targets_raise(self, optimization_level): """Test that trying to transpile a control-flow circuit for a backend that doesn't support the necessary operations in its `Target` will raise a more sensible error.""" target = Target(num_qubits=2) target.add_instruction(CXGate(), {(0, 1): None}) qc = QuantumCircuit(1, 1) with qc.for_loop((0,)): pass with self.assertRaisesRegex(TranspilerError, "The control-flow construct.*not supported"): transpile(qc, target=target, optimization_level=optimization_level) qc = QuantumCircuit(1, 1) with qc.if_test((qc.clbits[0], False)): pass with self.assertRaisesRegex(TranspilerError, "The control-flow construct.*not supported"): transpile(qc, target=target, optimization_level=optimization_level) qc = QuantumCircuit(1, 1) with qc.while_loop((qc.clbits[0], False)): pass with qc.for_loop((0, 1, 2)): pass with self.assertRaisesRegex(TranspilerError, "The control-flow construct.*not supported"): transpile(qc, target=target, optimization_level=optimization_level)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse dc = pulse.DriveChannel d0, d1, d2, d3, d4 = dc(0), dc(1), dc(2), dc(3), dc(4) with pulse.build(name='pulse_programming_in') as pulse_prog: pulse.play([1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], d0) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d1) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], d2) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d3) pulse.play([1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0], d4) pulse_prog.draw()
https://github.com/Qubico-Hack/tutorials
Qubico-Hack
import matplotlib.pyplot as plt import numpy as np from IPython.display import clear_output !pip install qiskit[all] from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap !pip install qiskit_algorithms from qiskit_algorithms.optimizers import COBYLA,L_BFGS_B from qiskit_algorithms.utils import algorithm_globals !pip install qiskit_machine_learning from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier, VQC from qiskit_machine_learning.algorithms.regressors import NeuralNetworkRegressor, VQR from qiskit_machine_learning.neural_networks import SamplerQNN, EstimatorQNN from qiskit_machine_learning.circuit.library import QNNCircuit algorithm_globals.random_seed = 42 num_inputs = 2 num_samples = 20 X = 2 * algorithm_globals.random.random([num_samples, num_inputs]) - 1 y01 = 1 * (np.sum(X, axis=1) >= 0) # in { 0, 1} y = 2 * y01 - 1 # in {-1, +1} y_one_hot = np.zeros((num_samples, 2)) for i in range(num_samples): y_one_hot[i, y01[i]] = 1 for x, y_target in zip(X, y): if y_target == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() # construct QNN with the QNNCircuit's default ZZFeatureMap feature map and RealAmplitudes ansatz. qc = QNNCircuit(num_qubits=2) qc.draw(output="mpl") estimator_qnn = EstimatorQNN(circuit=qc) # QNN maps inputs to [-1, +1] estimator_qnn.forward(X[0, :], algorithm_globals.random.random(estimator_qnn.num_weights)) # callback function that draws a live plot when the .fit() method is called def callback_graph(weights, obj_func_eval): clear_output(wait=True) objective_func_vals.append(obj_func_eval) plt.title("Objective function value against iteration") plt.xlabel("Iteration") plt.ylabel("Objective function value") plt.plot(range(len(objective_func_vals)), objective_func_vals) plt.show() # construct neural network classifier estimator_classifier = NeuralNetworkClassifier( estimator_qnn, optimizer=COBYLA(maxiter=60), callback=callback_graph ) # create empty array for callback to store evaluations of the objective function objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit classifier to data estimator_classifier.fit(X, y) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score classifier estimator_classifier.score(X, y) # evaluate data points y_predict = estimator_classifier.predict(X) # plot results # red == wrongly classified for x, y_target, y_p in zip(X, y, y_predict): if y_target == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") if y_target != y_p: plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2) plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() estimator_classifier.weights # construct a quantum circuit from the default ZZFeatureMap feature map and a customized RealAmplitudes ansatz qc = QNNCircuit(ansatz=RealAmplitudes(num_inputs, reps=1)) qc.draw(output="mpl") # parity maps bitstrings to 0 or 1 def parity(x): return "{:b}".format(x).count("1") % 2 output_shape = 2 # corresponds to the number of classes, possible outcomes of the (parity) mapping. # construct QNN sampler_qnn = SamplerQNN( circuit=qc, interpret=parity, output_shape=output_shape, ) # construct classifier sampler_classifier = NeuralNetworkClassifier( neural_network=sampler_qnn, optimizer=COBYLA(maxiter=30), callback=callback_graph ) # create empty array for callback to store evaluations of the objective function objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit classifier to data sampler_classifier.fit(X, y01) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score classifier sampler_classifier.score(X, y01) # evaluate data points y_predict = sampler_classifier.predict(X) # plot results # red == wrongly classified for x, y_target, y_p in zip(X, y01, y_predict): if y_target == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") if y_target != y_p: plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2) plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() sampler_classifier.weights # construct feature map, ansatz, and optimizer feature_map = ZZFeatureMap(num_inputs) ansatz = RealAmplitudes(num_inputs, reps=1) # construct variational quantum classifier vqc = VQC( feature_map=feature_map, ansatz=ansatz, loss="cross_entropy", optimizer=COBYLA(maxiter=30), callback=callback_graph, ) # create empty array for callback to store evaluations of the objective function objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit classifier to data vqc.fit(X, y_one_hot) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score classifier vqc.score(X, y_one_hot) # evaluate data points y_predict = vqc.predict(X) # plot results # red == wrongly classified for x, y_target, y_p in zip(X, y_one_hot, y_predict): if y_target[0] == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") if not np.all(y_target == y_p): plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2) plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() from sklearn.datasets import make_classification from sklearn.preprocessing import MinMaxScaler X, y = make_classification( n_samples=10, n_features=2, n_classes=3, n_redundant=0, n_clusters_per_class=1, class_sep=2.0, random_state=algorithm_globals.random_seed, ) X = MinMaxScaler().fit_transform(X) plt.scatter(X[:, 0], X[:, 1], c=y) y_cat = np.empty(y.shape, dtype=str) y_cat[y == 0] = "A" y_cat[y == 1] = "B" y_cat[y == 2] = "C" print(y_cat) vqc = VQC( num_qubits=2, optimizer=COBYLA(maxiter=30), callback=callback_graph, ) # create empty array for callback to store evaluations of the objective function objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit classifier to data vqc.fit(X, y_cat) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score classifier vqc.score(X, y_cat) predict = vqc.predict(X) print(f"Predicted labels: {predict}") print(f"Ground truth: {y_cat}") num_samples = 20 eps = 0.2 lb, ub = -np.pi, np.pi X_ = np.linspace(lb, ub, num=50).reshape(50, 1) f = lambda x: np.sin(x) X = (ub - lb) * algorithm_globals.random.random([num_samples, 1]) + lb y = f(X[:, 0]) + eps * (2 * algorithm_globals.random.random(num_samples) - 1) plt.plot(X_, f(X_), "r--") plt.plot(X, y, "bo") plt.show() # construct simple feature map param_x = Parameter("x") feature_map = QuantumCircuit(1, name="fm") feature_map.ry(param_x, 0) # construct simple ansatz param_y = Parameter("y") ansatz = QuantumCircuit(1, name="vf") ansatz.ry(param_y, 0) # construct a circuit qc = QNNCircuit(feature_map=feature_map, ansatz=ansatz) # construct QNN regression_estimator_qnn = EstimatorQNN(circuit=qc) # construct the regressor from the neural network regressor = NeuralNetworkRegressor( neural_network=regression_estimator_qnn, loss="squared_error", optimizer=L_BFGS_B(maxiter=5), callback=callback_graph, ) # create empty array for callback to store evaluations of the objective function objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit to data regressor.fit(X, y) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score the result regressor.score(X, y) # plot target function plt.plot(X_, f(X_), "r--") # plot data plt.plot(X, y, "bo") # plot fitted line y_ = regressor.predict(X_) plt.plot(X_, y_, "g-") plt.show() regressor.weights vqr = VQR( feature_map=feature_map, ansatz=ansatz, optimizer=L_BFGS_B(maxiter=5), callback=callback_graph, ) # create empty array for callback to store evaluations of the objective function objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit regressor vqr.fit(X, y) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score result vqr.score(X, y) # plot target function plt.plot(X_, f(X_), "r--") # plot data plt.plot(X, y, "bo") # plot fitted line y_ = vqr.predict(X_) plt.plot(X_, y_, "g-") plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/renatawong/classical-shadow-vqe
renatawong
# Installation of the requirements #!python -m pip install -r requirements.txt ''' (C) Renata Wong 2023 Qiskit code for testing fidelity of derandomised classical shadow on the ground state energy of molecules. Procedure: 1. Derandomize the molecule-in-question's Hamiltonian. 2. Choose a variational ansatz with initial parameters selected at random. 3. Apply the derandomized Hamiltonian as basis change operators to the ansatz. 4. Measure the ansatz in the Pauli Z basis and store the results as a shadow. 5. Obtain the expectation value of the molecular Hamiltonian from the shadow. 6. Optimize for minimum Hamiltonian expectation value. 7. Feed the calculated angles/parameters back to the ansatz. 8. Repeat steps 3-7 till the optimization is completed. 9. Output the minimized expectation value of the molecular Hamiltonian and the mean-square-root-error. Note: Below we perform calculations on the molecular Hamiltonian of H_2. To perform calculations on other molecules, you will need to specify their geometry, charge and spin to replace the values in the driver. Note: predicting_quantum_properties module comes from https://github.com/hsinyuan-huang/predicting-quantum-properties ''' from qiskit import QuantumCircuit, execute from qiskit_aer import QasmSimulator from qiskit_nature.units import DistanceUnit from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.mappers import BravyiKitaevMapper from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.algorithms import GroundStateEigensolver from qiskit.circuit.library import EfficientSU2 from qiskit.algorithms.optimizers import SLSQP, COBYLA, SPSA import time import numpy as np from functools import partial import matplotlib.pyplot as plt from collections import Counter from predicting_quantum_properties.prediction_shadow import estimate_exp from modified_derandomization import modified_derandomized_classical_shadow # handle deprecation issues import qiskit_nature qiskit_nature.settings.use_pauli_sum_op = False import h5py H5PY_DEFAULT_READONLY=1 # classically obtained ground state energy EXPECTED_EIGENVALUE = -1.86 # specifying the geometry of the molecule in question driver = PySCFDriver( atom="H 0 0 0; H 0 0 0.735", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) problem = driver.run() hamiltonian = problem.hamiltonian # electronic Hamiltonian of the system second_q_op = hamiltonian.second_q_op() # The Bravyi-Kitaev repserentation of the Fermionic Hamiltonian mapper = BravyiKitaevMapper() bkencoded_hamiltonian = mapper.map(second_q_op) print(bkencoded_hamiltonian) def process_hamiltonian(hamiltonian, derandomize = False): hamiltonian_observables = [] hamiltonian_coefficients = [] for observable in hamiltonian.paulis: op_list = [] for op_index, pauli_op in enumerate(observable): pauli_op = str(pauli_op) if pauli_op == 'I' or pauli_op == 'X' or pauli_op == 'Y' or pauli_op == 'Z': op_list.append((pauli_op, op_index)) hamiltonian_observables.append(op_list) hamiltonian_coefficients = hamiltonian.coeffs.real system_size = len(hamiltonian_observables[0]) # removing all occurrences of Pauli-I, for all-Pauli-I there is an empty list left # these observables are needed for estimate_exp() observables_xyze = [] for observable in hamiltonian_observables: XYZE = [] for pauli in observable: if pauli[0] != 'I': XYZE.append(pauli) observables_xyze.append(XYZE) # derandomisation procedure requires that coefficients are non-negative if derandomize == True: absolute_coefficients = [abs(coeffcient) for coeffcient in hamiltonian_coefficients] # removing the empty list as well # these observables are needed for derandomisation procedure observables_xyz = [] for idx, observable in enumerate(observables_xyze): if observable: observables_xyz.append(observable) else: absolute_coefficients.pop(idx) return system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients return system_size, observables_xyze, hamiltonian_coefficients # process the Hamiltonian to obtain properly formatted data hamiltonian_data = process_hamiltonian(bkencoded_hamiltonian, derandomize = True) system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients = hamiltonian_data #print('HAMILTONIAN\n', observables_xyze) ''' VARIATIONAL ANSATZ Note that for molecules other than H_2 you may need to specify a different number of reps. ''' reps = 1 ansatz = EfficientSU2(system_size, su2_gates=['rx', 'ry'], entanglement='circular', reps=reps, skip_final_rotation_layer=False) ansatz.decompose().draw('mpl') ''' COST FUNCTION ''' def basis_change_circuit(pauli_op): # Generating circuit with just the basis change operators # # pauli_op: n-qubit Pauli operator basis_change = QuantumCircuit(ansatz.num_qubits, ansatz.num_qubits) for idx, op in enumerate(pauli_op): if op == 'X': basis_change.h(idx) elif op == 'Y': basis_change.h(idx) basis_change.p(-np.pi/2, idx) return basis_change def min_cost(): return min(cost_history) def log_cost(cost): global cost_history cost_history.append(cost) def objective_function(operators, params): backend = QasmSimulator(method='statevector', shots=1) pauli_op_dict = Counter(tuple(x) for x in operators) shadow = [] for pauli_op in pauli_op_dict: qc = ansatz.bind_parameters(params) qc = qc.compose(basis_change_circuit(pauli_op)) qc.measure(reversed(range(system_size)), range(system_size)) result = execute(qc, backend, shots=pauli_op_dict[pauli_op]).result() counts = result.get_counts() # generate a separate circuit for each basis change Pauli operator output_str = list(list(counts.keys())[list(counts.values()).index(1)]) output = [int(i) for i in output_str] eigenvals = [x+1 if x == 0 else x-2 for x in output] snapshot = [(op, eigenval) for op, eigenval in zip(pauli_op, eigenvals)] shadow.append(snapshot) cost = 0.0 for term, weight in zip(observables_xyze, hamiltonian_coefficients): sum_product, match_count = estimate_exp(shadow, term) if match_count != 0: exp_val = sum_product / match_count cost += weight * exp_val log_cost(cost) return cost ''' RUNNING EXPERIMENTS ''' start_time = time.time() rmse_errors = [] print('NUMBER OF OPERATORS | DERANDOMISED OPERATORS | AVERAGE RMSE ERROR\n') measurement_range = [50, 100, 200, 600, 1000, 1600] for num_operators in measurement_range: derandomized_hamiltonian = modified_derandomized_classical_shadow(observables_xyz, num_operators, system_size, weight=absolute_coefficients) tuples = (tuple(pauli) for pauli in derandomized_hamiltonian) counts = Counter(tuples) optimizer = SPSA(maxiter=2000) cost_function = partial(objective_function, derandomized_hamiltonian) expectation_values = [] num_experiments = 5 for iteration in range(num_experiments): cost_history = [] params = np.random.rand(ansatz.num_parameters) result = optimizer.minimize(fun=cost_function, x0=params) minimal_cost = min_cost() expectation_values.append(minimal_cost) print("EXPERIMENT {}: GROUND STATE ENERGY FOUND = {}".format(iteration, minimal_cost)) rmse_derandomised_cs = np.sqrt(np.sum([(expectation_values[i] - EXPECTED_EIGENVALUE)**2 for i in range(num_experiments)])/num_experiments) rmse_errors.append(rmse_derandomised_cs) print('{} | {} | {}'.format(num_operators, counts, rmse_derandomised_cs)) elapsed_time = time.time() - start_time print("Execution time = ", time.strftime("%H:%M:%S", time.gmtime(elapsed_time))) points = measurement_range num_points = len(measurement_range) plt.plot([i for i in points], [rmse_errors[i] for i in range(num_points)], 'r', label='SPSA(maxiter=2000)') plt.xlabel('Number of measurements') plt.ylabel('Average RMSE error') plt.legend(loc=1) ''' Above we have assumed a particular ground state energy for the molecule of interest. Below we corroborate this assumption using a classical minimum eigensolver on our Hamiltonian. ''' converter = BravyiKitaevMapper() numpy_solver = NumPyMinimumEigensolver() calc = GroundStateEigensolver(converter, numpy_solver) res = calc.solve(problem) print('Electronic ground state energy:\n', res)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import json import time import warnings import matplotlib.pyplot as plt import numpy as np from IPython.display import clear_output from qiskit import ClassicalRegister, QuantumRegister from qiskit import QuantumCircuit from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import RealAmplitudes from qiskit.quantum_info import Statevector from qiskit.utils import algorithm_globals from qiskit_machine_learning.circuit.library import RawFeatureVector from qiskit_machine_learning.neural_networks import SamplerQNN algorithm_globals.random_seed = 42 def ansatz(num_qubits): return RealAmplitudes(num_qubits, reps=5) num_qubits = 5 circ = ansatz(num_qubits) circ.decompose().draw("mpl") def auto_encoder_circuit(num_latent, num_trash): qr = QuantumRegister(num_latent + 2 * num_trash + 1, "q") cr = ClassicalRegister(1, "c") circuit = QuantumCircuit(qr, cr) circuit.compose(ansatz(num_latent + num_trash), range(0, num_latent + num_trash), inplace=True) circuit.barrier() auxiliary_qubit = num_latent + 2 * num_trash # swap test circuit.h(auxiliary_qubit) for i in range(num_trash): circuit.cswap(auxiliary_qubit, num_latent + i, num_latent + num_trash + i) circuit.h(auxiliary_qubit) circuit.measure(auxiliary_qubit, cr[0]) return circuit num_latent = 3 num_trash = 2 circuit = auto_encoder_circuit(num_latent, num_trash) circuit.draw("mpl") def domain_wall(circuit, a, b): # Here we place the Domain Wall to qubits a - b in our circuit for i in np.arange(int(b / 2), int(b)): circuit.x(i) return circuit domain_wall_circuit = domain_wall(QuantumCircuit(5), 0, 5) domain_wall_circuit.draw("mpl") ae = auto_encoder_circuit(num_latent, num_trash) qc = QuantumCircuit(num_latent + 2 * num_trash + 1, 1) qc = qc.compose(domain_wall_circuit, range(num_latent + num_trash)) qc = qc.compose(ae) qc.draw("mpl") # Here we define our interpret for our SamplerQNN def identity_interpret(x): return x qnn = SamplerQNN( circuit=qc, input_params=[], weight_params=ae.parameters, interpret=identity_interpret, output_shape=2, ) def cost_func_domain(params_values): probabilities = qnn.forward([], params_values) # we pick a probability of getting 1 as the output of the network cost = np.sum(probabilities[:, 1]) # plotting part clear_output(wait=True) objective_func_vals.append(cost) plt.title("Objective function value against iteration") plt.xlabel("Iteration") plt.ylabel("Objective function value") plt.plot(range(len(objective_func_vals)), objective_func_vals) plt.show() return cost opt = COBYLA(maxiter=150) initial_point = algorithm_globals.random.random(ae.num_parameters) objective_func_vals = [] # make the plot nicer plt.rcParams["figure.figsize"] = (12, 6) start = time.time() opt_result = opt.minimize(cost_func_domain, initial_point) elapsed = time.time() - start print(f"Fit in {elapsed:0.2f} seconds") test_qc = QuantumCircuit(num_latent + num_trash) test_qc = test_qc.compose(domain_wall_circuit) ansatz_qc = ansatz(num_latent + num_trash) test_qc = test_qc.compose(ansatz_qc) test_qc.barrier() test_qc.reset(4) test_qc.reset(3) test_qc.barrier() test_qc = test_qc.compose(ansatz_qc.inverse()) test_qc.draw("mpl") test_qc = test_qc.assign_parameters(opt_result.x) domain_wall_state = Statevector(domain_wall_circuit).data output_state = Statevector(test_qc).data fidelity = np.sqrt(np.dot(domain_wall_state.conj(), output_state) ** 2) print("Fidelity of our Output State with our Input State: ", fidelity.real) def zero_idx(j, i): # Index for zero pixels return [ [i, j], [i - 1, j - 1], [i - 1, j + 1], [i - 2, j - 1], [i - 2, j + 1], [i - 3, j - 1], [i - 3, j + 1], [i - 4, j - 1], [i - 4, j + 1], [i - 5, j], ] def one_idx(i, j): # Index for one pixels return [[i, j - 1], [i, j - 2], [i, j - 3], [i, j - 4], [i, j - 5], [i - 1, j - 4], [i, j]] def get_dataset_digits(num, draw=True): # Create Dataset containing zero and one train_images = [] train_labels = [] for i in range(int(num / 2)): # First we introduce background noise empty = np.array([algorithm_globals.random.uniform(0, 0.1) for i in range(32)]).reshape( 8, 4 ) # Now we insert the pixels for the one for i, j in one_idx(2, 6): empty[j][i] = algorithm_globals.random.uniform(0.9, 1) train_images.append(empty) train_labels.append(1) if draw: plt.title("This is a One") plt.imshow(train_images[-1]) plt.show() for i in range(int(num / 2)): empty = np.array([algorithm_globals.random.uniform(0, 0.1) for i in range(32)]).reshape( 8, 4 ) # Now we insert the pixels for the zero for k, j in zero_idx(2, 6): empty[k][j] = algorithm_globals.random.uniform(0.9, 1) train_images.append(empty) train_labels.append(0) if draw: plt.imshow(train_images[-1]) plt.title("This is a Zero") plt.show() train_images = np.array(train_images) train_images = train_images.reshape(len(train_images), 32) for i in range(len(train_images)): sum_sq = np.sum(train_images[i] ** 2) train_images[i] = train_images[i] / np.sqrt(sum_sq) return train_images, train_labels train_images, __ = get_dataset_digits(2) num_latent = 3 num_trash = 2 fm = RawFeatureVector(2 ** (num_latent + num_trash)) ae = auto_encoder_circuit(num_latent, num_trash) qc = QuantumCircuit(num_latent + 2 * num_trash + 1, 1) qc = qc.compose(fm, range(num_latent + num_trash)) qc = qc.compose(ae) qc.draw("mpl") def identity_interpret(x): return x qnn = SamplerQNN( circuit=qc, input_params=fm.parameters, weight_params=ae.parameters, interpret=identity_interpret, output_shape=2, ) def cost_func_digits(params_values): probabilities = qnn.forward(train_images, params_values) cost = np.sum(probabilities[:, 1]) / train_images.shape[0] # plotting part clear_output(wait=True) objective_func_vals.append(cost) plt.title("Objective function value against iteration") plt.xlabel("Iteration") plt.ylabel("Objective function value") plt.plot(range(len(objective_func_vals)), objective_func_vals) plt.show() return cost with open("12_qae_initial_point.json", "r") as f: initial_point = json.load(f) opt = COBYLA(maxiter=150) objective_func_vals = [] # make the plot nicer plt.rcParams["figure.figsize"] = (12, 6) start = time.time() opt_result = opt.minimize(fun=cost_func_digits, x0=initial_point) elapsed = time.time() - start print(f"Fit in {elapsed:0.2f} seconds") # Test test_qc = QuantumCircuit(num_latent + num_trash) test_qc = test_qc.compose(fm) ansatz_qc = ansatz(num_latent + num_trash) test_qc = test_qc.compose(ansatz_qc) test_qc.barrier() test_qc.reset(4) test_qc.reset(3) test_qc.barrier() test_qc = test_qc.compose(ansatz_qc.inverse()) # sample new images test_images, test_labels = get_dataset_digits(2, draw=False) for image, label in zip(test_images, test_labels): original_qc = fm.assign_parameters(image) original_sv = Statevector(original_qc).data original_sv = np.reshape(np.abs(original_sv) ** 2, (8, 4)) param_values = np.concatenate((image, opt_result.x)) output_qc = test_qc.assign_parameters(param_values) output_sv = Statevector(output_qc).data output_sv = np.reshape(np.abs(output_sv) ** 2, (8, 4)) fig, (ax1, ax2) = plt.subplots(1, 2) ax1.imshow(original_sv) ax1.set_title("Input Data") ax2.imshow(output_sv) ax2.set_title("Output Data") plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/matteoacrossi/oqs-jupyterbook
matteoacrossi
# imports import numpy as np from qiskit import QuantumRegister, QuantumCircuit #################################### # Depolarizing channel on IBMQX2 # #################################### # Quantum register q = QuantumRegister(4, name="q") # Quantum circuit depolarizing = QuantumCircuit(q) # Depolarizing channel acting on q_2 ## Qubit identification system = 0 a_0 = 1 a_1 = 2 a_2 = 3 ## Define rotation angle theta = 0.0 ## Construct circuit depolarizing.ry(theta, q[a_0]) depolarizing.ry(theta, q[a_1]) depolarizing.ry(theta, q[a_2]) depolarizing.cx(q[a_0], q[system]) depolarizing.cy(q[a_1], q[system]) depolarizing.cz(q[a_2], q[system]) # Draw circuit depolarizing.draw(output='mpl') def depolarizing_channel(q, p, system, ancillae): """Returns a QuantumCircuit implementing depolarizing channel on q[system] Args: q (QuantumRegister): the register to use for the circuit p (float): the probability for the channel between 0 and 1 system (int): index of the system qubit ancillae (list): list of indices for the ancillary qubits Returns: A QuantumCircuit object """ # Write the code here... # Let's fix the quantum register and the qubit assignments # We create the quantum circuit q = QuantumRegister(5, name='q') # Index of the system qubit system = 2 # Indices of the ancillary qubits ancillae = [1, 3, 4] # For example, let's consider 10 equally spaced values of p p_values = np.linspace(0, 1, 10)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse dc = pulse.DriveChannel d0, d1, d2, d3, d4 = dc(0), dc(1), dc(2), dc(3), dc(4) with pulse.build(name='pulse_programming_in') as pulse_prog: pulse.play([1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], d0) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d1) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], d2) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d3) pulse.play([1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0], d4) pulse_prog.draw()
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test functionality to collect, split and consolidate blocks from DAGCircuits.""" import unittest from qiskit import QuantumRegister, ClassicalRegister from qiskit.converters import ( circuit_to_dag, circuit_to_dagdependency, circuit_to_instruction, dag_to_circuit, dagdependency_to_circuit, ) from qiskit.test import QiskitTestCase from qiskit.circuit import QuantumCircuit, Measure, Clbit from qiskit.dagcircuit.collect_blocks import BlockCollector, BlockSplitter, BlockCollapser class TestCollectBlocks(QiskitTestCase): """Tests to verify correctness of collecting, splitting, and consolidating blocks from DAGCircuit and DAGDependency. Additional tests appear as a part of CollectLinearFunctions and CollectCliffords passes. """ def test_collect_gates_from_dagcircuit_1(self): """Test collecting CX gates from DAGCircuits.""" qc = QuantumCircuit(5) qc.cx(0, 1) qc.cx(0, 2) qc.z(0) qc.cx(0, 3) qc.cx(0, 4) block_collector = BlockCollector(circuit_to_dag(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name == "cx", split_blocks=False, min_block_size=2, ) # The middle z-gate leads to two blocks of size 2 each self.assertEqual(len(blocks), 2) self.assertEqual(len(blocks[0]), 2) self.assertEqual(len(blocks[1]), 2) def test_collect_gates_from_dagcircuit_2(self): """Test collecting both CX and Z gates from DAGCircuits.""" qc = QuantumCircuit(5) qc.cx(0, 1) qc.cx(0, 2) qc.z(0) qc.cx(0, 3) qc.cx(0, 4) block_collector = BlockCollector(circuit_to_dag(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "z"], split_blocks=False, min_block_size=1, ) # All of the gates are part of a single block self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 5) def test_collect_gates_from_dagcircuit_3(self): """Test collecting CX gates from DAGCircuits.""" qc = QuantumCircuit(5) qc.cx(0, 1) qc.cx(0, 2) qc.z(0) qc.cx(1, 3) qc.cx(0, 3) qc.cx(0, 4) block_collector = BlockCollector(circuit_to_dag(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx"], split_blocks=False, min_block_size=1, ) # We should end up with two CX blocks: even though there is "a path # around z(0)", without commutativity analysis z(0) prevents from # including all CX-gates into the same block self.assertEqual(len(blocks), 2) def test_collect_gates_from_dagdependency_1(self): """Test collecting CX gates from DAGDependency.""" qc = QuantumCircuit(5) qc.cx(0, 1) qc.cx(0, 2) qc.z(0) qc.cx(0, 3) qc.cx(0, 4) block_collector = BlockCollector(circuit_to_dagdependency(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1, ) # The middle z-gate commutes with CX-gates, which leads to a single block of length 4 self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 4) def test_collect_gates_from_dagdependency_2(self): """Test collecting both CX and Z gates from DAGDependency.""" qc = QuantumCircuit(5) qc.cx(0, 1) qc.cx(0, 2) qc.z(0) qc.cx(0, 3) qc.cx(0, 4) block_collector = BlockCollector(circuit_to_dagdependency(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "z"], split_blocks=False, min_block_size=1, ) # All the gates are part of a single block self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 5) def test_collect_and_split_gates_from_dagcircuit(self): """Test collecting and splitting blocks from DAGCircuit.""" qc = QuantumCircuit(6) qc.cx(0, 1) qc.cx(3, 5) qc.cx(2, 4) qc.swap(1, 0) qc.cz(5, 3) block_collector = BlockCollector(circuit_to_dag(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: True, split_blocks=False, min_block_size=1, ) # All the gates are part of a single block self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 5) # Split the first block into sub-blocks over disjoint qubit sets # We should get 3 sub-blocks split_blocks = BlockSplitter().run(blocks[0]) self.assertEqual(len(split_blocks), 3) def test_collect_and_split_gates_from_dagdependency(self): """Test collecting and splitting blocks from DAGDependecy.""" qc = QuantumCircuit(6) qc.cx(0, 1) qc.cx(3, 5) qc.cx(2, 4) qc.swap(1, 0) qc.cz(5, 3) block_collector = BlockCollector(circuit_to_dagdependency(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: True, split_blocks=False, min_block_size=1, ) # All the gates are part of a single block self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 5) # Split the first block into sub-blocks over disjoint qubit sets # We should get 3 sub-blocks split_blocks = BlockSplitter().run(blocks[0]) self.assertEqual(len(split_blocks), 3) def test_circuit_has_measure(self): """Test that block collection works properly when there is a measure in the middle of the circuit.""" qc = QuantumCircuit(2, 1) qc.cx(1, 0) qc.x(0) qc.x(1) qc.measure(0, 0) qc.x(0) qc.cx(1, 0) block_collector = BlockCollector(circuit_to_dag(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["x", "cx"], split_blocks=False, min_block_size=1, ) # measure prevents combining the two blocks self.assertEqual(len(blocks), 2) self.assertEqual(len(blocks[0]), 3) self.assertEqual(len(blocks[1]), 2) def test_circuit_has_measure_dagdependency(self): """Test that block collection works properly when there is a measure in the middle of the circuit.""" qc = QuantumCircuit(2, 1) qc.cx(1, 0) qc.x(0) qc.x(1) qc.measure(0, 0) qc.x(0) qc.cx(1, 0) block_collector = BlockCollector(circuit_to_dagdependency(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["x", "cx"], split_blocks=False, min_block_size=1, ) # measure prevents combining the two blocks self.assertEqual(len(blocks), 2) self.assertEqual(len(blocks[0]), 3) self.assertEqual(len(blocks[1]), 2) def test_circuit_has_conditional_gates(self): """Test that block collection works properly when there the circuit contains conditional gates.""" qc = QuantumCircuit(2, 1) qc.x(0) qc.x(1) qc.cx(1, 0) qc.x(1).c_if(0, 1) qc.x(0) qc.x(1) qc.cx(0, 1) # If the filter_function does not look at conditions, we should collect all # gates into the block. block_collector = BlockCollector(circuit_to_dag(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["x", "cx"], split_blocks=False, min_block_size=1, ) self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 7) # If the filter_function does look at conditions, we should not collect the middle # conditional gate (note that x(1) following the measure is collected into the first # block). block_collector = BlockCollector(circuit_to_dag(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["x", "cx"] and not getattr(node.op, "condition", None), split_blocks=False, min_block_size=1, ) self.assertEqual(len(blocks), 2) self.assertEqual(len(blocks[0]), 4) self.assertEqual(len(blocks[1]), 2) def test_circuit_has_conditional_gates_dagdependency(self): """Test that block collection works properly when there the circuit contains conditional gates.""" qc = QuantumCircuit(2, 1) qc.x(0) qc.x(1) qc.cx(1, 0) qc.x(1).c_if(0, 1) qc.x(0) qc.x(1) qc.cx(0, 1) # If the filter_function does not look at conditions, we should collect all # gates into the block. block_collector = BlockCollector(circuit_to_dagdependency(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["x", "cx"], split_blocks=False, min_block_size=1, ) self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 7) # If the filter_function does look at conditions, we should not collect the middle # conditional gate (note that x(1) following the measure is collected into the first # block). block_collector = BlockCollector(circuit_to_dag(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["x", "cx"] and not getattr(node.op, "condition", None), split_blocks=False, min_block_size=1, ) self.assertEqual(len(blocks), 2) self.assertEqual(len(blocks[0]), 4) self.assertEqual(len(blocks[1]), 2) def test_multiple_collection_methods(self): """Test that block collection allows to collect blocks using several different filter functions.""" qc = QuantumCircuit(5) qc.cx(0, 1) qc.cx(0, 2) qc.swap(1, 4) qc.swap(4, 3) qc.z(0) qc.z(1) qc.z(2) qc.z(3) qc.z(4) qc.swap(3, 4) qc.cx(0, 3) qc.cx(0, 4) block_collector = BlockCollector(circuit_to_dag(qc)) linear_blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "swap"], split_blocks=False, min_block_size=1, ) cx_blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx"], split_blocks=False, min_block_size=1, ) swapz_blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["swap", "z"], split_blocks=False, min_block_size=1, ) # We should end up with two linear blocks self.assertEqual(len(linear_blocks), 2) self.assertEqual(len(linear_blocks[0]), 4) self.assertEqual(len(linear_blocks[1]), 3) # We should end up with two cx blocks self.assertEqual(len(cx_blocks), 2) self.assertEqual(len(cx_blocks[0]), 2) self.assertEqual(len(cx_blocks[1]), 2) # We should end up with one swap,z blocks self.assertEqual(len(swapz_blocks), 1) self.assertEqual(len(swapz_blocks[0]), 8) def test_min_block_size(self): """Test that the option min_block_size for collecting blocks works correctly.""" # original circuit circuit = QuantumCircuit(2) circuit.cx(0, 1) circuit.h(0) circuit.cx(0, 1) circuit.cx(1, 0) circuit.h(0) circuit.cx(0, 1) circuit.cx(1, 0) circuit.cx(0, 1) block_collector = BlockCollector(circuit_to_dag(circuit)) # When min_block_size = 1, we should obtain 3 linear blocks blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "swap"], split_blocks=False, min_block_size=1, ) self.assertEqual(len(blocks), 3) # When min_block_size = 2, we should obtain 2 linear blocks blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "swap"], split_blocks=False, min_block_size=2, ) self.assertEqual(len(blocks), 2) # When min_block_size = 3, we should obtain 1 linear block blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "swap"], split_blocks=False, min_block_size=3, ) self.assertEqual(len(blocks), 1) # When min_block_size = 4, we should obtain no linear blocks blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "swap"], split_blocks=False, min_block_size=4, ) self.assertEqual(len(blocks), 0) def test_split_blocks(self): """Test that splitting blocks of nodes into sub-blocks works correctly.""" # original circuit is linear circuit = QuantumCircuit(5) circuit.cx(0, 2) circuit.cx(1, 4) circuit.cx(2, 0) circuit.cx(0, 3) circuit.swap(3, 2) circuit.swap(4, 1) block_collector = BlockCollector(circuit_to_dag(circuit)) # If we do not split block into sub-blocks, we expect a single linear block. blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "swap"], split_blocks=False, min_block_size=2, ) self.assertEqual(len(blocks), 1) # If we do split block into sub-blocks, we expect two linear blocks: # one over qubits {0, 2, 3}, and another over qubits {1, 4}. blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "swap"], split_blocks=True, min_block_size=2, ) self.assertEqual(len(blocks), 2) def test_do_not_split_blocks(self): """Test that splitting blocks of nodes into sub-blocks works correctly.""" # original circuit is linear circuit = QuantumCircuit(5) circuit.cx(0, 3) circuit.cx(0, 2) circuit.cx(1, 4) circuit.swap(4, 2) block_collector = BlockCollector(circuit_to_dagdependency(circuit)) # Check that we have a single linear block blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "swap"], split_blocks=True, min_block_size=1, ) self.assertEqual(len(blocks), 1) def test_collect_blocks_with_cargs(self): """Test collecting and collapsing blocks with classical bits appearing as cargs.""" qc = QuantumCircuit(3) qc.h(0) qc.h(1) qc.h(2) qc.measure_all() dag = circuit_to_dag(qc) # Collect all measure instructions blocks = BlockCollector(dag).collect_all_matching_blocks( lambda node: isinstance(node.op, Measure), split_blocks=False, min_block_size=1 ) # We should have a single block consisting of 3 measures self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 3) self.assertEqual(blocks[0][0].op, Measure()) self.assertEqual(blocks[0][1].op, Measure()) self.assertEqual(blocks[0][2].op, Measure()) def _collapse_fn(circuit): op = circuit_to_instruction(circuit) op.name = "COLLAPSED" return op # Collapse block with measures into a single "COLLAPSED" block dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn) collapsed_qc = dag_to_circuit(dag) self.assertEqual(len(collapsed_qc.data), 5) self.assertEqual(collapsed_qc.data[0].operation.name, "h") self.assertEqual(collapsed_qc.data[1].operation.name, "h") self.assertEqual(collapsed_qc.data[2].operation.name, "h") self.assertEqual(collapsed_qc.data[3].operation.name, "barrier") self.assertEqual(collapsed_qc.data[4].operation.name, "COLLAPSED") self.assertEqual(collapsed_qc.data[4].operation.definition.num_qubits, 3) self.assertEqual(collapsed_qc.data[4].operation.definition.num_clbits, 3) def test_collect_blocks_with_cargs_dagdependency(self): """Test collecting and collapsing blocks with classical bits appearing as cargs, using DAGDependency.""" qc = QuantumCircuit(3) qc.h(0) qc.h(1) qc.h(2) qc.measure_all() dag = circuit_to_dagdependency(qc) # Collect all measure instructions blocks = BlockCollector(dag).collect_all_matching_blocks( lambda node: isinstance(node.op, Measure), split_blocks=False, min_block_size=1 ) # We should have a single block consisting of 3 measures self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 3) self.assertEqual(blocks[0][0].op, Measure()) self.assertEqual(blocks[0][1].op, Measure()) self.assertEqual(blocks[0][2].op, Measure()) def _collapse_fn(circuit): op = circuit_to_instruction(circuit) op.name = "COLLAPSED" return op # Collapse block with measures into a single "COLLAPSED" block dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn) collapsed_qc = dagdependency_to_circuit(dag) self.assertEqual(len(collapsed_qc.data), 5) self.assertEqual(collapsed_qc.data[0].operation.name, "h") self.assertEqual(collapsed_qc.data[1].operation.name, "h") self.assertEqual(collapsed_qc.data[2].operation.name, "h") self.assertEqual(collapsed_qc.data[3].operation.name, "barrier") self.assertEqual(collapsed_qc.data[4].operation.name, "COLLAPSED") self.assertEqual(collapsed_qc.data[4].operation.definition.num_qubits, 3) self.assertEqual(collapsed_qc.data[4].operation.definition.num_clbits, 3) def test_collect_blocks_with_clbits(self): """Test collecting and collapsing blocks with classical bits appearing under condition.""" qc = QuantumCircuit(4, 3) qc.cx(0, 1).c_if(0, 1) qc.cx(2, 3) qc.cx(1, 2) qc.cx(0, 1) qc.cx(2, 3).c_if(1, 0) dag = circuit_to_dag(qc) # Collect all cx gates (including the conditional ones) blocks = BlockCollector(dag).collect_all_matching_blocks( lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1 ) # We should have a single block consisting of all CX nodes self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 5) def _collapse_fn(circuit): op = circuit_to_instruction(circuit) op.name = "COLLAPSED" return op # Collapse block with measures into a single "COLLAPSED" block dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn) collapsed_qc = dag_to_circuit(dag) self.assertEqual(len(collapsed_qc.data), 1) self.assertEqual(collapsed_qc.data[0].operation.name, "COLLAPSED") self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 4) self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 2) def test_collect_blocks_with_clbits_dagdependency(self): """Test collecting and collapsing blocks with classical bits appearing under conditions, using DAGDependency.""" qc = QuantumCircuit(4, 3) qc.cx(0, 1).c_if(0, 1) qc.cx(2, 3) qc.cx(1, 2) qc.cx(0, 1) qc.cx(2, 3).c_if(1, 0) dag = circuit_to_dagdependency(qc) # Collect all cx gates (including the conditional ones) blocks = BlockCollector(dag).collect_all_matching_blocks( lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1 ) # We should have a single block consisting of all CX nodes self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 5) def _collapse_fn(circuit): op = circuit_to_instruction(circuit) op.name = "COLLAPSED" return op # Collapse block with measures into a single "COLLAPSED" block dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn) collapsed_qc = dagdependency_to_circuit(dag) self.assertEqual(len(collapsed_qc.data), 1) self.assertEqual(collapsed_qc.data[0].operation.name, "COLLAPSED") self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 4) self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 2) def test_collect_blocks_with_clbits2(self): """Test collecting and collapsing blocks with classical bits appearing under condition.""" qreg = QuantumRegister(4, "qr") creg = ClassicalRegister(3, "cr") cbit = Clbit() qc = QuantumCircuit(qreg, creg, [cbit]) qc.cx(0, 1).c_if(creg[1], 1) qc.cx(2, 3).c_if(cbit, 0) qc.cx(1, 2) qc.cx(0, 1).c_if(creg[2], 1) dag = circuit_to_dag(qc) # Collect all cx gates (including the conditional ones) blocks = BlockCollector(dag).collect_all_matching_blocks( lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1 ) # We should have a single block consisting of all CX nodes self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 4) def _collapse_fn(circuit): op = circuit_to_instruction(circuit) op.name = "COLLAPSED" return op # Collapse block with measures into a single "COLLAPSED" block dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn) collapsed_qc = dag_to_circuit(dag) self.assertEqual(len(collapsed_qc.data), 1) self.assertEqual(collapsed_qc.data[0].operation.name, "COLLAPSED") self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 4) self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 3) def test_collect_blocks_with_clbits2_dagdependency(self): """Test collecting and collapsing blocks with classical bits appearing under condition, using DAGDependency.""" qreg = QuantumRegister(4, "qr") creg = ClassicalRegister(3, "cr") cbit = Clbit() qc = QuantumCircuit(qreg, creg, [cbit]) qc.cx(0, 1).c_if(creg[1], 1) qc.cx(2, 3).c_if(cbit, 0) qc.cx(1, 2) qc.cx(0, 1).c_if(creg[2], 1) dag = circuit_to_dag(qc) # Collect all cx gates (including the conditional ones) blocks = BlockCollector(dag).collect_all_matching_blocks( lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1 ) # We should have a single block consisting of all CX nodes self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 4) def _collapse_fn(circuit): op = circuit_to_instruction(circuit) op.name = "COLLAPSED" return op # Collapse block with measures into a single "COLLAPSED" block dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn) collapsed_qc = dag_to_circuit(dag) self.assertEqual(len(collapsed_qc.data), 1) self.assertEqual(collapsed_qc.data[0].operation.name, "COLLAPSED") self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 4) self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 3) def test_collect_blocks_with_cregs(self): """Test collecting and collapsing blocks with classical registers appearing under condition.""" qreg = QuantumRegister(4, "qr") creg = ClassicalRegister(3, "cr") creg2 = ClassicalRegister(2, "cr2") qc = QuantumCircuit(qreg, creg, creg2) qc.cx(0, 1).c_if(creg, 3) qc.cx(1, 2) qc.cx(0, 1).c_if(creg[2], 1) dag = circuit_to_dag(qc) # Collect all cx gates (including the conditional ones) blocks = BlockCollector(dag).collect_all_matching_blocks( lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1 ) # We should have a single block consisting of all CX nodes self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 3) def _collapse_fn(circuit): op = circuit_to_instruction(circuit) op.name = "COLLAPSED" return op # Collapse block with measures into a single "COLLAPSED" block dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn) collapsed_qc = dag_to_circuit(dag) self.assertEqual(len(collapsed_qc.data), 1) self.assertEqual(collapsed_qc.data[0].operation.name, "COLLAPSED") self.assertEqual(len(collapsed_qc.data[0].operation.definition.cregs), 1) self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 3) self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 3) def test_collect_blocks_with_cregs_dagdependency(self): """Test collecting and collapsing blocks with classical registers appearing under condition, using DAGDependency.""" qreg = QuantumRegister(4, "qr") creg = ClassicalRegister(3, "cr") creg2 = ClassicalRegister(2, "cr2") qc = QuantumCircuit(qreg, creg, creg2) qc.cx(0, 1).c_if(creg, 3) qc.cx(1, 2) qc.cx(0, 1).c_if(creg[2], 1) dag = circuit_to_dagdependency(qc) # Collect all cx gates (including the conditional ones) blocks = BlockCollector(dag).collect_all_matching_blocks( lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1 ) # We should have a single block consisting of all CX nodes self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 3) def _collapse_fn(circuit): op = circuit_to_instruction(circuit) op.name = "COLLAPSED" return op # Collapse block with measures into a single "COLLAPSED" block dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn) collapsed_qc = dagdependency_to_circuit(dag) self.assertEqual(len(collapsed_qc.data), 1) self.assertEqual(collapsed_qc.data[0].operation.name, "COLLAPSED") self.assertEqual(len(collapsed_qc.data[0].operation.definition.cregs), 1) self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 3) self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 3) def test_collect_blocks_backwards_dagcircuit(self): """Test collecting H gates from DAGCircuit in the forward vs. the reverse directions.""" qc = QuantumCircuit(4) qc.h(0) qc.h(1) qc.h(2) qc.h(3) qc.cx(1, 2) qc.z(0) qc.z(1) qc.z(2) qc.z(3) block_collector = BlockCollector(circuit_to_dag(qc)) # When collecting in the forward direction, there are two blocks of # single-qubit gates: the first of size 6, and the second of size 2. blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["h", "z"], split_blocks=False, min_block_size=1, collect_from_back=False, ) self.assertEqual(len(blocks), 2) self.assertEqual(len(blocks[0]), 6) self.assertEqual(len(blocks[1]), 2) # When collecting in the backward direction, there are also two blocks of # single-qubit ates: but now the first is of size 2, and the second is of size 6. blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["h", "z"], split_blocks=False, min_block_size=1, collect_from_back=True, ) self.assertEqual(len(blocks), 2) self.assertEqual(len(blocks[0]), 2) self.assertEqual(len(blocks[1]), 6) def test_collect_blocks_backwards_dagdependency(self): """Test collecting H gates from DAGDependency in the forward vs. the reverse directions.""" qc = QuantumCircuit(4) qc.z(0) qc.z(1) qc.z(2) qc.z(3) qc.cx(1, 2) qc.h(0) qc.h(1) qc.h(2) qc.h(3) block_collector = BlockCollector(circuit_to_dagdependency(qc)) # When collecting in the forward direction, there are two blocks of # single-qubit gates: the first of size 6, and the second of size 2. blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["h", "z"], split_blocks=False, min_block_size=1, collect_from_back=False, ) self.assertEqual(len(blocks), 2) self.assertEqual(len(blocks[0]), 6) self.assertEqual(len(blocks[1]), 2) # When collecting in the backward direction, there are also two blocks of # single-qubit ates: but now the first is of size 1, and the second is of size 7 # (note that z(1) and CX(1, 2) commute). blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["h", "z"], split_blocks=False, min_block_size=1, collect_from_back=True, ) self.assertEqual(len(blocks), 2) self.assertEqual(len(blocks[0]), 1) self.assertEqual(len(blocks[1]), 7) def test_split_layers_dagcircuit(self): """Test that splitting blocks of nodes into layers works correctly.""" # original circuit is linear circuit = QuantumCircuit(5) circuit.cx(0, 2) circuit.cx(1, 4) circuit.cx(2, 0) circuit.cx(0, 3) circuit.swap(3, 2) circuit.swap(4, 1) block_collector = BlockCollector(circuit_to_dag(circuit)) # If we split the gates into depth-1 layers, we expect four linear blocks: # CX(0, 2), CX(1, 4) # CX(2, 0), CX(4, 1) # CX(0, 3) # CX(3, 2) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "swap"], split_blocks=False, min_block_size=1, split_layers=True, ) self.assertEqual(len(blocks), 4) self.assertEqual(len(blocks[0]), 2) self.assertEqual(len(blocks[1]), 2) self.assertEqual(len(blocks[2]), 1) self.assertEqual(len(blocks[3]), 1) def test_split_layers_dagdependency(self): """Test that splitting blocks of nodes into layers works correctly.""" # original circuit is linear circuit = QuantumCircuit(5) circuit.cx(0, 2) circuit.cx(1, 4) circuit.cx(2, 0) circuit.cx(0, 3) circuit.swap(3, 2) circuit.swap(4, 1) block_collector = BlockCollector(circuit_to_dagdependency(circuit)) # If we split the gates into depth-1 layers, we expect four linear blocks: # CX(0, 2), CX(1, 4) # CX(2, 0), CX(4, 1) # CX(0, 3) # CX(3, 2) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "swap"], split_blocks=False, min_block_size=1, split_layers=True, ) self.assertEqual(len(blocks), 4) self.assertEqual(len(blocks[0]), 2) self.assertEqual(len(blocks[1]), 2) self.assertEqual(len(blocks[2]), 1) self.assertEqual(len(blocks[3]), 1) if __name__ == "__main__": unittest.main()
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
import cirq import random import matplotlib.pyplot as plt import numpy as np import math def qft_dagger_cirq(qc, qubits, n): for qubit in range(n//2): qc.append(cirq.SWAP(qubits[qubit], qubits[n-qubit-1])) for j in range(n): for m in range(j): qc.append((cirq.CZ**(-1/2**(j-m)))(qubits[m],qubits[j])) qc.append(cirq.H(qubits[j])) def generalised_qpe_cirq(amt_estimation_qubits, angle, shots = 10000): # Create and set up circuit qubits = cirq.LineQubit.range(amt_estimation_qubits+1) circuit = cirq.Circuit() # Apply H-Gates to counting qubits: for qubit in range(amt_estimation_qubits): circuit.append(cirq.H(qubits[qubit])) #print(circuit) # Prepare our eigenstate |psi>: circuit.append(cirq.X(qubits[amt_estimation_qubits])) #print(circuit) repetitions = 1 for counting_qubit in range(amt_estimation_qubits): for i in range(repetitions): circuit.append((cirq.CZ**((angle/math.pi)))(qubits[counting_qubit],qubits[amt_estimation_qubits])); repetitions *= 2 #print(circuit) # Do the inverse QFT: qft_dagger_cirq(circuit, qubits, amt_estimation_qubits) # Measure of course! circuit.append(cirq.measure(*qubits[:-1], key='m')) simulator = cirq.Simulator() results = simulator.run(circuit , repetitions = shots) theta_estimates = np.sum(2 ** np.arange(amt_estimation_qubits) * results.measurements['m'], axis=1) / 2**amt_estimation_qubits print(theta_estimates) counts = dict() for i in theta_estimates: counts[i] = counts.get(i, 0) + 1 print(counts) unique,pos = np.unique(theta_estimates,return_inverse=True) counts = np.bincount(pos) maxpos = counts.argmax() print(unique[maxpos],counts[maxpos]) #generalised_qpe_cirq(7,(13*math.pi/9)) generalised_qpe_cirq(7,(13*math.pi/9))
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. """Tests for quantum channel representation transformations.""" import unittest import numpy as np from qiskit import QiskitError from qiskit.quantum_info.states import DensityMatrix from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.quantum_info.operators.operator import Operator from qiskit.quantum_info.operators.channel.choi import Choi from qiskit.quantum_info.operators.channel.superop import SuperOp from qiskit.quantum_info.operators.channel.kraus import Kraus from qiskit.quantum_info.operators.channel.stinespring import Stinespring from qiskit.quantum_info.operators.channel.ptm import PTM from qiskit.quantum_info.operators.channel.chi import Chi from .channel_test_case import ChannelTestCase class TestTransformations(ChannelTestCase): """Tests for Operator channel representation.""" unitary_mat = [ ChannelTestCase.UI, ChannelTestCase.UX, ChannelTestCase.UY, ChannelTestCase.UZ, ChannelTestCase.UH, ] unitary_choi = [ ChannelTestCase.choiI, ChannelTestCase.choiX, ChannelTestCase.choiY, ChannelTestCase.choiZ, ChannelTestCase.choiH, ] unitary_chi = [ ChannelTestCase.chiI, ChannelTestCase.chiX, ChannelTestCase.chiY, ChannelTestCase.chiZ, ChannelTestCase.chiH, ] unitary_sop = [ ChannelTestCase.sopI, ChannelTestCase.sopX, ChannelTestCase.sopY, ChannelTestCase.sopZ, ChannelTestCase.sopH, ] unitary_ptm = [ ChannelTestCase.ptmI, ChannelTestCase.ptmX, ChannelTestCase.ptmY, ChannelTestCase.ptmZ, ChannelTestCase.ptmH, ] def test_operator_to_operator(self): """Test Operator to Operator transformation.""" # Test unitary channels for mat in self.unitary_mat: chan1 = Operator(mat) chan2 = Operator(chan1) self.assertEqual(chan1, chan2) def test_operator_to_choi(self): """Test Operator to Choi transformation.""" # Test unitary channels for mat, choi in zip(self.unitary_mat, self.unitary_choi): chan1 = Choi(choi) chan2 = Choi(Operator(mat)) self.assertEqual(chan1, chan2) def test_operator_to_superop(self): """Test Operator to SuperOp transformation.""" # Test unitary channels for mat, sop in zip(self.unitary_mat, self.unitary_sop): chan1 = SuperOp(sop) chan2 = SuperOp(Operator(mat)) self.assertEqual(chan1, chan2) def test_operator_to_kraus(self): """Test Operator to Kraus transformation.""" # Test unitary channels for mat in self.unitary_mat: chan1 = Kraus(mat) chan2 = Kraus(Operator(mat)) self.assertEqual(chan1, chan2) def test_operator_to_stinespring(self): """Test Operator to Stinespring transformation.""" # Test unitary channels for mat in self.unitary_mat: chan1 = Stinespring(mat) chan2 = Stinespring(Operator(chan1)) self.assertEqual(chan1, chan2) def test_operator_to_chi(self): """Test Operator to Chi transformation.""" # Test unitary channels for mat, chi in zip(self.unitary_mat, self.unitary_chi): chan1 = Chi(chi) chan2 = Chi(Operator(mat)) self.assertEqual(chan1, chan2) def test_operator_to_ptm(self): """Test Operator to PTM transformation.""" # Test unitary channels for mat, ptm in zip(self.unitary_mat, self.unitary_ptm): chan1 = PTM(ptm) chan2 = PTM(Operator(mat)) self.assertEqual(chan1, chan2) def test_choi_to_operator(self): """Test Choi to Operator transformation.""" # Test unitary channels for mat, choi in zip(self.unitary_mat, self.unitary_choi): chan1 = Operator(mat) chan2 = Operator(Choi(choi)) self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True)) def test_choi_to_choi(self): """Test Choi to Choi transformation.""" # Test unitary channels for choi in self.unitary_choi: chan1 = Choi(choi) chan2 = Choi(chan1) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Choi(self.depol_choi(p)) chan2 = Choi(chan1) self.assertEqual(chan1, chan2) def test_choi_to_superop(self): """Test Choi to SuperOp transformation.""" # Test unitary channels for choi, sop in zip(self.unitary_choi, self.unitary_sop): chan1 = SuperOp(sop) chan2 = SuperOp(Choi(choi)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = SuperOp(self.depol_sop(p)) chan2 = SuperOp(Choi(self.depol_choi(p))) self.assertEqual(chan1, chan2) def test_choi_to_kraus(self): """Test Choi to Kraus transformation.""" # Test unitary channels for mat, choi in zip(self.unitary_mat, self.unitary_choi): chan1 = Kraus(mat) chan2 = Kraus(Choi(choi)) self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = DensityMatrix(np.diag([1, 0])) for p in [0.25, 0.5, 0.75, 1]: target = rho.evolve(Kraus(self.depol_kraus(p))) output = rho.evolve(Kraus(Choi(self.depol_choi(p)))) self.assertEqual(output, target) def test_choi_to_stinespring(self): """Test Choi to Stinespring transformation.""" # Test unitary channels for mat, choi in zip(self.unitary_mat, self.unitary_choi): chan1 = Kraus(mat) chan2 = Kraus(Choi(choi)) self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = DensityMatrix(np.diag([1, 0])) for p in [0.25, 0.5, 0.75, 1]: target = rho.evolve(Stinespring(self.depol_stine(p))) output = rho.evolve(Stinespring(Choi(self.depol_choi(p)))) self.assertEqual(output, target) def test_choi_to_chi(self): """Test Choi to Chi transformation.""" # Test unitary channels for choi, chi in zip(self.unitary_choi, self.unitary_chi): chan1 = Chi(chi) chan2 = Chi(Choi(choi)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Chi(self.depol_chi(p)) chan2 = Chi(Choi(self.depol_choi(p))) self.assertEqual(chan1, chan2) def test_choi_to_ptm(self): """Test Choi to PTM transformation.""" # Test unitary channels for choi, ptm in zip(self.unitary_choi, self.unitary_ptm): chan1 = PTM(ptm) chan2 = PTM(Choi(choi)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = PTM(self.depol_ptm(p)) chan2 = PTM(Choi(self.depol_choi(p))) self.assertEqual(chan1, chan2) def test_superop_to_operator(self): """Test SuperOp to Operator transformation.""" for mat, sop in zip(self.unitary_mat, self.unitary_sop): chan1 = Operator(mat) chan2 = Operator(SuperOp(sop)) self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True)) self.assertRaises(QiskitError, Operator, SuperOp(self.depol_sop(0.5))) def test_superop_to_choi(self): """Test SuperOp to Choi transformation.""" # Test unitary channels for choi, sop in zip(self.unitary_choi, self.unitary_sop): chan1 = Choi(choi) chan2 = Choi(SuperOp(sop)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0, 0.25, 0.5, 0.75, 1]: chan1 = Choi(self.depol_choi(p)) chan2 = Choi(SuperOp(self.depol_sop(p))) self.assertEqual(chan1, chan2) def test_superop_to_superop(self): """Test SuperOp to SuperOp transformation.""" # Test unitary channels for sop in self.unitary_sop: chan1 = SuperOp(sop) chan2 = SuperOp(chan1) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0, 0.25, 0.5, 0.75, 1]: chan1 = SuperOp(self.depol_sop(p)) chan2 = SuperOp(chan1) self.assertEqual(chan1, chan2) def test_superop_to_kraus(self): """Test SuperOp to Kraus transformation.""" # Test unitary channels for mat, sop in zip(self.unitary_mat, self.unitary_sop): chan1 = Kraus(mat) chan2 = Kraus(SuperOp(sop)) self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = DensityMatrix(np.diag([1, 0])) for p in [0.25, 0.5, 0.75, 1]: target = rho.evolve(Kraus(self.depol_kraus(p))) output = rho.evolve(Kraus(SuperOp(self.depol_sop(p)))) self.assertEqual(output, target) def test_superop_to_stinespring(self): """Test SuperOp to Stinespring transformation.""" # Test unitary channels for mat, sop in zip(self.unitary_mat, self.unitary_sop): chan1 = Stinespring(mat) chan2 = Stinespring(SuperOp(sop)) self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = DensityMatrix(np.diag([1, 0])) for p in [0.25, 0.5, 0.75, 1]: target = rho.evolve(Stinespring(self.depol_stine(p))) output = rho.evolve(Stinespring(SuperOp(self.depol_sop(p)))) self.assertEqual(output, target) def test_superop_to_chi(self): """Test SuperOp to Chi transformation.""" # Test unitary channels for sop, ptm in zip(self.unitary_sop, self.unitary_ptm): chan1 = PTM(ptm) chan2 = PTM(SuperOp(sop)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Chi(self.depol_chi(p)) chan2 = Chi(SuperOp(self.depol_sop(p))) self.assertEqual(chan1, chan2) def test_superop_to_ptm(self): """Test SuperOp to PTM transformation.""" # Test unitary channels for sop, ptm in zip(self.unitary_sop, self.unitary_ptm): chan1 = PTM(ptm) chan2 = PTM(SuperOp(sop)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = PTM(self.depol_ptm(p)) chan2 = PTM(SuperOp(self.depol_sop(p))) self.assertEqual(chan1, chan2) def test_kraus_to_operator(self): """Test Kraus to Operator transformation.""" for mat in self.unitary_mat: chan1 = Operator(mat) chan2 = Operator(Kraus(mat)) self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True)) self.assertRaises(QiskitError, Operator, Kraus(self.depol_kraus(0.5))) def test_kraus_to_choi(self): """Test Kraus to Choi transformation.""" # Test unitary channels for mat, choi in zip(self.unitary_mat, self.unitary_choi): chan1 = Choi(choi) chan2 = Choi(Kraus(mat)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Choi(self.depol_choi(p)) chan2 = Choi(Kraus(self.depol_kraus(p))) self.assertEqual(chan1, chan2) def test_kraus_to_superop(self): """Test Kraus to SuperOp transformation.""" # Test unitary channels for mat, sop in zip(self.unitary_mat, self.unitary_sop): chan1 = SuperOp(sop) chan2 = SuperOp(Kraus(mat)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = SuperOp(self.depol_sop(p)) chan2 = SuperOp(Kraus(self.depol_kraus(p))) self.assertEqual(chan1, chan2) def test_kraus_to_kraus(self): """Test Kraus to Kraus transformation.""" # Test unitary channels for mat in self.unitary_mat: chan1 = Kraus(mat) chan2 = Kraus(chan1) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Kraus(self.depol_kraus(p)) chan2 = Kraus(chan1) self.assertEqual(chan1, chan2) def test_kraus_to_stinespring(self): """Test Kraus to Stinespring transformation.""" # Test unitary channels for mat in self.unitary_mat: chan1 = Stinespring(mat) chan2 = Stinespring(Kraus(mat)) self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = DensityMatrix(np.diag([1, 0])) for p in [0.25, 0.5, 0.75, 1]: target = rho.evolve(Stinespring(self.depol_stine(p))) output = rho.evolve(Stinespring(Kraus(self.depol_kraus(p)))) self.assertEqual(output, target) def test_kraus_to_chi(self): """Test Kraus to Chi transformation.""" # Test unitary channels for mat, chi in zip(self.unitary_mat, self.unitary_chi): chan1 = Chi(chi) chan2 = Chi(Kraus(mat)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Chi(self.depol_chi(p)) chan2 = Chi(Kraus(self.depol_kraus(p))) self.assertEqual(chan1, chan2) def test_kraus_to_ptm(self): """Test Kraus to PTM transformation.""" # Test unitary channels for mat, ptm in zip(self.unitary_mat, self.unitary_ptm): chan1 = PTM(ptm) chan2 = PTM(Kraus(mat)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = PTM(self.depol_ptm(p)) chan2 = PTM(Kraus(self.depol_kraus(p))) self.assertEqual(chan1, chan2) def test_stinespring_to_operator(self): """Test Stinespring to Operator transformation.""" for mat in self.unitary_mat: chan1 = Operator(mat) chan2 = Operator(Stinespring(mat)) self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True)) self.assertRaises(QiskitError, Operator, Stinespring(self.depol_stine(0.5))) def test_stinespring_to_choi(self): """Test Stinespring to Choi transformation.""" # Test unitary channels for mat, choi in zip(self.unitary_mat, self.unitary_choi): chan1 = Choi(choi) chan2 = Choi(Stinespring(mat)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Choi(self.depol_choi(p)) chan2 = Choi(Stinespring(self.depol_stine(p))) self.assertEqual(chan1, chan2) def test_stinespring_to_superop(self): """Test Stinespring to SuperOp transformation.""" # Test unitary channels for mat, sop in zip(self.unitary_mat, self.unitary_sop): chan1 = SuperOp(sop) chan2 = SuperOp(Kraus(mat)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = SuperOp(self.depol_sop(p)) chan2 = SuperOp(Stinespring(self.depol_stine(p))) self.assertEqual(chan1, chan2) def test_stinespring_to_kraus(self): """Test Stinespring to Kraus transformation.""" # Test unitary channels for mat in self.unitary_mat: chan1 = Kraus(mat) chan2 = Kraus(Stinespring(mat)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Kraus(self.depol_kraus(p)) chan2 = Kraus(Stinespring(self.depol_stine(p))) self.assertEqual(chan1, chan2) def test_stinespring_to_stinespring(self): """Test Stinespring to Stinespring transformation.""" # Test unitary channels for mat in self.unitary_mat: chan1 = Stinespring(mat) chan2 = Stinespring(chan1) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Stinespring(self.depol_stine(p)) chan2 = Stinespring(chan1) self.assertEqual(chan1, chan2) def test_stinespring_to_chi(self): """Test Stinespring to Chi transformation.""" # Test unitary channels for mat, chi in zip(self.unitary_mat, self.unitary_chi): chan1 = Chi(chi) chan2 = Chi(Stinespring(mat)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Chi(self.depol_chi(p)) chan2 = Chi(Stinespring(self.depol_stine(p))) self.assertEqual(chan1, chan2) def test_stinespring_to_ptm(self): """Test Stinespring to PTM transformation.""" # Test unitary channels for mat, ptm in zip(self.unitary_mat, self.unitary_ptm): chan1 = PTM(ptm) chan2 = PTM(Stinespring(mat)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = PTM(self.depol_ptm(p)) chan2 = PTM(Stinespring(self.depol_stine(p))) self.assertEqual(chan1, chan2) def test_chi_to_operator(self): """Test Chi to Operator transformation.""" for mat, chi in zip(self.unitary_mat, self.unitary_chi): chan1 = Operator(mat) chan2 = Operator(Chi(chi)) self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True)) self.assertRaises(QiskitError, Operator, Chi(self.depol_chi(0.5))) def test_chi_to_choi(self): """Test Chi to Choi transformation.""" # Test unitary channels for chi, choi in zip(self.unitary_chi, self.unitary_choi): chan1 = Choi(choi) chan2 = Choi(Chi(chi)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Choi(self.depol_choi(p)) chan2 = Choi(Chi(self.depol_chi(p))) self.assertEqual(chan1, chan2) def test_chi_to_superop(self): """Test Chi to SuperOp transformation.""" # Test unitary channels for chi, sop in zip(self.unitary_chi, self.unitary_sop): chan1 = SuperOp(sop) chan2 = SuperOp(Chi(chi)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = SuperOp(self.depol_sop(p)) chan2 = SuperOp(Chi(self.depol_chi(p))) self.assertEqual(chan1, chan2) def test_chi_to_kraus(self): """Test Chi to Kraus transformation.""" # Test unitary channels for mat, chi in zip(self.unitary_mat, self.unitary_chi): chan1 = Kraus(mat) chan2 = Kraus(Chi(chi)) self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = DensityMatrix(np.diag([1, 0])) for p in [0.25, 0.5, 0.75, 1]: target = rho.evolve(Kraus(self.depol_kraus(p))) output = rho.evolve(Kraus(Chi(self.depol_chi(p)))) self.assertEqual(output, target) def test_chi_to_stinespring(self): """Test Chi to Stinespring transformation.""" # Test unitary channels for mat, chi in zip(self.unitary_mat, self.unitary_chi): chan1 = Kraus(mat) chan2 = Kraus(Chi(chi)) self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = DensityMatrix(np.diag([1, 0])) for p in [0.25, 0.5, 0.75, 1]: target = rho.evolve(Stinespring(self.depol_stine(p))) output = rho.evolve(Stinespring(Chi(self.depol_chi(p)))) self.assertEqual(output, target) def test_chi_to_chi(self): """Test Chi to Chi transformation.""" # Test unitary channels for chi in self.unitary_chi: chan1 = Chi(chi) chan2 = Chi(chan1) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Chi(self.depol_chi(p)) chan2 = Chi(chan1) self.assertEqual(chan1, chan2) def test_chi_to_ptm(self): """Test Chi to PTM transformation.""" # Test unitary channels for chi, ptm in zip(self.unitary_chi, self.unitary_ptm): chan1 = PTM(ptm) chan2 = PTM(Chi(chi)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = PTM(self.depol_ptm(p)) chan2 = PTM(Chi(self.depol_chi(p))) self.assertEqual(chan1, chan2) def test_ptm_to_operator(self): """Test PTM to Operator transformation.""" for mat, ptm in zip(self.unitary_mat, self.unitary_ptm): chan1 = Operator(mat) chan2 = Operator(PTM(ptm)) self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True)) self.assertRaises(QiskitError, Operator, PTM(self.depol_ptm(0.5))) def test_ptm_to_choi(self): """Test PTM to Choi transformation.""" # Test unitary channels for ptm, choi in zip(self.unitary_ptm, self.unitary_choi): chan1 = Choi(choi) chan2 = Choi(PTM(ptm)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Choi(self.depol_choi(p)) chan2 = Choi(PTM(self.depol_ptm(p))) self.assertEqual(chan1, chan2) def test_ptm_to_superop(self): """Test PTM to SuperOp transformation.""" # Test unitary channels for ptm, sop in zip(self.unitary_ptm, self.unitary_sop): chan1 = SuperOp(sop) chan2 = SuperOp(PTM(ptm)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = SuperOp(self.depol_sop(p)) chan2 = SuperOp(PTM(self.depol_ptm(p))) self.assertEqual(chan1, chan2) def test_ptm_to_kraus(self): """Test PTM to Kraus transformation.""" # Test unitary channels for mat, ptm in zip(self.unitary_mat, self.unitary_ptm): chan1 = Kraus(mat) chan2 = Kraus(PTM(ptm)) self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = DensityMatrix(np.diag([1, 0])) for p in [0.25, 0.5, 0.75, 1]: target = rho.evolve(Kraus(self.depol_kraus(p))) output = rho.evolve(Kraus(PTM(self.depol_ptm(p)))) self.assertEqual(output, target) def test_ptm_to_stinespring(self): """Test PTM to Stinespring transformation.""" # Test unitary channels for mat, ptm in zip(self.unitary_mat, self.unitary_ptm): chan1 = Kraus(mat) chan2 = Kraus(PTM(ptm)) self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = DensityMatrix(np.diag([1, 0])) for p in [0.25, 0.5, 0.75, 1]: target = rho.evolve(Stinespring(self.depol_stine(p))) output = rho.evolve(Stinespring(PTM(self.depol_ptm(p)))) self.assertEqual(output, target) def test_ptm_to_chi(self): """Test PTM to Chi transformation.""" # Test unitary channels for chi, ptm in zip(self.unitary_chi, self.unitary_ptm): chan1 = Chi(chi) chan2 = Chi(PTM(ptm)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Chi(self.depol_chi(p)) chan2 = Chi(PTM(self.depol_ptm(p))) self.assertEqual(chan1, chan2) def test_ptm_to_ptm(self): """Test PTM to PTM transformation.""" # Test unitary channels for ptm in self.unitary_ptm: chan1 = PTM(ptm) chan2 = PTM(chan1) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = PTM(self.depol_ptm(p)) chan2 = PTM(chan1) self.assertEqual(chan1, chan2) if __name__ == "__main__": unittest.main()
https://github.com/anpaschool/quantum-computing
anpaschool
from qiskit import * from math import pi from qiskit.visualization import plot_bloch_multivector # Let's do an X-gate on a |0> qubit qc = QuantumCircuit(1) qc.x(0) qc.draw('mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() print(out) plot_bloch_multivector(out) # Run the quantum circuit on a unitary simulator backend backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() # Show the results print(result.get_unitary(qc, decimals=3)) # Let's do an X-gate on a |0> qubit qc = QuantumCircuit(1) qc.y(0) qc.draw('mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() print(out) plot_bloch_multivector(out) # Run the quantum circuit on a unitary simulator backend backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) print(out) result = job.result() # Show the results print(result.get_unitary(qc, decimals=3)) qc = QuantumCircuit(1) qc.z(0) qc.draw(output='mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() print(out) plot_bloch_multivector(out) # Run the quantum circuit on a unitary simulator backend backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) print(out) result = job.result() # Show the results print(result.get_unitary(qc, decimals=3)) # Let's do an X-gate on a |0> qubit qc = QuantumCircuit(1) qc.x(0) qc.x(0) qc.y(0) qc.y(0) qc.z(0) qc.z(0) qc.draw('mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() print(out) plot_bloch_multivector(out) # Run the quantum circuit on a unitary simulator backend backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() # Show the results print(result.get_unitary(qc, decimals=3)) # Let's do an X-gate on a |0> qubit qc = QuantumCircuit(2) qc.x(0) qc.y(1) qc.draw('mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() print(out) plot_bloch_multivector(out) # Run the quantum circuit on a unitary simulator backend backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() # Show the results print(result.get_unitary(qc, decimals=3)) # Let's do an X-gate on a |0> qubit qc = QuantumCircuit(2) qc.x(0) qc.y(1) qc.z(0) qc.x(1) qc.draw('mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() print(out) plot_bloch_multivector(out) # Run the quantum circuit on a unitary simulator backend backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() # Show the results print(result.get_unitary(qc, decimals=3)) # Let's do an X-gate on a |0> qubit qc = QuantumCircuit(3) qc.x(0) qc.y(1) qc.z(2) qc.draw('mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() print(out) plot_bloch_multivector(out) # Run the quantum circuit on a unitary simulator backend backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() # Show the results print(result.get_unitary(qc, decimals=3))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeAuckland backend = FakeAuckland() ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) depths = [] gate_counts = [] non_local_gate_counts = [] levels = [str(x) for x in range(4)] for level in range(4): circ = transpile(ghz, backend, optimization_level=level) depths.append(circ.depth()) gate_counts.append(sum(circ.count_ops().values())) non_local_gate_counts.append(circ.num_nonlocal_gates()) fig, (ax1, ax2) = plt.subplots(2, 1) ax1.bar(levels, depths, label='Depth') ax1.set_xlabel("Optimization Level") ax1.set_ylabel("Depth") ax1.set_title("Output Circuit Depth") ax2.bar(levels, gate_counts, label='Number of Circuit Operations') ax2.bar(levels, non_local_gate_counts, label='Number of non-local gates') ax2.set_xlabel("Optimization Level") ax2.set_ylabel("Number of gates") ax2.legend() ax2.set_title("Number of output circuit gates") fig.tight_layout() plt.show()
https://github.com/ctuning/ck-qiskit
ctuning
#!/usr/bin/env python3 """ This script runs Variational-Quantum-Eigensolver using Qiskit library Example running it partially using CK infrastructure: ck virtual env --tag_groups='compiler,python qiskit,lib vqe,utils vqe,hamiltonian deployed,ansatz deployed,optimizer' \ --shell_cmd="$HOME/CK/ck-qiskit/program/qiskit-vqe/qiskit_vqe_common.py --start_param_value=0.5" """ import os import json import time import inspect import numpy as np from scipy import linalg as la from qiskit import QuantumProgram, register, QISKitError from qiskit.tools.apps.optimization import make_Hamiltonian, group_paulis from qiskit.tools.qi.pauli import Pauli, label_to_pauli from eval_hamiltonian import eval_hamiltonian from vqe_utils import cmdline_parse_and_report, get_first_callable, NumpyEncoder from vqe_hamiltonian import label_to_hamiltonian_coeff # the file contents will be different depending on the plugin choice import custom_ansatz # the file contents will be different depending on the plugin choice fun_evaluation_counter = 0 # global def vqe_for_qiskit(sample_number, pauli_list, timeout_seconds, json_stream_file): def expectation_estimation(current_params, report): timestamp_before_ee = time.time() timestamp_before_q_run = timestamp_before_ee # no point in taking consecutive timestamps ansatz_circuit = ansatz_function(current_params) global fun_evaluation_counter # Trying to recover from a timed-out run assuming it to be a temporary glitch: # for attempt in range(1,8): try: complex_energy, q_run_seconds = eval_hamiltonian(Q_program, pauli_list_grouped, ansatz_circuit, sample_number, q_device_name, timeout=timeout_seconds) energy = complex_energy.real break except QISKitError as e: print("{}, trying again -- attempt number {}, timeout: {} seconds".format(e, attempt, timeout_seconds)) if len(q_run_seconds)>0: # got the real measured q time total_q_run_seconds = sum( q_run_seconds ) else: # have to assume total_q_run_seconds = time.time() - timestamp_before_q_run q_run_seconds = [ total_q_run_seconds ] q_runs = len(q_run_seconds) total_q_run_shots = sample_number * q_runs q_run_shots = [sample_number] * q_runs report_this_iteration = { 'total_q_seconds_per_c_iteration' : total_q_run_seconds, 'seconds_per_individual_q_run' : q_run_seconds, 'total_q_shots_per_c_iteration' : total_q_run_shots, 'shots_per_individual_q_run' : q_run_shots, 'energy' : energy, } if report != 'TestMode': report['iterations'].append( report_this_iteration ) report['total_q_seconds'] += report_this_iteration['total_q_seconds_per_c_iteration'] # total_q_time += total report['total_q_shots'] += report_this_iteration['total_q_shots_per_c_iteration'] fun_evaluation_counter += 1 report_this_iteration['total_seconds_per_c_iteration'] = time.time() - timestamp_before_ee print(report_this_iteration, "\n") json_stream_file.write( json.dumps(report_this_iteration, cls=NumpyEncoder)+"\n" ) json_stream_file.flush() return energy # Initialise quantum program Q_program = QuantumProgram() # Groups a list of (coeff,Pauli) tuples into tensor product basis (tpb) sets pauli_list_grouped = group_paulis(pauli_list) report = { 'total_q_seconds': 0, 'total_q_shots':0, 'iterations' : [] } # Initial objective function value fun_initial = expectation_estimation(start_params, 'TestMode') print('Initial guess at start_params is: {:.4f}'.format(fun_initial)) timestamp_before_optimizer = time.time() optimizer_output = minimizer_function(expectation_estimation, start_params, my_args=(report), my_options = minimizer_options) report['total_seconds'] = time.time() - timestamp_before_optimizer # Also generate and provide a validated function value at the optimal point fun_validated = expectation_estimation(optimizer_output['x'], 'TestMode') print('Validated value at solution is: {:.4f}'.format(fun_validated)) # Exact (noiseless) calculation of the energy at the given point: complex_energy, _ = eval_hamiltonian(Q_program, pauli_list, ansatz_function(optimizer_output['x']), 1, 'local_statevector_simulator') optimizer_output['fun_exact'] = complex_energy.real optimizer_output['fun_validated'] = fun_validated print('Total Q seconds = %f' % report['total_q_seconds']) print('Total Q shots = %d' % report['total_q_shots']) print('Total seconds = %f' % report['total_seconds']) return (optimizer_output, report) if __name__ == '__main__': start_params, sample_number, q_device_name, minimizer_method, minimizer_options, minimizer_function = cmdline_parse_and_report( num_params = custom_ansatz.num_params, q_device_name_default = 'local_qasm_simulator', q_device_name_help = "Real devices: 'ibmqx4' or 'ibmqx5'. Use 'ibmq_qasm_simulator' for remote simulator or 'local_qasm_simulator' for local", minimizer_options_default = '{"maxfev":200, "xatol": 0.001, "fatol": 0.001}', start_param_value_default = 0.0 ) # q_device_name = os.environ.get('VQE_QUANTUM_BACKEND', 'local_qasm_simulator') # try 'local_qasm_simulator', 'ibmq_qasm_simulator', 'ibmqx4', 'ibmqx5' try: import Qconfig register(Qconfig.APItoken, Qconfig.config["url"], verify=False, hub=Qconfig.config["hub"], group=Qconfig.config["group"], project=Qconfig.config["project"]) except: print(""" WARNING: There's no connection with IBMQuantumExperience servers. cannot test I/O intesive tasks, will only test CPU intensive tasks running the jobs in the local simulator """) # Ignore warnings due to chopping of small imaginary part of the energy #import warnings #warnings.filterwarnings('ignore') # Load the Hamiltonian into Qiskit-friendly format: pauli_list = [ [label_to_hamiltonian_coeff[label], label_to_pauli(label)] for label in label_to_hamiltonian_coeff ] # Calculate Exact Energy classically, to compare with quantum solution: # H = make_Hamiltonian(pauli_list) classical_energy = np.amin(la.eigh(H)[0]) print('The exact ground state energy (the smallest eigenvalue of the Hamiltonian) is: {:.4f}'.format(classical_energy)) # Load the ansatz function from the plug-in ansatz_method = get_first_callable( custom_ansatz ) ansatz_function = getattr(custom_ansatz, ansatz_method) # ansatz_method is a string/name, ansatz_function is an imported callable timeout_seconds = int( os.environ.get('VQE_QUANTUM_TIMEOUT', '120') ) json_stream_file = open('vqe_stream.json', 'a') # ---------------------------------------- run VQE: -------------------------------------------------- (vqe_output, report) = vqe_for_qiskit(sample_number, pauli_list, timeout_seconds, json_stream_file) # ---------------------------------------- store the results: ---------------------------------------- json_stream_file.write( '# Experiment finished\n' ) json_stream_file.close() minimizer_src = inspect.getsource( minimizer_function ) ansatz_src = inspect.getsource( ansatz_function ) vqe_input = { "q_device_name" : q_device_name, "minimizer_method" : minimizer_method, "minimizer_src" : minimizer_src, "minimizer_options" : minimizer_options, "ansatz_method" : ansatz_method, "ansatz_src" : ansatz_src, "sample_number" : sample_number, "classical_energy" : classical_energy } output_dict = { "vqe_input" : vqe_input, "vqe_output" : vqe_output, "report" : report } formatted_json = json.dumps(output_dict, cls=NumpyEncoder, sort_keys = True, indent = 4) # print(formatted_json) with open('ibm_vqe_report.json', 'w') as json_file: json_file.write( formatted_json )
https://github.com/DRA-chaos/Quantum-Classical-Hyrid-Neural-Network-for-binary-image-classification-using-PyTorch-Qiskit-pipeline
DRA-chaos
!pip install qiskit import numpy as np import matplotlib.pyplot as plt import torch from torch.autograd import Function from torchvision import datasets, transforms import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import qiskit from qiskit import transpile, assemble from qiskit.visualization import * def to_numbers(tensor_list): num_list = [] for tensor in tensor_list: num_list += [tensor.item()] return num_list import numpy as np import torch from torch.autograd import Function import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import torchvision from torchvision import datasets, transforms from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, execute from qiskit.circuit import Parameter from qiskit import Aer from tqdm import tqdm from matplotlib import pyplot as plt %matplotlib inline class QiskitCircuit(): # Specify initial parameters and the quantum circuit def __init__(self,shots): self.theta = Parameter('Theta') self.shots = shots def create_circuit(): qr = QuantumRegister(1,'q') cr = ClassicalRegister(1,'c') ckt = QuantumCircuit(qr,cr) ckt.h(qr[0]) ckt.barrier() ckt.ry(self.theta,qr[0]) ckt.barrier() ckt.measure(qr,cr) return ckt self.circuit = create_circuit() def N_qubit_expectation_Z(self,counts, shots, nr_qubits): expects = np.zeros(nr_qubits) for key in counts.keys(): perc = counts[key]/shots check = np.array([(float(key[i])-1/2)*2*perc for i in range(nr_qubits)]) expects += check return expects def bind(self, parameters): [self.theta] = to_numbers(parameters) self.circuit.data[2][0]._params = to_numbers(parameters) def run(self, i): self.bind(i) backend = Aer.get_backend('qasm_simulator') job_sim = execute(self.circuit,backend,shots=self.shots) result_sim = job_sim.result() counts = result_sim.get_counts(self.circuit) return self.N_qubit_expectation_Z(counts,self.shots,1) class TorchCircuit(Function): @staticmethod def forward(ctx, i): if not hasattr(ctx, 'QiskitCirc'): ctx.QiskitCirc = QiskitCircuit(shots=100) exp_value = ctx.QiskitCirc.run(i[0]) result = torch.tensor([exp_value]) # store the result as a torch tensor ctx.save_for_backward(result, i) return result @staticmethod def backward(ctx, grad_output): s = np.pi/2 forward_tensor, i = ctx.saved_tensors # Obtain paramaters input_numbers = to_numbers(i[0]) gradient = [] for k in range(len(input_numbers)): input_plus_s = input_numbers input_plus_s[k] = input_numbers[k] + s # Shift up by s exp_value_plus = ctx.QiskitCirc.run(torch.tensor(input_plus_s))[0] result_plus_s = torch.tensor([exp_value_plus]) input_minus_s = input_numbers input_minus_s[k] = input_numbers[k] - s # Shift down by s exp_value_minus = ctx.QiskitCirc.run(torch.tensor(input_minus_s))[0] result_minus_s = torch.tensor([exp_value_minus]) gradient_result = (result_plus_s - result_minus_s) gradient.append(gradient_result) result = torch.tensor([gradient]) return result.float() * grad_output.float() #import torchvision #transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) # transform images to tensors/vectors #cifar_trainset = datasets.CIFAR10(root='./data1', train=True, download=True, transform=transform) #labels = cifar_trainset.targets # get the labels for the data #labels = labels.numpy() #idx1 = np.where(labels == 0) # filter on aeroplanes #idx2 = np.where(labels == 1) # filter on automobiles # Specify number of datapoints per class (i.e. there will be n pictures of automobiles and n pictures of aeroplanes in the training set) #n=100 # concatenate the data indices #idx = np.concatenate((idx1[0][0:n],idx2[0][0:n])) # create the filtered dataset for our training set #cifar_trainset.targets = labels[idx] #cifar_trainset.data = cifar_trainset.data[idx] #train_loader = torch.utils.data.DataLoader(cifar_trainset, batch_size=1, shuffle=True) import tensorflow import torchvision import torchvision transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) # transform images to tensors/vectors cifar_trainset = datasets.CIFAR10(root='./data1', train=True, download=True, transform=transform) labels = cifar_trainset.targets # get the labels for the data labels = np.array(labels) idx1 = np.where(labels == 0) # filter on aeroplanes idx2 = np.where(labels == 1) # filter on automobiles # Specify number of datapoints per class (i.e. there will be n pictures of automobiles and n pictures of aeroplanes in the training set) n=100 # concatenate the data indices idx = np.concatenate((idx1[0][0:n],idx2[0][0:n])) # create the filtered dataset for our training set cifar_trainset.targets = labels[idx] cifar_trainset.data = cifar_trainset.data[idx] train_loader = torch.utils.data.DataLoader(cifar_trainset, batch_size=1, shuffle=True) qc = TorchCircuit.apply class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 10, kernel_size=5) self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.conv2_drop = nn.Dropout2d() self.h1 = nn.Linear(500, 500) self.h2 = nn.Linear(500, 1) def forward(self,x): x = F.relu(F.max_pool2d(self.conv1(x), 2)) x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2)) x = x.view(-1, 500) x = F.relu(self.h1(x)) x = F.dropout(x, training=self.training) x = self.h2(x) x = qc(x) x = (x+1)/2 # Normalise the inputs to 1 or 0 x = torch.cat((x, 1-x), -1) return x network = Net() #input = input.permute(1,0,2,3) optimizer = optim.Adam(network.parameters(), lr=0.001) epochs = 15 loss_list = [] for epoch in range(epochs): total_loss = [] target_list = [] for batch_idx, (data, target) in enumerate(train_loader): target_list.append(target.item()) optimizer.zero_grad() output = network(data) loss = F.nll_loss(output, target) loss.backward() optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print(loss_list[-1]) # Normalise the loss between 0 and 1 for i in range(len(loss_list)): loss_list[i] += 1 # Plot the loss per epoch plt.plot(loss_list) network = Net() #input = input.permute(1,0,2,3) optimizer = optim.Adam(network.parameters(), lr=0.001) epochs = 5 loss_list = [] for epoch in range(epochs): total_loss = [] target_list = [] for batch_idx, (data, target) in enumerate(train_loader): target_list.append(target.item()) optimizer.zero_grad() output = network(data) loss = F.nll_loss(output, target) loss.backward() optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print(loss_list[-1]) # Normalise the loss between 0 and 1 for i in range(len(loss_list)): loss_list[i] += 1 # Plot the loss per epoch plt.plot(loss_list) network = Net() #input = input.permute(1,0,2,3) optimizer = optim.Adam(network.parameters(), lr=0.001) epochs = 15 loss_list = [] for epoch in range(epochs): total_loss = [] target_list = [] for batch_idx, (data, target) in enumerate(train_loader): target_list.append(target.item()) optimizer.zero_grad() output = network(data) loss = F.nll_loss(output, target) loss.backward() optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print(loss_list[-1]) # Normalise the loss between 0 and 1 for i in range(len(loss_list)): loss_list[i] += 1 # Plot the loss per epoch plt.plot(loss_list) network = Net() #input = input.permute(1,0,2,3) optimizer = optim.Adam(network.parameters(), lr=0.001) epochs = 20 loss_list = [] for epoch in range(epochs): total_loss = [] target_list = [] for batch_idx, (data, target) in enumerate(train_loader): target_list.append(target.item()) optimizer.zero_grad() output = network(data) loss = F.nll_loss(output, target) loss.backward() optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print(loss_list[-1]) # Normalise the loss between 0 and 1 for i in range(len(loss_list)): loss_list[i] += 1 # Plot the loss per epoch plt.plot(loss_list) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 20 loss_list = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format( 100. * (epoch + 1) / epochs, loss_list[-1])) plt.plot(loss_list) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) import torchvision transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) # transform images to tensors/vectors cifar_testset = datasets.CIFAR10(root='./data1', train=False, download=True, transform=transform) labels1 = cifar_testset.targets # get the labels for the data labels1 = np.array(labels1) idx1_ae = np.where(labels1 == 0) # filter on aeroplanes idx2_au = np.where(labels1 == 1) # filter on automobiles # Specify number of datapoints per class (i.e. there will be n pictures of automobiles and n pictures of aeroplanes in the training set) n=50 # concatenate the data indices idxa = np.concatenate((idx1_ae[0][0:n],idx2_au[0][0:n])) # create the filtered dataset for our training set cifar_testset.targets = labels[idxa] cifar_testset.data = cifar_testset.data[idxa] test_loader = torch.utils.data.DataLoader(cifar_testset, batch_size=1, shuffle=True) model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) qc = TorchCircuit.apply class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 10, kernel_size=5) self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.conv2_drop = nn.Dropout2d() self.h1 = nn.Linear(500, 500) self.h2 = nn.Linear(500, 11) def forward(self,x): x = F.relu(F.max_pool2d(self.conv1(x), 2)) x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2)) x = x.view(-1, 500) x = F.relu(self.h1(x)) x = F.dropout(x, training=self.training) x = self.h2(x) x = qc(x) x = (x+1)/2 # Normalise the inputs to 1 or 0 x = torch.cat((x, 1-x), -1) return x
https://github.com/UST-QuAntiL/nisq-analyzer-content
UST-QuAntiL
from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit # https://quantum-circuit.com/app_details/about/bw5r9HTiTHvQHtCB5 qc = QuantumCircuit() q = QuantumRegister(5, 'q') c = ClassicalRegister(3, 'c') qc.add_register(q) qc.add_register(c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[1]) qc.cx(q[2], q[3]) qc.cu1(0, q[1], q[0]) qc.cx(q[2], q[4]) qc.h(q[0]) qc.cu1(0, q[1], q[2]) qc.cu1(0, q[0], q[2]) qc.h(q[2]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) def get_circuit(**kwargs): """Get circuit of Shor with input 15.""" return qc
https://github.com/qiskit-community/qiskit-dell-runtime
qiskit-community
from dell_runtime import DellRuntimeProvider from dell_runtime import BackendProvider from qiskit import QuantumCircuit provider = DellRuntimeProvider() RUNTIME_PROGRAM = """ # This code is part of qiskit-runtime. # # (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. # This is a simplified version of the circuit-runner program. from qiskit.compiler import transpile, schedule def main( backend, user_messenger, circuits, initial_layout=None, seed_transpiler=None, optimization_level=None, transpiler_options=None, scheduling_method=None, schedule_circuit=False, inst_map=None, meas_map=None, measurement_error_mitigation=False, **kwargs, ): # transpiling the circuits using given transpile options transpiler_options = transpiler_options or {} circuits = transpile( circuits, initial_layout=initial_layout, seed_transpiler=seed_transpiler, optimization_level=optimization_level, backend=backend, **transpiler_options, ) if schedule_circuit: circuits = schedule( circuits=circuits, backend=backend, inst_map=inst_map, meas_map=meas_map, method=scheduling_method, ) if not isinstance(circuits, list): circuits = [circuits] # Compute raw results result = backend.run(circuits, **kwargs).result() if measurement_error_mitigation: # Performs measurement error mitigation. pass user_messenger.publish(result.to_dict(), final=True) """ RUNTIME_PROGRAM_METADATA = { "max_execution_time": 600, "description": "Qiskit test program" } program_id = provider.runtime.upload_program(RUNTIME_PROGRAM, metadata=RUNTIME_PROGRAM_METADATA) N = 6 qc = QuantumCircuit(N) qc.x(range(0, N)) qc.h(range(0, N)) for kk in range(N//2,0,-1): qc.ch(kk, kk-1) for kk in range(N//2, N-1): qc.ch(kk, kk+1) qc.measure_all() program_inputs = { 'circuits': qc, 'shots': 2048, 'optimization_level': 0, 'initial_layout': [0,1,4,7,10,12], 'measurement_error_mitigation': False } runtime_program = provider.runtime.program(program_id) job = provider.runtime.run(program_id, options=None, inputs=program_inputs) job.status()
https://github.com/xtophe388/QISKIT
xtophe388
# execute this cell twice to see the output due to an issue with matplotlib import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') from pprint import pprint import math # importing the QISKit from qiskit import QuantumProgram # To use API #import Qconfig def gate_mu3(qcirc,theta,phi,lam,a,b): qcirc.cx(a,b) qcirc.cu3(theta,phi,lam,b,a) qcirc.cx(a,b) n_nodes = 5 n_step = 3 # Creating Programs qp = QuantumProgram() # Creating Registers qr = qp.create_quantum_register('qr', n_nodes) cr = qp.create_classical_register('cr', n_nodes) # Creating Circuits qc = qp.create_circuit('QWalk', [qr], [cr]) # Creating of two partitions with M1' and M2 for i in range(0,n_nodes-1,2): gate_mu3(qc,math.pi, math.pi, 0, qr[i], qr[i+1]) for i in range(1,n_nodes,2): gate_mu3(qc,math.pi/2, 0, 0, qr[i], qr[i+1]) # import state tomography functions from qiskit.tools.visualization import plot_histogram, plot_state import numpy as np # execute the quantum circuit backend = 'local_unitary_simulator' # the device to run on qobj = qp.compile(['QWalk'], backend=backend) result = qp.run(qobj) initial_state = np.zeros(2**n_nodes) initial_state[1]=1.0 # state 0 = ....0000, state 1 = ...000001 QWalk = result.get_data('QWalk')['unitary'] #Applying QWalk n_step times for i in range(0,n_step): if i > 0: initial_state = np.copy(state_QWalk) # Copy previous state state_QWalk = np.dot(QWalk,initial_state) # Multiply on QWalk matrix rho_QWalk=np.outer(state_QWalk, state_QWalk.conj()) # Calculate density matrix print('step = ',i+1) # print number plot_state(rho_QWalk,'qsphere') # draw Quantum Sphere
https://github.com/Andres8bit/IBMQ-Quantum-Qiskit
Andres8bit
%matplotlib inline # initialization: %matplotlib inline %config InlineBackend.figure_format = 'svg' # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, BasicAer, IBMQ from qiskit.providers.ibmq import least_busy from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.tools.monitor import job_monitor from qiskit.visualization import * # Loading your IBM Q account(s) provider = IBMQ.load_account() # Simon's Algorithm: # Given an unknown blackbox funnction f, # which is quaranteed to be either 1:1 or 2:1. # That is to say # either: f is a 1 to 1 maping, # where for every unique x value maps to a single unique f(x). # or: f is a 2 to 1 maping, # where exactly 2 unique x vals map to the same f(x). # Given this blackbox function how quickly can we determine which type of function f is? # Then is f is 2:1 how quickly can we determine s, where if f is 2:1. # given x1,x2: f(x1) = f(x) # it is guaranteed: x1 CNOT x2 = s # ========== Classical Solution: ============ # The traditional approach requires us to check up to 2^[N-1] + 1 inputs. # Where N is the number of bits in the input. # Therefore we would have to check on avg. half of all inputs to be 100% positve the function was 2:1. # ========== Quantum Solution: ========== # Steps: # 1. Two n-qubit input registers are initialized to the 0 state: # |ψ1> = |0⟩^⊗n |0⟩^⊗n # 2. Apply a Hadamard transform to the first register: # |ψ2⟩ = 1/sqrt(2^n)*∑[x∈{0,1}^n] |x⟩|0⟩⊗n # 3. Apply the query function Qf: # |ψ3⟩=1/sqrt(2^n) * ∑x∈[{0,1}^n] |x⟩|f(x)⟩ # 4. Measure the second register. A certain value of f(x) will be observed. # BC of the setting of the problem, the observed value f(x) could # correspond to two possible inputs: x & y = x⊕s # Therefore the first register becomes: # |ψ4⟩ = [1/sqrt(2)]( |x⟩ + |y⟩ ) # 5. Apply Hadamard on the first regisiter: # |ψ5⟩ = 1/sqrt(2^[n+1])*∑z∈[{0,1}n] [ (−1)^(x⋅z) + (−1)^(y⋅z) ] | z⟩ # 6. Measuring the first register will give an output only if: # (−1)^(x⋅z)=(−1)^(y⋅z) # which means: # x*z = y*z # x*z = (x XOR s)*z # x*z = x*(z XOR s)*z # s*z = 0%2 # A string z whose inner product with s will be measured. Thus, repeating the # algorithm ~~ n times, we will be able to obtain n different values of z & the # following system of equations can be written: # # s*z1 = 0 # s*z2 = 0 # ... # s*zn = 0 # From which we can find s using Gaussian elimination. # currently using a fixed string implementation, should expand to a random general case: # Creating registers # qubits and classical bits for querying the oracle and finding the hidden period s n = 2*len(str(s)) simonCircuit = QuantumCircuit(n) barriers = True # Apply Hadamard gates before querying the oracle simonCircuit.h(range(len(str(s)))) # Apply barrier if barriers: simonCircuit.barrier() # Apply the query function ## 2-qubit oracle for s = 11 simonCircuit.cx(0, len(str(s)) + 0) simonCircuit.cx(0, len(str(s)) + 1) simonCircuit.cx(1, len(str(s)) + 0) simonCircuit.cx(1, len(str(s)) + 1) # Apply barrier if barriers: simonCircuit.barrier() # Apply Hadamard gates to the input register simonCircuit.h(range(len(str(s)))) # Measure ancilla qubits simonCircuit.measure_all() simonCircuit.draw(output='mpl') # use local simalator: backend = BasicAer.get_backend('qasm_simulator') shots = 1024 results = execute(simonCircuit,backend=backend,shots=shots).result() answer = results.get_counts() answer_plot = {} for measresult in answer.keys(): measresult_input = measresult[len(str(s)):] if measresult_input in answer_plot: answer_plot[measresult_input] += answer[measresult] else: answer_plot[measresult_input] = answer[measresult] print(answer_plot) plot_histogram(answer_plot) # Calculate the dot product of the results def sdotz(a,b): accum = 0 for i in range(len(a)): accum += int(a[i]) * int(b[i]) return( accum % 2 ) print('a,z,s.z(mod 2)') for z_rev in answer_plot: z = z_rev[::-1] print('{},{},{},{}={}'.format(s,z,s,z,sdotz(s,z))) # Run our circuit on the least busy backend shots = 1024 job = execute(simonCircuit,backend=backend,shots=shots) job_monitor(job,interval=2) # Categorize measurements by input register values answer_plot = {} for measresult in answer.keys(): measresult_input = measresult[len(str(s)):] if measresult_input in answer_plot: answer_plot[measresult_input] += answer[measresult] else: answer_plot[measresult_input] = answer[measresult] # Plot the categorized results print( answer_plot ) plot_histogram(answer_plot) # Calculate the dot product of the most significant results print('s, z, s.z (mod 2)') for z_rev in answer_plot: if answer_plot[z_rev] >= 0.1*shots: z = z_rev[::-1] print( '{}, {}, {}.{}={}'.format(s, z, s,z,sdotz(s,z)) )
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag from qiskit.visualization import dag_drawer q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') circ = QuantumCircuit(q, c) circ.h(q[0]) circ.cx(q[0], q[1]) circ.measure(q[0], c[0]) circ.rz(0.5, q[1]).c_if(c, 2) dag = circuit_to_dag(circ) dag_drawer(dag)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """A collection of discrete probability metrics.""" from __future__ import annotations import numpy as np def hellinger_distance(dist_p: dict, dist_q: dict) -> float: """Computes the Hellinger distance between two counts distributions. Parameters: dist_p (dict): First dict of counts. dist_q (dict): Second dict of counts. Returns: float: Distance References: `Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_ """ p_sum = sum(dist_p.values()) q_sum = sum(dist_q.values()) p_normed = {} for key, val in dist_p.items(): p_normed[key] = val / p_sum q_normed = {} for key, val in dist_q.items(): q_normed[key] = val / q_sum total = 0 for key, val in p_normed.items(): if key in q_normed: total += (np.sqrt(val) - np.sqrt(q_normed[key])) ** 2 del q_normed[key] else: total += val total += sum(q_normed.values()) dist = np.sqrt(total) / np.sqrt(2) return dist def hellinger_fidelity(dist_p: dict, dist_q: dict) -> float: """Computes the Hellinger fidelity between two counts distributions. The fidelity is defined as :math:`\\left(1-H^{2}\\right)^{2}` where H is the Hellinger distance. This value is bounded in the range [0, 1]. This is equivalent to the standard classical fidelity :math:`F(Q,P)=\\left(\\sum_{i}\\sqrt{p_{i}q_{i}}\\right)^{2}` that in turn is equal to the quantum state fidelity for diagonal density matrices. Parameters: dist_p (dict): First dict of counts. dist_q (dict): Second dict of counts. Returns: float: Fidelity Example: .. code-block:: from qiskit import QuantumCircuit, execute, BasicAer from qiskit.quantum_info.analysis import hellinger_fidelity qc = QuantumCircuit(5, 5) qc.h(2) qc.cx(2, 1) qc.cx(2, 3) qc.cx(3, 4) qc.cx(1, 0) qc.measure(range(5), range(5)) sim = BasicAer.get_backend('qasm_simulator') res1 = execute(qc, sim).result() res2 = execute(qc, sim).result() hellinger_fidelity(res1.get_counts(), res2.get_counts()) References: `Quantum Fidelity @ wikipedia <https://en.wikipedia.org/wiki/Fidelity_of_quantum_states>`_ `Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_ """ dist = hellinger_distance(dist_p, dist_q) return (1 - dist**2) ** 2
https://github.com/Tojarieh97/VQE
Tojarieh97
import sys sys.path.append('../../') import numpy as np from qiskit import QuantumCircuit from qiskit.opflow import I, X, Y, Z import matplotlib.pyplot as plt from volta.observables import sample_hamiltonian from volta.hamiltonians import BCS_hamiltonian EPSILONS = [3, 3] V = -2 hamiltonian = BCS_hamiltonian(EPSILONS, V) print(hamiltonian) eigenvalues, _ = np.linalg.eigh(hamiltonian.to_matrix()) print(f"Eigenvalues: {eigenvalues}") def create_circuit(n: int) -> list: return [QuantumCircuit(n) for _ in range(2)] n = hamiltonian.num_qubits init_states = create_circuit(n) def copy_unitary(list_states: list) -> list: out_states = [] for state in list_states: out_states.append(state.copy()) return out_states import textwrap def apply_initialization(list_states: list) -> None: for ind, state in enumerate(list_states): b = bin(ind)[2:] if len(b) != n: b = '0'*(n - len(b)) + b spl = textwrap.wrap(b, 1) for qubit, val in enumerate(spl): if val == '1': state.x(qubit) apply_initialization(init_states) initialization = copy_unitary(init_states) from qiskit.circuit.library import TwoLocal ansatz = TwoLocal(hamiltonian.num_qubits, ['ry','rz'], 'cx', reps=2) def apply_ansatz(ansatz: QuantumCircuit, list_states: list) -> None: for states in list_states: states.append(ansatz, range(n)) apply_ansatz(ansatz, init_states) init_states[1].draw('mpl') w = np.arange(n, 0, -1) w def _apply_varform_params(ansatz, params: list): """Get an hardware-efficient ansatz for n_qubits given parameters. """ # Define variational Form var_form = ansatz # Get Parameters from the variational form var_form_params = sorted(var_form.parameters, key=lambda p: p.name) # Check if the number of parameters is compatible assert len(var_form_params) == len(params), "The number of parameters don't match" # Create a dictionary with the parameters and values param_dict = dict(zip(var_form_params, params)) # Assing those values for the ansatz wave_function = var_form.assign_parameters(param_dict) return wave_function from qiskit import BasicAer from qiskit.utils import QuantumInstance def cost_function(params:list) -> float: backend = BasicAer.get_backend('qasm_simulator') backend = QuantumInstance(backend, shots=10000) cost = 0 # Define Ansatz for i, state in enumerate(init_states): qc = _apply_varform_params(state, params) # Hamiltonian hamiltonian_eval = sample_hamiltonian(hamiltonian=hamiltonian, ansatz=qc, backend=backend) cost += w[i] * hamiltonian_eval return cost from qiskit.aqua.components.optimizers import COBYLA optimizer = COBYLA(maxiter=1000) n_parameters = len(init_states[0].parameters) params = np.random.rand(n_parameters) optimal_params, mean_energy, n_iters = optimizer.optimize(num_vars=n_parameters, objective_function=cost_function, initial_point=params) mean_energy # Optimized first ansatz ansatz_1 = _apply_varform_params(ansatz, optimal_params) ansatz_1.name = 'U(θ)' apply_ansatz(ansatz_1, init_states) init_states[2].draw() from qiskit.aqua import QuantumInstance def cost_function_ind(ind: int, params:list) -> float: backend = BasicAer.get_backend('qasm_simulator') backend = QuantumInstance(backend, shots=10000) cost = 0 # Define Ansatz qc = _apply_varform_params(init_states[ind], params) # Hamiltonian hamiltonian_eval = sample_hamiltonian(hamiltonian=hamiltonian, ansatz=qc, backend=backend) cost += hamiltonian_eval return - cost from functools import partial cost = partial(cost_function_ind, 2) n_parameters = len(init_states[0].parameters) params = np.random.rand(n_parameters) optimal_params, energy_gs, n_iters = optimizer.optimize(num_vars=n_parameters, objective_function=cost, initial_point=params) energy_gs eigenvalues # Optimized second ansatz ansatz_2 = _apply_varform_params(ansatz, optimal_params) ansatz_2.name = 'V(ϕ)'
https://github.com/GabrielPontolillo/QiskitPBT
GabrielPontolillo
# class that inherits from property based test from qiskit import QuantumCircuit from QiskitPBT.property import Property from QiskitPBT.input_generators import RandomState, RandomUnitary from QiskitPBT.case_studies.quantum_teleportation.quantum_teleportation import quantum_teleportation class UnitaryBeforeAndAfterTeleport(Property): # specify the inputs that are to be generated def get_input_generators(self): state = RandomState(1) unitary = RandomUnitary(1, 1) return [state, unitary] # specify the preconditions for the test def preconditions(self, q0, unitary): return True # specify the operations to be performed on the input def operations(self, q0, unitary): # apply unitary on first qubit then teleport qc = QuantumCircuit(3, 3) qc.initialize(q0, [0]) qc.append(unitary, [0]) qt = quantum_teleportation() # stitch qc and quantum_teleportation together qc = qc.compose(qt) # apply teleport then apply unitary on third qubit qc2 = QuantumCircuit(3, 3) qc2.initialize(q0, [0]) qt2 = quantum_teleportation() # stitch qc and quantum_teleportation together qc2 = qc2.compose(qt2) qc2.append(unitary, [2]) self.statistical_analysis.assert_equal(self, [0, 1, 2], qc, [0, 1, 2], qc2)
https://github.com/minnukota381/Quantum-Computing-Qiskit
minnukota381
import qiskit as q %matplotlib inline from qiskit.visualization import plot_histogram from qiskit.tools.visualization import plot_bloch_multivector #secretnum = '10100' # convert decimal num to binary a = int(input("Enter Secret Number:")) secretnum = "{0:b}".format(a) circuit = q.QuantumCircuit(len(secretnum)+1, len(secretnum)) # circuit.h([0,1,2,3,4,5]) circuit.h(range(len(secretnum))) # circuit.x(6) # circuit.h(6) circuit.x(len(secretnum)) circuit.h(len(secretnum)) circuit.barrier() for i, j in enumerate(reversed(secretnum)): if j == '1': circuit.cx(i, len(secretnum)) # circuit.cx(5, 6) # circuit.cx(3, 6) # circuit.cx(0, 6) circuit.barrier() # circuit.h([0,1,2,3,4,5]) circuit.h(range(len(secretnum))) circuit.barrier() # circuit.measure([0,1,2,3,4,5],[0,1,2,3,4,5]) circuit.measure(range(len(secretnum)),range(len(secretnum))) circuit.barrier() circuit.draw(output='mpl') simulator = q.Aer.get_backend('qasm_simulator') result = q.execute(circuit, backend=simulator, shots=1).result() counts = result.get_counts() print(counts) counts = str(counts) counts = (counts[2:len(secretnum)+2]) print(counts) # convert binary num to decimal num = int(counts, 2) print("Your Secret Number is :", num) # convert decimal num to binary a = "{0:b}".format(50) print(a) # convert binary num to decimal # Convert a to base 2 s = int(a, 2) print(s)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# # your code is here # (you may find the values by hand (in mind) as well) # # vector |v> print("vector |v>") values = [-0.1, -0.3, 0.4, 0.5] total = 0 # summation of squares for i in range(len(values)): total += values[i]**2; # add the square of each value print("total is ",total) print("the missing part is",1-total) print("so, the value of 'a' can be",(1-total)**0.5,"or",-(1-total)**0.5) # square root of the missing part print() print("vector |u>") values = [1/(2**0.5), -1/(3**0.5)] total = 0 # summation of squares for i in range(len(values)): total += values[i]**2; # add the square of each value print("total is ",total) print("the missing part is",1-total) # the missing part is 1/b, square of 1/sqrt(b) # thus, b is 1/missing_part print("so, the value of 'b' should be",1/(1-total)) # # you may define your first function in a separate cell # # randomly creating a 2-dimensional quantum state from random import randrange def random_quantum_state(): first_entry = randrange(-100,101) second_entry = randrange(-100,101) length_square = first_entry**2+second_entry**2 while length_square == 0: first_entry = randrange(-100,101) second_entry = randrange(-100,101) length_square = first_entry**2+second_entry**2 first_entry = first_entry / length_square**0.5 second_entry = second_entry / length_square**0.5 return [first_entry,second_entry] # # your code is here # # testing whether a given quantum state is valid def is_quantum_state(quantum_state): length_square = 0 for i in range(len(quantum_state)): length_square += quantum_state[i]**2 print("summation of entry squares is",length_square) # there might be precision problem # the length may be very close to 1 but not exactly 1 # so we use the following trick if (length_square - 1)**2 < 0.00000001: return True return False # else # defining a function for Hadamard multiplication def hadamard(quantum_state): result_quantum_state = [0,0] # define with zero entries result_quantum_state[0] = (1/(2**0.5)) * quantum_state[0] + (1/(2**0.5)) * quantum_state[1] result_quantum_state[1] = (1/(2**0.5)) * quantum_state[0] - (1/(2**0.5)) * quantum_state[1] return result_quantum_state # we are ready for i in range(10): picked_quantum_state=random_quantum_state() print(picked_quantum_state,"this is randomly picked quantum state") print("Is it valid?",is_quantum_state(picked_quantum_state)) new_quantum_state = hadamard(picked_quantum_state) print(new_quantum_state,"this is new quantum state") print("Is it valid?",is_quantum_state(new_quantum_state)) print() # print an empty line
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import * from qiskit.visualization import plot_histogram # quantum circuit to make a Bell state bell = QuantumCircuit(2, 2) bell.h(0) bell.cx(0, 1) meas = QuantumCircuit(2, 2) meas.measure([0,1], [0,1]) # execute the quantum circuit backend = BasicAer.get_backend('qasm_simulator') # the device to run on circ = bell.compose(meas) result = backend.run(transpile(circ, backend), shots=1000).result() counts = result.get_counts(circ) print(counts) plot_histogram(counts) # Execute 2-qubit Bell state again second_result = backend.run(transpile(circ, backend), shots=1000).result() second_counts = second_result.get_counts(circ) # Plot results with legend legend = ['First execution', 'Second execution'] plot_histogram([counts, second_counts], legend=legend) plot_histogram([counts, second_counts], legend=legend, sort='desc', figsize=(15,12), color=['orange', 'black'], bar_labels=False) from qiskit.visualization import plot_state_city, plot_bloch_multivector from qiskit.visualization import plot_state_paulivec, plot_state_hinton from qiskit.visualization import plot_state_qsphere # execute the quantum circuit backend = BasicAer.get_backend('statevector_simulator') # the device to run on result = backend.run(transpile(bell, backend)).result() psi = result.get_statevector(bell) plot_state_city(psi) plot_state_hinton(psi) plot_state_qsphere(psi) plot_state_paulivec(psi) plot_bloch_multivector(psi) plot_state_city(psi, title="My City", color=['black', 'orange']) plot_state_hinton(psi, title="My Hinton") plot_state_paulivec(psi, title="My Paulivec", color=['purple', 'orange', 'green']) plot_bloch_multivector(psi, title="My Bloch Spheres") from qiskit.visualization import plot_bloch_vector plot_bloch_vector([0,1,0]) plot_bloch_vector([0,1,0], title='My Bloch Sphere') import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
import numpy as np from sklearn.datasets.samples_generator import make_blobs from qiskit.aqua.utils import split_dataset_to_data_and_labels from sklearn import svm from utility import breast_cancer_pca from matplotlib import pyplot as plt %matplotlib inline %load_ext autoreload %autoreload 2 n = 2 # number of principal components kept training_dataset_size = 20 testing_dataset_size = 10 sample_Total, training_input, test_input, class_labels = breast_cancer_pca(training_dataset_size, testing_dataset_size, n) data_train, _ = split_dataset_to_data_and_labels(training_input) data_test, _ = split_dataset_to_data_and_labels(test_input) print (f"data_train[0].shape: {data_train[0].shape}" ) print (f"data_train[1].shape: {data_train[1].shape}" ) # We use the function of scikit learn to generate linearly separable blobs centers = [(2.5,0),(0,2.5)] x, y = make_blobs(n_samples=100, centers=centers, n_features=2,random_state=0,cluster_std=0.5) fig,ax=plt.subplots(1,2,figsize=(12,4)) ax[0].scatter(data_train[0][:,0],data_train[0][:,1],c=data_train[1]) ax[0].set_title('Breast Cancer dataset'); ax[1].scatter(x[:,0],x[:,1],c=y) ax[1].set_title('Blobs linearly separable'); plt.scatter(data_train[0][:,0],data_train[0][:,1],c=data_train[1]) plt.title('Breast Cancer dataset'); model= svm.LinearSVC() model.fit(data_train[0], data_train[1]) #small utility function # some utility functions def make_meshgrid(x, y, h=.02): x_min, x_max = x.min() - 1, x.max() + 1 y_min, y_max = y.min() - 1, y.max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) return xx, yy def plot_contours(ax, clf, xx, yy, **params): Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) out = ax.contourf(xx, yy, Z, **params) return out accuracy_train = model.score(data_train[0], data_train[1]) accuracy_test = model.score(data_test[0], data_test[1]) X0, X1 = data_train[0][:, 0], data_train[0][:, 1] xx, yy = make_meshgrid(X0, X1) Z = model.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) fig,ax=plt.subplots(1,2,figsize=(15,5)) ax[0].contourf(xx, yy, Z, cmap=plt.cm.coolwarm) ax[0].scatter(data_train[0][:,0], data_train[0][:,1], c=data_train[1]) ax[0].set_title('Accuracy on the training set: '+str(accuracy_train)); ax[1].contourf(xx, yy, Z, cmap=plt.cm.coolwarm) ax[1].scatter(data_test[0][:,0], data_test[0][:,1], c=data_test[1]) ax[1].set_title('Accuracy on the test set: '+str(accuracy_test)); clf = svm.SVC(gamma = 'scale') clf.fit(data_train[0], data_train[1]); accuracy_train = clf.score(data_train[0], data_train[1]) accuracy_test = clf.score(data_test[0], data_test[1]) X0, X1 = data_train[0][:, 0], data_train[0][:, 1] xx, yy = make_meshgrid(X0, X1) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) fig,ax=plt.subplots(1,2,figsize=(15,5)) ax[0].contourf(xx, yy, Z, cmap=plt.cm.coolwarm) ax[0].scatter(data_train[0][:,0], data_train[0][:,1], c=data_train[1]) ax[0].set_title('Accuracy on the training set: '+str(accuracy_train)); ax[1].contourf(xx, yy, Z, cmap=plt.cm.coolwarm) ax[1].scatter(data_test[0][:,0], data_test[0][:,1], c=data_test[1]) ax[1].set_title('Accuracy on the test set: '+str(accuracy_test)); import qiskit as qk # Creating Qubits q = qk.QuantumRegister(2) # Creating Classical Bits c = qk.ClassicalRegister(2) circuit = qk.QuantumCircuit(q, c) circuit.draw('mpl') # Initialize empty circuit circuit = qk.QuantumCircuit(q, c) # Hadamard Gate on the first Qubit circuit.h(q[0]) # CNOT Gate on the first and second Qubits circuit.cx(q[0], q[1]) # Measuring the Qubits circuit.measure(q, c) circuit.draw('mpl') # Using Qiskit Aer's Qasm Simulator: Define where do you want to run the simulation. simulator = qk.BasicAer.get_backend('qasm_simulator') # Simulating the circuit using the simulator to get the result job = qk.execute(circuit, simulator, shots=100) result = job.result() # Getting the aggregated binary outcomes of the circuit. counts = result.get_counts(circuit) print (counts) from qiskit.aqua.components.feature_maps import SecondOrderExpansion feature_map = SecondOrderExpansion(feature_dimension=2, depth=1) x = np.array([0.6, 0.3]) #feature_map.construct_circuit(x) print(feature_map.construct_circuit(x)) from qiskit.aqua.algorithms import QSVM qsvm = QSVM(feature_map, training_input, test_input) #from qiskit.aqua import run_algorithm, QuantumInstance from qiskit.aqua import algorithm, QuantumInstance from qiskit import BasicAer backend = BasicAer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=10598, seed_transpiler=10598) result = qsvm.run(quantum_instance) plt.scatter(training_input['Benign'][:,0], training_input['Benign'][:,1]) plt.scatter(training_input['Malignant'][:,0], training_input['Malignant'][:,1]) length_data = len(training_input['Benign']) + len(training_input['Malignant']) print("size training set: {}".format(length_data)) #print("Matrix dimension: {}".format(result['kernel_matrix_training'].shape)) print("testing success ratio: ", result['testing_accuracy']) test_set = np.concatenate((test_input['Benign'], test_input['Malignant'])) y_test = qsvm.predict(test_set, quantum_instance) plt.scatter(test_set[:, 0], test_set[:,1], c=y_test) plt.show() plt.scatter(test_input['Benign'][:,0], test_input['Benign'][:,1]) plt.scatter(test_input['Malignant'][:,0], test_input['Malignant'][:,1]) plt.show()