repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/DmitriiNabok/QuantumKitchenSinks
DmitriiNabok
import numpy as np from matplotlib import pyplot as plt from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler from matplotlib.colors import ListedColormap seed = 12345 def plot_dataset(X, y, ax, axes=[-1, 1, -1, 1], marker='o', size=50, alpha=1.0, stepsize=0.5, grid=False, cmap=ListedColormap(['#FF0000', '#0000FF'])): """Simple routine to visualize a 2D dataset""" ax.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap, edgecolors='k', marker=marker, s=size, alpha=alpha) ax.axis(axes) ax.grid(grid, which='both') ax.set_xlabel(r"$x_1$", fontsize=24) ax.set_ylabel(r"$x_2$", fontsize=24, rotation=0) ax.xaxis.set_ticks(np.arange(axes[0], axes[1]+0.01, stepsize)) ax.yaxis.set_ticks(np.arange(axes[2], axes[3]+0.01, stepsize)) def visualize_dataset(): fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(18, 6)) ax1.set_title("Total", fontsize=24) plot_dataset(X, y, ax1) ax1.grid() ax2.set_title("Train", fontsize=24) plot_dataset(X_train, y_train, ax2, marker='s', size=80) ax2.grid() ax3.set_title("Test", fontsize=22) plot_dataset(X_test, y_test, ax3, marker='^', size=100) ax3.grid() plt.rcParams['font.size'] = 15 plt.tight_layout() plt.show() from sklearn.datasets import load_iris iris = load_iris() pair = [0, 2] X = iris.data[:, pair] y = iris.target # Data rescaling xmin = -1; xmax = 1 X = MinMaxScaler(feature_range=(xmin, xmax), copy=False).fit_transform(X) # Train/Test subdivision train_size = 20; test_size = 20 X_train, X_test, y_train, y_test = train_test_split( X, y, train_size=train_size, test_size=test_size, stratify=y, random_state=seed ) def iris_visualize_dataset(X, y, ax, marker='o'): n_classes = 3 plot_colors = ['#FF0000', '#0000FF', '#00FF00'] cmap = ListedColormap(plot_colors) for i, color in zip(range(n_classes), plot_colors): idx = np.where(y == i) ax.scatter( X[idx, 0], X[idx, 1], c=color, label=iris.target_names[i], edgecolor="black", s=50, marker=marker ) fig, axs = plt.subplots(1, 3, figsize=(18, 6)) iris_visualize_dataset(X, y, axs[0]) iris_visualize_dataset(X_train, y_train, axs[1], marker='s') iris_visualize_dataset(X_test, y_test, axs[2], marker='^') for ax in axs: ax.set_xlim(xmin, xmax) ax.set_ylim(xmin, xmax) ax.set_xlabel(iris.feature_names[pair[0]]) ax.set_ylabel(iris.feature_names[pair[1]]) plt.rcParams['font.size'] = 20 plt.suptitle("Iris dataset") plt.legend(loc="lower right") plt.tight_layout() plt.show() from sklearn.datasets import make_blobs from sklearn.preprocessing import MinMaxScaler n_samples = 400 X, y = make_blobs(n_samples=n_samples, n_features=2, centers=2, random_state=110, shuffle=True, cluster_std=1.2) y[y%2 == 0] = -1 y[y > 0] = 1 xmin = -1; xmax = 1 X = MinMaxScaler(feature_range=(xmin, xmax)).fit_transform(X) train_size = 20 test_size = 20 X_train, X_test, y_train, y_test = train_test_split( X, y, train_size=train_size, test_size=test_size, random_state=seed ) visualize_dataset() from sklearn.datasets import make_circles n_samples = 200 X, y = make_circles(n_samples, noise=0.1, factor=0.4, random_state=0) y[y%2 == 0] = -1 y[y > 0] = 1 xmin = -1; xmax = 1 X = MinMaxScaler(feature_range=(xmin, xmax)).fit_transform(X) train_size = 20 test_size = 20 X_train, X_test, y_train, y_test = train_test_split( X, y, train_size=train_size, test_size=test_size, random_state=seed ) visualize_dataset() from sklearn.datasets import make_gaussian_quantiles n_samples = 200 X, y = make_gaussian_quantiles(n_samples=n_samples, n_features=2, n_classes=2, shuffle=True, random_state=10) y = 2*y-1 # Data rescaling xmin = -1; xmax = 1 X = MinMaxScaler(feature_range=(xmin, xmax), copy=False).fit_transform(X) train_size = 20 test_size = 20 X_train, X_test, y_train, y_test = train_test_split( X, y, train_size=train_size, test_size=test_size, stratify=y, random_state=seed ) visualize_dataset() from sklearn.datasets import make_moons n_samples = 100 X, y = make_moons(n_samples=n_samples, noise=0.2, random_state=32345) y = 2*y-1 # Data rescaling xmin = -1; xmax = 1 X = MinMaxScaler(feature_range=(xmin, xmax), copy=False).fit_transform(X) train_size = 20 test_size = 20 X_train, X_test, y_train, y_test = train_test_split( X, y, train_size=train_size, test_size=test_size, stratify=y, random_state=seed ) visualize_dataset()
https://github.com/jdellaverson19/qiskit2020
jdellaverson19
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ The Bernstein-Vazirani algorithm. """ import logging import operator import numpy as np from qiskit import ClassicalRegister, QuantumCircuit from qiskit.aqua import AquaError, Pluggable, PluggableType, get_pluggable_class from qiskit.aqua.algorithms import QuantumAlgorithm from qiskit.aqua.utils import get_subsystem_density_matrix logger = logging.getLogger(__name__) class BernsteinVazirani(QuantumAlgorithm): """The Bernstein-Vazirani algorithm.""" CONFIGURATION = { 'name': 'BernsteinVazirani', 'description': 'Bernstein Vazirani', 'input_schema': { '$schema': 'http://json-schema.org/schema#', 'id': 'bv_schema', 'type': 'object', 'properties': { }, 'additionalProperties': False }, 'problems': ['hiddenstringfinding'], 'depends': [ { 'pluggable_type': 'oracle', 'default': { 'name': 'TruthTableOracle', }, }, ], } def __init__(self, oracle): self.validate(locals()) super().__init__() self._oracle = oracle self._circuit = None self._ret = {} @classmethod def init_params(cls, params, algo_input): if algo_input is not None: raise AquaError("Input instance not supported.") oracle_params = params.get(Pluggable.SECTION_KEY_ORACLE) oracle = get_pluggable_class( PluggableType.ORACLE, oracle_params['name']).init_params(params) return cls(oracle) def construct_circuit(self, measurement=False): """ Construct the quantum circuit Args: measurement (bool): Boolean flag to indicate if measurement should be included in the circuit. Returns: the QuantumCircuit object for the constructed circuit """ if self._circuit is not None: return self._circuit qc_preoracle = QuantumCircuit( self._oracle.variable_register, self._oracle.output_register, ) qc_preoracle.h(self._oracle.variable_register) qc_preoracle.x(self._oracle.output_register) qc_preoracle.h(self._oracle.output_register) qc_preoracle.barrier() # oracle circuit qc_oracle = self._oracle.circuit qc_oracle.barrier() # postoracle circuit qc_postoracle = QuantumCircuit( self._oracle.variable_register, self._oracle.output_register, ) qc_postoracle.h(self._oracle.variable_register) self._circuit = qc_preoracle + qc_oracle + qc_postoracle # measurement circuit if measurement: measurement_cr = ClassicalRegister(len(self._oracle.variable_register), name='m') self._circuit.add_register(measurement_cr) self._circuit.measure(self._oracle.variable_register, measurement_cr) return self._circuit def _run(self): if self._quantum_instance.is_statevector: qc = self.construct_circuit(measurement=False) result = self._quantum_instance.execute(qc) complete_state_vec = result.get_statevector(qc) variable_register_density_matrix = get_subsystem_density_matrix( complete_state_vec, range(len(self._oracle.variable_register), qc.width()) ) variable_register_density_matrix_diag = np.diag(variable_register_density_matrix) max_amplitude = max( variable_register_density_matrix_diag.min(), variable_register_density_matrix_diag.max(), key=abs ) max_amplitude_idx = np.where(variable_register_density_matrix_diag == max_amplitude)[0][0] top_measurement = np.binary_repr(max_amplitude_idx, len(self._oracle.variable_register)) else: qc = self.construct_circuit(measurement=True) measurement = self._quantum_instance.execute(qc).get_counts(qc) self._ret['measurement'] = measurement top_measurement = max(measurement.items(), key=operator.itemgetter(1))[0] self._ret['result'] = top_measurement return self._ret
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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. """Tests preset pass managers with 1Q backend""" from test import combine from ddt import ddt from qiskit import QuantumCircuit from qiskit.compiler import transpile from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import Fake1Q from qiskit.transpiler import TranspilerError def emptycircuit(): """Empty circuit""" return QuantumCircuit() def circuit_3516(): """Circuit from https://github.com/Qiskit/qiskit-terra/issues/3516 should fail""" circuit = QuantumCircuit(2, 1) circuit.h(0) circuit.ry(0.11, 1) circuit.measure([0], [0]) return circuit @ddt class Test1QFailing(QiskitTestCase): """1Q tests that should fail.""" @combine( circuit=[circuit_3516], level=[0, 1, 2, 3], dsc="Transpiling {circuit.__name__} at level {level} should fail", name="{circuit.__name__}_level{level}_fail", ) def test(self, circuit, level): """All the levels with all the 1Q backend""" with self.assertRaises(TranspilerError): transpile(circuit(), backend=Fake1Q(), optimization_level=level, seed_transpiler=42) @ddt class Test1QWorking(QiskitTestCase): """1Q tests that should work.""" @combine( circuit=[emptycircuit], level=[0, 1, 2, 3], dsc="Transpiling {circuit.__name__} at level {level} should work", name="{circuit.__name__}_level{level}_valid", ) def test_device(self, circuit, level): """All the levels with all the 1Q backend""" result = transpile( circuit(), backend=Fake1Q(), optimization_level=level, seed_transpiler=42 ) self.assertIsInstance(result, QuantumCircuit) @combine( circuit=[circuit_3516], level=[0, 1, 2, 3], dsc="Transpiling {circuit.__name__} at level {level} should work for simulator", name="{circuit.__name__}_level{level}_valid", ) def test_simulator(self, circuit, level): """All the levels with all the 1Q simulator backend""" # Set fake backend config to simulator backend = Fake1Q() backend._configuration.simulator = True result = transpile(circuit(), backend=backend, optimization_level=level, seed_transpiler=42) self.assertIsInstance(result, QuantumCircuit)
https://github.com/drnickallgood/simonqiskit
drnickallgood
from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.providers.aer import noise import pprint # Choose a real device to simulate IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') device = provider.get_backend('ibmq_vigo') properties = device.properties() coupling_map = device.configuration().coupling_map # Generate an Aer noise model for device noise_model = noise.device.basic_device_noise_model(properties) basis_gates = noise_model.basis_gates test2 = noise_model.to_dict() print("Noise Model") pprint.pprint(test2) print("\nCoupling Map") print(coupling_map) print("\nProperties") test = properties.to_dict() pprint.pprint(test) #print(properties) # Generate a quantum circuit #qc = QuantumCircuit(2, 2) #qc.h(0) #qc.cx(0, 1) #qc.measure([0, 1], [0, 1]) # Perform noisy simulation #backend = Aer.get_backend('qasm_simulator') ''' job_sim = execute(qc, backend, coupling_map=coupling_map, noise_model=noise_model, basis_gates=basis_gates) ''' #sim_result = job_sim.result() #print(sim_result.get_counts(qc))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import qiskit.qasm3 program = """ OPENQASM 3.0; include "stdgates.inc"; input float[64] a; qubit[3] q; bit[2] mid; bit[3] out; let aliased = q[0:1]; gate my_gate(a) c, t { gphase(a / 2); ry(a) c; cx c, t; } gate my_phase(a) c { ctrl @ inv @ gphase(a) c; } my_gate(a * 2) aliased[0], q[{1, 2}][0]; measure q[0] -> mid[0]; measure q[1] -> mid[1]; while (mid == "00") { reset q[0]; reset q[1]; my_gate(a) q[0], q[1]; my_phase(a - pi/2) q[1]; mid[0] = measure q[0]; mid[1] = measure q[1]; } if (mid[0]) { let inner_alias = q[{0, 1}]; reset inner_alias; } out = measure q; """ circuit = qiskit.qasm3.loads(program) circuit.draw("mpl")
https://github.com/Gopal-Dahale/qiskit-qulacs
Gopal-Dahale
"""Variational Quantum Eigensolver (VQE) tutorial.""" from IPython.display import clear_output import matplotlib.pyplot as plt import numpy as np from qiskit_nature.units import DistanceUnit from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.mappers import JordanWignerMapper from qiskit_nature.second_q.circuit.library import HartreeFock from qiskit_nature.second_q.algorithms import GroundStateEigensolver from qiskit_nature import settings from qiskit_algorithms.utils import algorithm_globals from qiskit.circuit.library import EfficientSU2 from qiskit_algorithms.optimizers import L_BFGS_B from qiskit_algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, VQE from qiskit_qulacs.qulacs_estimator import QulacsEstimator from qiskit_qulacs.qulacs_estimator_gradient import QulacsEstimatorGradient settings.use_pauli_sum_op = False algorithm_globals.random_seed = 42 driver = PySCFDriver( atom="H 0 0 0; H 0 0 0.735", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) problem = driver.run() fermionic_op = problem.hamiltonian.second_q_op() mapper = JordanWignerMapper() qubit_op = mapper.map(fermionic_op) print(qubit_op) print("Number of qubits:", qubit_op.num_qubits) print("Number of hamiltonian terms:", len(qubit_op)) # Get reference solution numpy_solver = NumPyMinimumEigensolver() calc = GroundStateEigensolver(mapper, numpy_solver) res_actual = calc.solve(problem) print(res_actual) exact_energy = res_actual.eigenvalues[0] print(f"Expected ground state energy: {exact_energy:.12f} Ha") # Hartree focks state num_particles = problem.num_particles num_spatial_orbitals = problem.num_spatial_orbitals init_state = HartreeFock( num_spatial_orbitals=num_spatial_orbitals, num_particles=num_particles, qubit_mapper=mapper, ) # ansatz ansatz = EfficientSU2(qubit_op.num_qubits, su2_gates=["ry"]).decompose() # Add the initial state init_state.barrier() ansatz = init_state.compose(ansatz) ansatz.draw("mpl") intermediate_info = [] def callback(eval_count, parameters, value, std): # pylint: disable=unused-argument """ A callback that can be registered with the optimizer to store the intermediate value and parameters. """ intermediate_info.append(value) clear_output(wait=True) plt.plot( intermediate_info, color="purple", lw=2, label=f"Simulated VQE {np.round(value,4)}", ) plt.ylabel("Energy") plt.xlabel("Iterations") # Exact ground state energy value plt.axhline( y=exact_energy, color="tab:red", ls="--", lw=2, label="Target: " + str(np.round(exact_energy, 4)), ) plt.legend() plt.grid() plt.show() optimizer = L_BFGS_B(maxiter=20) qulacs_estimator = QulacsEstimator() qulacs_gradient = QulacsEstimatorGradient() vqe = VQE( qulacs_estimator, ansatz, optimizer, callback=callback, gradient=qulacs_gradient ) result = vqe.compute_minimum_eigenvalue(operator=qubit_op) print(result) def rel_err(target, measured): """Compute the relative error.""" return abs((target - measured) / target) # Compute the relative error between the expected ground state energy and the VQE's output rel_error = rel_err(exact_energy, result.eigenvalue) print(f"Expected ground state energy: {exact_energy:.12f}") print(f"Computed ground state energy: {result.eigenvalue:.12f}") print(f"Relative error: {rel_error:.12f}")
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the MergeAdjacentBarriers pass""" import random import unittest from qiskit.transpiler.passes import MergeAdjacentBarriers from qiskit.converters import circuit_to_dag from qiskit import QuantumRegister, QuantumCircuit from qiskit.test import QiskitTestCase class TestMergeAdjacentBarriers(QiskitTestCase): """Test the MergeAdjacentBarriers pass""" def test_two_identical_barriers(self): """Merges two barriers that are identical into one ░ ░ ░ q_0: |0>─░──░─ -> q_0: |0>─░─ ░ ░ ░ """ qr = QuantumRegister(1, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr) circuit.barrier(qr) expected = QuantumCircuit(qr) expected.barrier(qr) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_numerous_identical_barriers(self): """Merges 5 identical barriers in a row into one ░ ░ ░ ░ ░ ░ ░ q_0: |0>─░──░──░──░──░──░─ -> q_0: |0>─░─ ░ ░ ░ ░ ░ ░ ░ """ qr = QuantumRegister(1, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr) circuit.barrier(qr) circuit.barrier(qr) circuit.barrier(qr) circuit.barrier(qr) circuit.barrier(qr) expected = QuantumCircuit(qr) expected.barrier(qr) expected = QuantumCircuit(qr) expected.barrier(qr) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_barriers_of_different_sizes(self): """Test two barriers of different sizes are merged into one ░ ░ ░ q_0: |0>─░──░─ q_0: |0>─░─ ░ ░ -> ░ q_1: |0>────░─ q_1: |0>─░─ ░ ░ """ qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr[0]) circuit.barrier(qr) expected = QuantumCircuit(qr) expected.barrier(qr) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_not_overlapping_barriers(self): """Test two barriers with no overlap are not merged (NB in these pictures they look like 1 barrier but they are actually 2 distinct barriers, this is just how the text drawer draws them) ░ ░ q_0: |0>─░─ q_0: |0>─░─ ░ -> ░ q_1: |0>─░─ q_1: |0>─░─ ░ ░ """ qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr[0]) circuit.barrier(qr[1]) expected = QuantumCircuit(qr) expected.barrier(qr[0]) expected.barrier(qr[1]) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_barriers_with_obstacle_before(self): """Test with an obstacle before the larger barrier ░ ░ ░ q_0: |0>──░───░─ q_0: |0>──────░─ ┌───┐ ░ -> ┌───┐ ░ q_1: |0>┤ H ├─░─ q_1: |0>┤ H ├─░─ └───┘ ░ └───┘ ░ """ qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr[0]) circuit.h(qr[1]) circuit.barrier(qr) expected = QuantumCircuit(qr) expected.h(qr[1]) expected.barrier(qr) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_barriers_with_obstacle_after(self): """Test with an obstacle after the larger barrier ░ ░ ░ q_0: |0>─░───░── q_0: |0>─░────── ░ ┌───┐ -> ░ ┌───┐ q_1: |0>─░─┤ H ├ q_1: |0>─░─┤ H ├ ░ └───┘ ░ └───┘ """ qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr) circuit.barrier(qr[0]) circuit.h(qr[1]) expected = QuantumCircuit(qr) expected.barrier(qr) expected.h(qr[1]) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_barriers_with_blocking_obstacle(self): """Test that barriers don't merge if there is an obstacle that is blocking ░ ┌───┐ ░ ░ ┌───┐ ░ q_0: |0>─░─┤ H ├─░─ -> q_0: |0>─░─┤ H ├─░─ ░ └───┘ ░ ░ └───┘ ░ """ qr = QuantumRegister(1, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr) circuit.h(qr) circuit.barrier(qr) expected = QuantumCircuit(qr) expected.barrier(qr) expected.h(qr) expected.barrier(qr) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_barriers_with_blocking_obstacle_long(self): """Test that barriers don't merge if there is an obstacle that is blocking ░ ┌───┐ ░ ░ ┌───┐ ░ q_0: |0>─░─┤ H ├─░─ q_0: |0>─░─┤ H ├─░─ ░ └───┘ ░ -> ░ └───┘ ░ q_1: |0>─────────░─ q_1: |0>─────────░─ ░ ░ """ qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr[0]) circuit.h(qr[0]) circuit.barrier(qr) expected = QuantumCircuit(qr) expected.barrier(qr[0]) expected.h(qr[0]) expected.barrier(qr) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_barriers_with_blocking_obstacle_narrow(self): """Test that barriers don't merge if there is an obstacle that is blocking ░ ┌───┐ ░ ░ ┌───┐ ░ q_0: |0>─░─┤ H ├─░─ q_0: |0>─░─┤ H ├─░─ ░ └───┘ ░ -> ░ └───┘ ░ q_1: |0>─░───────░─ q_1: |0>─░───────░─ ░ ░ ░ ░ """ qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr) circuit.h(qr[0]) circuit.barrier(qr) expected = QuantumCircuit(qr) expected.barrier(qr) expected.h(qr[0]) expected.barrier(qr) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_barriers_with_blocking_obstacle_twoQ(self): """Test that barriers don't merge if there is an obstacle that is blocking ░ ░ ░ ░ q_0: |0>─░───────░─ q_0: |0>─░───────░─ ░ ░ ░ ░ q_1: |0>─░───■───── -> q_1: |0>─░───■───── ░ ┌─┴─┐ ░ ░ ┌─┴─┐ ░ q_2: |0>───┤ X ├─░─ q_2: |0>───┤ X ├─░─ └───┘ ░ └───┘ ░ """ qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.barrier(0, 1) circuit.cx(1, 2) circuit.barrier(0, 2) expected = QuantumCircuit(qr) expected.barrier(0, 1) expected.cx(1, 2) expected.barrier(0, 2) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_output_deterministic(self): """Test that the output barriers have a deterministic ordering (independent of PYTHONHASHSEED). This is important to guarantee that any subsequent topological iterations through the circuit are also deterministic; it's in general not possible for all transpiler passes to produce identical outputs across all valid topological orderings, especially if those passes have some stochastic element.""" order = list(range(20)) random.Random(2023_02_10).shuffle(order) circuit = QuantumCircuit(20) circuit.barrier([5, 2, 3]) circuit.barrier([7, 11, 14, 2, 4]) circuit.barrier(order) # All the barriers should get merged together. expected = QuantumCircuit(20) expected.barrier(range(20)) output = MergeAdjacentBarriers()(circuit) self.assertEqual(expected, output) # This assertion is that the ordering of the arguments in the barrier is fixed. self.assertEqual(list(output.data[0].qubits), list(output.qubits)) if __name__ == "__main__": unittest.main()
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/drithidavuluri/Implementation-of-Algorithm-using-Qiskit
drithidavuluri
# Importing Libraries import torch from torch import cat, no_grad, manual_seed from torch.utils.data import DataLoader from torchvision import transforms import torch.optim as optim from torch.nn import ( Module, Conv2d, Linear, Dropout2d, NLLLoss ) import torch.nn.functional as F import numpy as np import matplotlib.pyplot as plt from qiskit_machine_learning.neural_networks import EstimatorQNN from qiskit_machine_learning.connectors import TorchConnector from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap from qiskit import QuantumCircuit from qiskit.visualization import circuit_drawer # Imports for CIFAR-10s from torchvision.datasets import CIFAR10 from torchvision import transforms def prepare_data(X, labels_to_keep, batch_size): # Filtering out labels (originally 0-9), leaving only labels 0 and 1 filtered_indices = [i for i in range(len(X.targets)) if X.targets[i] in labels_to_keep] X.data = X.data[filtered_indices] X.targets = [X.targets[i] for i in filtered_indices] # Defining dataloader with filtered data loader = DataLoader(X, batch_size=batch_size, shuffle=True) return loader # Set seed for reproducibility manual_seed(42) # CIFAR-10 data transformation transform = transforms.Compose([ transforms.ToTensor(), # convert the images to tensors transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) # Normalization usign mean and std. ]) labels_to_keep = [0, 1] batch_size = 1 # Preparing Train Data X_train = CIFAR10(root="./data", train=True, download=True, transform=transform) train_loader = prepare_data(X_train, labels_to_keep, batch_size) # Preparing Test Data X_test = CIFAR10(root="./data", train=False, download=True, transform=transform) test_loader = prepare_data(X_test, labels_to_keep, batch_size) print(f"Training dataset size: {len(train_loader.dataset)}") print(f"Test dataset size: {len(test_loader.dataset)}") # Defining and creating QNN def create_qnn(): feature_map = ZZFeatureMap(2) # ZZFeatureMap with 2 bits, entanglement between qubits based on the pairwise product of input features. ansatz = RealAmplitudes(2, reps=1) # parameters (angles, in the case of RealAmplitudes) that are adjusted during the training process to optimize the quantum model for a specific task. qc = QuantumCircuit(2) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) qnn = EstimatorQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, input_gradients=True, ) return qnn qnn = create_qnn() # Visualizing the QNN circuit circuit_drawer(qnn.circuit, output='mpl') # Defining torch NN module class Net(Module): def __init__(self, qnn): super().__init__() self.conv1 = Conv2d(3, 16, kernel_size=3, padding=1) self.conv2 = Conv2d(16, 32, kernel_size=3, padding=1) self.dropout = Dropout2d() self.fc1 = Linear(32 * 8 * 8, 64) self.fc2 = Linear(64, 2) # 2-dimensional input to QNN self.qnn = TorchConnector(qnn) self.fc3 = Linear(1, 1) # 1-dimensional output from QNN def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) x = x.view(x.shape[0], -1) x = F.relu(self.fc1(x)) x = self.fc2(x) x = self.qnn(x) x = self.fc3(x) return cat((x, 1 - x), -1) # Creating model model = Net(qnn) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model.to(device) # Defining model, optimizer, and loss function optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = NLLLoss() # Starting training epochs = 10 loss_list = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): data, target = data.to(device), target.to(device) # Move data to GPU optimizer.zero_grad(set_to_none=True) output = model(data) loss = loss_func(output, target) loss.backward() optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss) / len(total_loss)) print("Training [{:.0f}%]\tLoss: {:.4f}".format(100.0 * (epoch + 1) / epochs, loss_list[-1])) # Plotting loss convergence plt.plot(loss_list) plt.title("Hybrid NN Training Convergence") plt.xlabel("Training Iterations") plt.ylabel("Neg. Log Likelihood Loss") plt.show() # Saving the model torch.save( model.state_dict(), "model_cifar10_10EPOCHS.pt") # Loading the model qnn_cifar10 = create_qnn() model_cifar10 = Net(qnn_cifar10) model_cifar10.load_state_dict(torch.load("model_cifar10.pt")) correct = 0 total = 0 model_cifar10.eval() with torch.no_grad(): for data, target in test_loader: output = model_cifar10(data) _, predicted = torch.max(output.data, 1) total += target.size(0) correct += (predicted == target).sum().item() # Calculating and print test accuracy test_accuracy = correct / total * 100 print(f"Test Accuracy: {test_accuracy:.2f}%") # Plotting predicted labels n_samples_show = 6 count = 0 fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) model_cifar10.eval() with no_grad(): for batch_idx, (data, target) in enumerate(test_loader): if count == n_samples_show: break output = model_cifar10(data) if len(output.shape) == 1: output = output.reshape(1, *output.shape) pred = output.argmax(dim=1, keepdim=True) axes[count].imshow(np.transpose(data[0].numpy(), (1, 2, 0))) axes[count].set_xticks([]) axes[count].set_yticks([]) axes[count].set_title("Predicted {0}\n Actual {1}".format(pred.item(), target.item())) count += 1 plt.show()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeBoeblingen backend = FakeBoeblingen() ghz = QuantumCircuit(5) ghz.h(0) ghz.cx(0,range(1,5)) circ = transpile(ghz, backend, scheduling_method="asap") circ.draw(output='mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_optimization import QuadraticProgram problem = QuadraticProgram("sample") problem.binary_var("x") problem.binary_var("y") problem.maximize(linear={"x": 1, "y": -2}) print(problem.prettyprint()) from qiskit.algorithms import NumPyMinimumEigensolver from qiskit_optimization.algorithms import MinimumEigenOptimizer mes = NumPyMinimumEigensolver() meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_optimization.algorithms import MinimumEigenOptimizer mes = NumPyMinimumEigensolver() meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit import BasicAer from qiskit.algorithms import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.utils import QuantumInstance from qiskit_optimization.algorithms import MinimumEigenOptimizer backend = BasicAer.get_backend("qasm_simulator") shots = 1000 qins = QuantumInstance(backend=backend, shots=shots) mes = QAOA(optimizer=COBYLA(), quantum_instance=qins) meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit.algorithms.minimum_eigensolvers import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit_optimization.algorithms import MinimumEigenOptimizer shots = 1000 mes = QAOA(sampler=Sampler(), optimizer=COBYLA()) meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit import BasicAer from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import RealAmplitudes from qiskit.utils import QuantumInstance from qiskit_optimization.algorithms import MinimumEigenOptimizer backend = BasicAer.get_backend("qasm_simulator") shots = 1000 qins = QuantumInstance(backend=backend, shots=shots) mes = VQE(ansatz=RealAmplitudes(), optimizer=COBYLA(), quantum_instance=qins) meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit.algorithms.minimum_eigensolvers import SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Sampler from qiskit_optimization.algorithms import MinimumEigenOptimizer mes = SamplingVQE(sampler=Sampler(), ansatz=RealAmplitudes(), optimizer=COBYLA()) meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Estimator from qiskit_optimization.algorithms import MinimumEigenOptimizer mes = VQE(estimator=Estimator(), ansatz=RealAmplitudes(), optimizer=COBYLA()) try: meo = MinimumEigenOptimizer(min_eigen_solver=mes) except TypeError as ex: print(ex) from qiskit import BasicAer from qiskit.algorithms import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.utils import QuantumInstance from qiskit_optimization.algorithms import WarmStartQAOAOptimizer, SlsqpOptimizer backend = BasicAer.get_backend("qasm_simulator") shots = 1000 qins = QuantumInstance(backend=backend, shots=shots) qaoa = QAOA(optimizer=COBYLA(), quantum_instance=qins) optimizer = WarmStartQAOAOptimizer( pre_solver=SlsqpOptimizer(), relax_for_pre_solver=True, qaoa=qaoa, epsilon=0.25 ) result = optimizer.solve(problem) print(result) from qiskit.algorithms.minimum_eigensolvers import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit_optimization.algorithms import WarmStartQAOAOptimizer, SlsqpOptimizer qaoa = QAOA(sampler=Sampler(), optimizer=COBYLA()) optimizer = WarmStartQAOAOptimizer( pre_solver=SlsqpOptimizer(), relax_for_pre_solver=True, qaoa=qaoa, epsilon=0.25 ) result = optimizer.solve(problem) print(result) from qiskit import BasicAer from qiskit.algorithms.optimizers import COBYLA from qiskit.utils import QuantumInstance from qiskit_optimization.algorithms import GroverOptimizer backend = BasicAer.get_backend("qasm_simulator") shots = 1000 qins = QuantumInstance(backend=backend, shots=shots) optimizer = GroverOptimizer(num_value_qubits=3, num_iterations=3, quantum_instance=qins) result = optimizer.solve(problem) print(result) from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit_optimization.algorithms import GroverOptimizer optimizer = GroverOptimizer(num_value_qubits=3, num_iterations=3, sampler=Sampler()) result = optimizer.solve(problem) print(result) from qiskit import BasicAer from qiskit.algorithms.optimizers import COBYLA from qiskit.utils import QuantumInstance from qiskit.primitives import Sampler from qiskit_optimization.algorithms import GroverOptimizer backend = BasicAer.get_backend("qasm_simulator") shots = 1000 qins = QuantumInstance(backend=backend, shots=shots) try: optimizer = GroverOptimizer( num_value_qubits=3, num_iterations=3, quantum_instance=qins, sampler=Sampler() ) # raises an error because both quantum_instance and sampler are set. except ValueError as ex: print(ex) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/GabrielPontolillo/QiskitPBT
GabrielPontolillo
from qiskit import QuantumCircuit import random from QiskitPBT.input_generators import InputGenerator class RandomGroversOracleMarkedStatesPairGenerator(InputGenerator): def __init__(self, low: int, high: int, marked_states: str | int = "random"): if low < 2: raise ValueError("Low must be greater than or equal to 2") self.low = low self.high = high self.marked_states = marked_states # generate a random grover's oracle with less than half of the states marked def generate(self, seed): random.seed(seed) num_qubits = random.randint(self.low, self.high) circuit = QuantumCircuit(num_qubits) N = 2**(num_qubits-1) if self.marked_states == "random": # choose to generate a random number of marked states, guaranteed to be less than 1/2 N states M = random.randint(1, (N//2)-1) elif self.marked_states == "too_many": M = random.randint((N//2)+1, N-1) else: M = self.marked_states # chooses M random states to mark from the set of all states that can be marked with the given number of qubits marked_states = tuple(random.sample(range(N - 1), M)) for state in marked_states: marking_circ = marking_circuit(num_qubits, state) circuit = circuit.compose(marking_circ) return circuit, marked_states # this is under the assumption that the MSB is q_0 def marking_circuit(num_qubits: int, integer_to_mark: int): assert 0 <= integer_to_mark < 2 ** (num_qubits-1), f"tried to mark a state :{integer_to_mark} that is larger than: {2**(num_qubits-1) - 1} for the number of upper register qubits {num_qubits-1}" circuit = QuantumCircuit(num_qubits) # print(integer_to_mark) binary = bin(integer_to_mark)[2:] binary = '0' * (num_qubits - 1 - len(binary)) + binary binary = binary[::-1] for idx, bit in enumerate(binary): if bit == '0': circuit.x(idx) # control over all qubits in the circuit (minus workspace register) circuit.mcx(list(range(num_qubits - 1)), num_qubits - 1) # uncompute the marked state for idx, bit in enumerate(binary): if bit == '0': circuit.x(idx) return circuit
https://github.com/SanNare/qiskit-notebooks
SanNare
from qiskit import QuantumCircuit from qiskit.tools.visualization import plot_histogram from qiskit.extensions import UnitaryGate import numpy as np def logicalAnd(circuit,input_qubits,output_qubit): circuit.mcx(input_qubits,output_qubit) def logicalOr(circuit,input_qubits,output_qubit): for i in input_qubits: circuit.x(i) circuit.x(output_qubit) circuit.mcx(input_qubits,output_qubit) for i in input_qubits: circuit.x(i) def CNF(maxterms): n = len(maxterms[0]) m = len(maxterms) circuit = QuantumCircuit(n+m+1) o = n for t in maxterms: inp = [] for i in range(0,n): if t[i] == -1: circuit.x(i) inp.append(i) elif t[i] == 1: inp.append(i) logicalOr(circuit,inp,o) for i in range(0,n): if t[i] == -1: circuit.x(i) o = o+1 logicalAnd(circuit,list(range(n,n+m)),n+m) return circuit.to_gate() def diffusion(n): m = np.identity(2**n) for i in range(1,2**n): m[i][i] = -1 return UnitaryGate(m) def grover(maxterms,rounds = 0): n = len(maxterms[0]) #number of variables N = 2**n #solution space size m = len(maxterms) #number of maxterms if rounds == 0: r = int(np.ceil(np.pi/(4*np.arcsin(1/np.sqrt(N)))-0.5)) else: r = rounds circuit = QuantumCircuit(n+m+1,n) circuit.x(n+m) circuit.h(n+m) for i in range(n): circuit.h(i) cnf = CNF(maxterms) cnf.label = 'Uf' diff = diffusion(n) diff.label = 'Diff' for i in range(r): circuit.append(cnf,range(n+m+1)) for i in range(n,n+m): circuit.reset(i) for i in range(n): circuit.h(i) circuit.append(diff,range(n)) for i in range(n): circuit.h(i) for i in range(n): circuit.measure(i,i) return circuit maxterms = [[1,1,1],[-1,-1,-1]] # This seems to behave like f(x,y,z) = xyz + x'y'z' (DNF) even though the function is CNF circuit = grover(maxterms) #circuit = grover(maxterms) circuit.draw('mpl') from qiskit import Aer, execute simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, simulator, shots=1000).result() counts = result.get_counts(circuit) print(counts) plot_histogram(counts)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests PassManager.run()""" from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit.library import CXGate from qiskit.transpiler.preset_passmanagers import level_1_pass_manager from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeMelbourne from qiskit.transpiler import Layout, PassManager from qiskit.transpiler.passmanager_config import PassManagerConfig class TestPassManagerRun(QiskitTestCase): """Test default_pass_manager.run(circuit(s)).""" def test_bare_pass_manager_single(self): """Test that PassManager.run(circuit) returns a single circuit.""" qc = QuantumCircuit(1) pm = PassManager([]) new_qc = pm.run(qc) self.assertIsInstance(new_qc, QuantumCircuit) self.assertEqual(qc, new_qc) # pm has no passes def test_bare_pass_manager_single_list(self): """Test that PassManager.run([circuit]) returns a list with a single circuit.""" qc = QuantumCircuit(1) pm = PassManager([]) result = pm.run([qc]) self.assertIsInstance(result, list) self.assertEqual(len(result), 1) self.assertIsInstance(result[0], QuantumCircuit) self.assertEqual(result[0], qc) # pm has no passes def test_bare_pass_manager_multiple(self): """Test that PassManager.run(circuits) returns a list of circuits.""" qc0 = QuantumCircuit(1) qc1 = QuantumCircuit(2) pm = PassManager([]) result = pm.run([qc0, qc1]) self.assertIsInstance(result, list) self.assertEqual(len(result), 2) for qc, new_qc in zip([qc0, qc1], result): self.assertIsInstance(new_qc, QuantumCircuit) self.assertEqual(new_qc, qc) # pm has no passes def test_default_pass_manager_single(self): """Test default_pass_manager.run(circuit). circuit: qr0:-[H]--.------------ -> 1 | qr1:-----(+)--.-------- -> 2 | qr2:---------(+)--.---- -> 3 | qr3:-------------(+)--- -> 5 device: 0 - 1 - 2 - 3 - 4 - 5 - 6 | | | | | | 13 - 12 - 11 - 10 - 9 - 8 - 7 """ qr = QuantumRegister(4, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[2]) circuit.cx(qr[2], qr[3]) coupling_map = FakeMelbourne().configuration().coupling_map initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]] pass_manager = level_1_pass_manager( PassManagerConfig.from_backend( FakeMelbourne(), initial_layout=Layout.from_qubit_list(initial_layout), seed_transpiler=42, ) ) new_circuit = pass_manager.run(circuit) self.assertIsInstance(new_circuit, QuantumCircuit) bit_indices = {bit: idx for idx, bit in enumerate(new_circuit.qregs[0])} for instruction in new_circuit.data: if isinstance(instruction.operation, CXGate): self.assertIn([bit_indices[x] for x in instruction.qubits], coupling_map) def test_default_pass_manager_two(self): """Test default_pass_manager.run(circuitS). circuit1 and circuit2: qr0:-[H]--.------------ -> 1 | qr1:-----(+)--.-------- -> 2 | qr2:---------(+)--.---- -> 3 | qr3:-------------(+)--- -> 5 device: 0 - 1 - 2 - 3 - 4 - 5 - 6 | | | | | | 13 - 12 - 11 - 10 - 9 - 8 - 7 """ qr = QuantumRegister(4, "qr") circuit1 = QuantumCircuit(qr) circuit1.h(qr[0]) circuit1.cx(qr[0], qr[1]) circuit1.cx(qr[1], qr[2]) circuit1.cx(qr[2], qr[3]) circuit2 = QuantumCircuit(qr) circuit2.cx(qr[1], qr[2]) circuit2.cx(qr[0], qr[1]) circuit2.cx(qr[2], qr[3]) coupling_map = FakeMelbourne().configuration().coupling_map initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]] pass_manager = level_1_pass_manager( PassManagerConfig.from_backend( FakeMelbourne(), initial_layout=Layout.from_qubit_list(initial_layout), seed_transpiler=42, ) ) new_circuits = pass_manager.run([circuit1, circuit2]) self.assertIsInstance(new_circuits, list) self.assertEqual(len(new_circuits), 2) for new_circuit in new_circuits: self.assertIsInstance(new_circuit, QuantumCircuit) bit_indices = {bit: idx for idx, bit in enumerate(new_circuit.qregs[0])} for instruction in new_circuit.data: if isinstance(instruction.operation, CXGate): self.assertIn([bit_indices[x] for x in instruction.qubits], coupling_map)
https://github.com/rubenandrebarreiro/summer-school-on-quantum-computing-software-for-near-term-quantum-devices-2020
rubenandrebarreiro
import numpy as np import numpy.fft import matplotlib.pyplot as plt from qiskit.aqua.circuits import StateVectorCircuit from qiskit.circuit.library import QFT, Barrier from qiskit import QuantumCircuit, QuantumRegister, execute, Aer def normalize(ψ): n = np.linalg.norm(ψ) return ψ if n == 0 else ψ / n def wavefunction(circuit): backend = Aer.get_backend('statevector_simulator') return execute(circuit.copy(), backend).result().get_statevector() def exercise1(): l = 4 # Number of qubits N = 2**l L = 8 Δx = L/N x = -L/2 + Δx * np.arange(N) # # Discretize our function, and normalize it to turn it into a # quantum state f = normalize(np.exp(-x**2/2.0)) # # Use Qiskit to build a quantum circuit that constructs the # quantum state associated to the discretize function 'f' f_qc = StateVectorCircuit(f).construct_circuit() fig, ax = plt.subplots(nrows=1,ncols=1,figsize=(8,4)) ax.plot(x, f, '-') ax.plot(x, np.abs(wavefunction(f_qc)), '.') ax.set_title(f'$f$ with $N={N}$') exercise1() from qiskit.circuit.library import QFT QFT(3, insert_barriers=True).draw() def fQFT(nqubits, **kwdargs): circuit = QuantumCircuit(nqubits) return circuit.compose(QFT(nqubits, **kwdargs), qubits=list(reversed(range(0,nqubits)))) fQFT(3).draw() fQFT(3, insert_barriers=True, do_swaps=True, inverse=True).draw() def exercise3(): l = 4 # Number of qubits N = 2**l L = 8 Δx = L/N x = -L/2 + Δx * np.arange(N) # # The original function f = normalize(np.exp(-x**2/2.0)) # # Construct the circuit for the function 'f' f_qc = StateVectorCircuit(f).construct_circuit() # # Construct the circuit for the Quantum Fourier Transform qft_circuit = QFT(l, do_swaps=True) # # The QFT acts on the qubits of the circuit in the opposite # order than we would like. We explicit this order when # we compose the circuits qft_order = list(reversed(range(0, l))) # Ff = f_qc.compose(qft_circuit, qubits=qft_order) # # We can also compute the classical fourier transform using # Python's numpy library DFTf = np.fft.fft(f) fig, ax = plt.subplots(nrows=1,ncols=1,figsize=(8,4)) ax.plot(x, f, '-', label='f') ax.plot(x, normalize(np.abs(DFTf)), label='$\\tilde{f}$') ax.plot(x, np.abs(wavefunction(Ff)), '.', label='$QFT$') ax.set_title(f'$f$ with $N={N}$') ax.legend() exercise3() aux=QuantumCircuit(4) aux.cx(1,3) aux.cx(1,2) aux.draw() steps = QuantumCircuit(4) steps.compose(fQFT(3, insert_barriers=True), qubits=[0,1,2], inplace=True) steps.cx(2,3) steps.compose(fQFT(4, insert_barriers=True), inplace=True) steps.draw() def exercise6(): l = 4 # Number of input qubits N = 2**l L = 8 Δx = L/N x = -L/2 + Δx * np.arange(N) lfinal = l+2 # Number of qubits for interpolation xfinal = -L/2 + (Δx/2**(lfinal-l)) * np.arange(2**lfinal) # # Our circuit (with the final number of qubits) steps = QuantumCircuit(lfinal) # # The original function f = normalize(np.exp(-x**2/2.0)) # # The interpolated one ffinal = normalize(np.exp(-xfinal**2/2.0)) # # Construct the circuit for the function 'f' f_qc = StateVectorCircuit(f).construct_circuit() steps.compose(f_qc, qubits=range(0,l), inplace=True) # # Construct the circuit for the Quantum Fourier Transform steps.compose(fQFT(l, insert_barriers=True), qubits=list(range(0, l)), inplace=True) # # Implement padding for i in range(l, lfinal): steps.cx(l-1,i) # # Implement the inverse transform steps.compose(fQFT(lfinal, inverse=True, insert_barriers=True), inplace=True) #print(steps.draw()) fig, ax = plt.subplots(nrows=1,ncols=1,figsize=(8,4)) ax.plot(xfinal, ffinal, '-', label='exact') ax.plot(xfinal, np.abs(wavefunction(steps)), '.', label='interpolated') ax.set_title(f'Interpolate $f$ from {l} to {lfinal} qubits') ax.legend() exercise6()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# Necessary imports import numpy as np import matplotlib.pyplot as plt from torch import Tensor from torch.nn import Linear, CrossEntropyLoss, MSELoss from torch.optim import LBFGS from qiskit import QuantumCircuit from qiskit.utils import algorithm_globals from qiskit.circuit import Parameter from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap from qiskit_machine_learning.neural_networks import SamplerQNN, EstimatorQNN from qiskit_machine_learning.connectors import TorchConnector # Set seed for random generators algorithm_globals.random_seed = 42 # Generate random dataset # Select dataset dimension (num_inputs) and size (num_samples) num_inputs = 2 num_samples = 20 # Generate random input coordinates (X) and binary labels (y) X = 2 * algorithm_globals.random.random([num_samples, num_inputs]) - 1 y01 = 1 * (np.sum(X, axis=1) >= 0) # in { 0, 1}, y01 will be used for SamplerQNN example y = 2 * y01 - 1 # in {-1, +1}, y will be used for EstimatorQNN example # Convert to torch Tensors X_ = Tensor(X) y01_ = Tensor(y01).reshape(len(y)).long() y_ = Tensor(y).reshape(len(y), 1) # Plot dataset for x, y_target in zip(X, y): if y_target == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() # Set up a circuit feature_map = ZZFeatureMap(num_inputs) ansatz = RealAmplitudes(num_inputs) qc = QuantumCircuit(num_inputs) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) qc.draw("mpl") # Setup QNN qnn1 = EstimatorQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters ) # Set up PyTorch module # Note: If we don't explicitly declare the initial weights # they are chosen uniformly at random from [-1, 1]. initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn1.num_weights) - 1) model1 = TorchConnector(qnn1, initial_weights=initial_weights) print("Initial weights: ", initial_weights) # Test with a single input model1(X_[0, :]) # Define optimizer and loss optimizer = LBFGS(model1.parameters()) f_loss = MSELoss(reduction="sum") # Start training model1.train() # set model to training mode # Note from (https://pytorch.org/docs/stable/optim.html): # Some optimization algorithms such as LBFGS need to # reevaluate the function multiple times, so you have to # pass in a closure that allows them to recompute your model. # The closure should clear the gradients, compute the loss, # and return it. def closure(): optimizer.zero_grad() # Initialize/clear gradients loss = f_loss(model1(X_), y_) # Evaluate loss function loss.backward() # Backward pass print(loss.item()) # Print loss return loss # Run optimizer step4 optimizer.step(closure) # Evaluate model and compute accuracy y_predict = [] for x, y_target in zip(X, y): output = model1(Tensor(x)) y_predict += [np.sign(output.detach().numpy())[0]] print("Accuracy:", sum(y_predict == y) / len(y)) # Plot results # red == wrongly classified for x, y_target, y_p in zip(X, y, y_predict): if y_target == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") if y_target != y_p: plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2) plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() # Define feature map and ansatz feature_map = ZZFeatureMap(num_inputs) ansatz = RealAmplitudes(num_inputs, entanglement="linear", reps=1) # Define quantum circuit of num_qubits = input dim # Append feature map and ansatz qc = QuantumCircuit(num_inputs) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) # Define SamplerQNN and initial setup parity = lambda x: "{:b}".format(x).count("1") % 2 # optional interpret function output_shape = 2 # parity = 0, 1 qnn2 = SamplerQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, interpret=parity, output_shape=output_shape, ) # Set up PyTorch module # Reminder: If we don't explicitly declare the initial weights # they are chosen uniformly at random from [-1, 1]. initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn2.num_weights) - 1) print("Initial weights: ", initial_weights) model2 = TorchConnector(qnn2, initial_weights) # Define model, optimizer, and loss optimizer = LBFGS(model2.parameters()) f_loss = CrossEntropyLoss() # Our output will be in the [0,1] range # Start training model2.train() # Define LBFGS closure method (explained in previous section) def closure(): optimizer.zero_grad(set_to_none=True) # Initialize gradient loss = f_loss(model2(X_), y01_) # Calculate loss loss.backward() # Backward pass print(loss.item()) # Print loss return loss # Run optimizer (LBFGS requires closure) optimizer.step(closure); # Evaluate model and compute accuracy y_predict = [] for x in X: output = model2(Tensor(x)) y_predict += [np.argmax(output.detach().numpy())] print("Accuracy:", sum(y_predict == y01) / len(y01)) # plot results # red == wrongly classified for x, y_target, y_ in zip(X, y01, y_predict): if y_target == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") if y_target != y_: plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2) plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() # Generate random dataset num_samples = 20 eps = 0.2 lb, ub = -np.pi, np.pi f = lambda x: np.sin(x) X = (ub - lb) * algorithm_globals.random.random([num_samples, 1]) + lb y = f(X) + eps * (2 * algorithm_globals.random.random([num_samples, 1]) - 1) plt.plot(np.linspace(lb, ub), f(np.linspace(lb, ub)), "r--") plt.plot(X, y, "bo") plt.show() # Construct simple feature map param_x = Parameter("x") feature_map = QuantumCircuit(1, name="fm") feature_map.ry(param_x, 0) # Construct simple feature map param_y = Parameter("y") ansatz = QuantumCircuit(1, name="vf") ansatz.ry(param_y, 0) qc = QuantumCircuit(1) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) # Construct QNN qnn3 = EstimatorQNN(circuit=qc, input_params=[param_x], weight_params=[param_y]) # Set up PyTorch module # Reminder: If we don't explicitly declare the initial weights # they are chosen uniformly at random from [-1, 1]. initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn3.num_weights) - 1) model3 = TorchConnector(qnn3, initial_weights) # Define optimizer and loss function optimizer = LBFGS(model3.parameters()) f_loss = MSELoss(reduction="sum") # Start training model3.train() # set model to training mode # Define objective function def closure(): optimizer.zero_grad(set_to_none=True) # Initialize gradient loss = f_loss(model3(Tensor(X)), Tensor(y)) # Compute batch loss loss.backward() # Backward pass print(loss.item()) # Print loss return loss # Run optimizer optimizer.step(closure) # Plot target function plt.plot(np.linspace(lb, ub), f(np.linspace(lb, ub)), "r--") # Plot data plt.plot(X, y, "bo") # Plot fitted line y_ = [] for x in np.linspace(lb, ub): output = model3(Tensor([x])) y_ += [output.detach().numpy()[0]] plt.plot(np.linspace(lb, ub), y_, "g-") plt.show() # Additional torch-related imports import torch from torch import cat, no_grad, manual_seed from torch.utils.data import DataLoader from torchvision import datasets, transforms import torch.optim as optim from torch.nn import ( Module, Conv2d, Linear, Dropout2d, NLLLoss, MaxPool2d, Flatten, Sequential, ReLU, ) import torch.nn.functional as F # Train Dataset # ------------- # Set train shuffle seed (for reproducibility) manual_seed(42) batch_size = 1 n_samples = 100 # We will concentrate on the first 100 samples # Use pre-defined torchvision function to load MNIST train data X_train = datasets.MNIST( root="./data", train=True, download=True, transform=transforms.Compose([transforms.ToTensor()]) ) # Filter out labels (originally 0-9), leaving only labels 0 and 1 idx = np.append( np.where(X_train.targets == 0)[0][:n_samples], np.where(X_train.targets == 1)[0][:n_samples] ) X_train.data = X_train.data[idx] X_train.targets = X_train.targets[idx] # Define torch dataloader with filtered data train_loader = DataLoader(X_train, batch_size=batch_size, shuffle=True) n_samples_show = 6 data_iter = iter(train_loader) fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) while n_samples_show > 0: images, targets = data_iter.__next__() axes[n_samples_show - 1].imshow(images[0, 0].numpy().squeeze(), cmap="gray") axes[n_samples_show - 1].set_xticks([]) axes[n_samples_show - 1].set_yticks([]) axes[n_samples_show - 1].set_title("Labeled: {}".format(targets[0].item())) n_samples_show -= 1 # Test Dataset # ------------- # Set test shuffle seed (for reproducibility) # manual_seed(5) n_samples = 50 # Use pre-defined torchvision function to load MNIST test data X_test = datasets.MNIST( root="./data", train=False, download=True, transform=transforms.Compose([transforms.ToTensor()]) ) # Filter out labels (originally 0-9), leaving only labels 0 and 1 idx = np.append( np.where(X_test.targets == 0)[0][:n_samples], np.where(X_test.targets == 1)[0][:n_samples] ) X_test.data = X_test.data[idx] X_test.targets = X_test.targets[idx] # Define torch dataloader with filtered data test_loader = DataLoader(X_test, batch_size=batch_size, shuffle=True) # Define and create QNN def create_qnn(): feature_map = ZZFeatureMap(2) ansatz = RealAmplitudes(2, reps=1) qc = QuantumCircuit(2) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) # REMEMBER TO SET input_gradients=True FOR ENABLING HYBRID GRADIENT BACKPROP qnn = EstimatorQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, input_gradients=True, ) return qnn qnn4 = create_qnn() # Define torch NN module class Net(Module): def __init__(self, qnn): super().__init__() self.conv1 = Conv2d(1, 2, kernel_size=5) self.conv2 = Conv2d(2, 16, kernel_size=5) self.dropout = Dropout2d() self.fc1 = Linear(256, 64) self.fc2 = Linear(64, 2) # 2-dimensional input to QNN self.qnn = TorchConnector(qnn) # Apply torch connector, weights chosen # uniformly at random from interval [-1,1]. self.fc3 = Linear(1, 1) # 1-dimensional output from QNN def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) x = x.view(x.shape[0], -1) x = F.relu(self.fc1(x)) x = self.fc2(x) x = self.qnn(x) # apply QNN x = self.fc3(x) return cat((x, 1 - x), -1) model4 = Net(qnn4) # Define model, optimizer, and loss function optimizer = optim.Adam(model4.parameters(), lr=0.001) loss_func = NLLLoss() # Start training epochs = 10 # Set number of epochs loss_list = [] # Store loss history model4.train() # Set model to training mode for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad(set_to_none=True) # Initialize gradient output = model4(data) # Forward pass loss = loss_func(output, target) # Calculate loss loss.backward() # Backward pass optimizer.step() # Optimize weights total_loss.append(loss.item()) # Store loss loss_list.append(sum(total_loss) / len(total_loss)) print("Training [{:.0f}%]\tLoss: {:.4f}".format(100.0 * (epoch + 1) / epochs, loss_list[-1])) # Plot loss convergence plt.plot(loss_list) plt.title("Hybrid NN Training Convergence") plt.xlabel("Training Iterations") plt.ylabel("Neg. Log Likelihood Loss") plt.show() torch.save(model4.state_dict(), "model4.pt") qnn5 = create_qnn() model5 = Net(qnn5) model5.load_state_dict(torch.load("model4.pt")) model5.eval() # set model to evaluation mode with no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model5(data) if len(output.shape) == 1: output = output.reshape(1, *output.shape) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print( "Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%".format( sum(total_loss) / len(total_loss), correct / len(test_loader) / batch_size * 100 ) ) # Plot predicted labels n_samples_show = 6 count = 0 fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) model5.eval() with no_grad(): for batch_idx, (data, target) in enumerate(test_loader): if count == n_samples_show: break output = model5(data[0:1]) if len(output.shape) == 1: output = output.reshape(1, *output.shape) pred = output.argmax(dim=1, keepdim=True) axes[count].imshow(data[0].numpy().squeeze(), cmap="gray") axes[count].set_xticks([]) axes[count].set_yticks([]) axes[count].set_title("Predicted {}".format(pred.item())) count += 1 import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Tojarieh97/VQE
Tojarieh97
from openfermion.chem import MolecularData from openfermion.transforms import get_fermion_operator, jordan_wigner from openfermion.linalg import get_ground_state, get_sparse_operator import numpy import scipy import scipy.linalg # Load saved file for H2. diatomic_bond_length = 1.2 geometry = [('H', (0., 0., 0.)), ('H', (0., 0., diatomic_bond_length))] basis = 'sto-3g' multiplicity = 1 # Set Hamiltonian parameters. active_space_start = 1 active_space_stop = 3 # Generate and populate instance of MolecularData. molecule = MolecularData(geometry, basis, multiplicity, description="1.2") molecule.load() # Get the Hamiltonian in an active space. molecular_hamiltonian = molecule.get_molecular_hamiltonian( occupied_indices=range(1), active_indices=range(1, 2)) # Map operator to fermions and qubits. fermion_hamiltonian = get_fermion_operator(molecular_hamiltonian) qubit_hamiltonian = jordan_wigner(fermion_hamiltonian) qubit_hamiltonian.compress() print('The Jordan-Wigner Hamiltonian in canonical basis follows:\n{}'.format(qubit_hamiltonian)) # Get sparse operator and ground state energy. sparse_hamiltonian = get_sparse_operator(qubit_hamiltonian) energy, state = get_ground_state(sparse_hamiltonian) print('Ground state energy before rotation is {} Hartree.\n'.format(energy)) # Randomly rotate. n_orbitals = molecular_hamiltonian.n_qubits // 2 n_variables = int(n_orbitals * (n_orbitals - 1) / 2) numpy.random.seed(1) random_angles = numpy.pi * (1. - 2. * numpy.random.rand(n_variables)) kappa = numpy.zeros((n_orbitals, n_orbitals)) index = 0 for p in range(n_orbitals): for q in range(p + 1, n_orbitals): kappa[p, q] = random_angles[index] kappa[q, p] = -numpy.conjugate(random_angles[index]) index += 1 # Build the unitary rotation matrix. difference_matrix = kappa + kappa.transpose() rotation_matrix = scipy.linalg.expm(kappa) # Apply the unitary. molecular_hamiltonian.rotate_basis(rotation_matrix) # Get qubit Hamiltonian in rotated basis. qubit_hamiltonian = jordan_wigner(molecular_hamiltonian) qubit_hamiltonian.compress() print('The Jordan-Wigner Hamiltonian in rotated basis follows:\n{}'.format(qubit_hamiltonian)) # Get sparse Hamiltonian and energy in rotated basis. sparse_hamiltonian = get_sparse_operator(qubit_hamiltonian) energy, state = get_ground_state(sparse_hamiltonian) print('Ground state energy after rotation is {} Hartree.'.format(energy))
https://github.com/mspronesti/qlearnkit
mspronesti
import numbers from abc import ABC from typing import List, Dict, Optional, Union import numpy as np import logging from qiskit import QuantumCircuit from qiskit.providers import Backend from qiskit.result import Result from qiskit.tools import parallel_map from qiskit.utils import QuantumInstance from ..quantum_estimator import QuantumEstimator from ...circuits import SwaptestCircuit from ...encodings import EncodingMap logger = logging.getLogger(__name__) class QNeighborsBase(QuantumEstimator, ABC): def __init__(self, n_neighbors: int = 3, encoding_map: Optional[EncodingMap] = None, quantum_instance: Optional[Union[QuantumInstance, Backend]] = None): """ Base class for Nearest Neighbors algorithms Args: n_neighbors: number of neighbors. It's the :math:`k` parameter of the knn algorithm encoding_map: map to classical data to quantum states. This class does not impose any constraint on it. quantum_instance: the quantum instance to set. Can be a :class:`~qiskit.utils.QuantumInstance` or a :class:`~qiskit.providers.Backend` """ super().__init__(encoding_map, quantum_instance) if n_neighbors <= 0: raise ValueError(f"Expected n_neighbors > 0. Got {n_neighbors}") elif not isinstance(n_neighbors, numbers.Integral): raise TypeError( "n_neighbors does not take %s value, enter integer value" % type(n_neighbors) ) self.n_neighbors = n_neighbors def fit(self, X, y): """ Fits the model using X as training dataset and y as training labels Args: X: training dataset y: training labels """ self.X_train = np.asarray(X) self.y_train = np.asarray(y) logger.info("setting training data: ") for _X, _y in zip(X, y): logger.info("%s: %s", _X, _y) def _compute_fidelity(self, counts: Dict[str, int]): r""" Computes the fidelity, used as a measure of distance, from a dictionary of counts, which refers to the swap test circuit having a test datapoint and a train datapoint as inputs employing the following formula .. math:: \sqrt{\left | \frac{counts[0] - counts[1]}{n\_shots} \right | } Args: counts: the counts resulting after the simulation Returns: the computed fidelity """ counts_0 = counts.get('0', 0) counts_1 = counts.get('1', 1) # squared fidelity f_2 = np.abs(counts_0 - counts_1) / self._quantum_instance.run_config.shots return np.sqrt(f_2) def _get_fidelities(self, results: Result, test_size: int) -> np.ndarray: r""" Retrieves the list of all fidelities given the circuit results, computed via the :func:`calculate_fidelities` method Args: results: the simulation results test_size: the size of the test dataset Returns: numpy ndarray of all fidelities """ train_size = self.X_train.shape[0] all_counts = results.get_counts() # List[Dict(str, int)] fidelities = np.empty( shape=(test_size, train_size) ) for i, (counts) in enumerate(all_counts): fidelity = self._compute_fidelity(counts) # the i-th subarray of the ndarray `fidelities` contains # the values that we will use for the majority voting to # predict the label of the i-th test input data fidelities[i // train_size][i % train_size] = fidelity return fidelities @staticmethod def _construct_circuit(feature_vector_1: np.ndarray, feature_vector_2: np.ndarray, encoding_map: EncodingMap = None) -> QuantumCircuit: r""" Constructs a swap test circuit employing a controlled swap. For instance .. parsed-literal:: ┌───┐ ┌───┐┌─┐ q_0: ────┤ H ├─────■─┤ H ├┤M├ ┌───┴───┴───┐ │ └───┘└╥┘ q_1: ┤ circuit-0 ├─X───────╫─ ├───────────┤ │ ║ q_2: ┤ circuit-1 ├─X───────╫─ └───────────┘ ║ c: 1/══════════════════════╩═ 0 where feature_vector_1 = [1,0], feature_vector_2 = [0, 1] A swap test circuit allows to measure the fidelity between two quantum states, which can be interpreted as a distance measure of some sort. In other words, given two quanutm states :math:`|\alpha\rangle, \ |\beta\rangle` it measures how symmetric the state :math:`|\alpha\rangle \otimes |\beta\rangle` is Args: feature_vector_1: first feature vector feature_vector_2: second feature vector encoding_map: the mapping to quantum state to extract a :class:`~qiskit.QuantumCircuit` Returns: swap test circuit """ if len(feature_vector_1) != len(feature_vector_2): raise ValueError("Input state vectors must have same length to" "perform swap test. Lengths were:" f"{len(feature_vector_1)}" f"{len(feature_vector_2)}") if encoding_map is None: raise ValueError("encoding map must be specified to construct" "swap test circuit") q1 = encoding_map.construct_circuit(feature_vector_1) q2 = encoding_map.construct_circuit(feature_vector_2) return SwaptestCircuit(q1, q2) def _construct_circuits(self, X_test: np.ndarray) -> List[QuantumCircuit]: """ Creates the circuits to be executed on the gated quantum computer for the classification process Args: X_test: the unclassified input data """ logger.info("Starting parallel circuits construction ...") circuits = [] for i, xtest in enumerate(X_test): # computing distance of xtest with respect to # each point in X_train circuits_line = parallel_map( QNeighborsBase._construct_circuit, self.X_train, task_args=[xtest, self._encoding_map] ) circuits = circuits + circuits_line logger.info("Done.") return circuits def _kneighbors(self, y_train: np.ndarray, fidelities: np.ndarray, *, return_indices=False): """ Retrieves the training labels associated to the :math:`k` nearest neighbors and (optionally) their indices Args: y_train: the training labels fidelities: the fidelities array return_indices: (bool) weather to return the indices or not Returns: neigh_labels: ndarray of shape (n_queries, n_neighbors) Array representing the labels of the :math:`k` nearest points neigh_indices: ndarray of shape (n_queries, n_neighbors) Array representing the indices of the :math:`k` nearest points, only present if return_indices=True. """ if np.any(fidelities < -0.2) or np.any(fidelities > 1.2): raise ValueError("Detected fidelities values not in range 0<=F<=1:" f"{fidelities[fidelities < -0.2]}" f"{fidelities[fidelities > 1.2]}") # first sort neighbors neigh_indices = np.argsort(fidelities) # extract indices according to number of neighbors # and dimension n_queries, _ = fidelities.shape if n_queries == 1: neigh_indices = neigh_indices[-self.n_neighbors:] else: neigh_indices = neigh_indices[:, -self.n_neighbors:] neigh_labels = y_train[neigh_indices] if return_indices: return neigh_labels, neigh_indices else: return neigh_labels
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit from qiskit.quantum_info import DensityMatrix from qiskit.visualization import plot_state_hinton qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0,1) qc.ry(np.pi/3 , 0) qc.rx(np.pi/5, 1) state = DensityMatrix(qc) plot_state_hinton(state, title="New Hinton Plot")
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the linear amplitude function.""" import unittest from functools import partial from collections import defaultdict from ddt import ddt, data, unpack import numpy as np from qiskit import BasicAer, execute from qiskit.test.base import QiskitTestCase from qiskit.circuit import QuantumCircuit from qiskit.circuit.library import LinearAmplitudeFunction @ddt class TestLinearAmplitudeFunctional(QiskitTestCase): """Test the functional Pauli rotations.""" def assertFunctionIsCorrect(self, function_circuit, reference): """Assert that ``function_circuit`` implements the reference function ``reference``.""" num_ancillas = function_circuit.num_ancillas num_state_qubits = function_circuit.num_qubits - num_ancillas - 1 circuit = QuantumCircuit(function_circuit.num_qubits) circuit.h(list(range(num_state_qubits))) circuit.append(function_circuit.to_instruction(), list(range(circuit.num_qubits))) backend = BasicAer.get_backend("statevector_simulator") statevector = execute(circuit, backend).result().get_statevector() probabilities = defaultdict(float) for i, statevector_amplitude in enumerate(statevector): i = bin(i)[2:].zfill(circuit.num_qubits)[num_ancillas:] probabilities[i] += np.real(np.abs(statevector_amplitude) ** 2) unrolled_probabilities = [] unrolled_expectations = [] for i, probability in probabilities.items(): x, last_qubit = int(i[1:], 2), i[0] if last_qubit == "0": expected_amplitude = np.cos(reference(x)) / np.sqrt(2**num_state_qubits) else: expected_amplitude = np.sin(reference(x)) / np.sqrt(2**num_state_qubits) unrolled_probabilities += [probability] unrolled_expectations += [np.real(np.abs(expected_amplitude) ** 2)] np.testing.assert_almost_equal(unrolled_probabilities, unrolled_expectations) def evaluate_function( self, x_int, num_qubits, slope, offset, domain, image, rescaling_factor, breakpoints=None ): """A helper function to get the expected value of the linear amplitude function.""" a, b = domain c, d = image # map integer x to the domain of the function x = a + (b - a) / (2**num_qubits - 1) * x_int # apply the function if breakpoints is None: value = offset + slope * x else: value = 0 for i, point in enumerate(reversed(breakpoints)): if x >= point: value = offset[-(i + 1)] + slope[-(i + 1)] * (x - point) break # map the value to [0, 1] normalized = (value - c) / (d - c) # prepared value for taylor approximation return np.pi / 4 + np.pi * rescaling_factor / 2 * (normalized - 0.5) @data( (2, 1, 0, (0, 3), (0, 3), 0.1, None), (3, 1, 0, (0, 1), (0, 1), 0.01, None), (1, [0, 0], [0, 0], (0, 2), (0, 1), 0.1, [0, 1]), (2, [1, -1], [0, 1], (0, 2), (0, 1), 0.1, [0, 1]), (3, [1, 0, -1, 0], [0, 0.5, -0.5, -0.5], (0, 2.5), (-0.5, 0.5), 0.1, [0, 0.5, 1, 2]), ) @unpack def test_polynomial_function( self, num_state_qubits, slope, offset, domain, image, rescaling_factor, breakpoints ): """Test the polynomial rotation.""" reference = partial( self.evaluate_function, num_qubits=num_state_qubits, slope=slope, offset=offset, domain=domain, image=image, rescaling_factor=rescaling_factor, breakpoints=breakpoints, ) linear_f = LinearAmplitudeFunction( num_state_qubits, slope, offset, domain, image, rescaling_factor, breakpoints ) self.assertFunctionIsCorrect(linear_f, reference) def test_not_including_start_in_breakpoints(self): """Test not including the start of the domain works.""" num_state_qubits = 1 slope = [0, 0] offset = [0, 0] domain = (0, 2) image = (0, 1) rescaling_factor = 0.1 breakpoints = [1] reference = partial( self.evaluate_function, num_qubits=num_state_qubits, slope=slope, offset=offset, domain=domain, image=image, rescaling_factor=rescaling_factor, breakpoints=breakpoints, ) linear_f = LinearAmplitudeFunction( num_state_qubits, slope, offset, domain, image, rescaling_factor, breakpoints ) self.assertFunctionIsCorrect(linear_f, reference) def test_invalid_inputs_raise(self): """Test passing invalid inputs to the LinearAmplitudeFunction raises an error.""" # default values num_state_qubits = 1 slope = [0, 0] offset = [0, 0] domain = (0, 2) image = (0, 1) rescaling_factor = 0.1 breakpoints = [0, 1] with self.subTest("mismatching breakpoints size"): with self.assertRaises(ValueError): _ = LinearAmplitudeFunction( num_state_qubits, slope, offset, domain, image, rescaling_factor, [0] ) with self.subTest("mismatching offsets"): with self.assertRaises(ValueError): _ = LinearAmplitudeFunction( num_state_qubits, slope, [0], domain, image, rescaling_factor, breakpoints ) with self.subTest("mismatching slopes"): with self.assertRaises(ValueError): _ = LinearAmplitudeFunction( num_state_qubits, [0], offset, domain, image, rescaling_factor, breakpoints ) with self.subTest("breakpoints outside of domain"): with self.assertRaises(ValueError): _ = LinearAmplitudeFunction( num_state_qubits, slope, offset, (0, 0.2), image, rescaling_factor, breakpoints ) with self.subTest("breakpoints not sorted"): with self.assertRaises(ValueError): _ = LinearAmplitudeFunction( num_state_qubits, slope, offset, domain, image, rescaling_factor, [1, 0] ) def test_post_processing(self): """Test the ``post_processing`` method.""" num_state_qubits = 2 slope = 1 offset = -2 domain = (0, 2) image = (-2, 0) rescaling_factor = 0.1 circuit = LinearAmplitudeFunction( num_state_qubits, slope, offset, domain, image, rescaling_factor ) values = [0, 0.2, 0.5, 0.9, 1] def reference_post_processing(x): x = 2 / np.pi / rescaling_factor * (x - 0.5) + 0.5 return image[0] + (image[1] - image[0]) * x expected = [reference_post_processing(value) for value in values] actual = [circuit.post_processing(value) for value in values] self.assertListEqual(expected, actual) if __name__ == "__main__": unittest.main()
https://github.com/DLR-RB/QUEASARS
DLR-RB
from pathlib import Path import os import sys main_directory = Path(os.path.abspath("")).parent sys.path.append(str(main_directory)) from queasars.job_shop_scheduling.problem_instances import Machine, Operation, Job, JobShopSchedulingProblemInstance machines = (Machine(name="m0"), Machine(name="m1")) j0op1 = Operation(name="j0op0", machine=machines[0], processing_duration=2, job_name="j0") j0op2 = Operation(name="j0op1", machine=machines[1], processing_duration=1, job_name="j0") job0 = Job(name="j0", operations=(j0op1, j0op2)) j1op1 = Operation(name="j1op1", machine=machines[0], processing_duration=1, job_name="j1") j1op2 = Operation(name="j1op2", machine=machines[1], processing_duration=2, job_name="j1") job1 = Job(name="j1", operations=(j1op1, j1op2)) jssp_instance = JobShopSchedulingProblemInstance(name="Simple Instance", machines=machines, jobs=(job0, job1)) from queasars.job_shop_scheduling.visualization import plot_jssp_problem_instance_gantt plot = plot_jssp_problem_instance_gantt(problem_instance=jssp_instance) from queasars.job_shop_scheduling.domain_wall_hamiltonian_encoder import JSSPDomainWallHamiltonianEncoder encoder = JSSPDomainWallHamiltonianEncoder(jssp_instance=jssp_instance, makespan_limit=5, opt_all_operations_share=0.19, max_opt_value=100, encoding_penalty=319, overlap_constraint_penalty=319, precedence_constraint_penalty=275) print("needed qubits: ", encoder.n_qubits) hamiltonian = encoder.get_problem_hamiltonian() from qiskit import QuantumCircuit from qiskit.primitives import SamplerResult from qiskit.primitives.base import BaseSamplerV1 from qiskit.primitives.primitive_job import PrimitiveJob from qiskit.transpiler import PassManager # Sampler Primitive Wrapper to adjust for qiskit_ibm_runtime_primitives no longer # offering cloud transpilation for free class TranspilingSampler(BaseSamplerV1): def __init__(self, sampler: BaseSamplerV1, pass_manager: PassManager): super().__init__() self._sampler = sampler self._pass_manager = pass_manager def _run( self, circuits: tuple[QuantumCircuit, ...], parameter_values: tuple[tuple[float, ...], ...], **run_options ) -> PrimitiveJob[SamplerResult]: applied_circuits = [circuit.assign_parameters(params) for circuit, params in zip(circuits, parameter_values)] transpiled_circuits = self._pass_manager.run(applied_circuits) return self._sampler.run(transpiled_circuits, **run_options) import logging from qiskit_algorithms.optimizers import SPSA from qiskit_ibm_runtime import QiskitRuntimeService, Batch, Sampler from qiskit_ibm_runtime.fake_provider.backends import FakeOsaka from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from queasars.utility.spsa_termination import SPSATerminationChecker from queasars.minimum_eigensolvers.evqe.evqe import EVQEMinimumEigensolverConfiguration, EVQEMinimumEigensolver # Connect to the runtime service using your IBM quantum token runtime_service = QiskitRuntimeService(channel="ibm_quantum", token="Your token here!") # Uncomment the second line and replace the backend name accordingly if you want to use real Quantum Hardware! backend = FakeOsaka() #backend = runtime_service.backend("ibm_kyoto") # setup a pass manager to setup the transpilation process pass_manager = generate_preset_pass_manager(optimization_level=1, backend=backend) # Set up a session so that consecutive jobs may run in short succession. with Batch(service=runtime_service, backend=backend) as batch: # The EVQEMinimumEigensolver needs at least a sampler and can also use an estimator. # Here we only use a sampler, as the Critical Value at Risk objective value can # can only be used when only using the sampler. sampler = Sampler(session=batch, options={"shots": 512, "optimization_level": 0, "resilience_level": 0}) sampler = TranspilingSampler(sampler, pass_manager) estimator = None # If only a sampler is used, the expectation value with respect to the Hamiltonian # is calculated using the measurement distribution provided by the sampler. This # expectation value can also be calculated over only the lower tail of that distribution. # In that case the objective score is also called the Critical Value at Risk. distribution_alpha_tail = 0.5 # The EVQEMinimumEigensolver also needs a qiskit optimizer. It should be # configured to terminate quickly, so that mutations are not overtly expensive. # Here we use the SPSA optimizer with a very limited amount of iterations and a # large step size. termination_checker = SPSATerminationChecker(minimum_relative_change=0.01, allowed_consecutive_violations=2) optimizer = SPSA(maxiter=33, perturbation=0.35, learning_rate=0.43, trust_region=True, last_avg=1, resamplings=1, termination_checker=termination_checker.termination_check) # To help the EVQEMinimumEigensolver deal correctly with terminations based # on the amount of circuit evaluations used, an estimate can be given for how # many circuit evaluations the optimizer uses per optimization run. # SPSA makes two measurements per gradient approximation, which means in total it will # need 66 circuit evaluations for 33 iterations. optimizer_n_circuit_evaluations = 66 # To specify when the EVQEMinimumEigensolver should terminate either max_generations, # max_circuit_evaluations or a termination_criterion should be given. # Here we set a fixed generation limit, to reduce the runtime usage. max_generations = 3 max_circuit_evaluations = None termination_criterion = None # A random seed can be provided to control the randomness of the evolutionary process. random_seed = None # The population size determines how many individuals are evaluated each generation. # With a higher population size, fewer generations might be needed, but this also # makes each generation more expensive to evaluate. population_size = 5 # The initial individuals in the starting population can be initialized with # an arbitrary amount of layers and fully randomized parameter values. This # can be particularly useful if the state |0 .. 0> is a local minima and # the individuals should not start in that state n_initial_layers = 1 randomize_initial_parameter_values = True # Determines how many circuit layers apart two individuals need to be, to be considered to # be of a different species. Reasonable values might be in the range 1 - 5. speciation_genetic_distance_threshold = 1 # This implementation of EVQE offers both roulette wheel selection and tournament selection. # Since tournament selection is more robust, we use it here. use_tournament_selection = True tournament_size = 2 # The alpha and beta penalties penalize quantum circuits of increasing depth (alpha) and # increasing amount of controlled rotations (beta). increase them if the quantum circuits get to # deep or complicated. selection_alpha_penalty = 0.15 selection_beta_penalty = 0.02 # The parameter search probability determines how likely an individual is mutated by optimizing # all it's parameter values. This should not be too large as this is costly. parameter_search_probability = 0.39 # The topological search probability determines how likely a circuit layer is added to an individual # as a mutation. This should be a higher probability to encourage exploration of different circuits. topological_search_probability = 0.79 # The layer removal probability determines how likely circuit layers are removed from an individual # as a mutation. This is a very disruptive mutation and should only be used sparingly to counteract # circuit growth. layer_removal_probability = 0.02 # An executor for launching parallel computation can be specified. # This can be a dask Client or a python ThreadPoolExecutor. If None is # specified a ThreadPoolExecutor with population_size many threads will # be used parallel_executor = None # Discerns whether to only allow mutually exclusive access to the Sampler and # Estimator primitive respectively. This is needed if the Sampler or Estimator are not threadsafe and # a ThreadPoolExecutor with more than one thread or a Dask Client with more than one thread per process is used. # For safety reasons this is enabled by default. If the sampler and estimator are threadsafe disabling this # option may lead to performance improvements mutually_exclusive_primitives = True configuration = EVQEMinimumEigensolverConfiguration( sampler=sampler, estimator=estimator, distribution_alpha_tail=distribution_alpha_tail, optimizer=optimizer, optimizer_n_circuit_evaluations=optimizer_n_circuit_evaluations, max_generations=max_generations, max_circuit_evaluations=max_circuit_evaluations, termination_criterion=termination_criterion, random_seed=random_seed, population_size=population_size, n_initial_layers=n_initial_layers, randomize_initial_population_parameters=randomize_initial_parameter_values, speciation_genetic_distance_threshold=speciation_genetic_distance_threshold, use_tournament_selection=use_tournament_selection, tournament_size=tournament_size, selection_alpha_penalty=selection_alpha_penalty, selection_beta_penalty=selection_beta_penalty, parameter_search_probability=parameter_search_probability, topological_search_probability=topological_search_probability, layer_removal_probability=layer_removal_probability, parallel_executor=parallel_executor, mutually_exclusive_primitives=mutually_exclusive_primitives, ) eigensolver = EVQEMinimumEigensolver(configuration=configuration) logger = logging.getLogger("queasars.minimum_eigensolvers.base.evolving_ansatz_minimum_eigensolver") handler = logging.StreamHandler() logger.setLevel(logging.INFO) logger.addHandler(handler) result = eigensolver.compute_minimum_eigenvalue(operator=hamiltonian) from json import dump from queasars.minimum_eigensolvers.base.serialization import EvolvingAnsatzMinimumEigensolverResultJSONEncoder file_path = Path(main_directory, "examples", "queasars_result.json") with open(file_path, "w") as file: dump(obj=result, fp=file, indent=2, cls=EvolvingAnsatzMinimumEigensolverResultJSONEncoder) from qiskit.visualization import plot_distribution quasi_distribution = result.eigenstate.binary_probabilities() plot_distribution(quasi_distribution, number_to_keep=10) solutions = [] for bitstring, probability in quasi_distribution.items(): if probability < 0.1: continue solution = encoder.translate_result_bitstring(bitstring=bitstring) print("probability: ", probability) print(solution) solutions.append(solution) from queasars.job_shop_scheduling.visualization import plot_jssp_problem_solution_gantt for solution in solutions: if solution.is_valid: plot = plot_jssp_problem_solution_gantt(result=solution)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import DensityMatrix from qiskit.visualization import plot_state_city qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) # plot using a DensityMatrix state = DensityMatrix(qc) plot_state_city(state)
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ The Variational Quantum Eigensolver algorithm. See https://arxiv.org/abs/1304.3061 """ import logging import functools import numpy as np from qiskit import ClassicalRegister, QuantumCircuit from qiskit.aqua.algorithms.adaptive.vq_algorithm import VQAlgorithm from qiskit.aqua import AquaError, Pluggable, PluggableType, get_pluggable_class from qiskit.aqua.utils.backend_utils import is_aer_statevector_backend from qiskit.aqua.utils import find_regs_by_name logger = logging.getLogger(__name__) class VQE(VQAlgorithm): """ The Variational Quantum Eigensolver algorithm. See https://arxiv.org/abs/1304.3061 """ CONFIGURATION = { 'name': 'VQE', 'description': 'VQE Algorithm', 'input_schema': { '$schema': 'http://json-schema.org/schema#', 'id': 'vqe_schema', 'type': 'object', 'properties': { 'operator_mode': { 'type': 'string', 'default': 'matrix', 'oneOf': [ {'enum': ['matrix', 'paulis', 'grouped_paulis']} ] }, 'initial_point': { 'type': ['array', 'null'], "items": { "type": "number" }, 'default': None }, 'max_evals_grouped': { 'type': 'integer', 'default': 1 } }, 'additionalProperties': False }, 'problems': ['energy', 'ising'], 'depends': [ {'pluggable_type': 'optimizer', 'default': { 'name': 'L_BFGS_B' } }, {'pluggable_type': 'variational_form', 'default': { 'name': 'RYRZ' } }, ], } def __init__(self, operator, var_form, optimizer, operator_mode='matrix', initial_point=None, max_evals_grouped=1, aux_operators=None, callback=None): """Constructor. Args: operator (Operator): Qubit operator operator_mode (str): operator mode, used for eval of operator var_form (VariationalForm): parametrized variational form. optimizer (Optimizer): the classical optimization algorithm. initial_point (numpy.ndarray): optimizer initial point. max_evals_grouped (int): max number of evaluations performed simultaneously aux_operators (list of Operator): Auxiliary operators to be evaluated at each eigenvalue callback (Callable): a callback that can access the intermediate data during the optimization. Internally, four arguments are provided as follows the index of evaluation, parameters of variational form, evaluated mean, evaluated standard devation. """ self.validate(locals()) super().__init__(var_form=var_form, optimizer=optimizer, cost_fn=self._energy_evaluation, initial_point=initial_point) self._optimizer.set_max_evals_grouped(max_evals_grouped) self._callback = callback if initial_point is None: self._initial_point = var_form.preferred_init_points self._operator = operator self._operator_mode = operator_mode self._eval_count = 0 if aux_operators is None: self._aux_operators = [] else: self._aux_operators = [aux_operators] if not isinstance(aux_operators, list) else aux_operators logger.info(self.print_settings()) @classmethod def init_params(cls, params, algo_input): """ Initialize via parameters dictionary and algorithm input instance. Args: params (dict): parameters dictionary algo_input (EnergyInput): EnergyInput instance Returns: VQE: vqe object """ if algo_input is None: raise AquaError("EnergyInput instance is required.") operator = algo_input.qubit_op vqe_params = params.get(Pluggable.SECTION_KEY_ALGORITHM) operator_mode = vqe_params.get('operator_mode') initial_point = vqe_params.get('initial_point') max_evals_grouped = vqe_params.get('max_evals_grouped') # Set up variational form, we need to add computed num qubits # Pass all parameters so that Variational Form can create its dependents var_form_params = params.get(Pluggable.SECTION_KEY_VAR_FORM) var_form_params['num_qubits'] = operator.num_qubits var_form = get_pluggable_class(PluggableType.VARIATIONAL_FORM, var_form_params['name']).init_params(params) # Set up optimizer opt_params = params.get(Pluggable.SECTION_KEY_OPTIMIZER) optimizer = get_pluggable_class(PluggableType.OPTIMIZER, opt_params['name']).init_params(params) return cls(operator, var_form, optimizer, operator_mode=operator_mode, initial_point=initial_point, max_evals_grouped=max_evals_grouped, aux_operators=algo_input.aux_ops) @property def setting(self): """Prepare the setting of VQE as a string.""" ret = "Algorithm: {}\n".format(self._configuration['name']) params = "" for key, value in self.__dict__.items(): if key != "_configuration" and key[0] == "_": if "initial_point" in key and value is None: params += "-- {}: {}\n".format(key[1:], "Random seed") else: params += "-- {}: {}\n".format(key[1:], value) ret += "{}".format(params) return ret def print_settings(self): """ Preparing the setting of VQE into a string. Returns: str: the formatted setting of VQE """ ret = "\n" ret += "==================== Setting of {} ============================\n".format(self.configuration['name']) ret += "{}".format(self.setting) ret += "===============================================================\n" ret += "{}".format(self._var_form.setting) ret += "===============================================================\n" ret += "{}".format(self._optimizer.setting) ret += "===============================================================\n" return ret def construct_circuit(self, parameter, backend=None, use_simulator_operator_mode=False): """Generate the circuits. Args: parameters (numpy.ndarray): parameters for variational form. backend (qiskit.BaseBackend): backend object. use_simulator_operator_mode (bool): is backend from AerProvider, if True and mode is paulis, single circuit is generated. Returns: [QuantumCircuit]: the generated circuits with Hamiltonian. """ input_circuit = self._var_form.construct_circuit(parameter) if backend is None: warning_msg = "Circuits used in VQE depends on the backend type, " from qiskit import BasicAer if self._operator_mode == 'matrix': temp_backend_name = 'statevector_simulator' else: temp_backend_name = 'qasm_simulator' backend = BasicAer.get_backend(temp_backend_name) warning_msg += "since operator_mode is '{}', '{}' backend is used.".format( self._operator_mode, temp_backend_name) logger.warning(warning_msg) circuit = self._operator.construct_evaluation_circuit(self._operator_mode, input_circuit, backend, use_simulator_operator_mode) return circuit def _eval_aux_ops(self, threshold=1e-12, params=None): if params is None: params = self.optimal_params wavefn_circuit = self._var_form.construct_circuit(params) circuits = [] values = [] params = [] for operator in self._aux_operators: if not operator.is_empty(): temp_circuit = QuantumCircuit() + wavefn_circuit circuit = operator.construct_evaluation_circuit(self._operator_mode, temp_circuit, self._quantum_instance.backend, self._use_simulator_operator_mode) params.append(operator.aer_paulis) else: circuit = None circuits.append(circuit) if len(circuits) > 0: to_be_simulated_circuits = functools.reduce(lambda x, y: x + y, [c for c in circuits if c is not None]) if self._use_simulator_operator_mode: extra_args = {'expectation': { 'params': params, 'num_qubits': self._operator.num_qubits} } else: extra_args = {} result = self._quantum_instance.execute(to_be_simulated_circuits, **extra_args) for operator, circuit in zip(self._aux_operators, circuits): if circuit is None: mean, std = 0.0, 0.0 else: mean, std = operator.evaluate_with_result(self._operator_mode, circuit, self._quantum_instance.backend, result, self._use_simulator_operator_mode) mean = mean.real if abs(mean.real) > threshold else 0.0 std = std.real if abs(std.real) > threshold else 0.0 values.append((mean, std)) if len(values) > 0: aux_op_vals = np.empty([1, len(self._aux_operators), 2]) aux_op_vals[0, :] = np.asarray(values) self._ret['aux_ops'] = aux_op_vals def _run(self): """ Run the algorithm to compute the minimum eigenvalue. Returns: Dictionary of results """ if not self._quantum_instance.is_statevector and self._operator_mode == 'matrix': logger.warning('Qasm simulation does not work on {} mode, changing ' 'the operator_mode to "paulis"'.format(self._operator_mode)) self._operator_mode = 'paulis' self._use_simulator_operator_mode = \ is_aer_statevector_backend(self._quantum_instance.backend) \ and self._operator_mode != 'matrix' self._quantum_instance.circuit_summary = True self._eval_count = 0 self._ret = self.find_minimum(initial_point=self.initial_point, var_form=self.var_form, cost_fn=self._energy_evaluation, optimizer=self.optimizer) if self._ret['num_optimizer_evals'] is not None and self._eval_count >= self._ret['num_optimizer_evals']: self._eval_count = self._ret['num_optimizer_evals'] self._eval_time = self._ret['eval_time'] logger.info('Optimization complete in {} seconds.\nFound opt_params {} in {} evals'.format( self._eval_time, self._ret['opt_params'], self._eval_count)) self._ret['eval_count'] = self._eval_count self._ret['energy'] = self.get_optimal_cost() self._ret['eigvals'] = np.asarray([self.get_optimal_cost()]) self._ret['eigvecs'] = np.asarray([self.get_optimal_vector()]) self._eval_aux_ops() return self._ret # This is the objective function to be passed to the optimizer that is uses for evaluation def _energy_evaluation(self, parameters): """ Evaluate energy at given parameters for the variational form. Args: parameters (numpy.ndarray): parameters for variational form. Returns: float or list of float: energy of the hamiltonian of each parameter. """ num_parameter_sets = len(parameters) // self._var_form.num_parameters circuits = [] parameter_sets = np.split(parameters, num_parameter_sets) mean_energy = [] std_energy = [] for idx in range(len(parameter_sets)): parameter = parameter_sets[idx] circuit = self.construct_circuit(parameter, self._quantum_instance.backend, self._use_simulator_operator_mode) circuits.append(circuit) to_be_simulated_circuits = functools.reduce(lambda x, y: x + y, circuits) if self._use_simulator_operator_mode: extra_args = {'expectation': { 'params': [self._operator.aer_paulis], 'num_qubits': self._operator.num_qubits} } else: extra_args = {} result = self._quantum_instance.execute(to_be_simulated_circuits, **extra_args) for idx in range(len(parameter_sets)): mean, std = self._operator.evaluate_with_result( self._operator_mode, circuits[idx], self._quantum_instance.backend, result, self._use_simulator_operator_mode) mean_energy.append(np.real(mean)) std_energy.append(np.real(std)) self._eval_count += 1 if self._callback is not None: self._callback(self._eval_count, parameter_sets[idx], np.real(mean), np.real(std)) logger.info('Energy evaluation {} returned {}'.format(self._eval_count, np.real(mean))) return mean_energy if len(mean_energy) > 1 else mean_energy[0] def get_optimal_cost(self): if 'opt_params' not in self._ret: raise AquaError("Cannot return optimal cost before running the algorithm to find optimal params.") return self._ret['min_val'] def get_optimal_circuit(self): if 'opt_params' not in self._ret: raise AquaError("Cannot find optimal circuit before running the algorithm to find optimal params.") return self._var_form.construct_circuit(self._ret['opt_params']) def get_optimal_vector(self): if 'opt_params' not in self._ret: raise AquaError("Cannot find optimal vector before running the algorithm to find optimal params.") qc = self.get_optimal_circuit() if self._quantum_instance.is_statevector: ret = self._quantum_instance.execute(qc) self._ret['min_vector'] = ret.get_statevector(qc, decimals=16) else: c = ClassicalRegister(qc.width(), name='c') q = find_regs_by_name(qc, 'q') qc.add_register(c) qc.barrier(q) qc.measure(q, c) ret = self._quantum_instance.execute(qc) self._ret['min_vector'] = ret.get_counts(qc) return self._ret['min_vector'] @property def optimal_params(self): if 'opt_params' not in self._ret: raise AquaError("Cannot find optimal params before running the algorithm.") return self._ret['opt_params']
https://github.com/Axect/QuantumAlgorithms
Axect
import numpy as np from qiskit import BasicAer from qiskit.aqua import QuantumInstance from qiskit.aqua.algorithms import Simon from qiskit.aqua.components.oracles import TruthTableOracle bitmaps = [ '01101001', '10011001', '01100110' ] oracle = TruthTableOracle(bitmaps) def compute_mask(input_bitmaps): vals = list(zip(*input_bitmaps))[::-1] def find_pair(): for i in range(len(vals)): for j in range(i + 1, len(vals)): if vals[i] == vals[j]: return i, j return 0, 0 k1, k2 = find_pair() return np.binary_repr(k1 ^ k2, int(np.log2(len(input_bitmaps[0])))) mask = compute_mask(bitmaps) print(f'The groundtruth mask is {mask}.') simon = Simon(oracle) backend = BasicAer.get_backend('qasm_simulator') result = simon.run(QuantumInstance(backend, shots=1024)) print('The mask computed using Simon is {}.'.format(result['result'])) assert(result['result'] == mask) bitmaps = [ '00011110', '01100110', '10101010' ] mask = compute_mask(bitmaps) print(f'The groundtruth mask is {mask}.') oracle = TruthTableOracle(bitmaps) simon = Simon(oracle) result = simon.run(QuantumInstance(backend, shots=1024)) print('The mask computed using Simon is {}.'.format(result['result'])) assert(result['result'] == mask)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
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. """Tests for layouts of timeline drawer.""" import qiskit from qiskit.test import QiskitTestCase from qiskit.visualization.timeline import layouts class TestBitArrange(QiskitTestCase): """Tests for layout.bit_arrange.""" def setUp(self) -> None: """Setup.""" super().setUp() qregs = qiskit.QuantumRegister(3) cregs = qiskit.ClassicalRegister(3) self.regs = list(qregs) + list(cregs) def test_qreg_creg_ascending(self): """Test qreg_creg_ascending layout function.""" sorted_regs = layouts.qreg_creg_ascending(self.regs) ref_regs = [ self.regs[0], self.regs[1], self.regs[2], self.regs[3], self.regs[4], self.regs[5], ] self.assertListEqual(sorted_regs, ref_regs) def test_qreg_creg_descending(self): """Test qreg_creg_descending layout function.""" sorted_regs = layouts.qreg_creg_descending(self.regs) ref_regs = [ self.regs[2], self.regs[1], self.regs[0], self.regs[5], self.regs[4], self.regs[3], ] self.assertListEqual(sorted_regs, ref_regs) class TestAxisMap(QiskitTestCase): """Tests for layout.time_axis_map.""" def test_time_map_in_dt(self): """Test time_map_in_dt layout function.""" axis_config = layouts.time_map_in_dt(time_window=(-100, 500)) self.assertEqual(axis_config.window, (-100, 500)) self.assertEqual(axis_config.label, "System cycle time (dt)") ref_map = {0: "0", 100: "100", 200: "200", 300: "300", 400: "400", 500: "500"} self.assertDictEqual(axis_config.axis_map, ref_map)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for visualization tools.""" import unittest import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Qubit, Clbit from qiskit.visualization.circuit import _utils from qiskit.visualization import array_to_latex from qiskit.test import QiskitTestCase from qiskit.utils import optionals class TestVisualizationUtils(QiskitTestCase): """Tests for circuit drawer utilities.""" def setUp(self): super().setUp() self.qr1 = QuantumRegister(2, "qr1") self.qr2 = QuantumRegister(2, "qr2") self.cr1 = ClassicalRegister(2, "cr1") self.cr2 = ClassicalRegister(2, "cr2") self.circuit = QuantumCircuit(self.qr1, self.qr2, self.cr1, self.cr2) self.circuit.cx(self.qr2[0], self.qr2[1]) self.circuit.measure(self.qr2[0], self.cr2[0]) self.circuit.cx(self.qr2[1], self.qr2[0]) self.circuit.measure(self.qr2[1], self.cr2[1]) self.circuit.cx(self.qr1[0], self.qr1[1]) self.circuit.measure(self.qr1[0], self.cr1[0]) self.circuit.cx(self.qr1[1], self.qr1[0]) self.circuit.measure(self.qr1[1], self.cr1[1]) def test_get_layered_instructions(self): """_get_layered_instructions without reverse_bits""" (qregs, cregs, layered_ops) = _utils._get_layered_instructions(self.circuit) exp = [ [("cx", (self.qr2[0], self.qr2[1]), ()), ("cx", (self.qr1[0], self.qr1[1]), ())], [("measure", (self.qr2[0],), (self.cr2[0],))], [("measure", (self.qr1[0],), (self.cr1[0],))], [("cx", (self.qr2[1], self.qr2[0]), ()), ("cx", (self.qr1[1], self.qr1[0]), ())], [("measure", (self.qr2[1],), (self.cr2[1],))], [("measure", (self.qr1[1],), (self.cr1[1],))], ] self.assertEqual([self.qr1[0], self.qr1[1], self.qr2[0], self.qr2[1]], qregs) self.assertEqual([self.cr1[0], self.cr1[1], self.cr2[0], self.cr2[1]], cregs) self.assertEqual( exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_reverse_bits(self): """_get_layered_instructions with reverse_bits=True""" (qregs, cregs, layered_ops) = _utils._get_layered_instructions( self.circuit, reverse_bits=True ) exp = [ [("cx", (self.qr2[0], self.qr2[1]), ()), ("cx", (self.qr1[0], self.qr1[1]), ())], [("measure", (self.qr2[0],), (self.cr2[0],))], [("measure", (self.qr1[0],), (self.cr1[0],)), ("cx", (self.qr2[1], self.qr2[0]), ())], [("cx", (self.qr1[1], self.qr1[0]), ())], [("measure", (self.qr2[1],), (self.cr2[1],))], [("measure", (self.qr1[1],), (self.cr1[1],))], ] self.assertEqual([self.qr2[1], self.qr2[0], self.qr1[1], self.qr1[0]], qregs) self.assertEqual([self.cr2[1], self.cr2[0], self.cr1[1], self.cr1[0]], cregs) self.assertEqual( exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_remove_idle_wires(self): """_get_layered_instructions with idle_wires=False""" qr1 = QuantumRegister(3, "qr1") qr2 = QuantumRegister(3, "qr2") cr1 = ClassicalRegister(3, "cr1") cr2 = ClassicalRegister(3, "cr2") circuit = QuantumCircuit(qr1, qr2, cr1, cr2) circuit.cx(qr2[0], qr2[1]) circuit.measure(qr2[0], cr2[0]) circuit.cx(qr2[1], qr2[0]) circuit.measure(qr2[1], cr2[1]) circuit.cx(qr1[0], qr1[1]) circuit.measure(qr1[0], cr1[0]) circuit.cx(qr1[1], qr1[0]) circuit.measure(qr1[1], cr1[1]) (qregs, cregs, layered_ops) = _utils._get_layered_instructions(circuit, idle_wires=False) exp = [ [("cx", (qr2[0], qr2[1]), ()), ("cx", (qr1[0], qr1[1]), ())], [("measure", (qr2[0],), (cr2[0],))], [("measure", (qr1[0],), (cr1[0],))], [("cx", (qr2[1], qr2[0]), ()), ("cx", (qr1[1], qr1[0]), ())], [("measure", (qr2[1],), (cr2[1],))], [("measure", (qr1[1],), (cr1[1],))], ] self.assertEqual([qr1[0], qr1[1], qr2[0], qr2[1]], qregs) self.assertEqual([cr1[0], cr1[1], cr2[0], cr2[1]], cregs) self.assertEqual( exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_left_justification_simple(self): """Test _get_layered_instructions left justification simple since #2802 q_0: |0>───────■── ┌───┐ │ q_1: |0>┤ H ├──┼── ├───┤ │ q_2: |0>┤ H ├──┼── └───┘┌─┴─┐ q_3: |0>─────┤ X ├ └───┘ """ qc = QuantumCircuit(4) qc.h(1) qc.h(2) qc.cx(0, 3) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="left") l_exp = [ [ ("h", (Qubit(QuantumRegister(4, "q"), 1),), ()), ("h", (Qubit(QuantumRegister(4, "q"), 2),), ()), ], [("cx", (Qubit(QuantumRegister(4, "q"), 0), Qubit(QuantumRegister(4, "q"), 3)), ())], ] self.assertEqual( l_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_right_justification_simple(self): """Test _get_layered_instructions right justification simple since #2802 q_0: |0>──■─────── │ ┌───┐ q_1: |0>──┼──┤ H ├ │ ├───┤ q_2: |0>──┼──┤ H ├ ┌─┴─┐└───┘ q_3: |0>┤ X ├───── └───┘ """ qc = QuantumCircuit(4) qc.h(1) qc.h(2) qc.cx(0, 3) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="right") r_exp = [ [("cx", (Qubit(QuantumRegister(4, "q"), 0), Qubit(QuantumRegister(4, "q"), 3)), ())], [ ("h", (Qubit(QuantumRegister(4, "q"), 1),), ()), ("h", (Qubit(QuantumRegister(4, "q"), 2),), ()), ], ] self.assertEqual( r_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_left_justification_less_simple(self): """Test _get_layered_instructions left justification less simple example since #2802 ┌────────────┐┌───┐┌────────────┐ ┌─┐┌────────────┐┌───┐┌────────────┐ q_0: |0>┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├──────────────┤M├┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├ ├────────────┤└─┬─┘├────────────┤┌────────────┐└╥┘└────────────┘└─┬─┘├────────────┤ q_1: |0>┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├┤ U2(0,pi/1) ├─╫─────────────────■──┤ U2(0,pi/1) ├ └────────────┘ └────────────┘└────────────┘ ║ └────────────┘ q_2: |0>────────────────────────────────────────────────╫────────────────────────────────── ║ q_3: |0>────────────────────────────────────────────────╫────────────────────────────────── ║ q_4: |0>────────────────────────────────────────────────╫────────────────────────────────── ║ c1_0: 0 ════════════════════════════════════════════════╩══════════════════════════════════ """ qasm = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[5]; creg c1[1]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; u2(0,3.14159265358979) q[1]; measure q[0] -> c1[0]; u2(0,3.14159265358979) q[0]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; """ qc = QuantumCircuit.from_qasm_str(qasm) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="left") l_exp = [ [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("u2", (Qubit(QuantumRegister(5, "q"), 1),), ())], [ ( "measure", (Qubit(QuantumRegister(5, "q"), 0),), (Clbit(ClassicalRegister(1, "c1"), 0),), ) ], [("u2", (Qubit(QuantumRegister(5, "q"), 0),), ())], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], ] self.assertEqual( l_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_right_justification_less_simple(self): """Test _get_layered_instructions right justification less simple example since #2802 ┌────────────┐┌───┐┌────────────┐┌─┐┌────────────┐┌───┐┌────────────┐ q_0: |0>┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├┤M├┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├ ├────────────┤└─┬─┘├────────────┤└╥┘├────────────┤└─┬─┘├────────────┤ q_1: |0>┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├─╫─┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├ └────────────┘ └────────────┘ ║ └────────────┘ └────────────┘ q_2: |0>──────────────────────────────────╫────────────────────────────────── ║ q_3: |0>──────────────────────────────────╫────────────────────────────────── ║ q_4: |0>──────────────────────────────────╫────────────────────────────────── ║ c1_0: 0 ══════════════════════════════════╩══════════════════════════════════ """ qasm = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[5]; creg c1[1]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; u2(0,3.14159265358979) q[1]; measure q[0] -> c1[0]; u2(0,3.14159265358979) q[0]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; """ qc = QuantumCircuit.from_qasm_str(qasm) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="right") r_exp = [ [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [ ( "measure", (Qubit(QuantumRegister(5, "q"), 0),), (Clbit(ClassicalRegister(1, "c1"), 0),), ) ], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], ] self.assertEqual( r_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_op_with_cargs(self): """Test _get_layered_instructions op with cargs right of measure ┌───┐┌─┐ q_0: |0>┤ H ├┤M├───────────── └───┘└╥┘┌───────────┐ q_1: |0>──────╫─┤0 ├ ║ │ add_circ │ c_0: 0 ══════╩═╡0 ╞ └───────────┘ c_1: 0 ═════════════════════ """ qc = QuantumCircuit(2, 2) qc.h(0) qc.measure(0, 0) qc_2 = QuantumCircuit(1, 1, name="add_circ") qc_2.h(0).c_if(qc_2.cregs[0], 1) qc_2.measure(0, 0) qc.append(qc_2, [1], [0]) (_, _, layered_ops) = _utils._get_layered_instructions(qc) expected = [ [("h", (Qubit(QuantumRegister(2, "q"), 0),), ())], [ ( "measure", (Qubit(QuantumRegister(2, "q"), 0),), (Clbit(ClassicalRegister(2, "c"), 0),), ) ], [ ( "add_circ", (Qubit(QuantumRegister(2, "q"), 1),), (Clbit(ClassicalRegister(2, "c"), 0),), ) ], ] self.assertEqual( expected, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_nomathmode(self): """Test generate latex label default.""" self.assertEqual("abc", _utils.generate_latex_label("abc")) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_nomathmode_utf8char(self): """Test generate latex label utf8 characters.""" self.assertEqual( "{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label("∭X∀Y"), ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_mathmode_utf8char(self): """Test generate latex label mathtext with utf8.""" self.assertEqual( "abc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label("$abc_$∭X∀Y"), ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_mathmode_underscore_outside(self): """Test generate latex label with underscore outside mathmode.""" self.assertEqual( "abc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label("$abc$_∭X∀Y"), ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_escaped_dollar_signs(self): """Test generate latex label with escaped dollarsign.""" self.assertEqual("${\\ensuremath{\\forall}}$", _utils.generate_latex_label(r"\$∀\$")) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_escaped_dollar_sign_in_mathmode(self): """Test generate latex label with escaped dollar sign in mathmode.""" self.assertEqual( "a$bc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label(r"$a$bc$_∭X∀Y"), ) def test_array_to_latex(self): """Test array_to_latex produces correct latex string""" matrix = [ [np.sqrt(1 / 2), 1 / 16, 1 / np.sqrt(8) + 3j, -0.5 + 0.5j], [1 / 3 - 1 / 3j, np.sqrt(1 / 2) * 1j, 34.3210, -9 / 2], ] matrix = np.array(matrix) exp_str = ( "\\begin{bmatrix}\\frac{\\sqrt{2}}{2}&\\frac{1}{16}&" "\\frac{\\sqrt{2}}{4}+3i&-\\frac{1}{2}+\\frac{i}{2}\\\\" "\\frac{1}{3}+\\frac{i}{3}&\\frac{\\sqrt{2}i}{2}&34.321&-" "\\frac{9}{2}\\\\\\end{bmatrix}" ) result = array_to_latex(matrix, source=True).replace(" ", "").replace("\n", "") self.assertEqual(exp_str, result) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeVigoV2 from qiskit.visualization import plot_circuit_layout from qiskit.tools.monitor import job_monitor from qiskit.providers.fake_provider import FakeVigoV2 import matplotlib.pyplot as plt ghz = QuantumCircuit(3, 3) ghz.h(0) for idx in range(1,3): ghz.cx(0,idx) ghz.measure(range(3), range(3)) backend = FakeVigoV2() new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3) plot_circuit_layout(new_circ_lv3, backend)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np import matplotlib.pyplot as plt from IPython.display import display, clear_output from qiskit.primitives import Estimator from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.algorithms.observables_evaluator import estimate_observables from qiskit.algorithms.optimizers import COBYLA, SLSQP from qiskit.circuit import QuantumCircuit, Parameter from qiskit.circuit.library import TwoLocal from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit.utils import algorithm_globals from qiskit_nature.second_q.operators import FermionicOp from qiskit_nature.second_q.mappers import JordanWignerMapper def kronecker_delta_function(n: int, m: int) -> int: """An implementation of the Kronecker delta function. Args: n (int): The first integer argument. m (int): The second integer argument. Returns: Returns 1 if n = m, else returns 0. """ return int(n == m) def create_deuteron_hamiltonian( N: int, hbar_omega: float = 7.0, V_0: float = -5.68658111 ) -> SparsePauliOp: """Creates a version of the Deuteron Hamiltonian as a qubit operator. Args: N (int): An integer number that represents the dimension of the basis. hbar_omega (float, optional): The value of the product of hbar and omega. Defaults to 7.0. V_0 (float, optional): The value of the potential energy. Defaults to -5.68658111. Returns: SparsePauliOp: The qubit-space Hamiltonian that represents the Deuteron. """ hamiltonian_terms = {} for m in range(N): for n in range(N): label = "+_{} -_{}".format(str(n), str(m)) coefficient_kinect = (hbar_omega / 2) * ( (2 * n + 3 / 2) * kronecker_delta_function(n, m) - np.sqrt(n * (n + (1 / 2))) * kronecker_delta_function(n, m + 1) - np.sqrt((n + 1) * (n + (3 / 2)) * kronecker_delta_function(n, m - 1)) ) hamiltonian_terms[label] = coefficient_kinect coefficient_potential = ( V_0 * kronecker_delta_function(n, 0) * kronecker_delta_function(n, m) ) hamiltonian_terms[label] += coefficient_potential hamiltonian = FermionicOp(hamiltonian_terms, num_spin_orbitals=N) mapper = JordanWignerMapper() qubit_hamiltonian = mapper.map(hamiltonian) if not isinstance(qubit_hamiltonian, SparsePauliOp): qubit_hamiltonian = qubit_hamiltonian.primitive return qubit_hamiltonian deuteron_hamiltonians = [create_deuteron_hamiltonian(i) for i in range(1, 5)] for i, hamiltonian in enumerate(deuteron_hamiltonians): print("Deuteron Hamiltonian: H_{}".format(i + 1)) print(hamiltonian) print("\n") theta = Parameter(r"$\theta$") eta = Parameter(r"$\eta$") wavefunction = QuantumCircuit(1) wavefunction.ry(theta, 0) wavefunction.draw("mpl") wavefunction2 = QuantumCircuit(2) wavefunction2.x(0) wavefunction2.ry(theta, 1) wavefunction2.cx(1, 0) wavefunction2.draw("mpl") wavefunction3 = QuantumCircuit(3) wavefunction3.x(0) wavefunction3.ry(eta, 1) wavefunction3.ry(theta, 2) wavefunction3.cx(2, 0) wavefunction3.cx(0, 1) wavefunction3.ry(-eta, 1) wavefunction3.cx(0, 1) wavefunction3.cx(1, 0) wavefunction3.draw("mpl") ansatz = [wavefunction, wavefunction2, wavefunction3] reference_values = [] print("Exact binding energies calculated through numpy.linalg.eigh \n") for i, hamiltonian in enumerate(deuteron_hamiltonians): eigenvalues, eigenstates = np.linalg.eigh(hamiltonian.to_matrix()) reference_values.append(eigenvalues[0]) print("Exact binding energy for H_{}: {}".format(i + 1, eigenvalues[0])) print( "Results using Estimator for H_1, H_2 and H_3 with the ansatz given in the reference paper \n" ) for i in range(3): seed = 42 algorithm_globals.random_seed = seed vqe = VQE(Estimator(), ansatz=ansatz[i], optimizer=SLSQP()) vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i]) binding_energy = vqe_result.optimal_value print("Binding energy for H_{}: {} MeV".format(i + 1, binding_energy)) def callback(eval_count, parameters, mean, std): # Overwrites the same line when printing display("Evaluation: {}, Energy: {}, Std: {}".format(eval_count, mean, std)) clear_output(wait=True) counts.append(eval_count) values.append(mean) params.append(parameters) deviation.append(std) plots = [] for i in range(3): counts = [] values = [] params = [] deviation = [] seed = 42 algorithm_globals.random_seed = seed vqe = VQE(Estimator(), ansatz=ansatz[i], optimizer=COBYLA(), callback=callback) vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i]) plots.append([counts, values]) fig, ax = plt.subplots(nrows=3, ncols=1) fig.set_size_inches((12, 12)) for i, plot in enumerate(plots): ax[i].plot(plot[0], plot[1], "o-", label="COBYLA") ax[i].axhline( y=reference_values[i], color="k", linestyle="--", label=f"Reference Value: {reference_values[i]}", ) ax[i].legend() ax[i].set_xlabel("Cost Function Evaluations", fontsize=15) ax[i].set_ylabel(r"$\langle H_{} \rangle$ - Energy (MeV)".format(i + 1), fontsize=15) plt.show() twolocal_ansatzes = [] for i in range(1, 5): ansatz = TwoLocal( deuteron_hamiltonians[i - 1].num_qubits, ["rz", "ry"], "cx", entanglement="full", reps=i, initial_state=None, ) twolocal_ansatzes.append(ansatz) print("Results using Estimator for H_1, H_2, H_3 and H_4 with TwoLocal ansatz \n") seed = 42 algorithm_globals.random_seed = seed for i in range(4): vqe = VQE(Estimator(), ansatz=twolocal_ansatzes[i], optimizer=SLSQP()) vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i]) binding_energy = vqe_result.optimal_value print("Binding energy for H_{}:".format(i + 1), binding_energy, "MeV") seed = 42 algorithm_globals.random_seed = seed plots_tl = [] for i in range(4): counts = [] values = [] params = [] deviation = [] vqe = VQE( Estimator(), ansatz=twolocal_ansatzes[i], optimizer=SLSQP(), callback=callback, ) vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i]) plots_tl.append([counts, values]) fig, ax = plt.subplots(nrows=4, ncols=1) fig.set_size_inches((15, 15)) for i, plot in enumerate(plots_tl): ax[i].plot(plot[0], plot[1], "o-", label="COBYLA") ax[i].axhline( y=reference_values[i], color="k", linestyle="--", label=f"Reference Value: {reference_values[i]}", ) ax[i].legend() ax[i].set_xlabel("Cost Function Evaluations", fontsize=15) ax[i].set_ylabel(r"$\langle H_{} \rangle$ - Energy (MeV)".format(i + 1), fontsize=15) plt.show() def calculate_observables_exp_values( quantum_circuit: QuantumCircuit, observables: list, angles: list ) -> list: """Calculate the expectation value of an observable given the quantum circuit that represents the wavefunction and a list of parameters. Args: quantum_circuit (QuantumCircuit): A parameterized quantum circuit that represents the wavefunction of the system. observables (list): A list containing the observables that we want to know the expectation values. angles (list): A list with the values that will be used in the 'bind_parameters' method. Returns: list_exp_values (list): A list containing the expectation values of the observables given as input. """ list_exp_values = [] for observable in observables: exp_values = [] for angle in angles: qc = quantum_circuit.bind_parameters({theta: angle}) result = estimate_observables( Estimator(), quantum_state=qc, observables=[observable], ) exp_values.append(result[0][0]) list_exp_values.append(exp_values) return list_exp_values angles = list(np.linspace(-np.pi, np.pi, 100)) observables = [ Pauli("IZ"), Pauli("ZI"), Pauli("XX"), Pauli("YY"), deuteron_hamiltonians[1], ] h2_observables_exp_values = calculate_observables_exp_values(wavefunction2, observables, angles) fig, ax = plt.subplots(nrows=2, ncols=1) fig.set_size_inches((12, 12)) ax[0].plot(angles, h2_observables_exp_values[0], "o", label=r"$Z_0$") ax[0].plot(angles, h2_observables_exp_values[1], "o", label=r"$Z_1$") ax[0].plot(angles, h2_observables_exp_values[2], "o", label=r"$X_0X_1$") ax[0].plot(angles, h2_observables_exp_values[3], "o", label=r"$Y_0Y_1$") ax[0].axhline( y=1, color="k", linestyle="--", ) ax[0].axhline(y=-1, color="k", linestyle="--") ax[0].legend() ax[0].set_xlabel(r"Theta - $\theta$", fontsize=15) ax[0].set_ylabel(r"$\langle O \rangle $ - Operator Expectation Value", fontsize=15) ax[0].set_xticks( [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], labels=[r"$-\pi$", r"$-\pi/2$", "0", r"$\pi/2$", r"$\pi$"], ) ax[0].set_title( r"Expectation value of the observables $Z_0$, $Z_1$, $X_0X_1$ and $Y_0Y_1$ when we vary $\theta$ in the ansatz.", fontsize=15, ) ax[1].plot(angles, h2_observables_exp_values[4], "o") ax[1].axhline( y=reference_values[1], color="k", linestyle="--", label="Binding Energy: {} MeV".format(np.round(reference_values[1], 3)), ) ax[1].legend() ax[1].set_xlabel(r"Theta - $\theta$", fontsize=15) ax[1].set_ylabel(r"$\langle H_2 \rangle $ - Energy (MeV)", fontsize=15) ax[1].set_xticks( [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], labels=[r"$-\pi$", r"$-\pi/2$", "0", r"$\pi/2$", r"$\pi$"], ) ax[1].set_title( r"Behavior of the expectation value of $H_2$ when we vary $\theta$ in the ansatz.", fontsize=15 ) plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# # your solution is here #
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.quantum_info import SparsePauliOp H2_op = SparsePauliOp.from_list( [ ("II", -1.052373245772859), ("IZ", 0.39793742484318045), ("ZI", -0.39793742484318045), ("ZZ", -0.01128010425623538), ("XX", 0.18093119978423156), ] ) print(f"Number of qubits: {H2_op.num_qubits}") from qiskit.algorithms import NumPyMinimumEigensolver from qiskit.opflow import PauliSumOp numpy_solver = NumPyMinimumEigensolver() result = numpy_solver.compute_minimum_eigenvalue(operator=PauliSumOp(H2_op)) ref_value = result.eigenvalue.real print(f"Reference value: {ref_value:.5f}") # define ansatz and optimizer from qiskit.circuit.library import TwoLocal from qiskit.algorithms.optimizers import SPSA iterations = 125 ansatz = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") spsa = SPSA(maxiter=iterations) # define callback # note: Re-run this cell to restart lists before training counts = [] values = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) # define Aer Estimator for noiseless statevector simulation from qiskit.utils import algorithm_globals from qiskit_aer.primitives import Estimator as AerEstimator seed = 170 algorithm_globals.random_seed = seed noiseless_estimator = AerEstimator( run_options={"seed": seed, "shots": 1024}, transpile_options={"seed_transpiler": seed}, ) # instantiate and run VQE from qiskit.algorithms.minimum_eigensolvers import VQE vqe = VQE( noiseless_estimator, ansatz, optimizer=spsa, callback=store_intermediate_result ) result = vqe.compute_minimum_eigenvalue(operator=H2_op) print(f"VQE on Aer qasm simulator (no noise): {result.eigenvalue.real:.5f}") print( f"Delta from reference energy value is {(result.eigenvalue.real - ref_value):.5f}" ) import pylab pylab.rcParams["figure.figsize"] = (12, 4) pylab.plot(counts, values) pylab.xlabel("Eval count") pylab.ylabel("Energy") pylab.title("Convergence with no noise") from qiskit_aer.noise import NoiseModel from qiskit.providers.fake_provider import FakeVigo # fake providers contain data from real IBM Quantum devices stored in Qiskit Terra, # and are useful for extracting realistic noise models. device = FakeVigo() coupling_map = device.configuration().coupling_map noise_model = NoiseModel.from_backend(device) print(noise_model) noisy_estimator = AerEstimator( backend_options={ "method": "density_matrix", "coupling_map": coupling_map, "noise_model": noise_model, }, run_options={"seed": seed, "shots": 1024}, transpile_options={"seed_transpiler": seed}, ) # re-start callback variables counts = [] values = [] vqe.estimator = noisy_estimator result1 = vqe.compute_minimum_eigenvalue(operator=H2_op) print(f"VQE on Aer qasm simulator (with noise): {result1.eigenvalue.real:.5f}") print( f"Delta from reference energy value is {(result1.eigenvalue.real - ref_value):.5f}" ) if counts or values: pylab.rcParams["figure.figsize"] = (12, 4) pylab.plot(counts, values) pylab.xlabel("Eval count") pylab.ylabel("Energy") pylab.title("Convergence with noise") print(f"Reference value: {ref_value:.5f}") print(f"VQE on Aer qasm simulator (no noise): {result.eigenvalue.real:.5f}") print(f"VQE on Aer qasm simulator (with noise): {result1.eigenvalue.real:.5f}") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer all_pairs = ['00','01','10','11'] # # your code is here # # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer all_pairs = ['00','01','10','11'] for pair in all_pairs: # create a quantum curcuit with two qubits: Asja's and Balvis' qubits. # both are initially set to |0>. q = QuantumRegister(2,"q") # quantum register with 2 qubits c = ClassicalRegister(2,"c") # classical register with 2 bits qc = QuantumCircuit(q,c) # quantum circuit with quantum and classical registers # apply h-gate (Hadamard) to the Asja's qubit qc.h(q[1]) # apply cx-gate as CNOT(Asja's-qubit,Balvis'-qubit) qc.cx(q[1],q[0]) # they are separated from each other now # if a is 1, then apply z-gate to Asja's qubit if pair[0]=='1': qc.z(q[1]) # if b is 1, then apply x-gate (NOT) to Asja's qubit if pair[1]=='1': qc.x(q[1]) # Asja sends her qubit to Balvis qc.barrier() # apply cx-gate as CNOT(Asja's-qubit,Balvis'-qubit) qc.cx(q[1],q[0]) # apply h-gate (Hadamard) to the Asja's qubit qc.h(q[1]) # measure both qubits qc.barrier() qc.measure(q,c) # draw the circuit in Qiskit's reading order display(qc.draw(output='mpl',reverse_bits=True)) # compare the results with pair (a,b) job = execute(qc,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(qc) print(pair,"-->",counts) # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer all_pairs = ['00','01','10','11'] # # your code is here # # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer all_pairs = ['00','01','10','11'] for pair in all_pairs: # create a quantum curcuit with two qubits: Asja's and Balvis' qubits. # both are initially set to |0>. q = QuantumRegister(2,"q") # quantum register with 2 qubits c = ClassicalRegister(2,"c") # classical register with 2 bits qc = QuantumCircuit(q,c) # quantum circuit with quantum and classical registers # apply h-gate (Hadamard) to the Asja's qubit qc.h(q[1]) # apply cx-gate as CNOT(Asja's-qubit,Balvis'-qubit) qc.cx(q[1],q[0]) # they are separated from each other now # if a is 1, then apply z-gate to Balvis' qubit if pair[0]=='1': qc.z(q[0]) # if b is 1, then apply x-gate (NOT) to Balvis' qubit if pair[1]=='1': qc.x(q[0]) # Balvis sends his qubit to Asja qc.barrier() # apply cx-gate as CNOT(Asja's-qubit,Balvis'-qubit) qc.cx(q[1],q[0]) # apply h-gate (Hadamard) to the Asja's qubit qc.h(q[1]) # measure both qubits qc.barrier() qc.measure(q,c) # draw the circuit in Qiskit's reading order display(qc.draw(output='mpl',reverse_bits=True)) # compare the results with pair (a,b) job = execute(qc,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(qc) print(pair,"-->",counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_qsphere qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = Statevector(qc) plot_state_qsphere(state)
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
import maxcut_benchmark import auxiliary_functions as aux_fun import execute execute.set_noise_model(noise_model = None) maxcut_benchmark.verbose = False backend_id = "qasm_simulator" hub = "ibm-q" group = "open" project = "main" provider_backend = None exec_options = None num_qubits = 4 num_shots = 1000 restarts = 10 rounds = 2 degree = 3 max_circuits = 1 objective_func_type = 'approx_ratio' score_metric = [objective_func_type] # , 'fidelity' x_metric = ['cumulative_exec_time'] maxcut_benchmark.print_sample_circuit = False maxcut_benchmark.run(min_qubits=num_qubits, max_qubits=num_qubits, max_circuits=restarts, num_shots=num_shots, method=2, rounds=rounds, degree=degree, alpha=0.1, N=10, parameterized=False, score_metric=score_metric, x_metric=x_metric, num_x_bins=15, max_iter=30, backend_id=backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options, objective_func_type=objective_func_type, do_fidelities=True, save_res_to_file=False, save_final_counts=False, plot_results=False, detailed_save_names=False) aux_fun.plot_effects_of_initial_conditions() min_qubits = 4 max_qubits = 6 num_shots = 1000 restarts = 25 rounds = 1 degree = 3 objective_func_type = 'approx_ratio' score_metric = [objective_func_type] # , 'fidelity' x_metric = ['cumulative_exec_time'] aux_fun.radar_plot(min_qubits=min_qubits, max_qubits=max_qubits, num_shots=num_shots, restarts=restarts,rounds=rounds, degree=degree) degree = 3 # degree of graph rounds = 2 # number of rounds # Import modules and packages import maxcut_benchmark import time import sys sys.path[1:1] = [ "_common", "_common/qiskit", "maxcut/_common" ] sys.path[1:1] = [ "../../_common", "../../_common/qiskit", "../../maxcut/_common/" ] import common import execute as ex import metrics as metrics import os import numpy as np import json from qiskit import (Aer, execute) import matplotlib.pyplot as plt ex.set_noise_model(None) # Load the fixed angles from angles_regular_graphs.json taken from https://github.com/danlkv/fixed-angle-QAOA with open(os.path.join('..','_common','angles_regular_graphs.json'), 'r') as json_file: fixed_angles_orig = json.load(json_file) #'thetas_array', 'approx_ratio_list', 'num_qubits_list' deg_3_p_2 = fixed_angles_orig[str(degree)][str(rounds)] thetas_list = deg_3_p_2['beta'] + deg_3_p_2['gamma'] # betas are first followed by gammas for ind in range(rounds, rounds * 2): thetas_list[ind] *= 1 def ar_svs(num_qubits = 4, rounds = 2, degree = 3): """ For a given problem (num nodes + degree), obtain the fixed angle approximation ratio using the state vector simulator """ start = time.time() # Retrieve graph edges and optimal solution unique_id = i = 3 # degree instance_filename = os.path.join("..", "_common", common.INSTANCE_DIR, f"mc_{num_qubits:03d}_{i:03d}_000.txt") nodes, edges = common.read_maxcut_instance(instance_filename) opt, _ = common.read_maxcut_solution(instance_filename[:-4]+'.sol') ## Get the approximation ratio from the state vector simulator parameterized = False qc = maxcut_benchmark.MaxCut(num_qubits, i, edges, rounds, thetas_list, parameterized, measured = False) # qc2 = qc.decompose() backend_id='statevector_simulator' sv_backend = Aer.get_backend(backend_id) sv_result = execute(qc, sv_backend).result() # get the probability distribution cuts, counts, sizes = maxcut_benchmark.compute_cutsizes(sv_result, nodes, edges) sv_ar = np.sum([c * s for (c,s) in zip(counts, sizes)]) / opt end = time.time() # print("SVS for width={} took {} mins".format(num_qubits, (end-start)/60)) return sv_ar def ar_qasmSim(num_qubits = 4, rounds = 2, degree = 3, num_shots = 5000): """ For a given problem (num nodes + degree), obtain the fixed angle approximation ratio using the qasm simulator """ start = time.time() # Retrieve graph edges and optimal solution unique_id = i = 3 # degree instance_filename = os.path.join("..", "_common", common.INSTANCE_DIR, f"mc_{num_qubits:03d}_{i:03d}_000.txt") nodes, edges = common.read_maxcut_instance(instance_filename) opt, _ = common.read_maxcut_solution(instance_filename[:-4]+'.sol') ## Get the approximation ratio from qasm_simulator provider_backend=None hub="ibm-q" group="open" project="main" exec_options=None def execution_handler2 (qc, result, num_qubits, s_int, num_shots): # Stores the results to the global saved_result variable global saved_result saved_result = result ex.max_jobs_active = 1 backend_id='qasm_simulator' ex.init_execution(execution_handler2) ex.set_execution_target(backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options) # submit circuit for execution on target (simulator, cloud simulator, or hardware) qc = maxcut_benchmark.MaxCut(num_qubits, i, edges, rounds, thetas_list, parameterized = False, measured = True) qc2 = qc.decompose() ex.submit_circuit(qc2, num_qubits, unique_id, shots=num_shots) # Must wait for circuit to complete ex.finalize_execution(None, report_end=False) # ex.throttle_execution(metrics.finalize_group) # ex.finalize_execution(None, report_end=False) # print(saved_result) cuts, counts, sizes = maxcut_benchmark.compute_cutsizes(saved_result, nodes, edges) ar = - maxcut_benchmark.compute_sample_mean(counts, sizes) / opt end= time.time() # print("QASM Simulation for width={} took {} mins".format(num_qubits, (end-start)/60)) return ar degree = 3 num_shots = 1000 num_qubits_list = list(range(4,17,2)) svs_list = [0] * len(num_qubits_list) qsm_list = [0] * len(num_qubits_list) for ind, num_qubits in enumerate(num_qubits_list): svs_list[ind] = ar_svs(num_qubits = num_qubits, rounds = rounds, degree = degree) qsm_list[ind] = ar_qasmSim(num_qubits = num_qubits, rounds = rounds, degree = degree, num_shots = num_shots) print("Simulation for size {} done.".format(num_qubits)) maxcut_style = os.path.join(os.path.join('..','..', '_common','maxcut.mplstyle')) with plt.style.context(maxcut_style): fig, axs = plt.subplots(1, 1) suptitle = "Approximation Ratio for Fixed Angle Simulation\n rounds$={}$, degree=${}$ \n".format(rounds, degree) angle_str = "" for ind in range(rounds): angle_str += r"($\beta_{}={:.3f}$,".format(ind + 1, deg_3_p_2['beta'][ind]) angle_str += r" $\gamma_{}={:.3f}$) ".format(ind + 1, deg_3_p_2['gamma'][ind]) + "\n" angle_str = angle_str[:-2] # and add the title to the plot plt.suptitle(suptitle + angle_str) axs.plot(num_qubits_list, svs_list, marker='o', ls = '-', label = f"State Vector Simulation") axs.plot(num_qubits_list, qsm_list, marker='o', ls = '-', label = f"QASM Simulation") axs.axhline(y = deg_3_p_2['AR'], ls = 'dashed', label = f"Performance Guarantee") axs.set_ylabel('Approximation Ratio') axs.set_xlabel('Problem Size') axs.grid() axs.legend() fig.tight_layout() if not os.path.exists("__images"): os.mkdir("__images") plt.savefig(os.path.join("__images", "fixed_angle_ARs.png")) plt.savefig(os.path.join("__images", "fixed_angle_ARs.pdf"))
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) # with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) # with open(filename, "wb") as f: # pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) # with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump(backend.properties(), f) retrieved_jobs = jobs retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/biswaroopmukherjee/Quantum-Waddle
biswaroopmukherjee
import numpy as np import time import networkx as nx import matplotlib.pyplot as plt import random from qiskit import (QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer) %matplotlib qt steps = 5 n=4 def counts_to_prob_1d(counts): # Convert histogram counts to probability vector of size 1 x 2^n states = list(counts.keys()) state_counts = list(counts.values()) nshots = sum(state_counts) # Convert binary to integer index, reversing order as consistent w qiskit convention states_x = [int(s[::-1],2) for s in states] # Create array of probability values probabilities = np.zeros(2**n) probabilities[states_x] = state_counts probabilities /= nshots return probabilities def increment_gate(circuit, qpos, qcoin): n = len(qpos) for i in range(n): circuit.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla') def decrement_gate(circuit, qpos, qcoin): n = len(qpos) circuit.x(qcoin[0]) for i in range(n): if i+1 < n: circuit.x(qpos[i+1:]) circuit.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla') if i+1 < n: circuit.x(qpos[i+1:]) def step(circuit, qpos, qcoin): circuit.h(qcoin) circuit.barrier() increment_gate(circuit, qpos, qcoin) circuit.barrier() decrement_gate(circuit, qpos, qcoin) circuit.barrier() def run(steps): simulator = Aer.get_backend('qasm_simulator') qpos = QuantumRegister(n,'qc') qcoin = QuantumRegister(1,'qanc') cpos = ClassicalRegister(n,'cr') circuit = QuantumCircuit(qpos, qcoin, cpos) for i in range(steps): step(circuit, qpos, qcoin) # # Map the quantum measurement to the classical bits circuit.measure(qpos,cpos) # # Execute the circuit on the qasm simulator job = execute(circuit, simulator, shots=1000) # # Grab results from the job result = job.result() # # Returns counts counts = result.get_counts(circuit) return counts seed = 12 random.seed(seed) np.random.seed(seed) def plotCircleGraph(propabilities): G = nx.Graph() colorarray = [] # generate array of colors numProp = len(propabilities) for idx in range(numProp): colorarray.append([1-prop[idx],1-prop[idx],1]) # generate graph for idx in range(numProp-1): G.add_edge(idx, idx+1) # add last edge G.add_edge(0,numProp-1) nx.draw(G,pos=nx.circular_layout(G),node_color = colorarray,cmap=plt.cm.Blues) for i in range(steps+1): counts = run(i) prop = counts_to_prob_1d(counts) plotCircleGraph(prop) plt.pause(0.3) plt.close()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_city qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) # plot using a Statevector state = Statevector(qc) plot_state_city(state)
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from scipy.stats import kruskal, f_oneway import pandas as pd import numpy as np #if p value less than alpha reject qiskit_data = np.full(10000, 0.25) cirq_data = np.full(10000, 0.25) qs_data = np.full(10000, 0.25) kruskal(qiskit_data, cirq_data, qs_data) #if p value less than alpha reject qiskit_data = np.full(10000, 0.75) cirq_data = np.full(10000, 0.75) qs_data = np.full(10000, 0.75) kruskal(qiskit_data, cirq_data, qs_data) qiskit_data = np.concatenate((np.full(7576, 0.375), np.full(1253, 0.3125), np.full(359, 0.4375), np.full(218, 0.25), np.full(121, 0.5), np.full(101, 0.1875), np.full(66, 0.5625), np.full(57, 0.125), np.full(42, 0.625), np.full(41, 0.0625), np.full(35, 0), np.full(29, 0.9375), np.full(27, 0.8125), np.full(27, 0.6875), np.full(25, 0.75), np.full(23, 0.875))) print(qiskit_data) cirq_data = np.concatenate((np.full(7610, 0.375), np.full(1208, 0.3125), np.full(377, 0.4375), np.full(235, 0.25), np.full(129, 0.5), np.full(89, 0.1875), np.full(68, 0.5625), np.full(55, 0.125), np.full(36, 0.625), np.full(30, 0.0625), np.full(31, 0), np.full(28, 0.9375), np.full(24, 0.8125), np.full(34, 0.6875), np.full(25, 0.75), np.full(21, 0.875))) print(cirq_data) qs_data = np.concatenate((np.full(7593, 0.375), np.full(1247, 0.3125), np.full(384, 0.4375), np.full(213, 0.25), np.full(121, 0.5), np.full(114, 0.1875), np.full(61, 0.5625), np.full(35, 0.125), np.full(39, 0.625), np.full(28, 0.0625), np.full(38, 0), np.full(22, 0.9375), np.full(18, 0.8125), np.full(28, 0.6875), np.full(27, 0.75), np.full(32, 0.875))) print(qs_data) kruskal(qiskit_data, cirq_data, qs_data) qiskit_data = np.concatenate((np.full(137,0.375), np.full(9375,0.359375), np.full(235,0.34375), np.full(4,0.265625), np.full(52,0.390625), np.full(4,0.453125), np.full(58,0.328125), np.full(15,0.296875), np.full(10,0.421875), np.full(27,0.40625), np.full(1,0.890625), np.full(21,0.3125), np.full(1,0.140625), np.full(1,0.171875), np.full(5,0.53125), np.full(1,0.921875), np.full(2,0.21875), np.full(1,0), np.full(1,0.9375), np.full(1,0.203125), np.full(1,0.5625), np.full(4,0.234375), np.full(1,0.59375), np.full(1,0.09375), np.full(1,0.734375), np.full(7,0.4375), np.full(1,0.953125), np.full(2,0.1875), np.full(2,0.671875), np.full(1,0.0625), np.full(1,0.703125), np.full(1,0.796875), np.full(1,0.484375), np.full(11,0.28125), np.full(2,0.15625), np.full(2,0.609375), np.full(1,0.84375), np.full(1,0.65625), np.full(1,0.046875), np.full(3,0.25), np.full(2,0.5), np.full(1,0.46875))) print(qiskit_data) cirq_data = np.concatenate((np.full(143,0.375), np.full(9340,0.359375), np.full(3,0.484375), np.full(61,0.328125), np.full(13,0.40625), np.full(260,0.34375), np.full(1,0.921875), np.full(45,0.390625), np.full(13,0.421875), np.full(2,0.09375), np.full(5,0.234375), np.full(14,0.296875), np.full(3,0.4375), np.full(34,0.3125), np.full(1,0.765625), np.full(2,0.75), np.full(11,0.28125), np.full(6,0.46875), np.full(5,0.265625), np.full(2,0.140625), np.full(2,0.796875), np.full(2,0.515625), np.full(3,0.21875), np.full(2,0.703125), np.full(1,0.625), np.full(1,0.53125), np.full(1,0.984375), np.full(1,0.546875), np.full(2,0.640625), np.full(2,0.1875), np.full(2,0.15625), np.full(2,0.125), np.full(1,0.03125), np.full(1,0.859375), np.full(2,0.25), np.full(1,0.453125), np.full(3,0.046875), np.full(1,0.0625), np.full(1,0.953125), np.full(1,0.59375), np.full(1,0.90625), np.full(1,0.078125), np.full(1,0.78125), np.full(1,0.5))) print(cirq_data) qs_data = np.concatenate((np.full(9324,0.359375), np.full(290,0.34375), np.full(137,0.375), np.full(57,0.328125), np.full(30,0.390625), np.full(20,0.3125), np.full(18,0.296875), np.full(17,0.40625), np.full(13,0.421875), np.full(11,0.28125), np.full(10,0.4375), np.full(9,0.265625), np.full(8,0.25), np.full(6,0.453125), np.full(4,0.46875), np.full(4,0.515625), np.full(4,0.234375), np.full(3,0.5), np.full(3,0.1875), np.full(3,0.171875), np.full(2,0.125), np.full(2,0.21875), np.full(2,0.75), np.full(2,0.609375), np.full(2,0.140625), np.full(2,0.203125), np.full(1,0.53125), np.full(1,0.546875), np.full(1,0.640625), np.full(1,0.0625), np.full(1,0.78125), np.full(1,0.671875), np.full(1,0), np.full(1,0.484375), np.full(1,0.796875), np.full(1,0.921875), np.full(1,0.03125), np.full(1,0.015625), np.full(1,0.84375), np.full(1,0.578125), np.full(1,0.078125), np.full(1,0.9375), np.full(1,0.984375))) print(qs_data) # since we have so many 'categories' it makes more sense to run a traditional ANOVA test f_oneway(qiskit_data, cirq_data, qs_data) qiskit_data = np.concatenate((np.full(4969,0.71875), np.full(2,0.0546875), np.full(4,0.5078125), np.full(3171,0.7265625), np.full(48,0.6875), np.full(7,0.828125), np.full(53,0.7578125), np.full(176,0.703125), np.full(8,0.8125), np.full(406,0.734375), np.full(144,0.7421875), np.full(475,0.7109375), np.full(8,0.8359375), np.full(1,0.265625), np.full(3,0.484375), np.full(3,0.8828125), np.full(6,0.6015625), np.full(38,0.6796875), np.full(80,0.75), np.full(1,0.1640625), np.full(87,0.6953125), np.full(25,0.7734375), np.full(18,0.78125), np.full(5,0.5859375), np.full(5,0.9296875), np.full(14,0.6640625), np.full(10,0.6484375), np.full(3,0.8984375), np.full(2,0.6171875), np.full(31,0.765625), np.full(16,0.671875), np.full(14,0.7890625), np.full(4,0.8671875), np.full(7,0.625), np.full(12,0.6328125), np.full(4,0.609375), np.full(3,0.875), np.full(2,0.4765625), np.full(1,0.2734375), np.full(2,0.34375), np.full(1,0.40625), np.full(5,0.5390625), np.full(8,0.640625), np.full(6,0.796875), np.full(1,0.21875), np.full(9,0.8046875), np.full(4,0.5703125), np.full(1,0.4453125), np.full(3,0.5), np.full(1,0.046875), np.full(11,0.65625), np.full(6,0.8203125), np.full(7,0.84375), np.full(1,0.296875), np.full(2,0.015625), np.full(1,0.53125), np.full(1,0.953125), np.full(1,0.4140625), np.full(5,0.8515625), np.full(1,0.9921875), np.full(1,0.5234375), np.full(1,0.0390625), np.full(1,0.4609375), np.full(1,0.921875), np.full(4,0.59375), np.full(2,0.90625), np.full(9,0.578125), np.full(1,0.4921875), np.full(1,0.2578125), np.full(4,0.859375), np.full(1,0.4296875), np.full(1,0.5625), np.full(2,0), np.full(2,0.546875), np.full(2,0.234375), np.full(1,0.2109375), np.full(1,0.328125), np.full(3,0.890625), np.full(1,0.171875), np.full(1,0.375), np.full(4,0.9375), np.full(1,0.9609375), np.full(1,0.15625), np.full(1,0.390625), np.full(2,0.0859375), np.full(3,0.3984375), np.full(1,0.9140625), np.full(1,0.2265625), np.full(1,0.109375), np.full(1,0.203125), np.full(1,0.515625))) print(qiskit_data) cirq_data = np.concatenate((np.full(5010,0.71875), np.full(3207,0.7265625), np.full(372,0.734375), np.full(32,0.765625), np.full(153,0.7421875), np.full(164,0.703125), np.full(28,0.7734375), np.full(19,0.671875), np.full(454,0.7109375), np.full(5,0.8828125), np.full(19,0.6640625), np.full(78,0.6953125), np.full(11,0.7890625), np.full(1,0.3515625), np.full(8,0.640625), np.full(38,0.6875), np.full(88,0.75), np.full(10,0.65625), np.full(3,0.59375), np.full(45,0.7578125), np.full(3,0.328125), np.full(3,0.5234375), np.full(3,0.6171875), np.full(40,0.6796875), np.full(6,0.84375), np.full(9,0.6328125), np.full(1,0.359375), np.full(2,0.4296875), np.full(2,0.515625), np.full(6,0.5546875), np.full(13,0.796875), np.full(4,0.8671875), np.full(5,0.6015625), np.full(2,0.09375), np.full(10,0.8046875), np.full(2,0.1796875), np.full(4,0.5625), np.full(12,0.78125), np.full(7,0.828125), np.full(12,0.8203125), np.full(3,0.859375), np.full(3,0.875), np.full(1,0.4609375), np.full(4,0.578125), np.full(2,0.984375), np.full(3,0.96875), np.full(1,0.3359375), np.full(5,0.890625), np.full(8,0.625), np.full(5,0.8359375), np.full(3,0.171875), np.full(3,0.8515625), np.full(12,0.6484375), np.full(2,0.453125), np.full(1,0.90625), np.full(2,0.3828125), np.full(5,0.53125), np.full(1,0.1953125), np.full(1,0.03125), np.full(2,0.953125), np.full(1,0.34375), np.full(3,0.8125), np.full(1,0.0078125), np.full(1,0.9609375), np.full(1,0.0234375), np.full(2,0.609375), np.full(1,0.1015625), np.full(1,0.921875), np.full(3,0.9140625), np.full(7,0.546875), np.full(1,0.5703125), np.full(2,0.25), np.full(1,0.5), np.full(1,0.0703125), np.full(2,0.9765625), np.full(2,0.9453125), np.full(1,0.2890625), np.full(1,0.046875), np.full(1,0.9296875), np.full(1,0.8984375), np.full(1,0.203125), np.full(2,0.484375), np.full(2,0.5859375), np.full(1,0.2578125), np.full(1,0.2109375), np.full(1,0.21875))) print(cirq_data) qs_data = np.concatenate((np.full(4903,0.71875), np.full(3204,0.7265625), np.full(466,0.7109375), np.full(427,0.734375), np.full(162,0.703125), np.full(160,0.7421875), np.full(95,0.6953125), np.full(78,0.75), np.full(56,0.6875), np.full(41,0.6796875), np.full(38,0.7578125), np.full(30,0.765625), np.full(24,0.671875), np.full(21,0.65625), np.full(20,0.7734375), np.full(16,0.78125), np.full(15,0.8046875), np.full(14,0.6640625), np.full(14,0.6484375), np.full(13,0.7890625), np.full(11,0.796875), np.full(9,0.640625), np.full(8,0.8203125), np.full(6,0.6171875), np.full(6,0.6328125), np.full(5,0.8359375), np.full(5,0.8125), np.full(5,0.625), np.full(5,0.953125), np.full(5,0.5859375), np.full(4,0.9140625), np.full(4,0.609375), np.full(4,0.6015625), np.full(4,0.84375), np.full(4,0.875), np.full(4,0.8828125), np.full(4,0.59375), np.full(4,0.828125), np.full(4,0.5234375), np.full(3,0.90625), np.full(3,0.8984375), np.full(3,0.859375), np.full(3,0.9765625), np.full(3,0.1171875), np.full(3,0.5625), np.full(3,0.03125), np.full(3,0.8515625), np.full(3,0.21875), np.full(3,0.4921875), np.full(3,0.546875), np.full(2,0.515625), np.full(2,0.5390625), np.full(2,0.375), np.full(2,0.3125), np.full(2,0.9296875), np.full(2,0.8671875), np.full(2,0.53125), np.full(2,0.234375), np.full(2,0.5546875), np.full(2,0.0703125), np.full(2,0.203125), np.full(2,0.921875), np.full(2,0.5), np.full(2,0.5703125), np.full(2,0.3203125), np.full(2,0.046875), np.full(2,0.171875), np.full(2,0.9453125), np.full(2,0.3984375), np.full(1,0.484375), np.full(1,0.4140625), np.full(1,0.9375), np.full(1,0.15625), np.full(1,0.96875), np.full(1,0.421875), np.full(1,0.46875), np.full(1,0.4296875), np.full(1,0.9921875), np.full(1,0.109375), np.full(1,0.1328125), np.full(1,0.1796875), np.full(1,0.4765625), np.full(1,0.1015625), np.full(1,0.2890625), np.full(1,0.078125), np.full(1,0.265625), np.full(1,0.1953125), np.full(1,0.0078125), np.full(1,0.25), np.full(1,0.453125), np.full(1,0), np.full(1,0.390625), np.full(1,0.09375), np.full(1,0.5078125), np.full(1,0.890625), np.full(1,0.4609375), np.full(1,0.984375), np.full(1,0.3359375), np.full(1,0.0859375), np.full(1,0.2734375))) print(qs_data) # since we have so many 'categories' it makes more sense to run a traditional ANOVA test f_oneway(qiskit_data, cirq_data, qs_data)
https://github.com/trevorpiltch/Grovers-Algorithm
trevorpiltch
from qiskit import * from math import pi def amplifier(n): """Creates a general diffuser using V and V-Dagger gates""" circuit = QuantumCircuit(n) circuit.x(range(n)) #V circuit.cu1(pi/4, 0, 3) #V-dagger circuit.cx(0, 1) circuit.cu1(-pi/4, 1, 3) circuit.cx(0, 1) # V circuit.cu1(pi/4, 1, 3) #V-dagger circuit.cx(1, 2) circuit.cu1(-pi/4, 2, 3) # V circuit.cx(0, 2) circuit.cu1(pi/4, 2, 3) #V-dagger circuit.cx(1, 2) circuit.cu1(-pi/4, 2, 3) # V circuit.cx(0, 2) circuit.cu1(pi/4, 2, 3) circuit.x(range(n)) amplification = circuit.to_gate() amplification.name = 'Amplification' return amplification
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import matplotlib.pyplot as plt import numpy as np import dimod n_spins = 3 h = {v: np.random.uniform(-2, 2) for v in range(n_spins)} J = {(0, 1): np.random.uniform(-1, 1), (1, 2): np.random.uniform(-1, 1)} model = dimod.BinaryQuadraticModel(h, J, 0.0, dimod.SPIN) sampler = dimod.SimulatedAnnealingSampler() temperature = 1 response = sampler.sample(model, beta_range=[1/temperature, 1/temperature], num_reads=100) energies = [solution.energy for solution in response.data()] fig, ax = plt.subplots() probabilities = np.exp(-np.array(sorted(energies))/temperature) Z = probabilities.sum() probabilities /= Z ax.plot(energies, probabilities, linewidth=3) ax.set_xlim(min(energies), max(energies)) ax.set_xticks([]) ax.set_yticks([]) ax.set_xlabel('Energy') ax.set_ylabel('Probability') plt.show() from dimod.reference.samplers.simulated_annealing import greedy_coloring clamped_spins = {0: -1} num_sweeps = 1000 βs = [1.0 - 1.0*i / (num_sweeps - 1.) for i in range(num_sweeps)] # Set up the adjacency matrix. adj = {n: set() for n in h} for n0, n1 in J: adj[n0].add(n1) adj[n1].add(n0) # Use a vertex coloring for the graph and update the nodes by color __, colors = greedy_coloring(adj) spins = {v: np.random.choice((-1, 1)) if v not in clamped_spins else clamped_spins[v] for v in h} for β in βs: energy_diff_h = {v: -2 * spins[v] * h[v] for v in h} # for each color, do updates for color in colors: nodes = colors[color] energy_diff_J = {} for v0 in nodes: ediff = 0 for v1 in adj[v0]: if (v0, v1) in J: ediff += spins[v0] * spins[v1] * J[(v0, v1)] if (v1, v0) in J: ediff += spins[v0] * spins[v1] * J[(v1, v0)] energy_diff_J[v0] = -2. * ediff for v in filter(lambda x: x not in clamped_spins, nodes): logp = np.log(np.random.uniform(0, 1)) if logp < -1. * β * (energy_diff_h[v] + energy_diff_J[v]): spins[v] *= -1 spins
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=too-many-function-args, unexpected-keyword-arg """THIS FILE IS DEPRECATED AND WILL BE REMOVED IN RELEASE 0.9. """ import warnings from qiskit.converters import dag_to_circuit, circuit_to_dag from qiskit.transpiler import CouplingMap from qiskit import compiler from qiskit.transpiler.preset_passmanagers import (default_pass_manager_simulator, default_pass_manager) def transpile(circuits, backend=None, basis_gates=None, coupling_map=None, initial_layout=None, seed_mapper=None, pass_manager=None): """transpile one or more circuits. Args: circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile backend (BaseBackend): a backend to compile for basis_gates (list[str]): list of basis gate names supported by the target. Default: ['u1','u2','u3','cx','id'] coupling_map (list): coupling map (perhaps custom) to target in mapping initial_layout (Layout or dict or list): Initial position of virtual qubits on physical qubits. The final layout is not guaranteed to be the same, as the transpiler may permute qubits through swaps or other means. seed_mapper (int): random seed for the swap_mapper pass_manager (PassManager): a pass_manager for the transpiler stages Returns: QuantumCircuit or list[QuantumCircuit]: transpiled circuit(s). Raises: TranspilerError: in case of bad inputs to transpiler or errors in passes """ warnings.warn("qiskit.transpiler.transpile() has been deprecated and will be " "removed in the 0.9 release. Use qiskit.compiler.transpile() instead.", DeprecationWarning) return compiler.transpile(circuits=circuits, backend=backend, basis_gates=basis_gates, coupling_map=coupling_map, initial_layout=initial_layout, seed_transpiler=seed_mapper, pass_manager=pass_manager) def transpile_dag(dag, basis_gates=None, coupling_map=None, initial_layout=None, seed_mapper=None, pass_manager=None): """Deprecated - Use qiskit.compiler.transpile for transpiling from circuits to circuits. Transform a dag circuit into another dag circuit (transpile), through consecutive passes on the dag. Args: dag (DAGCircuit): dag circuit to transform via transpilation basis_gates (list[str]): list of basis gate names supported by the target. Default: ['u1','u2','u3','cx','id'] coupling_map (list): A graph of coupling:: [ [control0(int), target0(int)], [control1(int), target1(int)], ] eg. [[0, 2], [1, 2], [1, 3], [3, 4]} initial_layout (Layout or None): A layout object seed_mapper (int): random seed_mapper for the swap mapper pass_manager (PassManager): pass manager instance for the transpilation process If None, a default set of passes are run. Otherwise, the passes defined in it will run. If contains no passes in it, no dag transformations occur. Returns: DAGCircuit: transformed dag """ warnings.warn("transpile_dag has been deprecated and will be removed in the " "0.9 release. Circuits can be transpiled directly to other " "circuits with the transpile function.", DeprecationWarning) if basis_gates is None: basis_gates = ['u1', 'u2', 'u3', 'cx', 'id'] if pass_manager is None: # default set of passes # if a coupling map is given compile to the map if coupling_map: pass_manager = default_pass_manager(basis_gates, CouplingMap(coupling_map), initial_layout, seed_transpiler=seed_mapper) else: pass_manager = default_pass_manager_simulator(basis_gates) # run the passes specified by the pass manager # TODO return the property set too. See #1086 name = dag.name circuit = dag_to_circuit(dag) circuit = pass_manager.run(circuit) dag = circuit_to_dag(circuit) dag.name = name return dag
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag from qiskit.circuit.library.standard_gates import CHGate, U2Gate, CXGate from qiskit.converters import dag_to_circuit q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') circ = QuantumCircuit(q, c) circ.h(q[0]) circ.cx(q[0], q[1]) circ.measure(q[0], c[0]) circ.rz(0.5, q[1]).c_if(c, 2) dag = circuit_to_dag(circ) circuit = dag_to_circuit(dag) circuit.draw('mpl')
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Testing legacy instruction alignment pass.""" from qiskit import QuantumCircuit, pulse from qiskit.test import QiskitTestCase from qiskit.transpiler import InstructionDurations from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.passes import ( AlignMeasures, ValidatePulseGates, ALAPSchedule, TimeUnitConversion, ) class TestAlignMeasures(QiskitTestCase): """A test for measurement alignment pass.""" def setUp(self): super().setUp() instruction_durations = InstructionDurations() instruction_durations.update( [ ("rz", (0,), 0), ("rz", (1,), 0), ("x", (0,), 160), ("x", (1,), 160), ("sx", (0,), 160), ("sx", (1,), 160), ("cx", (0, 1), 800), ("cx", (1, 0), 800), ("measure", None, 1600), ] ) self.time_conversion_pass = TimeUnitConversion(inst_durations=instruction_durations) # reproduce old behavior of 0.20.0 before #7655 # currently default write latency is 0 self.scheduling_pass = ALAPSchedule( durations=instruction_durations, clbit_write_latency=1600, conditional_latency=0, ) self.align_measure_pass = AlignMeasures(alignment=16) def test_t1_experiment_type(self): """Test T1 experiment type circuit. (input) ┌───┐┌────────────────┐┌─┐ q_0: ┤ X ├┤ Delay(100[dt]) ├┤M├ └───┘└────────────────┘└╥┘ c: 1/════════════════════════╩═ 0 (aligned) ┌───┐┌────────────────┐┌─┐ q_0: ┤ X ├┤ Delay(112[dt]) ├┤M├ └───┘└────────────────┘└╥┘ c: 1/════════════════════════╩═ 0 This type of experiment slightly changes delay duration of interest. However the quantization error should be less than alignment * dt. """ circuit = QuantumCircuit(1, 1) circuit.x(0) circuit.delay(100, 0, unit="dt") circuit.measure(0, 0) timed_circuit = self.time_conversion_pass(circuit) scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"}) aligned_circuit = self.align_measure_pass( scheduled_circuit, property_set={"time_unit": "dt"} ) ref_circuit = QuantumCircuit(1, 1) ref_circuit.x(0) ref_circuit.delay(112, 0, unit="dt") ref_circuit.measure(0, 0) self.assertEqual(aligned_circuit, ref_circuit) def test_hanh_echo_experiment_type(self): """Test Hahn echo experiment type circuit. (input) ┌────┐┌────────────────┐┌───┐┌────────────────┐┌────┐┌─┐ q_0: ┤ √X ├┤ Delay(100[dt]) ├┤ X ├┤ Delay(100[dt]) ├┤ √X ├┤M├ └────┘└────────────────┘└───┘└────────────────┘└────┘└╥┘ c: 1/══════════════════════════════════════════════════════╩═ 0 (output) ┌────┐┌────────────────┐┌───┐┌────────────────┐┌────┐┌──────────────┐┌─┐ q_0: ┤ √X ├┤ Delay(100[dt]) ├┤ X ├┤ Delay(100[dt]) ├┤ √X ├┤ Delay(8[dt]) ├┤M├ └────┘└────────────────┘└───┘└────────────────┘└────┘└──────────────┘└╥┘ c: 1/══════════════════════════════════════════════════════════════════════╩═ 0 This type of experiment doesn't change duration of interest (two in the middle). However induces slight delay less than alignment * dt before measurement. This might induce extra amplitude damping error. """ circuit = QuantumCircuit(1, 1) circuit.sx(0) circuit.delay(100, 0, unit="dt") circuit.x(0) circuit.delay(100, 0, unit="dt") circuit.sx(0) circuit.measure(0, 0) timed_circuit = self.time_conversion_pass(circuit) scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"}) aligned_circuit = self.align_measure_pass( scheduled_circuit, property_set={"time_unit": "dt"} ) ref_circuit = QuantumCircuit(1, 1) ref_circuit.sx(0) ref_circuit.delay(100, 0, unit="dt") ref_circuit.x(0) ref_circuit.delay(100, 0, unit="dt") ref_circuit.sx(0) ref_circuit.delay(8, 0, unit="dt") ref_circuit.measure(0, 0) self.assertEqual(aligned_circuit, ref_circuit) def test_mid_circuit_measure(self): """Test circuit with mid circuit measurement. (input) ┌───┐┌────────────────┐┌─┐┌───────────────┐┌───┐┌────────────────┐┌─┐ q_0: ┤ X ├┤ Delay(100[dt]) ├┤M├┤ Delay(10[dt]) ├┤ X ├┤ Delay(120[dt]) ├┤M├ └───┘└────────────────┘└╥┘└───────────────┘└───┘└────────────────┘└╥┘ c: 2/════════════════════════╩══════════════════════════════════════════╩═ 0 1 (output) ┌───┐┌────────────────┐┌─┐┌───────────────┐┌───┐┌────────────────┐┌─┐ q_0: ┤ X ├┤ Delay(112[dt]) ├┤M├┤ Delay(10[dt]) ├┤ X ├┤ Delay(134[dt]) ├┤M├ └───┘└────────────────┘└╥┘└───────────────┘└───┘└────────────────┘└╥┘ c: 2/════════════════════════╩══════════════════════════════════════════╩═ 0 1 Extra delay is always added to the existing delay right before the measurement. Delay after measurement is unchanged. """ circuit = QuantumCircuit(1, 2) circuit.x(0) circuit.delay(100, 0, unit="dt") circuit.measure(0, 0) circuit.delay(10, 0, unit="dt") circuit.x(0) circuit.delay(120, 0, unit="dt") circuit.measure(0, 1) timed_circuit = self.time_conversion_pass(circuit) scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"}) aligned_circuit = self.align_measure_pass( scheduled_circuit, property_set={"time_unit": "dt"} ) ref_circuit = QuantumCircuit(1, 2) ref_circuit.x(0) ref_circuit.delay(112, 0, unit="dt") ref_circuit.measure(0, 0) ref_circuit.delay(10, 0, unit="dt") ref_circuit.x(0) ref_circuit.delay(134, 0, unit="dt") ref_circuit.measure(0, 1) self.assertEqual(aligned_circuit, ref_circuit) def test_mid_circuit_multiq_gates(self): """Test circuit with mid circuit measurement and multi qubit gates. (input) ┌───┐┌────────────────┐┌─┐ ┌─┐ q_0: ┤ X ├┤ Delay(100[dt]) ├┤M├──■───────■──┤M├ └───┘└────────────────┘└╥┘┌─┴─┐┌─┐┌─┴─┐└╥┘ q_1: ────────────────────────╫─┤ X ├┤M├┤ X ├─╫─ ║ └───┘└╥┘└───┘ ║ c: 2/════════════════════════╩═══════╩═══════╩═ 0 1 0 (output) ┌───┐ ┌────────────────┐┌─┐ ┌─────────────────┐ ┌─┐» q_0: ───────┤ X ├───────┤ Delay(112[dt]) ├┤M├──■──┤ Delay(1600[dt]) ├──■──┤M├» ┌──────┴───┴──────┐└────────────────┘└╥┘┌─┴─┐└───────┬─┬───────┘┌─┴─┐└╥┘» q_1: ┤ Delay(1872[dt]) ├───────────────────╫─┤ X ├────────┤M├────────┤ X ├─╫─» └─────────────────┘ ║ └───┘ └╥┘ └───┘ ║ » c: 2/══════════════════════════════════════╩═══════════════╩═══════════════╩═» 0 1 0 » « «q_0: ─────────────────── « ┌─────────────────┐ «q_1: ┤ Delay(1600[dt]) ├ « └─────────────────┘ «c: 2/═══════════════════ « Delay for the other channel paired by multi-qubit instruction is also scheduled. Delay (1872dt) = X (160dt) + Delay (100dt + extra 12dt) + Measure (1600dt). """ circuit = QuantumCircuit(2, 2) circuit.x(0) circuit.delay(100, 0, unit="dt") circuit.measure(0, 0) circuit.cx(0, 1) circuit.measure(1, 1) circuit.cx(0, 1) circuit.measure(0, 0) timed_circuit = self.time_conversion_pass(circuit) scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"}) aligned_circuit = self.align_measure_pass( scheduled_circuit, property_set={"time_unit": "dt"} ) ref_circuit = QuantumCircuit(2, 2) ref_circuit.x(0) ref_circuit.delay(112, 0, unit="dt") ref_circuit.measure(0, 0) ref_circuit.delay(160 + 112 + 1600, 1, unit="dt") ref_circuit.cx(0, 1) ref_circuit.delay(1600, 0, unit="dt") ref_circuit.measure(1, 1) ref_circuit.cx(0, 1) ref_circuit.delay(1600, 1, unit="dt") ref_circuit.measure(0, 0) self.assertEqual(aligned_circuit, ref_circuit) def test_alignment_is_not_processed(self): """Test avoid pass processing if delay is aligned.""" circuit = QuantumCircuit(2, 2) circuit.x(0) circuit.delay(160, 0, unit="dt") circuit.measure(0, 0) circuit.cx(0, 1) circuit.measure(1, 1) circuit.cx(0, 1) circuit.measure(0, 0) # pre scheduling is not necessary because alignment is skipped # this is to minimize breaking changes to existing code. transpiled = self.align_measure_pass(circuit, property_set={"time_unit": "dt"}) self.assertEqual(transpiled, circuit) def test_circuit_using_clbit(self): """Test a circuit with instructions using a common clbit. (input) ┌───┐┌────────────────┐┌─┐ q_0: ┤ X ├┤ Delay(100[dt]) ├┤M├────────────── └───┘└────────────────┘└╥┘ ┌───┐ q_1: ────────────────────────╫────┤ X ├────── ║ └─╥─┘ ┌─┐ q_2: ────────────────────────╫──────╫─────┤M├ ║ ┌────╨────┐└╥┘ c: 1/════════════════════════╩═╡ c_0 = T ╞═╩═ 0 └─────────┘ 0 (aligned) ┌───┐ ┌────────────────┐┌─┐┌────────────────┐ q_0: ───────┤ X ├───────┤ Delay(112[dt]) ├┤M├┤ Delay(160[dt]) ├─── ┌──────┴───┴──────┐└────────────────┘└╥┘└─────┬───┬──────┘ q_1: ┤ Delay(1872[dt]) ├───────────────────╫───────┤ X ├────────── └┬────────────────┤ ║ └─╥─┘ ┌─┐ q_2: ─┤ Delay(432[dt]) ├───────────────────╫─────────╫─────────┤M├ └────────────────┘ ║ ┌────╨────┐ └╥┘ c: 1/══════════════════════════════════════╩════╡ c_0 = T ╞═════╩═ 0 └─────────┘ 0 Looking at the q_0, the total schedule length T becomes 160 (x) + 112 (aligned delay) + 1600 (measure) + 160 (delay) = 2032. The last delay comes from ALAP scheduling called before the AlignMeasure pass, which aligns stop times as late as possible, so the start time of x(1).c_if(0) and the stop time of measure(0, 0) become T - 160. """ circuit = QuantumCircuit(3, 1) circuit.x(0) circuit.delay(100, 0, unit="dt") circuit.measure(0, 0) circuit.x(1).c_if(0, 1) circuit.measure(2, 0) timed_circuit = self.time_conversion_pass(circuit) scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"}) aligned_circuit = self.align_measure_pass( scheduled_circuit, property_set={"time_unit": "dt"} ) self.assertEqual(aligned_circuit.duration, 2032) ref_circuit = QuantumCircuit(3, 1) ref_circuit.x(0) ref_circuit.delay(112, 0, unit="dt") ref_circuit.delay(1872, 1, unit="dt") # 2032 - 160 ref_circuit.delay(432, 2, unit="dt") # 2032 - 1600 ref_circuit.measure(0, 0) ref_circuit.x(1).c_if(0, 1) ref_circuit.delay(160, 0, unit="dt") ref_circuit.measure(2, 0) self.assertEqual(aligned_circuit, ref_circuit) class TestPulseGateValidation(QiskitTestCase): """A test for pulse gate validation pass.""" def setUp(self): super().setUp() self.pulse_gate_validation_pass = ValidatePulseGates(granularity=16, min_length=64) def test_invalid_pulse_duration(self): """Kill pass manager if invalid pulse gate is found.""" # this is invalid duration pulse # this will cause backend error since this doesn't fit with waveform memory chunk. custom_gate = pulse.Schedule(name="custom_x_gate") custom_gate.insert( 0, pulse.Play(pulse.Constant(100, 0.1), pulse.DriveChannel(0)), inplace=True ) circuit = QuantumCircuit(1) circuit.x(0) circuit.add_calibration("x", qubits=(0,), schedule=custom_gate) with self.assertRaises(TranspilerError): self.pulse_gate_validation_pass(circuit) def test_short_pulse_duration(self): """Kill pass manager if invalid pulse gate is found.""" # this is invalid duration pulse # this will cause backend error since this doesn't fit with waveform memory chunk. custom_gate = pulse.Schedule(name="custom_x_gate") custom_gate.insert( 0, pulse.Play(pulse.Constant(32, 0.1), pulse.DriveChannel(0)), inplace=True ) circuit = QuantumCircuit(1) circuit.x(0) circuit.add_calibration("x", qubits=(0,), schedule=custom_gate) with self.assertRaises(TranspilerError): self.pulse_gate_validation_pass(circuit) def test_short_pulse_duration_multiple_pulse(self): """Kill pass manager if invalid pulse gate is found.""" # this is invalid duration pulse # however total gate schedule length is 64, which accidentally satisfies the constraints # this should fail in the validation custom_gate = pulse.Schedule(name="custom_x_gate") custom_gate.insert( 0, pulse.Play(pulse.Constant(32, 0.1), pulse.DriveChannel(0)), inplace=True ) custom_gate.insert( 32, pulse.Play(pulse.Constant(32, 0.1), pulse.DriveChannel(0)), inplace=True ) circuit = QuantumCircuit(1) circuit.x(0) circuit.add_calibration("x", qubits=(0,), schedule=custom_gate) with self.assertRaises(TranspilerError): self.pulse_gate_validation_pass(circuit) def test_valid_pulse_duration(self): """No error raises if valid calibration is provided.""" # this is valid duration pulse custom_gate = pulse.Schedule(name="custom_x_gate") custom_gate.insert( 0, pulse.Play(pulse.Constant(160, 0.1), pulse.DriveChannel(0)), inplace=True ) circuit = QuantumCircuit(1) circuit.x(0) circuit.add_calibration("x", qubits=(0,), schedule=custom_gate) # just not raise an error self.pulse_gate_validation_pass(circuit) def test_no_calibration(self): """No error raises if no calibration is addedd.""" circuit = QuantumCircuit(1) circuit.x(0) # just not raise an error self.pulse_gate_validation_pass(circuit)
https://github.com/SamperQuinto/QisKit
SamperQuinto
#initialization import matplotlib.pyplot as plt import numpy as np import math # importing Qiskit from qiskit import IBMQ, Aer, transpile, assemble from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister # import basic plot tools from qiskit.visualization import plot_histogram qpe = QuantumCircuit(4, 3) qpe.x(3) #Apply Hadamard gate for qubit in range(3): qpe.h(qubit) qpe.draw() repetitions = 1 for counting_qubit in range(3): for i in range(repetitions): qpe.cp(math.pi/4, counting_qubit, 3); # This is CU # we use 2*pi*(1/theta) repetitions *= 2 qpe.draw() def qft_dagger(qc, n): """n-qubit QFTdagger the first n qubits in circ""" # Don't forget the Swaps! for qubit in range(n//2): qc.swap(qubit, n-qubit-1) for j in range(n): for m in range(j): qc.cp(-math.pi/float(2**(j-m)), m, j) qc.h(j) qpe.barrier() # Apply inverse QFT qft_dagger(qpe, 3) # Measure qpe.barrier() for n in range(3): qpe.measure(n,n) qpe.draw() aer_sim = Aer.get_backend('aer_simulator') shots = 2048 t_qpe = transpile(qpe, aer_sim) qobj = assemble(t_qpe, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) # Create and set up circuit qpe2 = QuantumCircuit(4, 3) # Apply H-Gates to counting qubits: for qubit in range(3): qpe2.h(qubit) # Prepare our eigenstate |psi>: qpe2.x(3) # Do the controlled-U operations: angle = 2*math.pi/3 repetitions = 1 for counting_qubit in range(3): for i in range(repetitions): qpe2.cp(angle, counting_qubit, 3); repetitions *= 2 # Do the inverse QFT: qft_dagger(qpe2, 3) # Measure of course! for n in range(3): qpe2.measure(n,n) qpe2.draw() # Let's see the results! aer_sim = Aer.get_backend('aer_simulator') shots = 4096 t_qpe2 = transpile(qpe2, aer_sim) qobj = assemble(t_qpe2, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) # Create and set up circuit qpe3 = QuantumCircuit(6, 5) # Apply H-Gates to counting qubits: for qubit in range(5): qpe3.h(qubit) # Prepare our eigenstate |psi>: qpe3.x(5) # Do the controlled-U operations: angle = 2*math.pi/3 repetitions = 1 for counting_qubit in range(5): for i in range(repetitions): qpe3.cp(angle, counting_qubit, 5); repetitions *= 2 # Do the inverse QFT: qft_dagger(qpe3, 5) # Measure of course! qpe3.barrier() for n in range(5): qpe3.measure(n,n) qpe3.draw() # Let's see the results! aer_sim = Aer.get_backend('aer_simulator') shots = 4096 t_qpe3 = transpile(qpe3, aer_sim) qobj = assemble(t_qpe3, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/JavaFXpert/quantum-pong
JavaFXpert
#!/usr/bin/env python # # Copyright 2019 the original author or authors. # # 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 pygame from qiskit import BasicAer, execute from qiskit.tools.visualization import plot_state_qsphere from utils import load_image class QSphere(pygame.sprite.Sprite): """Displays a qsphere""" def __init__(self, circuit): pygame.sprite.Sprite.__init__(self) self.image = None self.rect = None self.set_circuit(circuit) # def update(self): # # Nothing yet # a = 1 def set_circuit(self, circuit): backend_sv_sim = BasicAer.get_backend('statevector_simulator') job_sim = execute(circuit, backend_sv_sim) result_sim = job_sim.result() quantum_state = result_sim.get_statevector(circuit, decimals=3) qsphere = plot_state_qsphere(quantum_state) qsphere.savefig("utils/data/bell_qsphere.png") self.image, self.rect = load_image('bell_qsphere.png', -1) self.rect.inflate_ip(-100, -100) self.image.convert()
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
%run init.ipynb c00,c01,c10,c11 = symbols('c_{00} c_{01} c_{10} c_{11}') psiAB = Matrix([[c00],[c01],[c10],[c11]]); psiAB rhoAB = psiAB*conjugate(psiAB.T); rhoAB rhoA = ptraceB(2,2,rhoAB); rhoB = ptraceA(2,2,rhoAB) rhoA, rhoB pauli(3)*pauli(1)*pauli(3), pauli(3)*pauli(2)*pauli(3), comm(pauli(3),pauli(1)), comm(pauli(3),pauli(2)) %run init.ipynb def pTraceL_num(dl, dr, rhoLR): rhoR = np.zeros((dr, dr), dtype=complex) for j in range(0, dr): for k in range(j, dr): for l in range(0, dl): rhoR[j,k] += rhoLR[l*dr+j,l*dr+k] if j != k: rhoR[k,j] = np.conj(rhoR[j,k]) return rhoR def pTraceR_num(dl, dr, rhoLR): rhoL = np.zeros((dl, dl), dtype=complex) for j in range(0, dl): for k in range(j, dl): for l in range(0, dr): rhoL[j,k] += rhoLR[j*dr+l,k*dr+l] if j != k: rhoL[k,j] = np.conj(rhoL[j,k]) return rhoL def coh_l1(rho): d = rho.shape[0]; C = 0 for j in range(0,d-1): for k in range(j+1,d): C += np.abs(rho[j,k]) return 2*C from numpy import linalg as LA def Econc_(rho): s2 = np.array([[0,-1j],[1j,0]]) R = rho@np.kron(s2,s2)@np.matrix.conjugate(rho)@np.kron(s2,s2) w, v = LA.eig(R) evm = max(abs(w[0]), abs(w[1]), abs(w[2]), abs(w[3])) Ec = 2*math.sqrt(abs(evm)) - math.sqrt(abs(w[0])) - math.sqrt(abs(w[1]))\ - math.sqrt(abs(w[2])) - math.sqrt(abs(w[3])) if Ec < 0.0: Ec = 0.0 return Ec import scipy.linalg.lapack as lapak def Econc(rho): s2 = np.array([[0,-1j],[1j,0]]) R = rho@np.kron(s2,s2)@np.matrix.conjugate(rho)@np.kron(s2,s2) ev = lapak.zheevd(R) evm = max(abs(ev[0][0]), abs(ev[0][1]), abs(ev[0][2]), abs(ev[0][3])) Ec = 2*math.sqrt(abs(evm)) - math.sqrt(abs(ev[0][0])) - math.sqrt(abs(ev[0][1]))\ - math.sqrt(abs(ev[0][2])) - math.sqrt(abs(ev[0][3])) if Ec < 0.0: Ec = 0.0 return Ec def concurrence_psi(rho): rho_r = pTraceL_num(2,2,rho) return math.sqrt(2*abs(1-np.matrix.trace(rho_r@rho_r))) def predict_jb(rho): return abs(rho[0,0]-rho[1,1]) import qiskit from qiskit import * nshots = 8192 IBMQ.load_account() #provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') device = provider.get_backend('ibmq_manila') simulator = Aer.get_backend('qasm_simulator') from qiskit.tools.monitor import job_monitor from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter q_exp = np.arange(0,1.1,0.1); N = len(q_exp) th_xi = np.zeros(N); th_xi = 2*np.arccos(np.sqrt(1-q_exp)) th_eta = np.zeros(N); th_eta = 2*np.arccos(np.sqrt(q_exp)) E_sim_10 = np.zeros(N); C_sim_0 = np.zeros(N); P_sim_0 = np.zeros(N) jobs_ids = [] for j in range(0,N): qr = QuantumRegister(5); qc = QuantumCircuit(qr) # prepara xi qc.u(th_xi[j],0,0,qr[1]) qc.cx(qr[1],qr[2]) qc.h([qr[1],qr[2]]) # prepara eta qc.u(th_eta[j],0,0,qr[3]) qc.cx(qr[3],qr[4]) qc.h([qr[3],qr[4]]) # tomografia qstc = state_tomography_circuits(qc, [qr[1],qr[2]]) job_sim = qiskit.execute(qstc, backend = simulator, shots=nshots) qstf_sim = StateTomographyFitter(job_sim.result(), qstc) rho_10_sim = qstf_sim.fit(method='lstsq') E_sim_10[j] = concurrence_psi(rho_10_sim) rho_0_sim = pTraceL_num(2, 2, rho_10_sim) C_sim_0[j] = coh_l1(rho_0_sim) P_sim_0[j] = predict_jb(rho_0_sim) qc.draw(output='mpl') q_exp = np.arange(0,1.1,0.1); N = len(q_exp) th_xi = np.zeros(N); th_xi = 2*np.arccos(np.sqrt(1-q_exp)) th_eta = np.zeros(N); th_eta = 2*np.arccos(np.sqrt(q_exp)) jobs_ids = [] for j in range(0,N): qr = QuantumRegister(5); qc = QuantumCircuit(qr) # prepara xi qc.u(th_xi[j],0,0,qr[1]) qc.cx(qr[1],qr[2]) qc.h([qr[1],qr[2]]) # prepara eta qc.u(th_eta[j],0,0,qr[3]) qc.cx(qr[3],qr[4]) qc.h([qr[3],qr[4]]) # tomografia qstc = state_tomography_circuits(qc, [qr[1],qr[2]]) job_exp = qiskit.execute(qstc, backend = device, shots=nshots) jobs_ids.append(job_exp.job_id()) print(job_exp.job_id()) job_monitor(job_exp) print(jobs_ids) f = open("jobs_ids_ES_pre_bbm.txt", "w") f.write(str(jobs_ids)) f.close() f = open("jobs_ids_ES_pre_bbm.txt","r") #jobs_ids_list = f.read() list_ids = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",") f.close() list_ids[0] print(list_ids) print(jobs_ids_list) len_ids = len('6368049443e1f0708afdaf73') print(len_ids) list_ids = [] for j in range(0,N): s = 0 if j > 0: s = 2 print(jobs_ids_list[(j*(len_ids+2+s)+2):(j+1)*(len_ids+2)+j*s]) list_ids.append(jobs_ids_list[(j*(len_ids+2+s)+2):(j+1)*(len_ids+2)+j*s]) list_ids[0] q_exp = np.arange(0,1.1,0.1); N = len(q_exp) E_exp_10 = np.zeros(N); C_exp_0 = np.zeros(N); P_exp_0 = np.zeros(N) for j in range(0,N): job = device.retrieve_job(list_ids[j]) qstf_exp = StateTomographyFitter(job.result(), qstc) rho_10_exp = qstf_exp.fit(method='lstsq'); E_exp_10[j] = Econc_(rho_10_exp) print(E_exp_10[j]) rho_0_exp = pTraceL_num(2, 2, rho_10_exp) C_exp_0[j] = coh_l1(rho_0_exp) P_exp[j] = predict_jb(rho_0_exp) import matplotlib matplotlib.rcParams.update({'font.size':11}); plt.figure(figsize = (7,5), dpi = 100) q = np.arange(0,1.01,0.01) Ei2 = 4*q*(1-q) Ci2 = (2*q-1)**2 Pi2 = np.zeros(len(q)) Pm = 1-2*q*(1-q) plt.plot(q, Ei2, '-', label=r'$E_{conc}(\xi_{AC})^2$') plt.plot(q, Ci2, '--', label=r'$C_{l_1}(\xi_C)^2$') plt.plot(q, Pi2, '-.', label=r'$P(\xi_C)^2$') plt.plot(q, Ei2+Ci2, ':', label=r'$E_{conc}(\xi_{AC})^{2}+C_{l_{1}}(\xi_{C})^{2}+P(\xi_C)^2$') plt.plot(q_exp, E_sim_10**2, 'X', label=r'$E_{conc}(\xi_{AC})^2_{sim}$') plt.plot(q_exp, C_sim_0**2, 'h', label=r'$C_{l_1}(\xi_C)^2_{sim}$') plt.plot(q_exp, P_sim_0**2, '>', label=r'$P(\xi_C)^2_{sim}$') plt.plot(q_exp, E_sim_10**2+C_sim_0**2+P_sim_0**2, '*', label=r'$E_{conc}(\xi_{AC})^{2}_{sim}+C_{l_{1}}(\xi_{C})^{2}_{sim}+P(\xi_C)^2_{sim}$') plt.plot(q_exp, E_exp_10**2, 's', label=r'$E_{conc}(\xi_{AC})^2_{exp}$') plt.plot(q_exp, C_exp_0**2, 'o', label=r'$C_{l_1}(\xi_C)^2_{exp}$') plt.plot(q_exp, P_exp_0**2, 'v', label=r'$P(\xi_C)^2_{exp}$') plt.plot(q_exp, E_exp_10**2+C_exp_0**2+P_exp_0**2, 'd', label=r'$E_{conc}(\xi_{AC})^{2}_{exp}+C_{l_{1}}(\xi_{C})^{2}_{exp}+P(\xi_C)^2_{exp}$') plt.legend(bbox_to_anchor=(1.75, 1.0), loc='upper right') plt.xlabel(r'$q$') plt.show() # error mitigation qr = QuantumRegister(5); qubit_list = [1,2] meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr) job = qiskit.execute(meas_calibs, backend = device, shots = nshots) print(job.job_id()) job_monitor(job) job = device.retrieve_job('636d895d04e46a1feb6227a9') meas_fitter = CompleteMeasFitter(job.result(), state_labels) q_exp = np.arange(0,1.1,0.1); N = len(q_exp) for j in range(0,N): job = device.retrieve_job(list_ids[j]) mitigated_results = meas_fitter.filter.apply(job.result()) qstf_exp = StateTomographyFitter(mitigated_results, qstc) rho_10_exp = qstf_exp.fit(method='lstsq'); E_exp_10[j] = Econc_(rho_10_exp) print(E_exp_10[j]) rho_0_exp = pTraceL_num(2, 2, rho_10_exp) C_exp_0[j] = coh_l1(rho_0_exp) P_exp[j] = predict_jb(rho_0_exp) import matplotlib matplotlib.rcParams.update({'font.size':11}); plt.figure(figsize = (7,5), dpi = 100) q = np.arange(0,1.01,0.01) Ei2 = 4*q*(1-q) Ci2 = (2*q-1)**2 Pi2 = np.zeros(len(q)) Pm = 1-2*q*(1-q) plt.plot(q, Ei2, '-', label=r'$E_{conc}(\xi_{AC})^2$') plt.plot(q, Ci2, '--', label=r'$C_{l_1}(\xi_C)^2$') plt.plot(q, Pi2, '-.', label=r'$P(\xi_C)^2$') plt.plot(q, Ei2+Ci2, ':', label=r'$E_{conc}(\xi_{AC})^{2}+C_{l_{1}}(\xi_{C})^{2}+P(\xi_C)^2$') plt.plot(q_exp, E_sim_10**2, 'X', label=r'$E_{conc}(\xi_{AC})^2_{sim}$') plt.plot(q_exp, C_sim_0**2, 'h', label=r'$C_{l_1}(\xi_C)^2_{sim}$') plt.plot(q_exp, P_sim_0**2, '>', label=r'$P(\xi_C)^2_{sim}$') plt.plot(q_exp, E_sim_10**2+C_sim_0**2+P_sim_0**2, '*', label=r'$E_{conc}(\xi_{AC})^{2}_{sim}+C_{l_{1}}(\xi_{C})^{2}_{sim}+P(\xi_C)^2_{sim}$') plt.plot(q_exp, E_exp_10**2, '^', label=r'$E_{conc}(\xi_{AC})^2_{exp}$') plt.plot(q_exp, C_exp_0**2, 'o', label=r'$C_{l_1}(\xi_C)^2_{exp}$') plt.plot(q_exp, P_exp_0**2, '.', label=r'$P(\xi_C)^2_{exp}$') plt.plot(q_exp, E_exp_10**2+C_exp_0**2+P_exp_0**2, 'd', label=r'$E_{conc}(\xi_{AC})^{2}_{exp}+C_{l_{1}}(\xi_{C})^{2}_{exp}+P(\xi_C)^2_{exp}$') plt.legend(bbox_to_anchor=(1.75, 1.0), loc='upper right') plt.xlabel(r'$q$') plt.savefig('fig_Eswap_pre_bbm.pdf') plt.show() qc.draw(output='mpl') def pTrace_3_num(rho_abc, da, db, dc): rho_ac = np.zeros(da*dc*da*dc, dtype=complex).reshape(da*dc,da*dc) for j in range(0,da): for l in range(0,dc): cj = j*dc+l ccj = j*db*dc+l for m in range(0,da): for o in range(0,dc): ck = m*dc+o cck = m*db*dc+o for k in range(0,db): rho_ac[cj,ck] = rho_ac[cj,ck] + rho_abc[ccj+k*dc,cck+k*dc] return rho_ac import numpy as np import math # projetores para a pos-seleção I2 = np.array([[1,0],[0,1]], dtype=complex) P00 = np.kron(np.kron(I2,np.array([[1,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],dtype=complex)), I2) # PhiP P01 = np.kron(np.kron(I2,np.array([[0,0,0,0],[0,1,0,0],[0,0,0,0],[0,0,0,0]],dtype=complex)), I2) # PsiP P10 = np.kron(np.kron(I2,np.array([[0,0,0,0],[0,0,0,0],[0,0,1,0],[0,0,0,0]],dtype=complex)), I2) # PhiM P11 = np.kron(np.kron(I2,np.array([[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1]],dtype=complex)), I2) # PsiM #P00+P01+P10+P11 q_exp = np.arange(0,1.1,0.1); N = len(q_exp) q_exp[0] = 0.03; q_exp[N-1] = 1-q_exp[0] th_xi = np.zeros(N); th_xi = 2*np.arccos(np.sqrt(1-q_exp)) th_eta = np.zeros(N); th_eta = 2*np.arccos(np.sqrt(q_exp)) E_phiP_04_sim = np.zeros(N); E_psiM_04_sim = np.zeros(N) E_psiP_04_sim = np.zeros(N); E_phiM_04_sim = np.zeros(N) C2_sim = np.zeros(N) for j in range(0,N): qr = QuantumRegister(5); qc = QuantumCircuit(qr) # prepara xi qc.u(th_xi[j],0,0,qr[0]) qc.cx(qr[0],qr[1]) qc.h([qr[0],qr[1]]) # prepara eta qc.u(th_eta[j],0,0,qr[3]) qc.cx(qr[3],qr[4]) qc.h([qr[3],qr[4]]) # BBM qc.cx(qr[1],qr[3]) qc.h(qr[1]) # circuito para tomografia qstc = state_tomography_circuits(qc, [qr[4],qr[3],qr[1],qr[0]]) # Simulacao job_sim = qiskit.execute(qstc, backend = simulator, shots=nshots) qstf_sim = StateTomographyFitter(job_sim.result(), qstc) rho_4310_sim = qstf_sim.fit(method='lstsq') # pos-selecao rho_PhiP = P00@rho_4310_sim@P00 pr_phiP = np.real(np.trace(rho_PhiP)) rho_PhiP = (1/pr_phiP)*rho_PhiP rho_PsiP = P01@rho_4310_sim@P01 pr_psiP = np.real(np.trace(rho_PsiP)) rho_PsiP = (1/pr_psiP)*rho_PsiP rho_PhiM = P10@rho_4310_sim@P10 pr_phiM = np.real(np.trace(rho_PhiM)) rho_PhiM = (1/pr_phiM)*rho_PhiM rho_PsiM = P11@rho_4310_sim@P11 pr_psiM = np.real(np.trace(rho_PsiM)) rho_PsiM = (1/pr_psiM)*rho_PsiM # estados reduzidos rho_PhiP_04 = pTrace_3_num(rho_PhiP,2,4,2) rho_PsiP_04 = pTrace_3_num(rho_PsiP,2,4,2) rho_PhiM_04 = pTrace_3_num(rho_PhiM,2,4,2) rho_PsiM_04 = pTrace_3_num(rho_PsiM,2,4,2) # emaranhamentos e probabilidades E_phiP_04_sim[j] = Econc_(rho_PhiP_04) E_phiM_04_sim[j] = Econc_(rho_PhiM_04) E_psiP_04_sim[j] = Econc_(rho_PsiP_04) E_psiM_04_sim[j] = Econc_(rho_PsiM_04) C2_sim[j] = 1 - 2*(pr_phiP+pr_psiP) provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') device = provider.get_backend('ibmq_manila') q_exp = np.arange(0,1.1,0.1); N = len(q_exp) q_exp[0] = 0.03; q_exp[N-1] = 1-q_exp[0] th_xi = np.zeros(N); th_xi = 2*np.arccos(np.sqrt(1-q_exp)) th_eta = np.zeros(N); th_eta = 2*np.arccos(np.sqrt(q_exp)) #jobs_ids2 = [] for j in range(N-1,N): qr = QuantumRegister(5); qc = QuantumCircuit(qr) # prepara xi qc.u(th_xi[j],0,0,qr[1]) qc.cx(qr[1],qr[2]) qc.h([qr[1],qr[2]]) # prepara eta qc.u(th_eta[j],0,0,qr[3]) qc.cx(qr[3],qr[4]) qc.h([qr[3],qr[4]]) # BBM qc.cx(qr[2],qr[3]) qc.h(qr[2]) # circuito para tomografia qstc = state_tomography_circuits(qc, [qr[4],qr[3],qr[2],qr[1]]) # Experimento job_exp = qiskit.execute(qstc, backend = device, shots=nshots) #jobs_ids2.append(job_exp.job_id()) print(job_exp.job_id()) job_monitor(job_exp) jobs_ids2.append('636e2c8910cc1925ad755b77') qc.draw(output='mpl') f = open("jobs_ids_ES_post_bbm.txt", "w") f.write(str(jobs_ids2)) f.close() f = open("jobs_ids_ES_post_bbm.txt","r") list_ids2 = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",") f.close() print(list_ids2) q_exp = np.arange(0,1.1,0.1); N = len(q_exp) q_exp[0] = 0.03; q_exp[N-1] = 1-q_exp[0] E_phiP_04_exp = np.zeros(N); E_psiM_04_exp = np.zeros(N) E_psiP_04_exp = np.zeros(N); E_phiM_04_exp = np.zeros(N) C2_exp = np.zeros(N) for j in range(0,N): job = device.retrieve_job(list_ids2[j]) qstf_exp = StateTomographyFitter(job.result(), qstc) rho_4310_exp = qstf_exp.fit(method='lstsq') # pos-selecao rho_PhiP = P00@rho_4310_exp@P00 pr_phiP = np.real(np.trace(rho_PhiP)) rho_PhiP = (1/pr_phiP)*rho_PhiP rho_PsiP = P01@rho_4310_exp@P01 pr_psiP = np.real(np.trace(rho_PsiP)) rho_PsiP = (1/pr_psiP)*rho_PsiP rho_PhiM = P10@rho_4310_exp@P10 pr_phiM = np.real(np.trace(rho_PhiM)) rho_PhiM = (1/pr_phiM)*rho_PhiM rho_PsiM = P11@rho_4310_exp@P11 pr_psiM = np.real(np.trace(rho_PsiM)) rho_PsiM = (1/pr_psiM)*rho_PsiM # estados reduzidos rho_PhiP_04 = pTrace_3_num(rho_PhiP,2,4,2) rho_PsiP_04 = pTrace_3_num(rho_PsiP,2,4,2) rho_PhiM_04 = pTrace_3_num(rho_PhiM,2,4,2) rho_PsiM_04 = pTrace_3_num(rho_PsiM,2,4,2) # emaranhamentos e probabilidades E_phiP_04_exp[j] = Econc_(rho_PhiP_04) E_phiM_04_exp[j] = Econc_(rho_PhiM_04) E_psiP_04_exp[j] = Econc_(rho_PsiP_04) E_psiM_04_exp[j] = Econc_(rho_PsiM_04) C2_exp[j] = 1 - 2*(pr_phiP+pr_psiP) print(C2_exp[j]) import matplotlib from matplotlib import pyplot as plt matplotlib.rcParams.update({'font.size':11}); plt.figure(figsize = (6,4), dpi = 100) q = np.arange(0,1.01,0.01) Ep = np.ones(len(q)); Em = (2*q*(1-q))/(1-2*q+2*q**2); C2 = 1-4*q*(1-q) plt.plot(q, Ep, '-', label=r'$E(\hat{\phi}_+)=E(\hat{\psi}_+)$') plt.plot(q, Em, '--', label=r'$E(\hat{\phi}_-)=E(\hat{\psi}_-)$') plt.plot(q, C2, '-.', label=r'$1-2(Pr(\hat{\phi}_+)+Pr(\hat{\psi}_+))$') plt.plot(q_exp, E_phiP_04_sim, 'o', label=r'$E(\hat{\phi}_+)_{sim}$') plt.plot(q_exp, E_phiM_04_sim, '*', label=r'$E(\hat{\phi}_-)_{sim}$') #plt.plot(q_exp, E_psiP_04_sim, 'X', label=r'$E(\hat{\psi}_+)_{sim}$') #plt.plot(q_exp, E_psiM_04_sim, '.', label=r'$E(\hat{\psi}_-)_{sim}$') plt.plot(q_exp, C2_sim, 'X', label=r'$1-2(Pr(\hat{\phi}_+)_{sim}+Pr(\hat{\psi}_+)_{sim})$') plt.plot(q_exp, E_phiP_04_exp, '<', label=r'$E(\hat{\phi}_+)_{exp}$') plt.plot(q_exp, E_phiM_04_exp, '>', label=r'$E(\hat{\phi}_-)_{exp}$') #plt.plot(q_exp, E_psiP_04_exp, '^', label=r'$E(\hat{\psi}_+)_{exp}$') #plt.plot(q_exp, E_psiM_04_exp, '.', label=r'$E(\hat{\psi}_-)_{exp}$') plt.plot(q_exp, C2_exp, '^', label=r'$1-2(Pr(\hat{\phi}_+)_{exp}+Pr(\hat{\psi}_+)_{exp})$') plt.xlabel(r'$q$') plt.legend(bbox_to_anchor=(1.8, 1.0), loc='upper right') plt.show() # error mitigation qr = QuantumRegister(5)#; qc = QuantumCircuit(qr) qubit_list = [1,2,3,4] meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr) job = qiskit.execute(meas_calibs, backend = device, shots = nshots) print(job.job_id()) job_monitor(job) job = device.retrieve_job('636e3407fb0a57272187586a') meas_fitter = CompleteMeasFitter(job.result(), state_labels) q_exp = np.arange(0,1.1,0.1); N = len(q_exp) q_exp[0] = 0.03; q_exp[N-1] = 1-q_exp[0] E_phiP_04_exp = np.zeros(N); E_psiM_04_exp = np.zeros(N) E_psiP_04_exp = np.zeros(N); E_phiM_04_exp = np.zeros(N) C2_exp = np.zeros(N) for j in range(0,N): job = device.retrieve_job(list_ids2[j]) mitigated_results = meas_fitter.filter.apply(job.result()) # error mitigation qstf_exp = StateTomographyFitter(mitigated_results, qstc) # error mitigation rho_4310_exp = qstf_exp.fit(method='lstsq') # pos-selecao rho_PhiP = P00@rho_4310_exp@P00 pr_phiP = np.real(np.trace(rho_PhiP)) rho_PhiP = (1/pr_phiP)*rho_PhiP rho_PsiP = P01@rho_4310_exp@P01 pr_psiP = np.real(np.trace(rho_PsiP)) rho_PsiP = (1/pr_psiP)*rho_PsiP rho_PhiM = P10@rho_4310_exp@P10 pr_phiM = np.real(np.trace(rho_PhiM)) rho_PhiM = (1/pr_phiM)*rho_PhiM rho_PsiM = P11@rho_4310_exp@P11 pr_psiM = np.real(np.trace(rho_PsiM)) rho_PsiM = (1/pr_psiM)*rho_PsiM # estados reduzidos rho_PhiP_04 = pTrace_3_num(rho_PhiP,2,4,2) rho_PsiP_04 = pTrace_3_num(rho_PsiP,2,4,2) rho_PhiM_04 = pTrace_3_num(rho_PhiM,2,4,2) rho_PsiM_04 = pTrace_3_num(rho_PsiM,2,4,2) # emaranhamentos e probabilidades E_phiP_04_exp[j] = Econc_(rho_PhiP_04) E_phiM_04_exp[j] = Econc_(rho_PhiM_04) E_psiP_04_exp[j] = Econc_(rho_PsiP_04) E_psiM_04_exp[j] = Econc_(rho_PsiM_04) C2_exp[j] = 1 - 2*(pr_phiP+pr_psiP) print(C2_exp[j]) import matplotlib from matplotlib import pyplot as plt matplotlib.rcParams.update({'font.size':11}); plt.figure(figsize = (6,4), dpi = 100) q = np.arange(0,1.01,0.01) Ep = np.ones(len(q)); Em = (2*q*(1-q))/(1-2*q+2*q**2); C2 = 1-4*q*(1-q) plt.plot(q, Ep, '-', label=r'$E(\hat{\phi}_+)=E(\hat{\psi}_+)$') plt.plot(q, Em, '--', label=r'$E(\hat{\phi}_-)=E(\hat{\psi}_-)$') plt.plot(q, C2, '-.', label=r'$1-2(Pr(\hat{\phi}_+)+Pr(\hat{\psi}_+))$') plt.plot(q_exp, E_phiP_04_sim, 'o', label=r'$E(\hat{\phi}_+)_{sim}$') plt.plot(q_exp, E_phiM_04_sim, '*', label=r'$E(\hat{\phi}_-)_{sim}$') #plt.plot(q_exp, E_psiP_04_sim, 'X', label=r'$E(\hat{\psi}_+)_{sim}$') #plt.plot(q_exp, E_psiM_04_sim, '.', label=r'$E(\hat{\psi}_-)_{sim}$') plt.plot(q_exp, C2_sim, 'X', label=r'$1-2(Pr(\hat{\phi}_+)_{sim}+Pr(\hat{\psi}_+)_{sim})$') plt.plot(q_exp, E_phiP_04_exp, '<', label=r'$E(\hat{\phi}_+)_{exp}$') plt.plot(q_exp, E_phiM_04_exp, '>', label=r'$E(\hat{\phi}_-)_{exp}$') #plt.plot(q_exp, E_psiP_04_exp, '^', label=r'$E(\hat{\psi}_+)_{exp}$') #plt.plot(q_exp, E_psiM_04_exp, '.', label=r'$E(\hat{\psi}_-)_{exp}$') plt.plot(q_exp, C2_exp, '^', label=r'$1-2(Pr(\hat{\phi}_+)_{exp}+Pr(\hat{\psi}_+)_{exp})$') plt.xlabel(r'$q$') plt.legend(bbox_to_anchor=(1.8, 1.0), loc='upper right') plt.savefig('fig_Eswap_post_bbm.pdf') plt.show() C = np.arange(0,1.1,0.1); E_PhiP = (1-C**2)/(1+C**2) E_PhiM = np.ones(len(C)) plt.plot(C, E_PhiP, '*'); plt.plot(C, E_PhiM, '.') plt.show() from qiskit import * qr = QuantumRegister(4); %run init.ipynb p,q = symbols('p q') ket_xi = Matrix([[sqrt(p)],[sqrt((1-p)/2)],[sqrt((1-p)/2)],[0]]) ket_eta = Matrix([[sqrt(q)],[sqrt((1-q)/2)],[sqrt((1-q)/2)],[0]]) ket_xi, ket_eta rho_xi = ket_xi*ket_xi.T rho_eta = ket_eta*ket_eta.T rho_xi, rho_eta def ptraceA(da, db, rho): rhoB = zeros(db,db) for j in range(0, db): for k in range(0, db): for l in range(0, da): rhoB[j,k] += rho[l*db+j,l*db+k] return rhoB def ptraceB(da, db, rho): rhoA = zeros(da,da) for j in range(0, da): for k in range(0, da): for l in range(0, db): rhoA[j,k] += rho[j*db+l,k*db+l] return rhoA rho_xi_A = ptraceB(2,2,rho_xi); rho_xi_C = ptraceA(2,2,rho_xi) rho_xi_A, rho_xi_C rho_eta_Cp = ptraceB(2,2,rho_eta); rho_eta_B = ptraceA(2,2,rho_eta) rho_eta_Cp, rho_eta_B c00,c01,c10,c11 = symbols('c_{00} c_{01} c_{10} c_{11}') d00,d01,d10,d11 = symbols('d_{00} d_{01} d_{10} d_{11}') def two_qb_basis(): zz = Matrix([[1],[0],[0],[0]]) zu = Matrix([[0],[1],[0],[0]]) uz = Matrix([[0],[0],[1],[0]]) uu = Matrix([[0],[0],[0],[1]]) return zz,zu,uz,uu zz,zu,uz,uu = two_qb_basis(); zz,zu,uz,uu def psi_p(c00,c01,c10,c11,d00,d01,d10,d11): zz,zu,uz,uu = two_qb_basis() psi = (c00*d00+c01*d10)*zz + (c00*d01+c01*d11)*zu + (c10*d00+c11*d10)*uz + (c10*d01+c11*d11)*uu return psi/sqrt(2) def psi_m(c00,c01,c10,c11,d00,d01,d10,d11): zz,zu,uz,uu = two_qb_basis() psi = (c00*d00-c01*d10)*zz + (c00*d01-c01*d11)*zu + (c10*d00-c11*d10)*uz + (c10*d01-c11*d11)*uu return psi/sqrt(2) def phi_p(c00,c01,c10,c11,d00,d01,d10,d11): zz,zu,uz,uu = two_qb_basis() psi = (c00*d10+c01*d00)*zz + (c00*d11+c01*d01)*zu + (c10*d10+c11*d00)*uz + (c10*d11+c11*d01)*uu return psi/sqrt(2) def phi_m(c00,c01,c10,c11,d00,d01,d10,d11): zz,zu,uz,uu = two_qb_basis() psi = (c00*d10-c01*d00)*zz + (c00*d11-c01*d01)*zu + (c10*d10-c11*d00)*uz + (c10*d11-c11*d01)*uu return psi/sqrt(2) c00 = sqrt(p); c01 = sqrt((1-p)/2); c10 = sqrt((1-p)/2); c11 = 0 d00 = sqrt(q); d01 = sqrt((1-q)/2); d10 = sqrt((1-q)/2); d11 = 0 psip = psi_p(c00,c01,c10,c11,d00,d01,d10,d11); psim = psi_m(c00,c01,c10,c11,d00,d01,d10,d11) phip = phi_p(c00,c01,c10,c11,d00,d01,d10,d11); phim = phi_m(c00,c01,c10,c11,d00,d01,d10,d11) simplify(psip), simplify(psim), simplify(phip), simplify(phim) psip_norm2 = psip.T*psip; simplify(psip_norm2) psim_norm2 = psim.T*psim; simplify(psim_norm2) phip_norm2 = phip.T*phip; simplify(phip_norm2) phim_norm2 = phim.T*phim; simplify(phim_norm2)
https://github.com/vandnaChaturvedi/Qauntum_algorithms_Qiskit
vandnaChaturvedi
#from qiskit_textbook.widgets import dj_widget #dj_widget(size="small", case="balanced") # initialization ####################################################################################################################### qiskit_edit_1 from qiskit import QuantumCircuit, execute from qiskit import QuantumRegister, ClassicalRegister from qiskit.tools.monitor import job_monitor from qiskit import * import time import matplotlib.pyplot as plt import argparse import sys from concurrent.futures import ThreadPoolExecutor import resource from time import sleep ######################################################################################################################### import numpy as np options = { 'plot': True, "rotation_error": {'rx':[0.9, 0.9], 'ry':[0.9, 0.9], 'rz':[0.9, 0.9]}, "tsp_model_error": [0.9, 0.9], "thermal_factor": 0.9, "decoherence_factor": 0.9, "depolarization_factor": 0.9, "bell_depolarization_factor": 0.9, "decay_factor": 0.89, } # importing Qiskit #from qiskit import IBMQ, Aer #from qiskit.providers.ibmq import least_busy #from qiskit import QuantumCircuit, assemble, transpile # import basic plot tools from qiskit.visualization import plot_histogram # set the length of the n-bit input string. n = 3 const_oracle = QuantumCircuit(n+1) output = np.random.randint(2) if output == 1: const_oracle.x(n) const_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) balanced_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() balanced_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Show oracle balanced_oracle.draw() dj_circuit = QuantumCircuit(n+1, n+1) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) dj_circuit.draw() dj_circuit = QuantumCircuit(n+1, n+1) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit += balanced_oracle dj_circuit.draw() dj_circuit = QuantumCircuit(n+1, n+1) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle # dj_circuit += balanced_oracle # Repeat H-gates for qubit in range(n): dj_circuit.h(qubit) dj_circuit.barrier() # Measure for i in range(n): dj_circuit.measure(i, i, basis='Ensemble', add_param='Z') # Display circuit dj_circuit.draw() # use local simulator backend = qiskit.BasicAer.get_backend('dm_simulator') job = execute(dj_circuit, backend=backend, shots=1) #job1 = execute(dj_circuit, backend=backend, backend_options=options, shots=1) job_result = job.result() #job_result1 = job1.result() #print(job_result['results'][0]['data']['densitymatrix']) #print(job_result1['results'][0]['data']['densitymatrix']) job_result['results'][0]['data']['ensemble_probability'] backend = qiskit.BasicAer.get_backend('dm_simulator') job1 = execute(dj_circuit, backend=backend, backend_options=options, shots=1) job_result1 = job1.result() job_result1['results'][0]['data']['ensemble_probability'] no_noise=job_result['results'][0]['data']['ensemble_probability'] x= no_noise.keys() y = no_noise.values() plt.bar(x, y, width=0.6, label='No Noise') plt.xlabel('combination of bits') plt.ylabel('Probablities') plt.title('Ensemble Probabilities') plt.figure(figsize=(3, 3)) plt.show() noisy=job_result1['results'][0]['data']['ensemble_probability'] x1 = noisy.keys() y1 = noisy.values() plt.bar(x1, y1, width=0.6, label='Noisy', color='coral') plt.xlabel('combination of bits') plt.ylabel('Probablities') plt.title('Ensemble Probabilities Over Noisy data') plt.show() def dj_oracle(case, n): # We need to make a QuantumCircuit object to return # This circuit has n+1 qubits: the size of the input, # plus one output qubit oracle_qc = QuantumCircuit(n+1) # First, let's deal with the case in which oracle is balanced if case == "balanced": # First generate a random number that tells us which CNOTs to # wrap in X-gates: b = np.random.randint(1,2**n) # Next, format 'b' as a binary string of length 'n', padded with zeros: b_str = format(b, '0'+str(n)+'b') # Next, we place the first X-gates. Each digit in our binary string # corresponds to a qubit, if the digit is 0, we do nothing, if it's 1 # we apply an X-gate to that qubit: for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Do the controlled-NOT gates for each qubit, using the output qubit # as the target: for qubit in range(n): oracle_qc.cx(qubit, n) # Next, place the final X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Case in which oracle is constant if case == "constant": # First decide what the fixed output of the oracle will be # (either always 0 or always 1) output = np.random.randint(2) if output == 1: oracle_qc.x(n) oracle_gate = oracle_qc.to_gate() oracle_gate.name = "Oracle" # To show when we display the circuit return oracle_gate def dj_algorithm(oracle, n): dj_circuit = QuantumCircuit(n+1, n) # Set up the output qubit: dj_circuit.x(n) dj_circuit.h(n) # And set up the input register: for qubit in range(n): dj_circuit.h(qubit) # Let's append the oracle gate to our circuit: dj_circuit.append(oracle, range(n+1)) # Finally, perform the H-gates again and measure: for qubit in range(n): dj_circuit.h(qubit) for i in range(n): dj_circuit.measure(i, i, basis='Ensemble', add_param='Z') return dj_circuit n = 4 oracle_gate = dj_oracle('balanced', n) dj_circuit = dj_algorithm(oracle_gate, n) dj_circuit.draw() ##NO_NOISE backend = qiskit.BasicAer.get_backend('dm_simulator') job = execute(dj_circuit, backend=backend, shots=1) job_result = job.result() print(job_result['results'][0]['data']['densitymatrix']) ##plot_histogram(answer) ###no histrogram because of single shot in DM simulator ## Noisy job1 = execute(dj_circuit, backend=backend, backend_options=options, shots=1) job_result1 = job1.result() print(job_result1['results'][0]['data']['densitymatrix']) from qiskit.visualization import plot_state_city get_ipython().run_line_magic('matplotlib', 'inline') plot_state_city(job_result1['results'][0]['data']['densitymatrix'], color=['midnightblue', 'midnightblue'],title="Density Matrix_no_noise") ##no_noise_ensemble_probabs job_result['results'][0]['data']['ensemble_probability'] ##noisy_ensemble_probabs job_result1['results'][0]['data']['ensemble_probability'] no_noise=job_result['results'][0]['data']['ensemble_probability'] noisy=job_result1['results'][0]['data']['ensemble_probability'] labels = noisy.keys() without_noise = no_noise.values() with_noise = noisy.values() x = np.arange(len(labels)) # the label locations width = 0.35 # the width of the bars fig, ax = plt.subplots() rects1 = ax.bar(x - width/2, without_noise, width, label='Without Noise') rects2 = ax.bar(x + width/2, with_noise, width, label='With Noise') # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Probability') ax.set_title('Ensemble Probabilities with Noise') ax.set_xticks(x) ax.set_xticklabels(labels) ax.legend() plt.show() # Load our saved IBMQ accounts and get the least busy backend device with greater than or equal to (n+1) qubits IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.tools.monitor import job_monitor transpiled_dj_circuit = transpile(dj_circuit, backend, optimization_level=3) job = backend.run(transpiled_dj_circuit) job_monitor(job, interval=2) # Get the results of the computation results = job.result() answer = results.get_counts() plot_histogram(answer) from qiskit_textbook.problems import dj_problem_oracle oracle = dj_problem_oracle(1) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/PayalSolanki2906/Quantum_algorithms_using_Qiskit
PayalSolanki2906
from qiskit import QuantumCircuit, assemble, Aer from qiskit.visualization import plot_histogram, plot_bloch_vector from cmath import sqrt, pi, exp sim = Aer.get_backend('aer_simulator') qc = QuantumCircuit(1) # Create a quantum circuit with one qubit initial_state = [0,1] qc.initialize(initial_state, 0) sim = Aer.get_backend('aer_simulator') qc.save_statevector() ## this converts output in to state vector qobj = assemble(qc) ## this assembles quantum circuit job = sim.run(qobj) ## this is for running the job ket = job.result().get_statevector() print(ket) qc.measure_all() qc.draw() qobj = assemble(qc) counts = sim.run(qobj).result().get_counts() plot_histogram(counts) qc1 = QuantumCircuit(1) # Create a quantum circuit with one qubit initial_state = [1/sqrt(2),1/sqrt(2)] # Define initial_state as |1> qc1.initialize(initial_state, 0) # Apply initialisation operation to the 0th qubit qc1.draw() # Let's view our circuit sim = Aer.get_backend('aer_simulator') qc1.save_statevector() ## this converts output in to state vector qobj = assemble(qc1) ## this assembles quantum circuit job = sim.run(qobj) ## this is for running the job ket = job.result().get_statevector() print(ket) qc1.measure_all() qc1.draw() qobj = assemble(qc1) counts = sim.run(qobj).result().get_counts() plot_histogram(counts) state1 = [1/sqrt(3),sqrt(2/3)] i=complex(0,1) state2 = [exp(-i*pi)*1/sqrt(3),exp(-i*pi)*sqrt(2/3)] ## adding a global phase never changes the probabilities. initial_state = state1 # Define state |q_0> qc = QuantumCircuit(1) # Must redefine qc qc.initialize(initial_state, 0) # Initialize the 0th qubit in the state `initial_state` qc.save_statevector() # Save statevector qobj = assemble(qc) results = sim.run(qobj).result().get_counts() plot_histogram(results) initial_state = state2 # Define state |q_0> qc = QuantumCircuit(1) # Must redefine qc qc.initialize(initial_state, 0) # Initialize the 0th qubit in the state `initial_state` qc.save_statevector() # Save statevector qobj = assemble(qc) state = sim.run(qobj).result().get_statevector() # Execute the circuit print(state) # Print the result qobj = assemble(qc) results = sim.run(qobj).result().get_counts() plot_histogram(results) from qiskit_textbook.widgets import plot_bloch_vector_spherical coords = [pi/2,0,1] # [Theta, Phi, Radius] plot_bloch_vector_spherical(coords) # Bloch Vector with spherical coordinates from qiskit_textbook.widgets import plot_bloch_vector_spherical coords = [2*pi,0,1] # [Theta, Phi, Radius] plot_bloch_vector_spherical(coords) # Bloch Vector with spherical coordinates from qiskit_textbook.widgets import plot_bloch_vector_spherical coords = [pi,0,1] # [Theta, Phi, Radius] plot_bloch_vector_spherical(coords) # Bloch Vector with spherical coordinates from qiskit_textbook.widgets import plot_bloch_vector_spherical coords = [pi/2,0,1] # [Theta, Phi, Radius] plot_bloch_vector_spherical(coords) # Bloch Vector with spherical coordinates from qiskit_textbook.widgets import plot_bloch_vector_spherical coords = [pi/2,-pi/2,1] # [Theta, Phi, Radius] plot_bloch_vector_spherical(coords) # Bloch Vector with spherical coordinates
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
import numpy as np from qiskit import * import matplotlib qr = QuantumRegister(2) #measurements from quantum bits = use classical register cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.draw() # adding quantum gates to create entanglement (Hadamart gate) circuit.h(qr[0]) %matplotlib inline circuit.draw(output='mpl') #two qubit operation control X (logical if) circuit.cx(qr[0], qr[1]) circuit.draw(output='mpl') #entanglement achieved #measurement, storing measurements into computational register circuit.measure(qr,cr) circuit.draw(output='mpl') #performance simulations simulator = Aer.get_backend('qasm_simulator') execute(circuit, backend = simulator) result = execute(circuit, backend = simulator).result() #plotting results from qiskit.tools.visualization import plot_histogram plot_histogram(result.get_counts(circuit)) #running circuit on quantum computer IBMQ.load_account() provider= IBMQ.get_provider('ibm-q') qcomp = provider.get_backend('ibmq_manila') job= execute(circuit, backend=qcomp) from qiskit.tools import job_monitor job_monitor(job) result = job.result() from qiskit.tools.visualization import plot_histogram plot_histogram(result.get_counts(circuit), title='Performance metric on Quantum Computer')
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
Qiskit-Extensions
import numpy as np from qiskit import QuantumCircuit qc_0 = QuantumCircuit(7) for i in range(7): qc_0.rx(np.pi / 4, i) qc_0.cx(0, 3) qc_0.cx(1, 3) qc_0.cx(2, 3) qc_0.cx(3, 4) qc_0.cx(3, 5) qc_0.cx(3, 6) qc_0.cx(0, 3) qc_0.cx(1, 3) qc_0.cx(2, 3) qc_0.draw("mpl") from qiskit.quantum_info import SparsePauliOp observable = SparsePauliOp(["ZIIIIII", "IIIZIII", "IIIIIIZ"]) from circuit_knitting.cutting.instructions import Move qc_1 = QuantumCircuit(8) for i in [*range(4), *range(5, 8)]: qc_1.rx(np.pi / 4, i) qc_1.cx(0, 3) qc_1.cx(1, 3) qc_1.cx(2, 3) qc_1.append(Move(), [3, 4]) qc_1.cx(4, 5) qc_1.cx(4, 6) qc_1.cx(4, 7) qc_1.append(Move(), [4, 3]) qc_1.cx(0, 3) qc_1.cx(1, 3) qc_1.cx(2, 3) qc_1.draw("mpl") observable_expanded = SparsePauliOp(["ZIIIIIII", "IIIIZIII", "IIIIIIIZ"]) from circuit_knitting.cutting import partition_problem partitioned_problem = partition_problem( circuit=qc_1, partition_labels="AAAABBBB", observables=observable_expanded.paulis ) subcircuits = partitioned_problem.subcircuits subobservables = partitioned_problem.subobservables bases = partitioned_problem.bases subobservables subcircuits["A"].draw("mpl") subcircuits["B"].draw("mpl") print(f"Sampling overhead: {np.prod([basis.overhead for basis in bases])}") from circuit_knitting.cutting import generate_cutting_experiments subexperiments, coefficients = generate_cutting_experiments( circuits=subcircuits, observables=subobservables, num_samples=np.inf ) from qiskit_ibm_runtime.fake_provider import FakeManilaV2 backend = FakeManilaV2() from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager # Transpile the subexperiments to ISA circuits pass_manager = generate_preset_pass_manager(optimization_level=1, backend=backend) isa_subexperiments = { label: pass_manager.run(partition_subexpts) for label, partition_subexpts in subexperiments.items() } from qiskit_ibm_runtime import SamplerV2, Batch # Submit each partition's subexperiments to the Qiskit Runtime Sampler # primitive, in a single batch so that the jobs will run back-to-back. with Batch(backend=backend) as batch: sampler = SamplerV2(mode=batch) jobs = { label: sampler.run(subsystem_subexpts, shots=2**12) for label, subsystem_subexpts in isa_subexperiments.items() } # Retrieve results results = {label: job.result() for label, job in jobs.items()} from circuit_knitting.cutting import reconstruct_expectation_values reconstructed_expvals = reconstruct_expectation_values( results, coefficients, subobservables, ) final_expval = np.dot(reconstructed_expvals, observable.coeffs) from qiskit_aer.primitives import EstimatorV2 estimator = EstimatorV2() exact_expval = estimator.run([(qc_0, observable)]).result()[0].data.evs print(f"Reconstructed expectation value: {np.real(np.round(final_expval, 8))}") print(f"Exact expectation value: {np.round(exact_expval, 8)}") print(f"Error in estimation: {np.real(np.round(final_expval-exact_expval, 8))}") print( f"Relative error in estimation: {np.real(np.round((final_expval-exact_expval) / exact_expval, 8))}" )
https://github.com/WhenTheyCry96/qiskitHackathon2022
WhenTheyCry96
%load_ext autoreload %autoreload 2 import os import warnings import numpy as np import pyEPR as epr import qiskit_metal as metal from collections import OrderedDict import scqubits as scq from scipy.constants import c, h, pi, hbar, e from qiskit_metal import designs, draw, MetalGUI, Dict, Headings from qiskit_metal.qlibrary.tlines.meandered import RouteMeander from qiskit_metal.qlibrary.tlines.anchored_path import RouteAnchors from qiskit_metal.analyses.quantization import LOManalysis, EPRanalysis from qiskit_metal.analyses.em.cpw_calculations import guided_wavelength from qiskit_metal.qlibrary.qubits.transmon_pocket_cl import TransmonPocketCL from qiskit_metal.qlibrary.lumped.cap_3_interdigital import Cap3Interdigital from qiskit_metal.qlibrary.terminations.launchpad_wb_coupled import LaunchpadWirebondCoupled from qiskit_metal.analyses.quantization.lumped_capacitive import load_q3d_capacitance_matrix from qiskit_metal.analyses.quantization.lom_core_analysis import CompositeSystem, Cell, Subsystem, QuantumSystemRegistry ws_path = os.getcwd() warnings.filterwarnings("ignore") design = designs.DesignPlanar() design.overwrite_enabled = True #constants: phi0 = h/(2*e) varphi0 = phi0/(2*pi) # project target parameters f_qList = np.around(np.linspace(5.25, 5.75, 4),2) # GHz f_rList = f_qList + 1.8 # GHz L_JJList = np.around(varphi0**2/((f_qList*1e9+300e6)**2/(8*300e6))/h*1e9, 2) # nH # initial CPW readout lengths def find_resonator_length(frequency, line_width, line_gap, N): #frequency in GHz #line_width/line_gap in um #N -> 2 for lambda/2, 4 for lambda/4 [lambdaG, etfSqrt, q] = guided_wavelength(frequency*10**9, line_width*10**-6, line_gap*10**-6, 750*10**-6, 200*10**-9) return str(lambdaG/N*10**3)+" mm" find_resonator_length(f_rList, 10, 6, 2) design.chips.main.size_x = '12mm' design.chips.main.size_y = '10mm' gui = MetalGUI(design) design.delete_all_components() design_span_x = 5 design_span_y = 3 half_chip_width = design_span_x / 2 half_chip_height = design_span_y / 2 connection_pads_options = dict( a = dict(loc_W=1, loc_H=-1), b = dict(loc_W=1, loc_H=1), c = dict(loc_W=-1, loc_H=-1) ) connection23_pads_options = dict( a = dict(loc_W=1, loc_H=-1), c = dict(loc_W=-1, loc_H=-1) ) transmons = [] transmons.append(TransmonPocketCL(design, 'Q1', options=dict(pos_x=f'-{half_chip_width}mm', pos_y=f'{-half_chip_height}mm', connection_pads=dict(**connection_pads_options)))) transmons.append(TransmonPocketCL(design, 'Q2', options=dict(pos_x=f'0mm', pos_y=f'{half_chip_height}mm', orientation=-90, connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection23_pads_options)))) transmons.append(TransmonPocketCL(design, 'Q3', options=dict(pos_x=f'0mm', pos_y=f'{-half_chip_height}mm', orientation=90, connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection23_pads_options)))) transmons.append(TransmonPocketCL(design, 'Q4', options=dict(pos_x=f'{half_chip_width}mm', pos_y=f'{half_chip_height}mm', orientation=180, connection_pads=dict(**connection_pads_options)))) gui.rebuild() gui.autoscale() fillet='99.99um' options = Dict( meander=Dict( lead_start='0.1mm', lead_end='0.1mm', asymmetry='0 um') ) def connect(component_name: str, component1: str, pin1: str, component2: str, pin2: str, length: str, asymmetry='0 um', start_strght='0 um', end_strght='0 um', flip=False): """Connect two pins with a CPW.""" myoptions = Dict( pin_inputs=Dict( start_pin=Dict( component=component1, pin=pin1), end_pin=Dict( component=component2, pin=pin2)), lead=Dict( start_straight=start_strght, end_straight=end_strght ), total_length=length, fillet = '99.9um') myoptions.update(options) myoptions.meander.asymmetry = asymmetry myoptions.meander.lead_direction_inverted = 'true' if flip else 'false' return RouteMeander(design, component_name, myoptions) asym_h = 100 asym_v = 100 cpw = [] cpw.append(connect('cpw1', 'Q1', 'b', 'Q2', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm')) cpw.append(connect('cpw3', 'Q4', 'b', 'Q3', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm')) cpw.append(connect('cpw4', 'Q3', 'd', 'Q1', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm')) cpw.append(connect('cpw5', 'Q2', 'd', 'Q4', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm')) gui.rebuild() gui.autoscale() readouts_lwc = [] control_lwc = [] offset_x = 0 offset_y = 1 #Readouts readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R1', options = dict( pos_x = '-5mm', pos_y = f'-{half_chip_height+offset_y}mm', lead_length = '30um'))) readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R2', options = dict( pos_x = '-1mm', pos_y = '4mm', orientation = -90, lead_length = '30um'))) readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R3', options = dict( pos_x = '1mm', pos_y = '-4mm', orientation = 90, lead_length = '30um'))) readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R4', options = dict( pos_x = '5mm', pos_y = f'{half_chip_height+offset_y}mm', orientation = 180, lead_length = '30um'))) #Controls control_lwc.append(LaunchpadWirebondCoupled(design, 'CL1', options = dict( pos_x = '-5mm', pos_y = '2mm', lead_length = '30um'))) control_lwc.append(LaunchpadWirebondCoupled(design, 'CL2', options = dict( pos_x = '4mm', pos_y = '4mm', orientation = -90, lead_length = '30um'))) control_lwc.append(LaunchpadWirebondCoupled(design, 'CL3', options = dict( pos_x = '-4mm', pos_y = '-4mm', orientation = 90, lead_length = '30um'))) control_lwc.append(LaunchpadWirebondCoupled(design, 'CL4', options = dict( pos_x = '5mm', pos_y = '-2mm', orientation = 180, lead_length = '30um'))) gui.rebuild() gui.autoscale() readout_lines = [] asym_14 = 700 asym_23 = 700 options = Dict( lead=Dict( start_straight='330um', end_straight='0um'), fillet='99.99um') readout_lines.append(connect('ol1', 'Q1', 'c', 'R1', 'tie', '8 mm', f'{asym_14}um')) options = Dict( lead=Dict( start_straight='430um', end_straight='0um'), fillet='99.99um') readout_lines.append(connect('ol2', 'Q2', 'c', 'R2', 'tie', '8 mm', f'{asym_23}um')) readout_lines.append(connect('ol3', 'Q3', 'c', 'R3', 'tie', '8 mm', f'{asym_23}um')) readout_lines.append(connect('ol4', 'Q4', 'c', 'R4', 'tie', '8 mm', f'{asym_14}um')) gui.rebuild() gui.autoscale() control_lines = [] def connectRouteAnchor(name: str, component1: str, pin1: str, component2: str, pin2: str, anchor_points: OrderedDict) -> RouteAnchors: options_line_cl = dict( pin_inputs = dict(start_pin = dict(component = component1, pin = pin1), end_pin = dict(component = component2, pin = pin2)), anchors = anchor_points, lead = dict(start_straight = '200um', end_straight = '225um'), fillet = fillet ) return RouteAnchors(design, name, options_line_cl) anchors1c = OrderedDict() anchors1c[0] = np.array([-4, -1.42]) anchors1c[1] = np.array([-4, 2]) control_lines.append(connectRouteAnchor('line_cl1', 'Q1', 'Charge_Line', 'CL1', 'tie', anchors1c)) anchors2c = OrderedDict() anchors2c[0] = np.array([0.08, 3.25]) anchors2c[1] = np.array([4, 3.25]) control_lines.append(connectRouteAnchor('line_cl2', 'Q2', 'Charge_Line', 'CL2', 'tie', anchors2c)) anchors3c = OrderedDict() anchors3c[0] = np.array([-0.08, -3.25]) anchors3c[1] = np.array([-4, -3.25]) control_lines.append(connectRouteAnchor('line_cl3', 'Q3', 'Charge_Line', 'CL3', 'tie', anchors3c)) anchors4c = OrderedDict() anchors4c[0] = np.array([4, 1.42]) anchors4c[1] = np.array([4, -2]) control_lines.append(connectRouteAnchor('line_cl4', 'Q4', 'Charge_Line', 'CL4', 'tie', anchors4c)) gui.rebuild() gui.autoscale() gui.screenshot(name="full_design.png") # constants: phi0 = h/(2*e) varphi0 = phi0/(2*pi) # project target parameters f_qList = np.around(np.linspace(5.25, 5.75, 4),2) # GHz f_rList = f_qList + 1.8 # GHz L_JJList = np.around(varphi0**2/((f_qList*1e9+300e6)**2/(8*300e6))/h*1e9, 2) # nH # initial CPW readout lengths def find_resonator_length(frequency, line_width, line_gap, N): #frequency in GHz #line_width/line_gap in um #N -> 2 for lambda/2, 4 for lambda/4 [lambdaG, etfSqrt, q] = guided_wavelength(frequency*10**9, line_width*10**-6, line_gap*10**-6, 750*10**-6, 200*10**-9) return str(lambdaG/N*10**3)+" mm" find_resonator_length(f_rList, 10, 6, 2) # CPW busline length is determined to be 7 mm cpw[0].options.total_length = '7.0mm' cpw[1].options.total_length = '7.0mm' cpw[2].options.total_length = '7.0mm' cpw[3].options.total_length = '7.0mm' gui.rebuild() gui.autoscale() # qubit 1 design target f: 5.25 GHz # readout resonator target f: 7.05 GHz # qubit 2 design target f: 5.42 GHz # readout resonator target f: 7.22 GHz # qubit 3 design target f: 5.58 GHz # readout resonator target f: 7.38 GHz # qubit 4 design target f: 5.75 GHz # readout resonator target f: 7.55 GHz # tuning parameters C_JJ4f = 2 L_JJ4f = 11.7 C_JJ4 = str(C_JJ4f)+' fF' L_JJ4 = str(L_JJ4f)+' nH' transmons[3].options.pad_gap = '35um' transmons[3].options.pad_width = '500um' transmons[3].options.pad_height = '125um' transmons[3].options.connection_pads.c.pad_gap = '40um' transmons[3].options.connection_pads.a.pad_gap = '60um' # cpw5 transmons[3].options.connection_pads.a.pad_width = '40um' # cpw5 transmons[3].options.connection_pads.b.pad_gap = '60um' # cpw3 transmons[3].options.connection_pads.b.pad_width = '30um' # cpw3 readout_lines[3].options.total_length = '7.5mm' gui.rebuild() gui.autoscale() # EPR analysis eig_q4 = EPRanalysis(design, "hfss") hfss4 = eig_q4.sim.renderer hfss4.start() hfss4.activate_ansys_design("TransmonQ4", 'eigenmode') hfss4.render_design(['Q4', 'ol4', 'cpw3', 'cpw5'], [('cpw3', 'end'), ('cpw5', 'start'), ('ol4', 'end')]) # Analysis properties setup4 = hfss4.pinfo.setup setup4.n_modes = 6 setup4.passes = 10 setup4.min_freq_ghz = 4 print(f""" Number of eigenmodes to find = {setup4.n_modes} Number of simulation passes = {setup4.passes} Convergence freq max delta percent diff = {setup4.delta_f} """) pinfo4 = hfss4.pinfo pinfo4.design.set_variable('Lj4', L_JJ4) pinfo4.design.set_variable('Cj4', C_JJ4) setup4.analyze() eig_q4.sim.convergence_t, eig_q4.sim.convergence_f, _ = hfss4.get_convergences() eig_q4.sim.plot_convergences() pinfo4.junctions['jj'] = {'Lj_variable': 'Lj4', 'rect': 'JJ_rect_Lj_Q4_rect_jj', 'line': 'JJ_Lj_Q4_rect_jj_', 'Cj_variable': 'Cj4'} pinfo4.validate_junction_info() pinfo4.dissipative['dielectrics_bulk'] = ['main'] hfss4.set_mode(1, "Setup") hfss4.modeler._modeler.ShowWindow() hfss4.plot_fields('main') eprd4 = epr.DistributedAnalysis(pinfo4) ℰ_elec = eprd4.calc_energy_electric() ℰ_elec_substrate = eprd4.calc_energy_electric(None, 'main') ℰ_mag = eprd4.calc_energy_magnetic() print(f""" ℰ_elec_all = {ℰ_elec} ℰ_elec_substrate = {ℰ_elec_substrate} EPR of substrate = {ℰ_elec_substrate / ℰ_elec * 100 :.1f}% ℰ_mag_all = {ℰ_mag} ℰ_mag % of ℰ_elec_all = {ℰ_mag / ℰ_elec * 100 :.1f}% """) eprd4.do_EPR_analysis() #epra4 = epr.QuantumAnalysis(eprd4.data_filename) #epra4.analyze_all_variations(cos_trunc = 8, fock_trunc = 7) c4 = LOManalysis(design, "q3d") q3d4 = c4.sim.renderer q3d4.start() q3d4.activate_ansys_design("TransmonQ4_q3d", 'capacitive') q3d4.render_design(['Q4'], [('Q4', 'a'),('Q4', 'b'),('Q4', 'c')]) q3d4.add_q3d_setup(name="Setup", max_passes=15, min_converged_passes=5, percent_error=0.1) q3d4.analyze_setup("Setup") c4.sim.capacitance_matrix, c4.sim.units = q3d4.get_capacitance_matrix() c4.sim.capacitance_all_passes, _ = q3d4.get_capacitance_all_passes() c4.sim.capacitance_matrix c4.setup.junctions = Dict({'Lj':L_JJ4f, 'Cj':C_JJ4f}) c4.setup.freq_readout = 7.45 c4.setup.freq_bus = [8.25, 8.25, 15] c4.run_lom() c4.lumped_oscillator_all QuantumSystemRegistry.registry() # Q4 path4= ws_path+"/Project71_TransmonQ4_q3d.txt" t4_mat, _, _, _ = load_q3d_capacitance_matrix(path4) # Cell 4 Transmon-4 opt4 = dict( node_rename = {'a_connector_pad_Q4': 'cpw5', 'b_connector_pad_Q4': 'cpw3', 'c_connector_pad_Q4': 'readout4'}, cap_mat = t4_mat, ind_dict = {('pad_top_Q4', 'pad_bot_Q4'): 11.7}, # junction inductance in nH jj_dict = {('pad_top_Q4', 'pad_bot_Q4'): 'j4'}, cj_dict = {('pad_top_Q4', 'pad_bot_Q4'): 2} # junction capacitance in fF ) cell_4 = Cell(opt4) # subsystem 1: Transmon-4 transmon4 = Subsystem(name='transmon4', sys_type='TRANSMON', nodes=['j4']) # Resonator Subsystems q_opts = dict( Z0 = 50, # characteristic impedance in Ohm vp = 0.404314 * 3e8 # phase velocity ) # subsystem 3: Q2 readout resonator ro4 = Subsystem(name='readout4', sys_type='TL_RESONATOR', nodes=['readout4'], q_opts=dict(f_res = 7.57, **q_opts)) # subsystem 4: bus3 resonator cpw3 = Subsystem(name='cpw3', sys_type='TL_RESONATOR', nodes=['cpw3'], q_opts=dict(f_res = 8.2, **q_opts)) # subsystem 15: bus5 resonator cpw5 = Subsystem(name='cpw5', sys_type='TL_RESONATOR', nodes=['cpw5'], q_opts=dict(f_res = 8.29, **q_opts)) composite_sys = CompositeSystem( subsystems=[transmon4, ro4, cpw3, cpw5], cells=[cell_4], grd_node='ground_main_plane', nodes_force_keep=['readout4', 'cpw3', 'cpw5'] ) cg = composite_sys.circuitGraph() print(cg) hilbertspace = composite_sys.create_hilbertspace() print(hilbertspace) # Convert the hilbert space into # "Interaction Picture" hilbertspace = composite_sys.add_interaction() hilbertspace.hamiltonian() hamiltonian_results = composite_sys.hamiltonian_results(hilbertspace, evals_count=30) composite_sys.compute_gs()
https://github.com/qclib/qclib
qclib
# Copyright 2021 qclib project. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ''' Toffoli decomposition explained in Lemma 8 from Quantum Circuits for Isometries. https://arxiv.org/abs/1501.06911 ''' from numpy import pi from qiskit import QuantumCircuit from qiskit.circuit import Gate class Toffoli(Gate): def __init__(self, cancel=None): self.cancel = cancel super().__init__('toffoli', 3, [], "Toffoli") def _define(self): self.definition = QuantumCircuit(3) theta = pi / 4. control_qubits = self.definition.qubits[:2] target_qubit = self.definition.qubits[-1] if self.cancel != 'left': self.definition.u(theta=-theta, phi=0., lam=0., qubit=target_qubit) self.definition.cx(control_qubits[0], target_qubit) self.definition.u(theta=-theta, phi=0., lam=0., qubit=target_qubit) self.definition.cx(control_qubits[1], target_qubit) if self.cancel != 'right': self.definition.u(theta=theta, phi=0., lam=0., qubit=target_qubit) self.definition.cx(control_qubits[0], target_qubit) self.definition.u(theta=theta, phi=0., lam=0., qubit=target_qubit) @staticmethod def ccx(circuit, controls=None, target=None, cancel=None): if controls is None or target is None: circuit.append(Toffoli(cancel), circuit.qubits[:3]) else: circuit.append(Toffoli(cancel), [*controls, target])
https://github.com/Axect/QuantumAlgorithms
Axect
import qiskit qiskit.__qiskit_version__ # useful additional packages import numpy as np import matplotlib.pyplot as plt %matplotlib inline # importing Qiskit from qiskit import BasicAer, IBMQ from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.compiler import transpile from qiskit.tools.monitor import job_monitor # import basic plot tools from qiskit.tools.visualization import plot_histogram # Load our saved IBMQ accounts IBMQ.load_account() n = 13 # the length of the first register for querying the oracle # Choose a type of oracle at random. With probability half it is constant, # and with the same probability it is balanced oracleType, oracleValue = np.random.randint(2), np.random.randint(2) if oracleType == 0: print("The oracle returns a constant value ", oracleValue) else: print("The oracle returns a balanced function") a = np.random.randint(1,2**n) # this is a hidden parameter for balanced oracle. # Creating registers # n qubits for querying the oracle and one qubit for storing the answer qr = QuantumRegister(n+1) #all qubits are initialized to zero # for recording the measurement on the first register cr = ClassicalRegister(n) circuitName = "DeutschJozsa" djCircuit = QuantumCircuit(qr, cr) # Create the superposition of all input queries in the first register by applying the Hadamard gate to each qubit. for i in range(n): djCircuit.h(qr[i]) # Flip the second register and apply the Hadamard gate. djCircuit.x(qr[n]) djCircuit.h(qr[n]) # Apply barrier to mark the beginning of the oracle djCircuit.barrier() if oracleType == 0:#If the oracleType is "0", the oracle returns oracleValue for all input. if oracleValue == 1: djCircuit.x(qr[n]) else: djCircuit.iden(qr[n]) else: # Otherwise, it returns the inner product of the input with a (non-zero bitstring) for i in range(n): if (a & (1 << i)): djCircuit.cx(qr[i], qr[n]) # Apply barrier to mark the end of the oracle djCircuit.barrier() # Apply Hadamard gates after querying the oracle for i in range(n): djCircuit.h(qr[i]) # Measurement djCircuit.barrier() for i in range(n): djCircuit.measure(qr[i], cr[i]) #draw the circuit djCircuit.draw(output='mpl',scale=0.5) backend = BasicAer.get_backend('qasm_simulator') shots = 1000 job = execute(djCircuit, backend=backend, shots=shots) results = job.result() answer = results.get_counts() plot_histogram(answer) backend = IBMQ.get_backend('ibmq_16_melbourne') djCompiled = transpile(djCircuit, backend=backend, optimization_level=1) djCompiled.draw(output='mpl',scale=0.5) job = execute(djCompiled, backend=backend, shots=1024) job_monitor(job) results = job.result() answer = results.get_counts() threshold = int(0.01 * shots) # the threshold of plotting significant measurements filteredAnswer = {k: v for k,v in answer.items() if v >= threshold} # filter the answer for better view of plots removedCounts = np.sum([ v for k,v in answer.items() if v < threshold ]) # number of counts removed filteredAnswer['other_bitstrings'] = removedCounts # the removed counts are assigned to a new index plot_histogram(filteredAnswer) print(filteredAnswer)
https://github.com/joshy91/PythonQiskit
joshy91
import numpy as np import scipy from scipy.linalg import expm import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler, MinMaxScaler from sklearn.decomposition import PCA import pandas as pd from qiskit import BasicAer from qiskit.aqua.input import ClassificationInput from qiskit.aqua import run_algorithm def Currency(training_size, test_size, n, PLOT_DATA): class_labels = [r'Buy', r'Sell', r'Hold'] training_url = "https://drive.google.com/file/d/1dGr9w629hZMlHcTvNw1sGlhm3J57osze/view?usp=sharing" training=pd.read_csv(training_url, sep=',',header=0) trainingNP = training.to_numpy() sample_train = trainingNP[:,:-2] label_train = trainingNP[:,-2] label_train[label_train == 'Buy'] = 0 label_train[label_train == 'Sell'] = 1 label_train[label_train == 'Hold'] = 2 test_url = "https://drive.google.com/file/d/1wsyURMe0wRXysJvLn1T9bXIsMqd8MocG/view?usp=sharing" test=pd.read_csv(test_url, sep=',',header=0) testNP = test.to_numpy() sample_test = testNP[:,:-2] label_test = testNP[:,-2] label_test[label_test == 'Buy'] = 0 label_test[label_test == 'Sell'] = 1 label_test[label_test == 'Hold'] = 2 # Now we standarize for gaussian around 0 with unit variance std_scale = StandardScaler().fit(sample_train) sample_train = std_scale.transform(sample_train) sample_test = std_scale.transform(sample_test) # Now reduce number of features to number of qubits pca = PCA(n_components=n).fit(sample_train) sample_train = pca.transform(sample_train) sample_test = pca.transform(sample_test) # Scale to the range (-1,+1) samples = np.append(sample_train, sample_test, axis=0) minmax_scale = MinMaxScaler((-1, 1)).fit(samples) sample_train = minmax_scale.transform(sample_train) sample_test = minmax_scale.transform(sample_test) # Pick training size number of samples from each distro training_input = {key: (sample_train[label_train == k, :])[:training_size] for k, key in enumerate(class_labels)} test_input = {key: (sample_test[label_test == k, :])[:test_size] for k, key in enumerate(class_labels)} if PLOT_DATA: for k in range(0, 3): plt.scatter(sample_train[label_train == k, 0][:training_size], sample_train[label_train == k, 1][:training_size]) plt.title("PCA dim. reduced Currency dataset") plt.show() return sample_train, training_input, test_input, class_labels n = 2 # dimension of each data point sample_Total, training_input, test_input, class_labels = Currency( training_size=80, test_size=20, n=n, PLOT_DATA=True ) temp = [test_input[k] for k in test_input] total_array = np.concatenate(temp) aqua_dict = { 'problem': {'name': 'classification', 'random_seed': 10598}, 'algorithm': { 'name': 'QSVM' }, 'feature_map': {'name': 'SecondOrderExpansion', 'depth': 2, 'entangler_map': [[0, 1]]}, 'multiclass_extension': {'name': 'AllPairs'}, 'backend': {'shots': 1024} } backend = BasicAer.get_backend('qasm_simulator') algo_input = ClassificationInput(training_input, test_input, total_array) result = run_algorithm(aqua_dict, algo_input, backend=backend) for k,v in result.items(): print("'{}' : {}".format(k, v))
https://github.com/Pitt-JonesLab/slam_decomposition
Pitt-JonesLab
from abc import ABC import numpy as np from qiskit import QuantumCircuit from qiskit.circuit.library import SwapGate from qiskit.quantum_info import * from weylchamber import J_T_LI, bell_basis, c1c2c3, canonical_gate, g1g2g3 from slam.utils.gates.custom_gates import BerkeleyGate """ Defines functions that the optimizer attempts to minimize, Each function is some metric of fidelity between unitaries, where 0 means best and 1 means worst Experiment to find some metrics perform better/faster than others """ class LineSegmentDistanceCost(ABC): # distance from current weyl chamber point to a line segment in the chamber # for example, used to optimize gate which reaches the line of gates which build SWAP in k=2 def __init__(self, line_segment): self.line_segment = line_segment def distance(self, qc): c = c1c2c3(Operator(qc).data) # return distance from c to the line segment return np.linalg.norm( np.cross( self.line_segment[1] - self.line_segment[0], self.line_segment[0] - c ) ) / np.linalg.norm(self.line_segment[1] - self.line_segment[0]) class BsqSwapCost(LineSegmentDistanceCost): def __init__(self): super().__init__( line_segment=[ np.array(c1c2c3(BerkeleyGate().to_matrix())), np.array(c1c2c3(SwapGate().power(1 / 2).to_matrix())), ] ) # B gate to sqswap class EntanglementCostFunction(ABC): # concurrence, mutual info, negativity, entanglement of formation, entropy of entanglement def __init__(self, state="w"): self.state_prep = QuantumCircuit(3) if state == "w": self.state_prep.ry(2 * np.arccos(1 / np.sqrt(3)), 0) self.state_prep.ch(0, 1) self.state_prep.cx(1, 2) self.state_prep.cx(0, 1) self.state_prep.x(0) elif state == "ghz": self.state_prep.h(0) self.state_prep.cx(0, 1) self.state_prep.cx(0, 2) else: raise NotImplementedError self.state_prep.barrier() def entanglement_monotone(self, qc): self.full = self.state_prep.compose(qc) self.statevector = Statevector(self.full) class MutualInformation(EntanglementCostFunction): # I could code this to be more flexible # for now I am going to hardcode 3Q states in with partial tracing def entanglement_monotone(self, qc): # append on the entangled state circuit # the goal of minimizing the cost means undoing the entangled state super().entanglement_monotone(qc) state1 = partial_trace(self.statevector, [0]) state2 = partial_trace(self.statevector, [1]) state3 = partial_trace(self.statevector, [2]) return sum( [ mutual_information(state1), mutual_information(state2), mutual_information(state3), ] ) class MutualInformationSquare(EntanglementCostFunction): def entanglement_monotone(self, qc): super().entanglement_monotone(qc) state1 = partial_trace(self.statevector, [0]) state2 = partial_trace(self.statevector, [1]) state3 = partial_trace(self.statevector, [2]) return sum( [ mutual_information(state1) ** 2, mutual_information(state2) ** 2, mutual_information(state3) ** 2, ] ) class Negativity(EntanglementCostFunction): def entanglement_monotone(self, qc): return super().entanglement_monotone(qc) class Formation(EntanglementCostFunction): def entanglement_monotone(self, qc): return super().entanglement_monotone(qc) class EntropyofEntanglement(EntanglementCostFunction): def entanglement_monotone(self, qc): return super().entanglement_monotone(qc) class UnitaryCostFunction(ABC): def __init__(self): # experimenting with this # normalize cost using max_cost = c(swap, identity) # swap = np.array([[1,0,0,0], [0,0,1,0], [0,1,0,0], [0,0,0,1]]) # id = np.array([[1,0,0,0], [0,1,0,0], [0,0,1,0],[0,0,0,1]]) self.normalization = 1 # self.unitary_fidelity(id, swap) # logging.debug(self.normalization) def unitary_fidelity(self, current_u, target_u): raise NotImplementedError # def fidelity_lambda(self, target_u): # return lambda current_u: self.unitary_fidelity(current_u, target_u) class BasicCostInverse(UnitaryCostFunction): # don't subtract 1 def unitary_fidelity(self, current_u, target_u): h = np.matrix(target_u).getH() return np.abs(np.trace(np.matmul(h, current_u))) / np.array(current_u).shape[0] class BasicCost(UnitaryCostFunction): def unitary_fidelity(self, current_u, target_u): h = np.matrix(target_u).getH() return ( 1 - np.abs(np.trace(np.matmul(h, current_u))) / np.array(current_u).shape[0] ) class ContinuousUnitaryCostFunction(BasicCost): """Used to fit a template to a unitary behavior at all timesteps rather than just the final state.""" def __init__(self, timesteps): super().__init__() self.timesteps = timesteps def unitary_fidelity(self, current_u, target_u): # combine the unitary and its square root # used for fitting a continuous time evolution, at t=1 and t=1/2 from qiskit.extensions import UnitaryGate cost = 0 for i in np.linspace(0, 1, self.timesteps + 1): # +1 because skip 0 current_u_frac = UnitaryGate(current_u).power(i).to_matrix() target_u_frac = UnitaryGate(target_u).power(i).to_matrix() cost += super().unitary_fidelity(current_u_frac, target_u_frac) return cost class SquareCost(UnitaryCostFunction): def unitary_fidelity(self, current_u, target_u): h = np.matrix(target_u).getH() d = np.array(target_u).shape[0] return 1 - (np.abs(np.trace(np.matmul(h, current_u))) ** 2 + d) / (d * (d + 1)) class BasicReducedCost(BasicCost): # version that eliminates exterior 1Q gates by converting to can basis # need to also convert the template to can basis for similarity def unitary_fidelity(self, current_u, target_u): can_target = np.matrix(canonical_gate(*c1c2c3(target_u))) can_current = np.matrix(canonical_gate(*c1c2c3(current_u))) return super().unitary_fidelity(can_current, can_target) class SquareReducedCost(SquareCost): def unitary_fidelity(self, current_u, target_u): can_target = np.matrix(canonical_gate(*c1c2c3(target_u))) can_current = np.matrix(canonical_gate(*c1c2c3(current_u))) return super().unitary_fidelity(can_current, can_target) class SquareReducedBellCost(SquareCost): def unitary_fidelity(self, current_u, target_u): bell_target = np.matrix(bell_basis(target_u)) bell_current = np.matrix(bell_basis(current_u)) return super().unitary_fidelity(bell_current, bell_target) class WeylEuclideanCost(UnitaryCostFunction): def unitary_fidelity(self, current_u, target_u): if (4, 4) != current_u.shape: raise ValueError("Weyl chamber only for 2Q gates") c_target = c1c2c3(target_u) c_current = c1c2c3(current_u) return np.linalg.norm(np.array(c_target) - np.array(c_current)) class MakhlinEuclideanCost(UnitaryCostFunction): def unitary_fidelity(self, current_u, target_u): if (4, 4) != current_u.shape: raise ValueError("Weyl chamber only for 2Q gates") g_target = g1g2g3(target_u) g_current = g1g2g3(current_u) return np.linalg.norm(np.array(g_target) - np.array(g_current)) class MakhlinFunctionalCost(UnitaryCostFunction): def unitary_fidelity(self, current_u, target_u): return J_T_LI(target_u, current_u)
https://github.com/Qiskit/qiskit-qasm3-import
Qiskit
import qiskit_qasm3_import project = 'Qiskit OpenQASM 3 Importer' copyright = '2022, Jake Lishman' author = 'Jake Lishman' version = qiskit_qasm3_import.__version__ release = qiskit_qasm3_import.__version__ extensions = [ "sphinx.ext.autodoc", "sphinx.ext.intersphinx", "reno.sphinxext", 'qiskit_sphinx_theme', ] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # Document the docstring for the class and the __init__ method together. autoclass_content = "both" html_theme = "qiskit-ecosystem" html_title = f"{project} {release}" intersphinx_mapping = { "qiskit-terra": ("https://docs.quantum.ibm.com/api/qiskit/", None), }
https://github.com/Qiskit/feedback
Qiskit
import matplotlib.pyplot as plt import numpy as np from IPython.display import clear_output from qiskit import QuantumCircuit, Aer from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit import ParameterVector from qiskit.circuit.library import ZFeatureMap from qiskit.opflow import AerPauliExpectation, PauliSumOp from qiskit.utils import QuantumInstance, algorithm_globals from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier from qiskit_machine_learning.neural_networks import TwoLayerQNN from sklearn.model_selection import train_test_split algorithm_globals.random_seed = 12345 # We now define a two qubit unitary as defined in [3] def conv_circuit(params): target = QuantumCircuit(2) target.rz(-np.pi / 2, 1) target.cx(1, 0) target.rz(params[0], 0) target.ry(params[1], 1) target.cx(0, 1) target.ry(params[2], 1) target.cx(1, 0) target.rz(np.pi / 2, 0) return target # Let's draw this circuit and see what it looks like params = ParameterVector("θ", length=3) circuit = conv_circuit(params) circuit.draw("mpl") def conv_layer(num_qubits, param_prefix): qc = QuantumCircuit(num_qubits, name="Convolutional Layer") qubits = list(range(num_qubits)) param_index = 0 params = ParameterVector(param_prefix, length=num_qubits * 3) for q1, q2 in zip(qubits[0::2], qubits[1::2]): qc = qc.compose(conv_circuit(params[param_index : (param_index + 3)]), [q1, q2]) qc.barrier() param_index += 3 for q1, q2 in zip(qubits[1::2], qubits[2::2] + [0]): qc = qc.compose(conv_circuit(params[param_index : (param_index + 3)]), [q1, q2]) qc.barrier() param_index += 3 qc_inst = qc.to_instruction() qc = QuantumCircuit(num_qubits) qc.append(qc_inst, qubits) return qc circuit = conv_layer(4, "θ") circuit.decompose().draw("mpl") def pool_circuit(params): target = QuantumCircuit(2) target.rz(-np.pi / 2, 1) target.cx(1, 0) target.rz(params[0], 0) target.ry(params[1], 1) target.cx(0, 1) target.ry(params[2], 1) return target params = ParameterVector("θ", length=3) circuit = pool_circuit(params) circuit.draw("mpl") def pool_layer(sources, sinks, param_prefix): num_qubits = len(sources) + len(sinks) qc = QuantumCircuit(num_qubits, name="Pooling Layer") param_index = 0 params = ParameterVector(param_prefix, length=num_qubits // 2 * 3) for source, sink in zip(sources, sinks): qc = qc.compose(pool_circuit(params[param_index : (param_index + 3)]), [source, sink]) qc.barrier() param_index += 3 qc_inst = qc.to_instruction() qc = QuantumCircuit(num_qubits) qc.append(qc_inst, range(num_qubits)) return qc sources = [0, 1] sinks = [2, 3] circuit = pool_layer(sources, sinks, "θ") circuit.decompose().draw("mpl") def generate_dataset(num_images): images = [] labels = [] hor_array = np.zeros((6, 8)) ver_array = np.zeros((4, 8)) j = 0 for i in range(0, 7): if i != 3: hor_array[j][i] = np.pi / 2 hor_array[j][i + 1] = np.pi / 2 j += 1 j = 0 for i in range(0, 4): ver_array[j][i] = np.pi / 2 ver_array[j][i + 4] = np.pi / 2 j += 1 for n in range(num_images): rng = algorithm_globals.random.integers(0, 2) if rng == 0: labels.append(-1) random_image = algorithm_globals.random.integers(0, 6) images.append(np.array(hor_array[random_image])) elif rng == 1: labels.append(1) random_image = algorithm_globals.random.integers(0, 4) images.append(np.array(ver_array[random_image])) # Create noise for i in range(8): if images[-1][i] == 0: images[-1][i] = algorithm_globals.random.uniform(0, np.pi / 4) return images, labels images, labels = generate_dataset(50) train_images, test_images, train_labels, test_labels = train_test_split( images, labels, test_size=0.3 ) fig, ax = plt.subplots(2, 2, figsize=(10, 6), subplot_kw={"xticks": [], "yticks": []}) for i in range(4): ax[i // 2, i % 2].imshow( train_images[i].reshape(2, 4), # Change back to 2 by 4 aspect="equal", ) plt.subplots_adjust(wspace=0.1, hspace=0.025) fig, ax = plt.subplots(2, 2, figsize=(10, 6), subplot_kw={"xticks": [], "yticks": []}) for i in range(4): ax[i // 2, i % 2].imshow( train_images[i].reshape(2, 4), # Change back to 2 by 4 aspect="equal", ) plt.subplots_adjust(wspace=0.1, hspace=0.025) feature_map = ZFeatureMap(8) feature_map.decompose().draw("mpl") quantum_instance = QuantumInstance(Aer.get_backend("aer_simulator"), shots=1024) feature_map = ZFeatureMap(8) ansatz = QuantumCircuit(8, name="Ansatz") # First Convolutional Layer ansatz.compose(conv_layer(8, "с1"), list(range(8)), inplace=True) # First Pooling Layer ansatz.compose(pool_layer([0, 1, 2, 3], [4, 5, 6, 7], "p1"), list(range(8)), inplace=True) # Second Convolutional Layer ansatz.compose(conv_layer(4, "c2"), list(range(4, 8)), inplace=True) # Second Pooling Layer ansatz.compose(pool_layer([0, 1], [2, 3], "p2"), list(range(4, 8)), inplace=True) # Third Convolutional Layer ansatz.compose(conv_layer(2, "c3"), list(range(6, 8)), inplace=True) # Third Pooling Layer ansatz.compose(pool_layer([0], [1], "p3"), list(range(6, 8)), inplace=True) # Combining the feature map and ansatz circuit = QuantumCircuit(8) circuit.compose(feature_map, range(8), inplace=True) circuit.compose(ansatz, range(8), inplace=True) observable = PauliSumOp.from_list([("Z" + "I" * 7, 1)]) qnn = TwoLayerQNN( num_qubits=8, feature_map=feature_map, ansatz=ansatz, observable=observable, exp_val=AerPauliExpectation(), quantum_instance=quantum_instance, ) circuit.draw("mpl") 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() opflow_classifier = NeuralNetworkClassifier( qnn, optimizer=COBYLA(maxiter=400), # Set max iterations here callback=callback_graph, initial_point=algorithm_globals.random.random(qnn.num_weights), ) x = np.asarray(train_images) y = np.asarray(train_labels) objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) opflow_classifier.fit(x, y) # score classifier print(f"Accuracy from the train data : {np.round(100 * opflow_classifier.score(x, y), 2)}%") test_images, test_labels = generate_dataset(10) y_predict = opflow_classifier.predict(test_images) x = np.asarray(test_images) y = np.asarray(test_labels) print(f"Accuracy from the test data : {np.round(100 * opflow_classifier.score(x, y), 2)}%") # Let's see some examples in our dataset fig, ax = plt.subplots(1, 2, figsize=(10, 6), subplot_kw={"xticks": [], "yticks": []}) for i in range(0, 2): ax[i % 2].imshow(test_images[i].reshape(2, 4), aspect="equal") if y_predict[i] == -1: ax[i % 2].set_title("The QCNN predicts this is a Horizontal Line") if y_predict[i] == +1: ax[ i % 2].set_title("The QCNN predicts this is a Vertical Line") plt.subplots_adjust(wspace=0.1, hspace=0.5) !jupyter nbconvert 'QCNN_presentation.ipynb' --to slides --post serve import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
from sympy import * init_printing(use_unicode=True) mu_u = Matrix([[-1],[+1],[+1]]); mu_u A_R = Matrix([[1,1,-1,-1],[1,-1,1,-1],[1,-1,-1,1]]); A_R p1,p2,p3,p4 = symbols('p_1 p_2 p_3 p_4') p4 = 1-p1-p2-p3 cl = A_R[:,0]*p1 + A_R[:,1]*p2 + A_R[:,2]*p3 + A_R[:,3]*p4 mu_u - cl s1 = Matrix([[0,1],[1,0]]) s2 = Matrix([[0,-1j],[1j,0]]) s1*s2 import numpy as np a = [] # gera uma lista com com todos os 512 estados ônticos for j in range(-1,2,2): for k in range(-1,2,2): for l in range(-1,2,2): for m in range(-1,2,2): for n in range(-1,2,2): for o in range(-1,2,2): for p in range(-1,2,2): for q in range(-1,2,2): for r in range(-1,2,2): a.append(np.array([j,k,l,m,n,o,p,q,r])) a[10], a[10][5], len(a) mu = [] # gera, a partir dos estados ônticos, uma lista com os 512 vetores de medida, muitos dos quais são iguais for j in range(0,2**9): r1 = a[j][0]*a[j][1]*a[j][2] r2 = a[j][3]*a[j][4]*a[j][5] r3 = a[j][6]*a[j][7]*a[j][8] c1 = a[j][0]*a[j][3]*a[j][6] c2 = a[j][1]*a[j][4]*a[j][7] c3 = a[j][2]*a[j][5]*a[j][8] mu.append([r1,r2,r3,c1,c2,c3]) mu[0], len(mu) mu_ = [] # remove as repeticoes do vetor de medida for j in range(0,2**6): if mu[j] not in mu_: mu_.append(mu[j]) mu_, len(mu_), mu_[1] A_R = np.zeros((6,16))#; A_R for j in range(0,16): A_R[:,j] = mu_[j] print(A_R) print(A_R.shape) def rpv_zhsl(d): # vetor de probabilidades aleatório rn = np.zeros(d-1) for j in range(0,d-1): rn[j] = np.random.random() rpv = np.zeros(d) rpv[0] = 1.0 - rn[0]**(1.0/(d-1.0)) norm = rpv[0] if d > 2: for j in range(1,d-1): rpv[j] = (1.0 - rn[j]**(1.0/(d-j-1)))*(1.0-norm) norm = norm + rpv[j] rpv[d-1] = 1.0 - norm return rpv rpv = rpv_zhsl(16) print(rpv) print(np.linalg.norm(rpv)) mu_Q = np.zeros((6,1)); mu_Q = np.array([1,1,1,1,1,-1]); print(mu_Q.shape) p = np.zeros((16,1)); p = rpv_zhsl(16); print(p.shape) vec = mu_Q - A_R@p print(vec) def objective(x): mu_Q = np.array([1,1,1,1,1,-1]) vec = mu_Q - A_R@x return np.linalg.norm(vec) from scipy.optimize import minimize # define o vinculo como sendo uma distribuicao de probabilidades constraints = [{'type': 'eq', 'fun': lambda x: np.sum(x)-1}, {'type':'ineq', 'fun': lambda x: x}, {'type':'ineq', 'fun': lambda x: 1-x}] # 'eq' quer dizer = 0 e 'ineq' quer dizer >=0 np.random.seed(130000) x0 = rpv_zhsl(16) print(x0) result = minimize(objective, x0, constraints=constraints, method='trust-constr') print('melhor distribuicao de probabilidades', result.x) print(objective(result.x)) from qiskit import * import numpy as np import math import qiskit nshots = 8192 IBMQ.load_account() provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') device = provider.get_backend('ibmq_manila') simulator = Aer.get_backend('qasm_simulator') from qiskit.tools.monitor import job_monitor #from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter #from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.visualization import plot_histogram qr = QuantumRegister(3) cr = ClassicalRegister(1) qc = QuantumCircuit(qr,cr) qc.barrier() # mede XI qc.h(0) qc.cx(0,2) qc.barrier() # mede IX qc.h(1) qc.cx(1,2) qc.barrier() # mede XX qc.cx(0,2) qc.cx(1,2) qc.barrier() qc.measure(2,0) qc.draw('mpl') job_sim = execute(qc, backend=simulator, shots=nshots) counts_sim = job_sim.result().get_counts(qc) job_exp = execute(qc, backend=device, shots=nshots) print(job_exp.job_id()) job_monitor(job_exp) counts_exp = job_exp.result().get_counts(qc) counts_exp plot_histogram([counts_sim, counts_exp], legend=['sim', 'exp']) qr = QuantumRegister(3) cr = ClassicalRegister(1) qc = QuantumCircuit(qr,cr) qc.barrier() # mede YI qc.sdg(0) qc.h(0) qc.cx(0,2) qc.barrier() # mede IY qc.sdg(1) qc.h(1) qc.cx(1,2) qc.barrier() # mede YY qc.cx(0,2) qc.cx(1,2) qc.barrier() qc.measure(2,0) qc.draw('mpl') job_sim = execute(qc, backend=simulator, shots=nshots) counts_sim = job_sim.result().get_counts(qc) job_exp = execute(qc, backend=device, shots=nshots) print(job_exp.job_id()) job_monitor(job_exp) counts_exp = job_exp.result().get_counts(qc) counts_exp plot_histogram([counts_sim, counts_exp], legend=['sim', 'exp']) qr = QuantumRegister(3) cr = ClassicalRegister(1) qc = QuantumCircuit(qr,cr) qc.barrier() qc.h(0) qc.cx(0,2) # mede XI qc.barrier() qc.sdg(1) qc.h(1) qc.cx(1,2) # mede IX qc.barrier() qc.cx(0,2); qc.cx(1,2) qc.barrier() qc.measure(2,0) qc.draw('mpl') job_sim = execute(qc, backend=simulator, shots=nshots) counts_sim = job_sim.result().get_counts(qc) job_exp = execute(qc, backend=device, shots=nshots) print(job_exp.job_id()) job_monitor(job_exp) counts_exp = job_exp.result().get_counts(qc) counts_exp plot_histogram([counts_sim, counts_exp], legend=['sim', 'exp']) qr = QuantumRegister(3) cr = ClassicalRegister(1) qc = QuantumCircuit(qr,cr) qc.barrier() qc.sdg(0) qc.h(0) qc.cx(0,2) # mede XI qc.barrier() qc.h(1) qc.cx(1,2) # mede IX qc.barrier() qc.cx(0,2); qc.cx(1,2) qc.barrier() qc.measure(2,0) qc.draw('mpl') job_sim = execute(qc, backend=simulator, shots=nshots) counts_sim = job_sim.result().get_counts(qc) job_exp = execute(qc, backend=device, shots=nshots) print(job_exp.job_id()) job_monitor(job_exp) counts_exp = job_exp.result().get_counts(qc) counts_exp plot_histogram([counts_sim, counts_exp], legend=['sim', 'exp']) I = Matrix([[1,0],[0,1]]); X = Matrix([[0,1],[1,0]]); Y = Matrix([[0,-1j],[1j,0]]); Z = Matrix([[1,0],[0,-1]]) I,X,Y,Z XX = kronecker_product(X,X); XX.eigenvects() YY = kronecker_product(Y,Y); YY.eigenvects() ZZ = kronecker_product(Z,Z); ZZ.eigenvects() qr = QuantumRegister(3) cr = ClassicalRegister(1) qc = QuantumCircuit(qr,cr) qc.barrier() # mede ZZ qc.cx(0,2) qc.cx(1,2) qc.barrier() # mede XX qc.h([0,1]) qc.cx(0,2) qc.cx(1,2) qc.barrier() # mede YY qc.h([0,1]) qc.sdg([0,1]) qc.h([0,1]) qc.cx(0,2) qc.cx(1,2) qc.barrier() qc.measure(2,0) qc.draw('mpl') job_sim = execute(qc, backend=simulator, shots=nshots) counts_sim = job_sim.result().get_counts(qc) job_exp = execute(qc, backend=device, shots=nshots) print(job_exp.job_id()) job_monitor(job_exp) counts_exp = job_exp.result().get_counts(qc) counts_exp plot_histogram([counts_sim, counts_exp], legend=['sim', 'exp']) XY = kronecker_product(X,Y); XY.eigenvects() YX = kronecker_product(Y,X); YX.eigenvects() qr = QuantumRegister(3) cr = ClassicalRegister(1) qc = QuantumCircuit(qr,cr) qc.barrier() # mede ZZ qc.cx(0,2) qc.cx(1,2) qc.barrier() # mede XX qc.sdg(1) qc.h([0,1]) qc.cx(0,2) qc.cx(1,2) qc.barrier() # mede YY qc.h([0,1]) qc.sdg(0) qc.s(1) qc.h([0,1]) qc.cx(0,2) qc.cx(1,2) qc.barrier() qc.measure(2,0) qc.draw('mpl') job_sim = execute(qc, backend=simulator, shots=nshots) counts_sim = job_sim.result().get_counts(qc) job_exp = execute(qc, backend=device, shots=nshots) print(job_exp.job_id()) job_monitor(job_exp) counts_exp = job_exp.result().get_counts(qc) counts_exp plot_histogram([counts_sim, counts_exp], legend=['sim', 'exp']) cr1 = {'0': 7921, '1': 271} cr2 = {'0': 7944, '1': 248} cr3 = {'0': 7754, '1': 438} cc1 = {'0': 7913, '1': 279} cc2 = {'0': 7940, '1': 252} cc3 = {'0': 610, '1': 7582} r1a = (cr1['0']-cr1['1'])/(cr1['0']+cr1['1']) r2a = (cr2['0']-cr2['1'])/(cr2['0']+cr2['1']) r3a = (cr3['0']-cr3['1'])/(cr3['0']+cr3['1']) c1a = (cc1['0']-cc1['1'])/(cc1['0']+cc1['1']) c2a = (cc2['0']-cc2['1'])/(cc2['0']+cc2['1']) c3a = (cc3['0']-cc3['1'])/(cc3['0']+cc3['1']) print(r1a,r2a,r3a,c1a,c2a,c3a) def objective(x): mu_Q = np.array([0.93,0.94,0.89,0.93,0.94,-0.85]) vec = mu_Q - A_R@x return np.linalg.norm(vec) constraints = [{'type': 'eq', 'fun': lambda x: np.sum(x)-1}, {'type':'ineq', 'fun': lambda x: x}, {'type':'ineq', 'fun': lambda x: 1-x}] np.random.seed(130000) x0 = rpv_zhsl(16) result = minimize(objective, x0, constraints=constraints, method='trust-constr') print('melhor distribuicao de probabilidades', result.x) print(objective(result.x))
https://github.com/Qubico-Hack/tutorials
Qubico-Hack
!pip install qiskit-machine-learning !pip install --upgrade matplotlib !pip install pylatexenc !pip install pillow # Necessary imports import numpy as np import matplotlib.pyplot as plt from torch import Tensor from torch.nn import Linear, CrossEntropyLoss, MSELoss from torch.optim import LBFGS from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap from qiskit_algorithms.utils import algorithm_globals from qiskit_machine_learning.neural_networks import SamplerQNN, EstimatorQNN from qiskit_machine_learning.connectors import TorchConnector # Set seed for random generators algorithm_globals.random_seed = 42 #Generate random dataset # Select dataset dimension (num_inputs) and size (num_samples) num_inputs = 2 num_samples = 20 # Generate random input coordinates (X) and binary labels (y) X = 2 * algorithm_globals.random.random([num_samples, num_inputs]) - 1 y01 = 1 * (np.sum(X, axis=1) >= 0) # in { 0, 1}, y01 will be used for SamplerQNN example y = 2 * y01 - 1 # in {-1, +1}, y will be used for EstimatorQNN example # Convert to torch Tensors X_ = Tensor(X) y01_ = Tensor(y01).reshape(len(y)).long() y_ = Tensor(y).reshape(len(y), 1) # Plot dataset for x, y_target in zip(X, y): if y_target == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() # Set up a circuit feature_map = ZZFeatureMap(num_inputs) ansatz = RealAmplitudes(num_inputs) qc = QuantumCircuit(num_inputs) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) qc.draw("mpl") # Setup QNN qnn1 = EstimatorQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters ) # Set up PyTorch module # Note: If we don't explicitly declare the initial weights # they are chosen uniformly at random from [-1, 1]. initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn1.num_weights) - 1) model1 = TorchConnector(qnn1, initial_weights=initial_weights) print("Initial weights: ", initial_weights) #Test with a single input model1(X_[0, :]) # Define optimizer and loss optimizer = LBFGS(model1.parameters()) f_loss = MSELoss(reduction="sum") # Start training model1.train() # set model to training mode # Note from (https://pytorch.org/docs/stable/optim.html): # Some optimization algorithms such as LBFGS need to # reevaluate the function multiple times, so you have to # pass in a closure that allows them to recompute your model. # The closure should clear the gradients, compute the loss, # and return it. def closure(): optimizer.zero_grad() # Initialize/clear gradients loss = f_loss(model1(X_), y_) # Evaluate loss function loss.backward() # Backward pass print(loss.item()) # Print loss return loss # Run optimizer step4 optimizer.step(closure) # Evaluate model and compute accuracy model1.eval() y_predict = [] for x, y_target in zip(X, y): output = model1(Tensor(x)) y_predict += [np.sign(output.detach().numpy())[0]] print("Accuracy:", sum(y_predict == y) / len(y)) # Plot results # red == wrongly classified for x, y_target, y_p in zip(X, y, y_predict): if y_target == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") if y_target != y_p: plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2) plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() #Define feature map and ansatz feature_map = ZZFeatureMap(num_inputs) ansatz = RealAmplitudes(num_inputs, entanglement="linear", reps=1) # Define quantum circuit of num_qubits = input dim # Append feature map and ansatz qc = QuantumCircuit(num_inputs) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) # Define SamplerQNN and initial setup parity = lambda x: "{:b}".format(x).count("1") % 2 # optional interpret function output_shape = 2 # parity = 0, 1 qnn2 = SamplerQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, interpret=parity, output_shape=output_shape, ) # Set up PyTorch module # Reminder: If we don't explicitly declare the initial weights # they are chosen uniformly at random from [-1, 1]. initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn2.num_weights) - 1) print("Initial weights: ", initial_weights) model2 = TorchConnector(qnn2, initial_weights) # Define model, optimizer, and loss optimizer = LBFGS(model2.parameters()) f_loss = CrossEntropyLoss() # Our output will be in the [0,1] range # Start training model2.train() # Define LBFGS closure method (explained in previous section) def closure(): optimizer.zero_grad(set_to_none=True) # Initialize gradient loss = f_loss(model2(X_), y01_) # Calculate loss loss.backward() # Backward pass print(loss.item()) # Print loss return loss # Run optimizer (LBFGS requires closure) optimizer.step(closure); # Evaluate model and compute accuracy model2.eval() y_predict = [] for x in X: output = model2(Tensor(x)) y_predict += [np.argmax(output.detach().numpy())] print("Accuracy:", sum(y_predict == y01) / len(y01)) # plot results # red == wrongly classified for x, y_target, y_ in zip(X, y01, y_predict): if y_target == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") if y_target != y_: plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2) plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() # Generate random dataset num_samples = 20 eps = 0.2 lb, ub = -np.pi, np.pi f = lambda x: np.sin(x) X = (ub - lb) * algorithm_globals.random.random([num_samples, 1]) + lb y = f(X) + eps * (2 * algorithm_globals.random.random([num_samples, 1]) - 1) plt.plot(np.linspace(lb, ub), f(np.linspace(lb, ub)), "r--") plt.plot(X, y, "bo") plt.show() # Construct simple feature map param_x = Parameter("x") feature_map = QuantumCircuit(1, name="fm") feature_map.ry(param_x, 0) # Construct simple parameterized ansatz param_y = Parameter("y") ansatz = QuantumCircuit(1, name="vf") ansatz.ry(param_y, 0) qc = QuantumCircuit(1) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) # Construct QNN qnn3 = EstimatorQNN(circuit=qc, input_params=[param_x], weight_params=[param_y]) # Set up PyTorch module # Reminder: If we don't explicitly declare the initial weights # they are chosen uniformly at random from [-1, 1]. initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn3.num_weights) - 1) model3 = TorchConnector(qnn3, initial_weights) # Define optimizer and loss function optimizer = LBFGS(model3.parameters()) f_loss = MSELoss(reduction="sum") # Start training model3.train() # set model to training mode # Define objective function def closure(): optimizer.zero_grad(set_to_none=True) # Initialize gradient loss = f_loss(model3(Tensor(X)), Tensor(y)) # Compute batch loss loss.backward() # Backward pass print(loss.item()) # Print loss return loss # Run optimizer optimizer.step(closure) # Plot target function plt.plot(np.linspace(lb, ub), f(np.linspace(lb, ub)), "r--") # Plot data plt.plot(X, y, "bo") # Plot fitted line model3.eval() y_ = [] for x in np.linspace(lb, ub): output = model3(Tensor([x])) y_ += [output.detach().numpy()[0]] plt.plot(np.linspace(lb, ub), y_, "g-") plt.show() # Additional torch-related imports import torch from torch import cat, no_grad, manual_seed from torch.utils.data import DataLoader from torchvision import datasets, transforms import torch.optim as optim from torch.nn import ( Module, Conv2d, Linear, Dropout2d, NLLLoss, MaxPool2d, Flatten, Sequential, ReLU, ) import torch.nn.functional as F # Train Dataset # ------------- # Set train shuffle seed (for reproducibility) manual_seed(42) batch_size = 1 n_samples = 100 # We will concentrate on the first 100 samples # Use pre-defined torchvision function to load MNIST train data X_train = datasets.MNIST( root="./data", train=True, download=True, transform=transforms.Compose([transforms.ToTensor()]) ) # Filter out labels (originally 0-9), leaving only labels 0 and 1 idx = np.append( np.where(X_train.targets == 0)[0][:n_samples], np.where(X_train.targets == 1)[0][:n_samples] ) X_train.data = X_train.data[idx] X_train.targets = X_train.targets[idx] # Define torch dataloader with filtered data train_loader = DataLoader(X_train, batch_size=batch_size, shuffle=True) # Quick visualization of images of handwritten 0s and 1s n_samples_show = 6 data_iter = iter(train_loader) fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) while n_samples_show > 0: images, targets = data_iter.__next__() axes[n_samples_show - 1].imshow(images[0, 0].numpy().squeeze(), cmap="gray") axes[n_samples_show - 1].set_xticks([]) axes[n_samples_show - 1].set_yticks([]) axes[n_samples_show - 1].set_title("Labeled: {}".format(targets[0].item())) n_samples_show -= 1 # Test Dataset # ------------- # Set test shuffle seed (for reproducibility) # manual_seed(5) n_samples = 50 # Use pre-defined torchvision function to load MNIST test data X_test = datasets.MNIST( root="./data", train=False, download=True, transform=transforms.Compose([transforms.ToTensor()]) ) # Filter out labels (originally 0-9), leaving only labels 0 and 1 idx = np.append( np.where(X_test.targets == 0)[0][:n_samples], np.where(X_test.targets == 1)[0][:n_samples] ) X_test.data = X_test.data[idx] X_test.targets = X_test.targets[idx] # Define torch dataloader with filtered data test_loader = DataLoader(X_test, batch_size=batch_size, shuffle=True) # Define and create QNN def create_qnn(): feature_map = ZZFeatureMap(2) ansatz = RealAmplitudes(2, reps=1) qc = QuantumCircuit(2) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) # REMEMBER TO SET input_gradients=True FOR ENABLING HYBRID GRADIENT BACKPROP qnn = EstimatorQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, input_gradients=True, ) return qnn qnn4 = create_qnn() # Define torch NN module class Net(Module): def __init__(self, qnn): super().__init__() self.conv1 = Conv2d(1, 2, kernel_size=5) self.conv2 = Conv2d(2, 16, kernel_size=5) self.dropout = Dropout2d() self.fc1 = Linear(256, 64) self.fc2 = Linear(64, 2) # 2-dimensional input to QNN self.qnn = TorchConnector(qnn) # Apply torch connector, weights chosen # uniformly at random from interval [-1,1]. self.fc3 = Linear(1, 1) # 1-dimensional output from QNN def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) x = x.view(x.shape[0], -1) x = F.relu(self.fc1(x)) x = self.fc2(x) x = self.qnn(x) # apply QNN x = self.fc3(x) return cat((x, 1 - x), -1) model4 = Net(qnn4) # Define model, optimizer, and loss function optimizer = optim.Adam(model4.parameters(), lr=0.001) loss_func = NLLLoss() # Start training epochs = 10 # Set number of epochs loss_list = [] # Store loss history model4.train() # Set model to training mode for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad(set_to_none=True) # Initialize gradient output = model4(data) # Forward pass loss = loss_func(output, target) # Calculate loss loss.backward() # Backward pass optimizer.step() # Optimize weights total_loss.append(loss.item()) # Store loss loss_list.append(sum(total_loss) / len(total_loss)) print("Training [{:.0f}%]\tLoss: {:.4f}".format(100.0 * (epoch + 1) / epochs, loss_list[-1])) # Plot loss convergence plt.plot(loss_list) plt.title("Hybrid NN Training Convergence") plt.xlabel("Training Iterations") plt.ylabel("Neg. Log Likelihood Loss") plt.show() #Save the trained model torch.save(model4.state_dict(), "model4.pt") #Recreating the model and loading the state from the previously saved file. qnn5 = create_qnn() model5 = Net(qnn5) model5.load_state_dict(torch.load("model4.pt")) model5.eval() # set model to evaluation mode with no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model5(data) if len(output.shape) == 1: output = output.reshape(1, *output.shape) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print( "Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%".format( sum(total_loss) / len(total_loss), correct / len(test_loader) / batch_size * 100 ) ) # Plot predicted labels n_samples_show = 6 count = 0 fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) model5.eval() with no_grad(): for batch_idx, (data, target) in enumerate(test_loader): if count == n_samples_show: break output = model5(data[0:1]) if len(output.shape) == 1: output = output.reshape(1, *output.shape) pred = output.argmax(dim=1, keepdim=True) axes[count].imshow(data[0].numpy().squeeze(), cmap="gray") axes[count].set_xticks([]) axes[count].set_yticks([]) axes[count].set_title("Predicted {}".format(pred.item())) count += 1 import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 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. r""" .. _pulse_builder: ============= Pulse Builder ============= .. We actually want people to think of these functions as being defined within the ``qiskit.pulse`` namespace, not the submodule ``qiskit.pulse.builder``. .. currentmodule: qiskit.pulse Use the pulse builder DSL to write pulse programs with an imperative syntax. .. warning:: The pulse builder interface is still in active development. It may have breaking API changes without deprecation warnings in future releases until otherwise indicated. The pulse builder provides an imperative API for writing pulse programs with less difficulty than the :class:`~qiskit.pulse.Schedule` API. It contextually constructs a pulse schedule and then emits the schedule for execution. For example, to play a series of pulses on channels is as simple as: .. plot:: :include-source: 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() To begin pulse programming we must first initialize our program builder context with :func:`build`, after which we can begin adding program statements. For example, below we write a simple program that :func:`play`\s a pulse: .. plot:: :include-source: from qiskit import execute, pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.play(pulse.Constant(100, 1.0), d0) pulse_prog.draw() The builder initializes a :class:`.pulse.Schedule`, ``pulse_prog`` and then begins to construct the program within the context. The output pulse schedule will survive after the context is exited and can be executed like a normal Qiskit schedule using ``qiskit.execute(pulse_prog, backend)``. Pulse programming has a simple imperative style. This leaves the programmer to worry about the raw experimental physics of pulse programming and not constructing cumbersome data structures. We can optionally pass a :class:`~qiskit.providers.Backend` to :func:`build` to enable enhanced functionality. Below, we prepare a Bell state by automatically compiling the required pulses from their gate-level representations, while simultaneously applying a long decoupling pulse to a neighboring qubit. We terminate the experiment with a measurement to observe the state we prepared. This program which mixes circuits and pulses will be automatically lowered to be run as a pulse program: .. plot:: :include-source: import math from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse3Q # TODO: This example should use a real mock backend. backend = FakeOpenPulse3Q() d2 = pulse.DriveChannel(2) with pulse.build(backend) as bell_prep: pulse.u2(0, math.pi, 0) pulse.cx(0, 1) with pulse.build(backend) as decoupled_bell_prep_and_measure: # We call our bell state preparation schedule constructed above. with pulse.align_right(): pulse.call(bell_prep) pulse.play(pulse.Constant(bell_prep.duration, 0.02), d2) pulse.barrier(0, 1, 2) registers = pulse.measure_all() decoupled_bell_prep_and_measure.draw() With the pulse builder we are able to blend programming on qubits and channels. While the pulse schedule is based on instructions that operate on channels, the pulse builder automatically handles the mapping from qubits to channels for you. In the example below we demonstrate some more features of the pulse builder: .. code-block:: import math from qiskit import pulse, QuantumCircuit from qiskit.pulse import library from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: # Create a pulse. gaussian_pulse = library.gaussian(10, 1.0, 2) # Get the qubit's corresponding drive channel from the backend. d0 = pulse.drive_channel(0) d1 = pulse.drive_channel(1) # Play a pulse at t=0. pulse.play(gaussian_pulse, d0) # Play another pulse directly after the previous pulse at t=10. pulse.play(gaussian_pulse, d0) # The default scheduling behavior is to schedule pulses in parallel # across channels. For example, the statement below # plays the same pulse on a different channel at t=0. pulse.play(gaussian_pulse, d1) # We also provide pulse scheduling alignment contexts. # The default alignment context is align_left. # The sequential context schedules pulse instructions sequentially in time. # This context starts at t=10 due to earlier pulses above. with pulse.align_sequential(): pulse.play(gaussian_pulse, d0) # Play another pulse after at t=20. pulse.play(gaussian_pulse, d1) # We can also nest contexts as each instruction is # contained in its local scheduling context. # The output of a child context is a context-schedule # with the internal instructions timing fixed relative to # one another. This is schedule is then called in the parent context. # Context starts at t=30. with pulse.align_left(): # Start at t=30. pulse.play(gaussian_pulse, d0) # Start at t=30. pulse.play(gaussian_pulse, d1) # Context ends at t=40. # Alignment context where all pulse instructions are # aligned to the right, ie., as late as possible. with pulse.align_right(): # Shift the phase of a pulse channel. pulse.shift_phase(math.pi, d1) # Starts at t=40. pulse.delay(100, d0) # Ends at t=140. # Starts at t=130. pulse.play(gaussian_pulse, d1) # Ends at t=140. # Acquire data for a qubit and store in a memory slot. pulse.acquire(100, 0, pulse.MemorySlot(0)) # We also support a variety of macros for common operations. # Measure all qubits. pulse.measure_all() # Delay on some qubits. # This requires knowledge of which channels belong to which qubits. # delay for 100 cycles on qubits 0 and 1. pulse.delay_qubits(100, 0, 1) # Call a quantum circuit. The pulse builder lazily constructs a quantum # circuit which is then transpiled and scheduled before inserting into # a pulse schedule. # NOTE: Quantum register indices correspond to physical qubit indices. qc = QuantumCircuit(2, 2) qc.cx(0, 1) pulse.call(qc) # Calling a small set of standard gates and decomposing to pulses is # also supported with more natural syntax. pulse.u3(0, math.pi, 0, 0) pulse.cx(0, 1) # It is also be possible to call a preexisting schedule tmp_sched = pulse.Schedule() tmp_sched += pulse.Play(gaussian_pulse, d0) pulse.call(tmp_sched) # We also support: # frequency instructions pulse.set_frequency(5.0e9, d0) # phase instructions pulse.shift_phase(0.1, d0) # offset contexts with pulse.phase_offset(math.pi, d0): pulse.play(gaussian_pulse, d0) The above is just a small taste of what is possible with the builder. See the rest of the module documentation for more information on its capabilities. .. autofunction:: build Channels ======== Methods to return the correct channels for the respective qubit indices. .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as drive_sched: d0 = pulse.drive_channel(0) print(d0) .. parsed-literal:: DriveChannel(0) .. autofunction:: acquire_channel .. autofunction:: control_channels .. autofunction:: drive_channel .. autofunction:: measure_channel Instructions ============ Pulse instructions are available within the builder interface. Here's an example: .. plot:: :include-source: from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as drive_sched: d0 = pulse.drive_channel(0) a0 = pulse.acquire_channel(0) pulse.play(pulse.library.Constant(10, 1.0), d0) pulse.delay(20, d0) pulse.shift_phase(3.14/2, d0) pulse.set_phase(3.14, d0) pulse.shift_frequency(1e7, d0) pulse.set_frequency(5e9, d0) with pulse.build() as temp_sched: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), d0) pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), d0) pulse.call(temp_sched) pulse.acquire(30, a0, pulse.MemorySlot(0)) drive_sched.draw() .. autofunction:: acquire .. autofunction:: barrier .. autofunction:: call .. autofunction:: delay .. autofunction:: play .. autofunction:: reference .. autofunction:: set_frequency .. autofunction:: set_phase .. autofunction:: shift_frequency .. autofunction:: shift_phase .. autofunction:: snapshot Contexts ======== Builder aware contexts that modify the construction of a pulse program. For example an alignment context like :func:`align_right` may be used to align all pulses as late as possible in a pulse program. .. plot:: :include-source: from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_right(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will start at t=80 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog.draw() .. autofunction:: align_equispaced .. autofunction:: align_func .. autofunction:: align_left .. autofunction:: align_right .. autofunction:: align_sequential .. autofunction:: circuit_scheduler_settings .. autofunction:: frequency_offset .. autofunction:: phase_offset .. autofunction:: transpiler_settings Macros ====== Macros help you add more complex functionality to your pulse program. .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as measure_sched: mem_slot = pulse.measure(0) print(mem_slot) .. parsed-literal:: MemorySlot(0) .. autofunction:: measure .. autofunction:: measure_all .. autofunction:: delay_qubits Circuit Gates ============= To use circuit level gates within your pulse program call a circuit with :func:`call`. .. warning:: These will be removed in future versions with the release of a circuit builder interface in which it will be possible to calibrate a gate in terms of pulses and use that gate in a circuit. .. code-block:: import math from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as u3_sched: pulse.u3(math.pi, 0, math.pi, 0) .. autofunction:: cx .. autofunction:: u1 .. autofunction:: u2 .. autofunction:: u3 .. autofunction:: x Utilities ========= The utility functions can be used to gather attributes about the backend and modify how the program is built. .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as u3_sched: print('Number of qubits in backend: {}'.format(pulse.num_qubits())) samples = 160 print('There are {} samples in {} seconds'.format( samples, pulse.samples_to_seconds(160))) seconds = 1e-6 print('There are {} seconds in {} samples.'.format( seconds, pulse.seconds_to_samples(1e-6))) .. parsed-literal:: Number of qubits in backend: 1 There are 160 samples in 3.5555555555555554e-08 seconds There are 1e-06 seconds in 4500 samples. .. autofunction:: active_backend .. autofunction:: active_transpiler_settings .. autofunction:: active_circuit_scheduler_settings .. autofunction:: num_qubits .. autofunction:: qubit_channels .. autofunction:: samples_to_seconds .. autofunction:: seconds_to_samples """ import collections import contextvars import functools import itertools import uuid import warnings from contextlib import contextmanager from functools import singledispatchmethod from typing import ( Any, Callable, ContextManager, Dict, Iterable, List, Mapping, Optional, Set, Tuple, TypeVar, Union, NewType, ) import numpy as np from qiskit import circuit from qiskit.circuit.library import standard_gates as gates from qiskit.circuit.parameterexpression import ParameterExpression, ParameterValueType from qiskit.pulse import ( channels as chans, configuration, exceptions, instructions, macros, library, transforms, ) from qiskit.providers.backend import BackendV2 from qiskit.pulse.instructions import directives from qiskit.pulse.schedule import Schedule, ScheduleBlock from qiskit.pulse.transforms.alignments import AlignmentKind #: contextvars.ContextVar[BuilderContext]: active builder BUILDER_CONTEXTVAR = contextvars.ContextVar("backend") T = TypeVar("T") StorageLocation = NewType("StorageLocation", Union[chans.MemorySlot, chans.RegisterSlot]) def _compile_lazy_circuit_before(function: Callable[..., T]) -> Callable[..., T]: """Decorator thats schedules and calls the lazily compiled circuit before executing the decorated builder method.""" @functools.wraps(function) def wrapper(self, *args, **kwargs): self._compile_lazy_circuit() return function(self, *args, **kwargs) return wrapper def _requires_backend(function: Callable[..., T]) -> Callable[..., T]: """Decorator a function to raise if it is called without a builder with a set backend. """ @functools.wraps(function) def wrapper(self, *args, **kwargs): if self.backend is None: raise exceptions.BackendNotSet( 'This function requires the builder to have a "backend" set.' ) return function(self, *args, **kwargs) return wrapper class _PulseBuilder: """Builder context class.""" __alignment_kinds__ = { "left": transforms.AlignLeft(), "right": transforms.AlignRight(), "sequential": transforms.AlignSequential(), } def __init__( self, backend=None, block: Optional[ScheduleBlock] = None, name: Optional[str] = None, default_alignment: Union[str, AlignmentKind] = "left", default_transpiler_settings: Mapping = None, default_circuit_scheduler_settings: Mapping = None, ): """Initialize the builder context. .. note:: At some point we may consider incorporating the builder into the :class:`~qiskit.pulse.Schedule` class. However, the risk of this is tying the user interface to the intermediate representation. For now we avoid this at the cost of some code duplication. Args: backend (Backend): Input backend to use in builder. If not set certain functionality will be unavailable. block: Initital ``ScheduleBlock`` to build on. name: Name of pulse program to be built. default_alignment: Default scheduling alignment for builder. One of ``left``, ``right``, ``sequential`` or an instance of :class:`~qiskit.pulse.transforms.alignments.AlignmentKind` subclass. default_transpiler_settings: Default settings for the transpiler. default_circuit_scheduler_settings: Default settings for the circuit to pulse scheduler. Raises: PulseError: When invalid ``default_alignment`` or `block` is specified. """ #: Backend: Backend instance for context builder. self._backend = backend #: Union[None, ContextVar]: Token for this ``_PulseBuilder``'s ``ContextVar``. self._backend_ctx_token = None #: QuantumCircuit: Lazily constructed quantum circuit self._lazy_circuit = None #: Dict[str, Any]: Transpiler setting dictionary. self._transpiler_settings = default_transpiler_settings or {} #: Dict[str, Any]: Scheduler setting dictionary. self._circuit_scheduler_settings = default_circuit_scheduler_settings or {} #: List[ScheduleBlock]: Stack of context. self._context_stack = [] #: str: Name of the output program self._name = name # Add root block if provided. Schedule will be built on top of this. if block is not None: if isinstance(block, ScheduleBlock): root_block = block elif isinstance(block, Schedule): root_block = self._naive_typecast_schedule(block) else: raise exceptions.PulseError( f"Input `block` type {block.__class__.__name__} is " "not a valid format. Specify a pulse program." ) self._context_stack.append(root_block) # Set default alignment context alignment = _PulseBuilder.__alignment_kinds__.get(default_alignment, default_alignment) if not isinstance(alignment, AlignmentKind): raise exceptions.PulseError( f"Given `default_alignment` {repr(default_alignment)} is " "not a valid transformation. Set one of " f'{", ".join(_PulseBuilder.__alignment_kinds__.keys())}, ' "or set an instance of `AlignmentKind` subclass." ) self.push_context(alignment) def __enter__(self) -> ScheduleBlock: """Enter this builder context and yield either the supplied schedule or the schedule created for the user. Returns: The schedule that the builder will build on. """ self._backend_ctx_token = BUILDER_CONTEXTVAR.set(self) output = self._context_stack[0] output._name = self._name or output.name return output @_compile_lazy_circuit_before def __exit__(self, exc_type, exc_val, exc_tb): """Exit the builder context and compile the built pulse program.""" self.compile() BUILDER_CONTEXTVAR.reset(self._backend_ctx_token) @property def backend(self): """Returns the builder backend if set. Returns: Optional[Backend]: The builder's backend. """ return self._backend @_compile_lazy_circuit_before def push_context(self, alignment: AlignmentKind): """Push new context to the stack.""" self._context_stack.append(ScheduleBlock(alignment_context=alignment)) @_compile_lazy_circuit_before def pop_context(self) -> ScheduleBlock: """Pop the last context from the stack.""" if len(self._context_stack) == 1: raise exceptions.PulseError("The root context cannot be popped out.") return self._context_stack.pop() def get_context(self) -> ScheduleBlock: """Get current context. Notes: New instruction can be added by `.append_subroutine` or `.append_instruction` method. Use above methods rather than directly accessing to the current context. """ return self._context_stack[-1] @property @_requires_backend def num_qubits(self): """Get the number of qubits in the backend.""" # backendV2 if isinstance(self.backend, BackendV2): return self.backend.num_qubits return self.backend.configuration().n_qubits @property def transpiler_settings(self) -> Mapping: """The builder's transpiler settings.""" return self._transpiler_settings @transpiler_settings.setter @_compile_lazy_circuit_before def transpiler_settings(self, settings: Mapping): self._compile_lazy_circuit() self._transpiler_settings = settings @property def circuit_scheduler_settings(self) -> Mapping: """The builder's circuit to pulse scheduler settings.""" return self._circuit_scheduler_settings @circuit_scheduler_settings.setter @_compile_lazy_circuit_before def circuit_scheduler_settings(self, settings: Mapping): self._compile_lazy_circuit() self._circuit_scheduler_settings = settings @_compile_lazy_circuit_before def compile(self) -> ScheduleBlock: """Compile and output the built pulse program.""" # Not much happens because we currently compile as we build. # This should be offloaded to a true compilation module # once we define a more sophisticated IR. while len(self._context_stack) > 1: current = self.pop_context() self.append_subroutine(current) return self._context_stack[0] def _compile_lazy_circuit(self): """Call a context QuantumCircuit (lazy circuit) and append the output pulse schedule to the builder's context schedule. Note that the lazy circuit is not stored as a call instruction. """ if self._lazy_circuit: lazy_circuit = self._lazy_circuit # reset lazy circuit self._lazy_circuit = self._new_circuit() self.call_subroutine(self._compile_circuit(lazy_circuit)) def _compile_circuit(self, circ) -> Schedule: """Take a QuantumCircuit and output the pulse schedule associated with the circuit.""" from qiskit import compiler # pylint: disable=cyclic-import transpiled_circuit = compiler.transpile(circ, self.backend, **self.transpiler_settings) sched = compiler.schedule( transpiled_circuit, self.backend, **self.circuit_scheduler_settings ) return sched def _new_circuit(self): """Create a new circuit for lazy circuit scheduling.""" return circuit.QuantumCircuit(self.num_qubits) @_compile_lazy_circuit_before def append_instruction(self, instruction: instructions.Instruction): """Add an instruction to the builder's context schedule. Args: instruction: Instruction to append. """ self._context_stack[-1].append(instruction) def append_reference(self, name: str, *extra_keys: str): """Add external program as a :class:`~qiskit.pulse.instructions.Reference` instruction. Args: name: Name of subroutine. extra_keys: Assistance keys to uniquely specify the subroutine. """ inst = instructions.Reference(name, *extra_keys) self.append_instruction(inst) @_compile_lazy_circuit_before def append_subroutine(self, subroutine: Union[Schedule, ScheduleBlock]): """Append a :class:`ScheduleBlock` to the builder's context schedule. This operation doesn't create a reference. Subroutine is directly appended to current context schedule. Args: subroutine: ScheduleBlock to append to the current context block. Raises: PulseError: When subroutine is not Schedule nor ScheduleBlock. """ if not isinstance(subroutine, (ScheduleBlock, Schedule)): raise exceptions.PulseError( f"'{subroutine.__class__.__name__}' is not valid data format in the builder. " "'Schedule' and 'ScheduleBlock' can be appended to the builder context." ) if len(subroutine) == 0: return if isinstance(subroutine, Schedule): subroutine = self._naive_typecast_schedule(subroutine) self._context_stack[-1].append(subroutine) @singledispatchmethod def call_subroutine( self, subroutine: Union[circuit.QuantumCircuit, Schedule, ScheduleBlock], name: Optional[str] = None, value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None, **kw_params: ParameterValueType, ): """Call a schedule or circuit defined outside of the current scope. The ``subroutine`` is appended to the context schedule as a call instruction. This logic just generates a convenient program representation in the compiler. Thus, this doesn't affect execution of inline subroutines. See :class:`~pulse.instructions.Call` for more details. Args: subroutine: Target schedule or circuit to append to the current context. name: Name of subroutine if defined. value_dict: Parameter object and assigned value mapping. This is more precise way to identify a parameter since mapping is managed with unique object id rather than name. Especially there is any name collision in a parameter table. kw_params: Parameter values to bind to the target subroutine with string parameter names. If there are parameter name overlapping, these parameters are updated with the same assigned value. Raises: PulseError: - When input subroutine is not valid data format. """ raise exceptions.PulseError( f"Subroutine type {subroutine.__class__.__name__} is " "not valid data format. Call QuantumCircuit, " "Schedule, or ScheduleBlock." ) @call_subroutine.register def _( self, target_block: ScheduleBlock, name: Optional[str] = None, value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None, **kw_params: ParameterValueType, ): if len(target_block) == 0: return # Create local parameter assignment local_assignment = {} for param_name, value in kw_params.items(): params = target_block.get_parameters(param_name) if not params: raise exceptions.PulseError( f"Parameter {param_name} is not defined in the target subroutine. " f'{", ".join(map(str, target_block.parameters))} can be specified.' ) for param in params: local_assignment[param] = value if value_dict: if local_assignment.keys() & value_dict.keys(): warnings.warn( "Some parameters provided by 'value_dict' conflict with one through " "keyword arguments. Parameter values in the keyword arguments " "are overridden by the dictionary values.", UserWarning, ) local_assignment.update(value_dict) if local_assignment: target_block = target_block.assign_parameters(local_assignment, inplace=False) if name is None: # Add unique string, not to accidentally override existing reference entry. keys = (target_block.name, uuid.uuid4().hex) else: keys = (name,) self.append_reference(*keys) self.get_context().assign_references({keys: target_block}, inplace=True) @call_subroutine.register def _( self, target_schedule: Schedule, name: Optional[str] = None, value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None, **kw_params: ParameterValueType, ): if len(target_schedule) == 0: return self.call_subroutine( self._naive_typecast_schedule(target_schedule), name=name, value_dict=value_dict, **kw_params, ) @call_subroutine.register def _( self, target_circuit: circuit.QuantumCircuit, name: Optional[str] = None, value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None, **kw_params: ParameterValueType, ): if len(target_circuit) == 0: return self._compile_lazy_circuit() self.call_subroutine( self._compile_circuit(target_circuit), name=name, value_dict=value_dict, **kw_params, ) @_requires_backend def call_gate(self, gate: circuit.Gate, qubits: Tuple[int, ...], lazy: bool = True): """Call the circuit ``gate`` in the pulse program. The qubits are assumed to be defined on physical qubits. If ``lazy == True`` this circuit will extend a lazily constructed quantum circuit. When an operation occurs that breaks the underlying circuit scheduling assumptions such as adding a pulse instruction or changing the alignment context the circuit will be transpiled and scheduled into pulses with the current active settings. Args: gate: Gate to call. qubits: Qubits to call gate on. lazy: If false the circuit will be transpiled and pulse scheduled immediately. Otherwise, it will extend the active lazy circuit as defined above. """ try: iter(qubits) except TypeError: qubits = (qubits,) if lazy: self._call_gate(gate, qubits) else: self._compile_lazy_circuit() self._call_gate(gate, qubits) self._compile_lazy_circuit() def _call_gate(self, gate, qargs): if self._lazy_circuit is None: self._lazy_circuit = self._new_circuit() self._lazy_circuit.append(gate, qargs=qargs) @staticmethod def _naive_typecast_schedule(schedule: Schedule): # Naively convert into ScheduleBlock from qiskit.pulse.transforms import inline_subroutines, flatten, pad preprocessed_schedule = inline_subroutines(flatten(schedule)) pad(preprocessed_schedule, inplace=True, pad_with=instructions.TimeBlockade) # default to left alignment, namely ASAP scheduling target_block = ScheduleBlock(name=schedule.name) for _, inst in preprocessed_schedule.instructions: target_block.append(inst, inplace=True) return target_block def get_dt(self): """Retrieve dt differently based on the type of Backend""" if isinstance(self.backend, BackendV2): return self.backend.dt return self.backend.configuration().dt def build( backend=None, schedule: Optional[ScheduleBlock] = None, name: Optional[str] = None, default_alignment: Optional[Union[str, AlignmentKind]] = "left", default_transpiler_settings: Optional[Dict[str, Any]] = None, default_circuit_scheduler_settings: Optional[Dict[str, Any]] = None, ) -> ContextManager[ScheduleBlock]: """Create a context manager for launching the imperative pulse builder DSL. To enter a building context and starting building a pulse program: .. code-block:: from qiskit import execute, pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.play(pulse.Constant(100, 0.5), d0) While the output program ``pulse_prog`` cannot be executed as we are using a mock backend. If a real backend is being used, executing the program is done with: .. code-block:: python qiskit.execute(pulse_prog, backend) Args: backend (Backend): A Qiskit backend. If not supplied certain builder functionality will be unavailable. schedule: A pulse ``ScheduleBlock`` in which your pulse program will be built. name: Name of pulse program to be built. default_alignment: Default scheduling alignment for builder. One of ``left``, ``right``, ``sequential`` or an alignment context. default_transpiler_settings: Default settings for the transpiler. default_circuit_scheduler_settings: Default settings for the circuit to pulse scheduler. Returns: A new builder context which has the active builder initialized. """ return _PulseBuilder( backend=backend, block=schedule, name=name, default_alignment=default_alignment, default_transpiler_settings=default_transpiler_settings, default_circuit_scheduler_settings=default_circuit_scheduler_settings, ) # Builder Utilities def _active_builder() -> _PulseBuilder: """Get the active builder in the active context. Returns: The active active builder in this context. Raises: exceptions.NoActiveBuilder: If a pulse builder function is called outside of a builder context. """ try: return BUILDER_CONTEXTVAR.get() except LookupError as ex: raise exceptions.NoActiveBuilder( "A Pulse builder function was called outside of " "a builder context. Try calling within a builder " 'context, eg., "with pulse.build() as schedule: ...".' ) from ex def active_backend(): """Get the backend of the currently active builder context. Returns: Backend: The active backend in the currently active builder context. Raises: exceptions.BackendNotSet: If the builder does not have a backend set. """ builder = _active_builder().backend if builder is None: raise exceptions.BackendNotSet( 'This function requires the active builder to have a "backend" set.' ) return builder def append_schedule(schedule: Union[Schedule, ScheduleBlock]): """Call a schedule by appending to the active builder's context block. Args: schedule: Schedule or ScheduleBlock to append. """ _active_builder().append_subroutine(schedule) def append_instruction(instruction: instructions.Instruction): """Append an instruction to the active builder's context schedule. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.builder.append_instruction(pulse.Delay(10, d0)) print(pulse_prog.instructions) .. parsed-literal:: ((0, Delay(10, DriveChannel(0))),) """ _active_builder().append_instruction(instruction) def num_qubits() -> int: """Return number of qubits in the currently active backend. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): print(pulse.num_qubits()) .. parsed-literal:: 2 .. note:: Requires the active builder context to have a backend set. """ if isinstance(active_backend(), BackendV2): return active_backend().num_qubits return active_backend().configuration().n_qubits def seconds_to_samples(seconds: Union[float, np.ndarray]) -> Union[int, np.ndarray]: """Obtain the number of samples that will elapse in ``seconds`` on the active backend. Rounds down. Args: seconds: Time in seconds to convert to samples. Returns: The number of samples for the time to elapse """ dt = _active_builder().get_dt() if isinstance(seconds, np.ndarray): return (seconds / dt).astype(int) return int(seconds / dt) def samples_to_seconds(samples: Union[int, np.ndarray]) -> Union[float, np.ndarray]: """Obtain the time in seconds that will elapse for the input number of samples on the active backend. Args: samples: Number of samples to convert to time in seconds. Returns: The time that elapses in ``samples``. """ return samples * _active_builder().get_dt() def qubit_channels(qubit: int) -> Set[chans.Channel]: """Returns the set of channels associated with a qubit. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): print(pulse.qubit_channels(0)) .. parsed-literal:: {MeasureChannel(0), ControlChannel(0), DriveChannel(0), AcquireChannel(0), ControlChannel(1)} .. note:: Requires the active builder context to have a backend set. .. note:: A channel may still be associated with another qubit in this list such as in the case where significant crosstalk exists. """ # implement as the inner function to avoid API change for a patch release in 0.24.2. def get_qubit_channels_v2(backend: BackendV2, qubit: int): r"""Return a list of channels which operate on the given ``qubit``. Returns: List of ``Channel``\s operated on my the given ``qubit``. """ channels = [] # add multi-qubit channels for node_qubits in backend.coupling_map: if qubit in node_qubits: control_channel = backend.control_channel(node_qubits) if control_channel: channels.extend(control_channel) # add single qubit channels channels.append(backend.drive_channel(qubit)) channels.append(backend.measure_channel(qubit)) channels.append(backend.acquire_channel(qubit)) return channels # backendV2 if isinstance(active_backend(), BackendV2): return set(get_qubit_channels_v2(active_backend(), qubit)) return set(active_backend().configuration().get_qubit_channels(qubit)) def _qubits_to_channels(*channels_or_qubits: Union[int, chans.Channel]) -> Set[chans.Channel]: """Returns the unique channels of the input qubits.""" channels = set() for channel_or_qubit in channels_or_qubits: if isinstance(channel_or_qubit, int): channels |= qubit_channels(channel_or_qubit) elif isinstance(channel_or_qubit, chans.Channel): channels.add(channel_or_qubit) else: raise exceptions.PulseError( f'{channel_or_qubit} is not a "Channel" or qubit (integer).' ) return channels def active_transpiler_settings() -> Dict[str, Any]: """Return the current active builder context's transpiler settings. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() transpiler_settings = {'optimization_level': 3} with pulse.build(backend, default_transpiler_settings=transpiler_settings): print(pulse.active_transpiler_settings()) .. parsed-literal:: {'optimization_level': 3} """ return dict(_active_builder().transpiler_settings) def active_circuit_scheduler_settings() -> Dict[str, Any]: """Return the current active builder context's circuit scheduler settings. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() circuit_scheduler_settings = {'method': 'alap'} with pulse.build( backend, default_circuit_scheduler_settings=circuit_scheduler_settings): print(pulse.active_circuit_scheduler_settings()) .. parsed-literal:: {'method': 'alap'} """ return dict(_active_builder().circuit_scheduler_settings) # Contexts @contextmanager def align_left() -> ContextManager[None]: """Left alignment pulse scheduling context. Pulse instructions within this context are scheduled as early as possible by shifting them left to the earliest available time. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_left(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will start at t=0 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog = pulse.transforms.block_to_schedule(pulse_prog) assert pulse_prog.ch_start_time(d0) == pulse_prog.ch_start_time(d1) Yields: None """ builder = _active_builder() builder.push_context(transforms.AlignLeft()) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def align_right() -> AlignmentKind: """Right alignment pulse scheduling context. Pulse instructions within this context are scheduled as late as possible by shifting them right to the latest available time. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_right(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will start at t=80 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog = pulse.transforms.block_to_schedule(pulse_prog) assert pulse_prog.ch_stop_time(d0) == pulse_prog.ch_stop_time(d1) Yields: None """ builder = _active_builder() builder.push_context(transforms.AlignRight()) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def align_sequential() -> AlignmentKind: """Sequential alignment pulse scheduling context. Pulse instructions within this context are scheduled sequentially in time such that no two instructions will be played at the same time. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_sequential(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will also start at t=100 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog = pulse.transforms.block_to_schedule(pulse_prog) assert pulse_prog.ch_stop_time(d0) == pulse_prog.ch_start_time(d1) Yields: None """ builder = _active_builder() builder.push_context(transforms.AlignSequential()) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def align_equispaced(duration: Union[int, ParameterExpression]) -> AlignmentKind: """Equispaced alignment pulse scheduling context. Pulse instructions within this context are scheduled with the same interval spacing such that the total length of the context block is ``duration``. If the total free ``duration`` cannot be evenly divided by the number of instructions within the context, the modulo is split and then prepended and appended to the returned schedule. Delay instructions are automatically inserted in between pulses. This context is convenient to write a schedule for periodical dynamic decoupling or the Hahn echo sequence. Examples: .. plot:: :include-source: from qiskit import pulse d0 = pulse.DriveChannel(0) x90 = pulse.Gaussian(10, 0.1, 3) x180 = pulse.Gaussian(10, 0.2, 3) with pulse.build() as hahn_echo: with pulse.align_equispaced(duration=100): pulse.play(x90, d0) pulse.play(x180, d0) pulse.play(x90, d0) hahn_echo.draw() Args: duration: Duration of this context. This should be larger than the schedule duration. Yields: None Notes: The scheduling is performed for sub-schedules within the context rather than channel-wise. If you want to apply the equispaced context for each channel, you should use the context independently for channels. """ builder = _active_builder() builder.push_context(transforms.AlignEquispaced(duration=duration)) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def align_func( duration: Union[int, ParameterExpression], func: Callable[[int], float] ) -> AlignmentKind: """Callback defined alignment pulse scheduling context. Pulse instructions within this context are scheduled at the location specified by arbitrary callback function `position` that takes integer index and returns the associated fractional location within [0, 1]. Delay instruction is automatically inserted in between pulses. This context may be convenient to write a schedule of arbitrary dynamical decoupling sequences such as Uhrig dynamical decoupling. Examples: .. plot:: :include-source: import numpy as np from qiskit import pulse d0 = pulse.DriveChannel(0) x90 = pulse.Gaussian(10, 0.1, 3) x180 = pulse.Gaussian(10, 0.2, 3) def udd10_pos(j): return np.sin(np.pi*j/(2*10 + 2))**2 with pulse.build() as udd_sched: pulse.play(x90, d0) with pulse.align_func(duration=300, func=udd10_pos): for _ in range(10): pulse.play(x180, d0) pulse.play(x90, d0) udd_sched.draw() Args: duration: Duration of context. This should be larger than the schedule duration. func: A function that takes an index of sub-schedule and returns the fractional coordinate of of that sub-schedule. The returned value should be defined within [0, 1]. The pulse index starts from 1. Yields: None Notes: The scheduling is performed for sub-schedules within the context rather than channel-wise. If you want to apply the numerical context for each channel, you need to apply the context independently to channels. """ builder = _active_builder() builder.push_context(transforms.AlignFunc(duration=duration, func=func)) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def general_transforms(alignment_context: AlignmentKind) -> ContextManager[None]: """Arbitrary alignment transformation defined by a subclass instance of :class:`~qiskit.pulse.transforms.alignments.AlignmentKind`. Args: alignment_context: Alignment context instance that defines schedule transformation. Yields: None Raises: PulseError: When input ``alignment_context`` is not ``AlignmentKind`` subclasses. """ if not isinstance(alignment_context, AlignmentKind): raise exceptions.PulseError("Input alignment context is not `AlignmentKind` subclass.") builder = _active_builder() builder.push_context(alignment_context) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def transpiler_settings(**settings) -> ContextManager[None]: """Set the currently active transpiler settings for this context. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): print(pulse.active_transpiler_settings()) with pulse.transpiler_settings(optimization_level=3): print(pulse.active_transpiler_settings()) .. parsed-literal:: {} {'optimization_level': 3} """ builder = _active_builder() curr_transpiler_settings = builder.transpiler_settings builder.transpiler_settings = collections.ChainMap(settings, curr_transpiler_settings) try: yield finally: builder.transpiler_settings = curr_transpiler_settings @contextmanager def circuit_scheduler_settings(**settings) -> ContextManager[None]: """Set the currently active circuit scheduler settings for this context. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): print(pulse.active_circuit_scheduler_settings()) with pulse.circuit_scheduler_settings(method='alap'): print(pulse.active_circuit_scheduler_settings()) .. parsed-literal:: {} {'method': 'alap'} """ builder = _active_builder() curr_circuit_scheduler_settings = builder.circuit_scheduler_settings builder.circuit_scheduler_settings = collections.ChainMap( settings, curr_circuit_scheduler_settings ) try: yield finally: builder.circuit_scheduler_settings = curr_circuit_scheduler_settings @contextmanager def phase_offset(phase: float, *channels: chans.PulseChannel) -> ContextManager[None]: """Shift the phase of input channels on entry into context and undo on exit. Examples: .. code-block:: import math from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: with pulse.phase_offset(math.pi, d0): pulse.play(pulse.Constant(10, 1.0), d0) assert len(pulse_prog.instructions) == 3 Args: phase: Amount of phase offset in radians. channels: Channels to offset phase of. Yields: None """ for channel in channels: shift_phase(phase, channel) try: yield finally: for channel in channels: shift_phase(-phase, channel) @contextmanager def frequency_offset( frequency: float, *channels: chans.PulseChannel, compensate_phase: bool = False ) -> ContextManager[None]: """Shift the frequency of inputs channels on entry into context and undo on exit. Examples: .. code-block:: python :emphasize-lines: 7, 16 from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build(backend) as pulse_prog: # shift frequency by 1GHz with pulse.frequency_offset(1e9, d0): pulse.play(pulse.Constant(10, 1.0), d0) assert len(pulse_prog.instructions) == 3 with pulse.build(backend) as pulse_prog: # Shift frequency by 1GHz. # Undo accumulated phase in the shifted frequency frame # when exiting the context. with pulse.frequency_offset(1e9, d0, compensate_phase=True): pulse.play(pulse.Constant(10, 1.0), d0) assert len(pulse_prog.instructions) == 4 Args: frequency: Amount of frequency offset in Hz. channels: Channels to offset frequency of. compensate_phase: Compensate for accumulated phase accumulated with respect to the channels' frame at its initial frequency. Yields: None """ builder = _active_builder() # TODO: Need proper implementation of compensation. t0 may depend on the parent context. # For example, the instruction position within the equispaced context depends on # the current total number of instructions, thus adding more instruction after # offset context may change the t0 when the parent context is transformed. t0 = builder.get_context().duration for channel in channels: shift_frequency(frequency, channel) try: yield finally: if compensate_phase: duration = builder.get_context().duration - t0 accumulated_phase = 2 * np.pi * ((duration * builder.get_dt() * frequency) % 1) for channel in channels: shift_phase(-accumulated_phase, channel) for channel in channels: shift_frequency(-frequency, channel) # Channels def drive_channel(qubit: int) -> chans.DriveChannel: """Return ``DriveChannel`` for ``qubit`` on the active builder backend. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): assert pulse.drive_channel(0) == pulse.DriveChannel(0) .. note:: Requires the active builder context to have a backend set. """ # backendV2 if isinstance(active_backend(), BackendV2): return active_backend().drive_channel(qubit) return active_backend().configuration().drive(qubit) def measure_channel(qubit: int) -> chans.MeasureChannel: """Return ``MeasureChannel`` for ``qubit`` on the active builder backend. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): assert pulse.measure_channel(0) == pulse.MeasureChannel(0) .. note:: Requires the active builder context to have a backend set. """ # backendV2 if isinstance(active_backend(), BackendV2): return active_backend().measure_channel(qubit) return active_backend().configuration().measure(qubit) def acquire_channel(qubit: int) -> chans.AcquireChannel: """Return ``AcquireChannel`` for ``qubit`` on the active builder backend. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): assert pulse.acquire_channel(0) == pulse.AcquireChannel(0) .. note:: Requires the active builder context to have a backend set. """ # backendV2 if isinstance(active_backend(), BackendV2): return active_backend().acquire_channel(qubit) return active_backend().configuration().acquire(qubit) def control_channels(*qubits: Iterable[int]) -> List[chans.ControlChannel]: """Return ``ControlChannel`` for ``qubit`` on the active builder backend. Return the secondary drive channel for the given qubit -- typically utilized for controlling multi-qubit interactions. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): assert pulse.control_channels(0, 1) == [pulse.ControlChannel(0)] .. note:: Requires the active builder context to have a backend set. Args: qubits: Tuple or list of ordered qubits of the form `(control_qubit, target_qubit)`. Returns: List of control channels associated with the supplied ordered list of qubits. """ # backendV2 if isinstance(active_backend(), BackendV2): return active_backend().control_channel(qubits) return active_backend().configuration().control(qubits=qubits) # Base Instructions def delay(duration: int, channel: chans.Channel, name: Optional[str] = None): """Delay on a ``channel`` for a ``duration``. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.delay(10, d0) Args: duration: Number of cycles to delay for on ``channel``. channel: Channel to delay on. name: Name of the instruction. """ append_instruction(instructions.Delay(duration, channel, name=name)) def play( pulse: Union[library.Pulse, np.ndarray], channel: chans.PulseChannel, name: Optional[str] = None ): """Play a ``pulse`` on a ``channel``. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.play(pulse.Constant(10, 1.0), d0) Args: pulse: Pulse to play. channel: Channel to play pulse on. name: Name of the pulse. """ if not isinstance(pulse, library.Pulse): pulse = library.Waveform(pulse) append_instruction(instructions.Play(pulse, channel, name=name)) def acquire( duration: int, qubit_or_channel: Union[int, chans.AcquireChannel], register: StorageLocation, **metadata: Union[configuration.Kernel, configuration.Discriminator], ): """Acquire for a ``duration`` on a ``channel`` and store the result in a ``register``. Examples: .. code-block:: from qiskit import pulse acq0 = pulse.AcquireChannel(0) mem0 = pulse.MemorySlot(0) with pulse.build() as pulse_prog: pulse.acquire(100, acq0, mem0) # measurement metadata kernel = pulse.configuration.Kernel('linear_discriminator') pulse.acquire(100, acq0, mem0, kernel=kernel) .. note:: The type of data acquire will depend on the execution ``meas_level``. Args: duration: Duration to acquire data for qubit_or_channel: Either the qubit to acquire data for or the specific :class:`~qiskit.pulse.channels.AcquireChannel` to acquire on. register: Location to store measured result. metadata: Additional metadata for measurement. See :class:`~qiskit.pulse.instructions.Acquire` for more information. Raises: exceptions.PulseError: If the register type is not supported. """ if isinstance(qubit_or_channel, int): qubit_or_channel = chans.AcquireChannel(qubit_or_channel) if isinstance(register, chans.MemorySlot): append_instruction( instructions.Acquire(duration, qubit_or_channel, mem_slot=register, **metadata) ) elif isinstance(register, chans.RegisterSlot): append_instruction( instructions.Acquire(duration, qubit_or_channel, reg_slot=register, **metadata) ) else: raise exceptions.PulseError(f'Register of type: "{type(register)}" is not supported') def set_frequency(frequency: float, channel: chans.PulseChannel, name: Optional[str] = None): """Set the ``frequency`` of a pulse ``channel``. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.set_frequency(1e9, d0) Args: frequency: Frequency in Hz to set channel to. channel: Channel to set frequency of. name: Name of the instruction. """ append_instruction(instructions.SetFrequency(frequency, channel, name=name)) def shift_frequency(frequency: float, channel: chans.PulseChannel, name: Optional[str] = None): """Shift the ``frequency`` of a pulse ``channel``. Examples: .. code-block:: python :emphasize-lines: 6 from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.shift_frequency(1e9, d0) Args: frequency: Frequency in Hz to shift channel frequency by. channel: Channel to shift frequency of. name: Name of the instruction. """ append_instruction(instructions.ShiftFrequency(frequency, channel, name=name)) def set_phase(phase: float, channel: chans.PulseChannel, name: Optional[str] = None): """Set the ``phase`` of a pulse ``channel``. Examples: .. code-block:: python :emphasize-lines: 8 import math from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.set_phase(math.pi, d0) Args: phase: Phase in radians to set channel carrier signal to. channel: Channel to set phase of. name: Name of the instruction. """ append_instruction(instructions.SetPhase(phase, channel, name=name)) def shift_phase(phase: float, channel: chans.PulseChannel, name: Optional[str] = None): """Shift the ``phase`` of a pulse ``channel``. Examples: .. code-block:: import math from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.shift_phase(math.pi, d0) Args: phase: Phase in radians to shift channel carrier signal by. channel: Channel to shift phase of. name: Name of the instruction. """ append_instruction(instructions.ShiftPhase(phase, channel, name)) def snapshot(label: str, snapshot_type: str = "statevector"): """Simulator snapshot. Examples: .. code-block:: from qiskit import pulse with pulse.build() as pulse_prog: pulse.snapshot('first', 'statevector') Args: label: Label for snapshot. snapshot_type: Type of snapshot. """ append_instruction(instructions.Snapshot(label, snapshot_type=snapshot_type)) def call( target: Optional[Union[circuit.QuantumCircuit, Schedule, ScheduleBlock]], name: Optional[str] = None, value_dict: Optional[Dict[ParameterValueType, ParameterValueType]] = None, **kw_params: ParameterValueType, ): """Call the subroutine within the currently active builder context with arbitrary parameters which will be assigned to the target program. .. note:: If the ``target`` program is a :class:`.ScheduleBlock`, then a :class:`.Reference` instruction will be created and appended to the current context. The ``target`` program will be immediately assigned to the current scope as a subroutine. If the ``target`` program is :class:`.Schedule`, it will be wrapped by the :class:`.Call` instruction and appended to the current context to avoid a mixed representation of :class:`.ScheduleBlock` and :class:`.Schedule`. If the ``target`` program is a :class:`.QuantumCircuit` it will be scheduled and the new :class:`.Schedule` will be added as a :class:`.Call` instruction. Examples: 1. Calling a schedule block (recommended) .. code-block:: from qiskit import circuit, pulse from qiskit.providers.fake_provider import FakeBogotaV2 backend = FakeBogotaV2() with pulse.build() as x_sched: pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0)) with pulse.build() as pulse_prog: pulse.call(x_sched) print(pulse_prog) .. parsed-literal:: ScheduleBlock( ScheduleBlock( Play( Gaussian(duration=160, amp=(0.1+0j), sigma=40), DriveChannel(0) ), name="block0", transform=AlignLeft() ), name="block1", transform=AlignLeft() ) The actual program is stored in the reference table attached to the schedule. .. code-block:: print(pulse_prog.references) .. parsed-literal:: ReferenceManager: - ('block0', '634b3b50bd684e26a673af1fbd2d6c81'): ScheduleBlock(Play(Gaussian(... In addition, you can call a parameterized target program with parameter assignment. .. code-block:: amp = circuit.Parameter("amp") with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0)) with pulse.build() as pulse_prog: pulse.call(subroutine, amp=0.1) pulse.call(subroutine, amp=0.3) print(pulse_prog) .. parsed-literal:: ScheduleBlock( ScheduleBlock( Play( Gaussian(duration=160, amp=(0.1+0j), sigma=40), DriveChannel(0) ), name="block2", transform=AlignLeft() ), ScheduleBlock( Play( Gaussian(duration=160, amp=(0.3+0j), sigma=40), DriveChannel(0) ), name="block2", transform=AlignLeft() ), name="block3", transform=AlignLeft() ) If there is a name collision between parameters, you can distinguish them by specifying each parameter object in a python dictionary. For example, .. code-block:: amp1 = circuit.Parameter('amp') amp2 = circuit.Parameter('amp') with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, amp1, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, amp2, 40), pulse.DriveChannel(1)) with pulse.build() as pulse_prog: pulse.call(subroutine, value_dict={amp1: 0.1, amp2: 0.3}) print(pulse_prog) .. parsed-literal:: ScheduleBlock( ScheduleBlock( Play(Gaussian(duration=160, amp=(0.1+0j), sigma=40), DriveChannel(0)), Play(Gaussian(duration=160, amp=(0.3+0j), sigma=40), DriveChannel(1)), name="block4", transform=AlignLeft() ), name="block5", transform=AlignLeft() ) 2. Calling a schedule .. code-block:: x_sched = backend.instruction_schedule_map.get("x", (0,)) with pulse.build(backend) as pulse_prog: pulse.call(x_sched) print(pulse_prog) .. parsed-literal:: ScheduleBlock( Call( Schedule( ( 0, Play( Drag( duration=160, amp=(0.18989731546729305+0j), sigma=40, beta=-1.201258305015517, name='drag_86a8' ), DriveChannel(0), name='drag_86a8' ) ), name="x" ), name='x' ), name="block6", transform=AlignLeft() ) Currently, the backend calibrated gates are provided in the form of :class:`~.Schedule`. The parameter assignment mechanism is available also for schedules. However, the called schedule is not treated as a reference. 3. Calling a quantum circuit .. code-block:: backend = FakeBogotaV2() qc = circuit.QuantumCircuit(1) qc.x(0) with pulse.build(backend) as pulse_prog: pulse.call(qc) print(pulse_prog) .. parsed-literal:: ScheduleBlock( Call( Schedule( ( 0, Play( Drag( duration=160, amp=(0.18989731546729305+0j), sigma=40, beta=-1.201258305015517, name='drag_86a8' ), DriveChannel(0), name='drag_86a8' ) ), name="circuit-87" ), name='circuit-87' ), name="block7", transform=AlignLeft() ) .. warning:: Calling a circuit from a schedule is not encouraged. Currently, the Qiskit execution model is migrating toward the pulse gate model, where schedules are attached to circuits through the :meth:`.QuantumCircuit.add_calibration` method. Args: target: Target circuit or pulse schedule to call. name: Optional. A unique name of subroutine if defined. When the name is explicitly provided, one cannot call different schedule blocks with the same name. value_dict: Optional. Parameters assigned to the ``target`` program. If this dictionary is provided, the ``target`` program is copied and then stored in the main built schedule and its parameters are assigned to the given values. This dictionary is keyed on :class:`~.Parameter` objects, allowing parameter name collision to be avoided. kw_params: Alternative way to provide parameters. Since this is keyed on the string parameter name, the parameters having the same name are all updated together. If you want to avoid name collision, use ``value_dict`` with :class:`~.Parameter` objects instead. """ _active_builder().call_subroutine(target, name, value_dict, **kw_params) def reference(name: str, *extra_keys: str): """Refer to undefined subroutine by string keys. A :class:`~qiskit.pulse.instructions.Reference` instruction is implicitly created and a schedule can be separately registered to the reference at a later stage. .. code-block:: python from qiskit import pulse with pulse.build() as main_prog: pulse.reference("x_gate", "q0") with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0)) main_prog.assign_references(subroutine_dict={("x_gate", "q0"): subroutine}) Args: name: Name of subroutine. extra_keys: Helper keys to uniquely specify the subroutine. """ _active_builder().append_reference(name, *extra_keys) # Directives def barrier(*channels_or_qubits: Union[chans.Channel, int], name: Optional[str] = None): """Barrier directive for a set of channels and qubits. This directive prevents the compiler from moving instructions across the barrier. Consider the case where we want to enforce that one pulse happens after another on separate channels, this can be done with: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build(backend) as barrier_pulse_prog: pulse.play(pulse.Constant(10, 1.0), d0) pulse.barrier(d0, d1) pulse.play(pulse.Constant(10, 1.0), d1) Of course this could have been accomplished with: .. code-block:: from qiskit.pulse import transforms with pulse.build(backend) as aligned_pulse_prog: with pulse.align_sequential(): pulse.play(pulse.Constant(10, 1.0), d0) pulse.play(pulse.Constant(10, 1.0), d1) barrier_pulse_prog = transforms.target_qobj_transform(barrier_pulse_prog) aligned_pulse_prog = transforms.target_qobj_transform(aligned_pulse_prog) assert barrier_pulse_prog == aligned_pulse_prog The barrier allows the pulse compiler to take care of more advanced scheduling alignment operations across channels. For example in the case where we are calling an outside circuit or schedule and want to align a pulse at the end of one call: .. code-block:: import math d0 = pulse.DriveChannel(0) with pulse.build(backend) as pulse_prog: with pulse.align_right(): pulse.x(1) # Barrier qubit 1 and d0. pulse.barrier(1, d0) # Due to barrier this will play before the gate on qubit 1. pulse.play(pulse.Constant(10, 1.0), d0) # This will end at the same time as the pulse above due to # the barrier. pulse.x(1) .. note:: Requires the active builder context to have a backend set if qubits are barriered on. Args: channels_or_qubits: Channels or qubits to barrier. name: Name for the barrier """ channels = _qubits_to_channels(*channels_or_qubits) if len(channels) > 1: append_instruction(directives.RelativeBarrier(*channels, name=name)) # Macros def macro(func: Callable): """Wrap a Python function and activate the parent builder context at calling time. This enables embedding Python functions as builder macros. This generates a new :class:`pulse.Schedule` that is embedded in the parent builder context with every call of the decorated macro function. The decorated macro function will behave as if the function code was embedded inline in the parent builder context after parameter substitution. Examples: .. plot:: :include-source: from qiskit import pulse @pulse.macro def measure(qubit: int): pulse.play(pulse.GaussianSquare(16384, 256, 15872), pulse.measure_channel(qubit)) mem_slot = pulse.MemorySlot(qubit) pulse.acquire(16384, pulse.acquire_channel(qubit), mem_slot) return mem_slot with pulse.build(backend=backend) as sched: mem_slot = measure(0) print(f"Qubit measured into {mem_slot}") sched.draw() Args: func: The Python function to enable as a builder macro. There are no requirements on the signature of the function, any calls to pulse builder methods will be added to builder context the wrapped function is called from. Returns: Callable: The wrapped ``func``. """ func_name = getattr(func, "__name__", repr(func)) @functools.wraps(func) def wrapper(*args, **kwargs): _builder = _active_builder() # activate the pulse builder before calling the function with build(backend=_builder.backend, name=func_name) as built: output = func(*args, **kwargs) _builder.call_subroutine(built) return output return wrapper def measure( qubits: Union[List[int], int], registers: Union[List[StorageLocation], StorageLocation] = None, ) -> Union[List[StorageLocation], StorageLocation]: """Measure a qubit within the currently active builder context. At the pulse level a measurement is composed of both a stimulus pulse and an acquisition instruction which tells the systems measurement unit to acquire data and process it. We provide this measurement macro to automate the process for you, but if desired full control is still available with :func:`acquire` and :func:`play`. To use the measurement it is as simple as specifying the qubit you wish to measure: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() qubit = 0 with pulse.build(backend) as pulse_prog: # Do something to the qubit. qubit_drive_chan = pulse.drive_channel(0) pulse.play(pulse.Constant(100, 1.0), qubit_drive_chan) # Measure the qubit. reg = pulse.measure(qubit) For now it is not possible to do much with the handle to ``reg`` but in the future we will support using this handle to a result register to build up ones program. It is also possible to supply this register: .. code-block:: with pulse.build(backend) as pulse_prog: pulse.play(pulse.Constant(100, 1.0), qubit_drive_chan) # Measure the qubit. mem0 = pulse.MemorySlot(0) reg = pulse.measure(qubit, mem0) assert reg == mem0 .. note:: Requires the active builder context to have a backend set. Args: qubits: Physical qubit to measure. registers: Register to store result in. If not selected the current behavior is to return the :class:`MemorySlot` with the same index as ``qubit``. This register will be returned. Returns: The ``register`` the qubit measurement result will be stored in. """ backend = active_backend() try: qubits = list(qubits) except TypeError: qubits = [qubits] if registers is None: registers = [chans.MemorySlot(qubit) for qubit in qubits] else: try: registers = list(registers) except TypeError: registers = [registers] measure_sched = macros.measure( qubits=qubits, backend=backend, qubit_mem_slots={qubit: register.index for qubit, register in zip(qubits, registers)}, ) # note this is not a subroutine. # just a macro to automate combination of stimulus and acquisition. # prepare unique reference name based on qubit and memory slot index. qubits_repr = "&".join(map(str, qubits)) mslots_repr = "&".join((str(r.index) for r in registers)) _active_builder().call_subroutine(measure_sched, name=f"measure_{qubits_repr}..{mslots_repr}") if len(qubits) == 1: return registers[0] else: return registers def measure_all() -> List[chans.MemorySlot]: r"""Measure all qubits within the currently active builder context. A simple macro function to measure all of the qubits in the device at the same time. This is useful for handling device ``meas_map`` and single measurement constraints. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: # Measure all qubits and return associated registers. regs = pulse.measure_all() .. note:: Requires the active builder context to have a backend set. Returns: The ``register``\s the qubit measurement results will be stored in. """ backend = active_backend() qubits = range(num_qubits()) registers = [chans.MemorySlot(qubit) for qubit in qubits] measure_sched = macros.measure( qubits=qubits, backend=backend, qubit_mem_slots={qubit: qubit for qubit in qubits}, ) # note this is not a subroutine. # just a macro to automate combination of stimulus and acquisition. _active_builder().call_subroutine(measure_sched, name="measure_all") return registers def delay_qubits(duration: int, *qubits: Union[int, Iterable[int]]): r"""Insert delays on all of the :class:`channels.Channel`\s that correspond to the input ``qubits`` at the same time. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse3Q backend = FakeOpenPulse3Q() with pulse.build(backend) as pulse_prog: # Delay for 100 cycles on qubits 0, 1 and 2. regs = pulse.delay_qubits(100, 0, 1, 2) .. note:: Requires the active builder context to have a backend set. Args: duration: Duration to delay for. qubits: Physical qubits to delay on. Delays will be inserted based on the channels returned by :func:`pulse.qubit_channels`. """ qubit_chans = set(itertools.chain.from_iterable(qubit_channels(qubit) for qubit in qubits)) with align_left(): for chan in qubit_chans: delay(duration, chan) # Gate instructions def call_gate(gate: circuit.Gate, qubits: Tuple[int, ...], lazy: bool = True): """Call a gate and lazily schedule it to its corresponding pulse instruction. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: from qiskit import pulse from qiskit.pulse import builder from qiskit.circuit.library import standard_gates as gates from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: builder.call_gate(gates.CXGate(), (0, 1)) We can see the role of the transpiler in scheduling gates by optimizing away two consecutive CNOT gates: .. code-block:: with pulse.build(backend) as pulse_prog: with pulse.transpiler_settings(optimization_level=3): builder.call_gate(gates.CXGate(), (0, 1)) builder.call_gate(gates.CXGate(), (0, 1)) assert pulse_prog == pulse.Schedule() .. note:: If multiple gates are called in a row they may be optimized by the transpiler, depending on the :func:`pulse.active_transpiler_settings``. .. note:: Requires the active builder context to have a backend set. Args: gate: Circuit gate instance to call. qubits: Qubits to call gate on. lazy: If ``false`` the gate will be compiled immediately, otherwise it will be added onto a lazily evaluated quantum circuit to be compiled when the builder is forced to by a circuit assumption being broken, such as the inclusion of a pulse instruction or new alignment context. """ _active_builder().call_gate(gate, qubits, lazy=lazy) def cx(control: int, target: int): # pylint: disable=invalid-name """Call a :class:`~qiskit.circuit.library.standard_gates.CXGate` on the input physical qubits. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: pulse.cx(0, 1) """ call_gate(gates.CXGate(), (control, target)) def u1(theta: float, qubit: int): # pylint: disable=invalid-name """Call a :class:`~qiskit.circuit.library.standard_gates.U1Gate` on the input physical qubit. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: import math from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: pulse.u1(math.pi, 1) """ call_gate(gates.U1Gate(theta), qubit) def u2(phi: float, lam: float, qubit: int): # pylint: disable=invalid-name """Call a :class:`~qiskit.circuit.library.standard_gates.U2Gate` on the input physical qubit. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: import math from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: pulse.u2(0, math.pi, 1) """ call_gate(gates.U2Gate(phi, lam), qubit) def u3(theta: float, phi: float, lam: float, qubit: int): # pylint: disable=invalid-name """Call a :class:`~qiskit.circuit.library.standard_gates.U3Gate` on the input physical qubit. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: import math from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: pulse.u3(math.pi, 0, math.pi, 1) """ call_gate(gates.U3Gate(theta, phi, lam), qubit) def x(qubit: int): """Call a :class:`~qiskit.circuit.library.standard_gates.XGate` on the input physical qubit. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: pulse.x(0) """ call_gate(gates.XGate(), qubit)
https://github.com/abbarreto/qiskit3
abbarreto
https://github.com/ichen17/Learning-Qiskit
ichen17
from qiskit import * from qiskit.tools.jupyter import * from qiskit import pulse from qiskit import IBMQ from qiskit.ignis.mitigation.measurement import (complete_meas_cal, tensored_meas_cal, CompleteMeasFitter, TensoredMeasFitter) IBMQ.save_account("26595118309e0ea848015d3f7458b040ec723a9c11afd2d777038533a5a2b8079312af1e3713e370053f85bf7dd5d77f72993b0f04c2cd561e4c31f5a40c910c") IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science') backend = provider.get_backend('ibmq_rome') backend_config = backend.configuration() assert backend_config.open_pulse, "Backend doesn't support Pulse" dt = backend_config.dt print(f"Sampling time: {dt*1e9} ns") backend_defaults = backend.defaults() import numpy as np # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz us = 1.0e-6 # Microseconds ns = 1.0e-9 # Nanoseconds # We will find the qubit frequency for the following qubit. #qubit = 0 frequencies_GHzs = [] for qubit in range(5): # The sweep will be centered around the estimated qubit frequency. center_frequency_Hz = backend_defaults.qubit_freq_est[qubit] # The default frequency is given in Hz # warning: this will change in a future release print(f"Qubit {qubit} has an estimated frequency of {center_frequency_Hz / GHz} GHz.") # scale factor to remove factors of 10 from the data scale_factor = 1e-14 # We will sweep 40 MHz around the estimated frequency frequency_span_Hz = 40 * MHz # in steps of 1 MHz. frequency_step_Hz = 1 * MHz # We will sweep 20 MHz above and 20 MHz below the estimated frequency frequency_min = center_frequency_Hz - frequency_span_Hz / 2 frequency_max = center_frequency_Hz + frequency_span_Hz / 2 # Construct an np array of the frequencies for our experiment frequencies_GHz = np.arange(frequency_min / GHz, frequency_max / GHz, frequency_step_Hz / GHz) frequencies_GHzs.append(frequencies_GHz) print(f"The sweep will go from {frequency_min / GHz} GHz to {frequency_max / GHz} GHz in steps of {frequency_step_Hz / MHz} MHz.") def get_closest_multiple_of_16(num): return int(num + 8 ) - (int(num + 8 ) % 16) from qiskit import pulse # This is where we access all of our Pulse features! from qiskit.pulse import Play # This Pulse module helps us build sampled pulses for common pulse shapes from qiskit.pulse import library as pulse_lib # Drive pulse parameters (us = microseconds) #drive_sigma_us = 0.004444 # This determines the actual width of the gaussian #0.0075 drive_sigma_us = 0.009 drive_samples_us = drive_sigma_us*8 # This is a truncating parameter, because gaussians don't have # a natural finite length drive_sigma = get_closest_multiple_of_16(drive_sigma_us * us /dt) # The width of the gaussian in units of dt drive_samples = get_closest_multiple_of_16(drive_samples_us * us /dt) # The truncating parameter in units of dt drive_amp = 0.05 # Drive pulse samples drive_pulse = pulse_lib.gaussian(duration=drive_samples, sigma=drive_sigma, amp=drive_amp, name='freq_sweep_excitation_pulse') drive_pulse = pulse_lib.gaussian(duration=drive_samples, sigma=drive_sigma, amp=drive_amp, name='freq_sweep_excitation_pulse') drive_sigma meas_map_idx = None for i, measure_group in enumerate(backend_config.meas_map): if qubit in measure_group: meas_map_idx = i break assert meas_map_idx is not None, f"Couldn't find qubit {qubit} in the meas_map!" inst_sched_map = backend_defaults.instruction_schedule_map measure = inst_sched_map.get('measure', qubits=backend_config.meas_map[meas_map_idx]) drive = [] meas = [] acq = [] for qubit in range(5): drive_chan = pulse.DriveChannel(qubit) drive.append(drive_chan) meas_chan = pulse.MeasureChannel(qubit) meas.append(meas_chan) acq_chan = pulse.AcquireChannel(qubit) acq.append(acq_chan) schedule = pulse.Schedule(name='Frequency sweep') schedule_frequencies = [] for i, j in enumerate(drive): schedule += Play(drive_pulse, j) # The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration # Create the frequency settings for the sweep (MUST BE IN HZ) frequencies_Hz = frequencies_GHzs[i]*GHz schedule_frequencies += [{j: freq} for freq in frequencies_Hz] schedule += measure << schedule.duration schedule.draw(label=True) from qiskit import assemble num_shots_per_frequency = 1024 frequency_sweep_program = assemble(schedule, backend=backend, meas_level=1, meas_return='avg', shots=num_shots_per_frequency, schedule_los=schedule_frequencies) job = backend.run(frequency_sweep_program) from qiskit import pulse with pulse.build(name='Pulse') as arb: pulse.play(drive_pulse, pulse.DriveChannel(0)) arb.draw() from qiskit.tools.monitor import job_monitor job_monitor(job) frequency_sweep_results = job.result(timeout=120) scale_factor = 1e-7 import matplotlib.pyplot as plt qubit = 0 sweep_values_total = [] for j in range(5): sweep_values = [] #for i in range(len(frequency_sweep_results.results)): for i in range(41*j,41*(j+1)): # Get the results from the ith experiment res = frequency_sweep_results.get_memory(i)*scale_factor # Get the results for `qubit` from this experiment sweep_values.append(res[j]) #frequency_q= list(frequency_for_qubits[j])*7 print(len(sweep_values)) sweep_values_total.append(sweep_values) plt.scatter(frequencies_GHzs[j], np.real(sweep_values), color='black') # plot real part of sweep values plt.xlim([min(frequencies_GHzs[j]), max(frequencies_GHzs[j])]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured signal [a.u.]") plt.show() from scipy.optimize import curve_fit def fit_function(x_values, y_values, function, init_params): fitparams, conv = curve_fit(function, x_values, y_values, init_params) y_fit = function(x_values, *fitparams) return fitparams, y_fit Q_freq=[] for i in range(5): fit_params, y_fit = fit_function(frequencies_GHzs[i], np.real(np.real(sweep_values_total[i])), lambda x, A, q_freq, B, C: (A / np.pi) * (B / ((x - q_freq)**2 + B**2)) + C, [0.02, frequencies_GHzs[i][20], 0.002, -2.17] # initial parameters for curve_fit ) plt.scatter(frequencies_GHzs[i], np.real(sweep_values_total[i]), color='black') plt.plot(frequencies_GHzs[i], y_fit, color='red') plt.xlim([min(frequencies_GHzs[i]), max(frequencies_GHzs[i])]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured Signal [a.u.]") plt.show() Q_freq.append(fit_params[1]) Q_freq num_rabi_points = 50 # Drive amplitude values to iterate over: 50 amplitudes evenly spaced from 0 to 0.75 drive_amp_min = 0 drive_amp_max = 0.20 drive_amps = np.linspace(drive_amp_min, drive_amp_max, num_rabi_points) rabi_schedules = [] for drive_amp in drive_amps: rabi_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_amp, sigma=drive_sigma, name=f"Rabi drive amplitude = {drive_amp}") this_schedule = pulse.Schedule(name=f"Rabi drive amplitude = {drive_amp}") this_schedule += Play(rabi_pulse, drive[0]) # Reuse the measure instruction from the frequency sweep experiment this_schedule += measure << this_schedule.duration rabi_schedules.append(this_schedule) rabi_schedules[-1].draw(label=True) num_shots_per_point = 1024 rabi_experiment_program = assemble(rabi_schedules, backend=backend, meas_level=1, meas_return='avg', shots=num_shots_per_point, schedule_los=[{drive_chan: Q_freq[0]*GHz}] * num_rabi_points) print(job.job_id()) job = backend.run(rabi_experiment_program) job_monitor(job) rabi_results = job.result(timeout=120) def baseline_remove(values): return np.array(values) - np.mean(values) rabi_values = [] for i in range(num_rabi_points): # Get the results for `qubit` from the ith experiment rabi_values.append(rabi_results.get_memory(i)[qubit]*scale_factor) rabi_values = np.real(baseline_remove(rabi_values)) plt.xlabel("Drive amp [a.u.]") plt.ylabel("Measured signal [a.u.]") plt.scatter(drive_amps, rabi_values, color='black') # plot real part of Rabi values plt.show() fit_params, y_fit = fit_function(drive_amps, rabi_values, lambda x, A, B, drive_period, phi: (A*np.cos(2*np.pi*x/drive_period - phi) + B), [2, 0, 0.2, 0]) plt.scatter(drive_amps, rabi_values, color='black') plt.plot(drive_amps, y_fit, color='red') drive_period = fit_params[2] # get period of rabi oscillation plt.axvline(drive_period/4*3, color='red', linestyle='--') plt.axvline(drive_period, color='red', linestyle='--') #plt.annotate("", xy=(drive_period, 0), xytext=(drive_period/2,0), arrowprops=dict(arrowstyle="<->", color='red')) #plt.annotate("$\pi$", xy=(drive_period/2-0.03, 0.1), color='red') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() print(fit_params) fit_params[2] pi_half_amp = abs(drive_period / 4) pi_amp= abs(drive_period / 2) print(f"Square root x (amp.)= {pi_half_amp}") print(f"Square root x (amp.)= {pi_amp}") time_max_us = 1.5 time_step_us = 0.025 times_us = np.arange(0.025, time_max_us, time_step_us) # Convert to units of dt delay_times_dt = times_us * us / dt # Drive parameters # The drive amplitude for pi/2 is simply half the amplitude of the pi pulse drive_amp = pi_amp / 2 # x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees x90_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_amp, sigma=drive_sigma, name='x90_pulse') ramsey_schedules = [] for delay in delay_times_dt: this_schedule = pulse.Schedule(name=f"Ramsey delay = {delay * dt / us} us") this_schedule |= Play(x90_pulse, drive[0]) this_schedule |= Play(x90_pulse, drive[0]) << int(this_schedule.duration + delay) this_schedule |= measure << int(this_schedule.duration) ramsey_schedules.append(this_schedule) ramsey_schedules[0].draw(label=True) num_shots = 256 detuning_MHz = -1 ramsey_frequency = round(Q_freq[0]*GHz + detuning_MHz * MHz, 6) # need ramsey freq in Hz ramsey_program = assemble(ramsey_schedules, backend=backend, meas_level=1, meas_return='avg', shots=num_shots, schedule_los=[{drive_chan: ramsey_frequency}]*len(ramsey_schedules) ) job = backend.run(ramsey_program) # print(job.job_id()) job_monitor(job) ramsey_results = job.result(timeout=120) ramsey_values = [] for i in range(len(times_us)): ramsey_values.append(ramsey_results.get_memory(i)[0]*scale_factor) plt.scatter(times_us, np.real(ramsey_values), color='black') plt.xlim(0, np.max(times_us)) plt.title("Ramsey Experiment", fontsize=15) plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15) plt.ylabel('Measured Signal [a.u.]', fontsize=15) plt.show() fit_params, y_fit = fit_function(times_us, np.real(ramsey_values), lambda x, A, del_f_MHz, C, B: ( A* np.cos(2*np.pi*del_f_MHz*x - 0.56) + B*x**(C) ), [0.15588132, 0.0554278, -0.04492174, 2.21367894] ) # Off-resonance component _, del_f_MHz, _, _, = fit_params # freq is MHz since times in us plt.scatter(times_us, np.real(ramsey_values), color='black') plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.2f} MHz") plt.xlim(0, np.max(times_us)) plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15) plt.ylabel('Measured Signal [a.u.]', fontsize=15) plt.title('Ramsey Experiment', fontsize=15) plt.legend() plt.show() fit_params precise_qubit_freq = Q_freq[0]*GHz + (del_f_MHz - detuning_MHz) * MHz # get new freq in Hz print(f"Our updated qubit frequency is now {round(precise_qubit_freq/GHz, 6)} GHz. " f"It used to be {round(Q_freq[0]*GHz / GHz, 6)} GHz") ramsey_results.get_memory(0) pi_half_pulse = pulse_lib.gaussian(duration=drive_samples, amp=pi_half_amp, sigma=drive_sigma, name='Square root x') from qiskit import pulse with pulse.build(name='Square root x') as xrx: pulse.play(pi_half_pulse, pulse.DriveChannel(0)) xrx.draw() def X_circuit1(n=20,qubit=0): Xcircuit = [] for i in range(n): xcircuit_z_q0 = QuantumCircuit(5,1) xcircuit_x_q0 = QuantumCircuit(5,1) xcircuit_y_q0 = QuantumCircuit(5,1) for j in range(i): xcircuit_z_q0.sx(qubit) xcircuit_z_q0.sx(qubit) xcircuit_z_q0.barrier() xcircuit_z_q0.sx(qubit) xcircuit_z_q0.sx(qubit) xcircuit_z_q0.barrier() xcircuit_x_q0.sx(qubit) xcircuit_x_q0.sx(qubit) xcircuit_x_q0.barrier() xcircuit_x_q0.sx(qubit) xcircuit_x_q0.sx(qubit) xcircuit_x_q0.barrier() xcircuit_y_q0.sx(qubit) xcircuit_y_q0.sx(qubit) xcircuit_y_q0.barrier() xcircuit_y_q0.sx(qubit) xcircuit_y_q0.sx(qubit) xcircuit_y_q0.barrier() xcircuit_x_q0.h(qubit) xcircuit_y_q0.sdg(qubit) xcircuit_y_q0.h(qubit) xcircuit_z_q0.measure(qubit,0) xcircuit_x_q0.measure(qubit,0) xcircuit_y_q0.measure(qubit,0) xcircuit_z_q0.add_calibration('sx', [0], xrx) xcircuit_x_q0.add_calibration('sx', [0], xrx) xcircuit_y_q0.add_calibration('sx', [0], xrx) xcircuit_z_q0 = transpile(xcircuit_z_q0, backend) xcircuit_x_q0 = transpile(xcircuit_x_q0, backend) xcircuit_y_q0 = transpile(xcircuit_y_q0, backend) Xcircuit.append(xcircuit_z_q0) Xcircuit.append(xcircuit_x_q0) Xcircuit.append(xcircuit_y_q0) return Xcircuit q=0 qr = QuantumRegister(5) qubit_list = [q] meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list, qr=qr, circlabel='mcal') circuit_x = X_circuit1(20,0) reps=2 all_jobs = [] all_jobs_mit = [] for ii in range(reps): # Run QPT on backend shots = 8192 il = [0,1,2,3,4] #job_backend = execute(stabilizer_circuits, Aer.get_backend('qasm_simulator'), shots=shots, initial_layout=il,basis_gates=basis_gates,noise_model=noise_model) job_backend = execute(circuit_x, backend, shots=shots, initial_layout=il) #job_mit_backend = execute(meas_cal_circuits, Aer.get_backend('qasm_simulator'), shots=shots, initial_layout=il,basis_gates=basis_gates,noise_model=noise_model) job_mit_backend = execute(meas_calibs, backend, shots=shots, initial_layout=il) print('Job IDs ({}/{}): \n measurement calibration: {}\n stabilizer measurements: {}'.format( ii+1, reps, job_mit_backend.job_id(), job_backend.job_id())) all_jobs.append(job_backend) all_jobs_mit.append(job_mit_backend) for job in all_jobs: job_monitor(job) try: if job.error_message() is not None: print(job.error_message()) except: pass cal_results = all_jobs_mit[1].result() results = all_jobs[1].result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, qubit_list=qubit_list, circlabel='mcal') print(meas_fitter.cal_matrix) meas_fitter.plot_calibration() from qiskit.tools.visualization import * import matplotlib.pyplot as plt import math import numpy as np Result_nomit = results.get_counts(0) mitigated_counts = meas_fitter.filter.apply(results).get_counts(0) plot_histogram([Result_nomit, mitigated_counts], legend=['raw', 'mitigated']) (0.719/0.990)**(1/80)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for 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/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_right(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will start at t=80 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog.draw()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=no-name-in-module,broad-except,cyclic-import """Contains Qiskit (terra) version.""" import os import subprocess from collections.abc import Mapping import warnings ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) def _minimal_ext_cmd(cmd): # construct minimal environment env = {} for k in ["SYSTEMROOT", "PATH"]: v = os.environ.get(k) if v is not None: env[k] = v # LANGUAGE is used on win32 env["LANGUAGE"] = "C" env["LANG"] = "C" env["LC_ALL"] = "C" with subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, cwd=os.path.join(os.path.dirname(ROOT_DIR)), ) as proc: stdout, stderr = proc.communicate() if proc.returncode > 0: error_message = stderr.strip().decode("ascii") raise OSError(f"Command {cmd} exited with code {proc.returncode}: {error_message}") return stdout def git_version(): """Get the current git head sha1.""" # Determine if we're at main try: out = _minimal_ext_cmd(["git", "rev-parse", "HEAD"]) git_revision = out.strip().decode("ascii") except OSError: git_revision = "Unknown" return git_revision with open(os.path.join(ROOT_DIR, "VERSION.txt")) as version_file: VERSION = version_file.read().strip() def get_version_info(): """Get the full version string.""" # Adding the git rev number needs to be done inside # write_version_py(), otherwise the import of scipy.version messes # up the build under Python 3. full_version = VERSION if not os.path.exists(os.path.join(os.path.dirname(ROOT_DIR), ".git")): return full_version try: release = _minimal_ext_cmd(["git", "tag", "-l", "--points-at", "HEAD"]) except Exception: # pylint: disable=broad-except return full_version git_revision = git_version() if not release: full_version += ".dev0+" + git_revision[:7] return full_version __version__ = get_version_info() class QiskitVersion(Mapping): """DEPRECATED in 0.25.0 use qiskit.__version__""" __slots__ = ["_version_dict", "_loaded"] def __init__(self): self._version_dict = { "qiskit-terra": __version__, "qiskit": None, } self._loaded = False def _load_versions(self): warnings.warn( "qiskit.__qiskit_version__ is deprecated since " "Qiskit Terra 0.25.0, and will be removed 3 months or more later. " "Instead, you should use qiskit.__version__. The other packages listed in the" "former qiskit.__qiskit_version__ have their own __version__ module level dunder, " "as standard in PEP 8.", category=DeprecationWarning, stacklevel=3, ) from importlib.metadata import version try: # TODO: Update to use qiskit_aer instead when we remove the # namespace redirect from qiskit.providers import aer self._version_dict["qiskit-aer"] = aer.__version__ except Exception: self._version_dict["qiskit-aer"] = None try: from qiskit import ignis self._version_dict["qiskit-ignis"] = ignis.__version__ except Exception: self._version_dict["qiskit-ignis"] = None try: from qiskit.providers import ibmq self._version_dict["qiskit-ibmq-provider"] = ibmq.__version__ except Exception: self._version_dict["qiskit-ibmq-provider"] = None try: import qiskit_nature self._version_dict["qiskit-nature"] = qiskit_nature.__version__ except Exception: self._version_dict["qiskit-nature"] = None try: import qiskit_finance self._version_dict["qiskit-finance"] = qiskit_finance.__version__ except Exception: self._version_dict["qiskit-finance"] = None try: import qiskit_optimization self._version_dict["qiskit-optimization"] = qiskit_optimization.__version__ except Exception: self._version_dict["qiskit-optimization"] = None try: import qiskit_machine_learning self._version_dict["qiskit-machine-learning"] = qiskit_machine_learning.__version__ except Exception: self._version_dict["qiskit-machine-learning"] = None try: self._version_dict["qiskit"] = version("qiskit") except Exception: self._version_dict["qiskit"] = None self._loaded = True def __repr__(self): if not self._loaded: self._load_versions() return repr(self._version_dict) def __str__(self): if not self._loaded: self._load_versions() return str(self._version_dict) def __getitem__(self, key): if not self._loaded: self._load_versions() return self._version_dict[key] def __iter__(self): if not self._loaded: self._load_versions() return iter(self._version_dict) def __len__(self): return len(self._version_dict) __qiskit_version__ = QiskitVersion()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test pulse builder with backendV2 context utilities.""" import numpy as np from qiskit import circuit, pulse from qiskit.pulse import builder, macros from qiskit.pulse.instructions import directives from qiskit.pulse.transforms import target_qobj_transform from qiskit.providers.fake_provider import FakeMumbaiV2 from qiskit.pulse import instructions from qiskit.test import QiskitTestCase class TestBuilderV2(QiskitTestCase): """Test the pulse builder context with backendV2.""" def setUp(self): super().setUp() self.backend = FakeMumbaiV2() def assertScheduleEqual(self, program, target): """Assert an error when two pulse programs are not equal. .. note:: Two programs are converted into standard execution format then compared. """ self.assertEqual(target_qobj_transform(program), target_qobj_transform(target)) class TestContextsV2(TestBuilderV2): """Test builder contexts.""" def test_transpiler_settings(self): """Test the transpiler settings context. Tests that two cx gates are optimized away with higher optimization level. """ twice_cx_qc = circuit.QuantumCircuit(2) twice_cx_qc.cx(0, 1) twice_cx_qc.cx(0, 1) with pulse.build(self.backend) as schedule: with pulse.transpiler_settings(optimization_level=0): builder.call(twice_cx_qc) self.assertNotEqual(len(schedule.instructions), 0) with pulse.build(self.backend) as schedule: with pulse.transpiler_settings(optimization_level=3): builder.call(twice_cx_qc) self.assertEqual(len(schedule.instructions), 0) def test_scheduler_settings(self): """Test the circuit scheduler settings context.""" inst_map = pulse.InstructionScheduleMap() d0 = pulse.DriveChannel(0) test_x_sched = pulse.Schedule() test_x_sched += instructions.Delay(10, d0) inst_map.add("x", (0,), test_x_sched) ref_sched = pulse.Schedule() ref_sched += pulse.instructions.Call(test_x_sched) x_qc = circuit.QuantumCircuit(2) x_qc.x(0) with pulse.build(backend=self.backend) as schedule: with pulse.transpiler_settings(basis_gates=["x"]): with pulse.circuit_scheduler_settings(inst_map=inst_map): builder.call(x_qc) self.assertScheduleEqual(schedule, ref_sched) def test_phase_compensated_frequency_offset(self): """Test that the phase offset context properly compensates for phase accumulation with backendV2.""" d0 = pulse.DriveChannel(0) with pulse.build(self.backend) as schedule: with pulse.frequency_offset(1e9, d0, compensate_phase=True): pulse.delay(10, d0) reference = pulse.Schedule() reference += instructions.ShiftFrequency(1e9, d0) reference += instructions.Delay(10, d0) reference += instructions.ShiftPhase( -2 * np.pi * ((1e9 * 10 * self.backend.target.dt) % 1), d0 ) reference += instructions.ShiftFrequency(-1e9, d0) self.assertScheduleEqual(schedule, reference) class TestChannelsV2(TestBuilderV2): """Test builder channels.""" def test_drive_channel(self): """Text context builder drive channel.""" with pulse.build(self.backend): self.assertEqual(pulse.drive_channel(0), pulse.DriveChannel(0)) def test_measure_channel(self): """Text context builder measure channel.""" with pulse.build(self.backend): self.assertEqual(pulse.measure_channel(0), pulse.MeasureChannel(0)) def test_acquire_channel(self): """Text context builder acquire channel.""" with pulse.build(self.backend): self.assertEqual(pulse.acquire_channel(0), pulse.AcquireChannel(0)) def test_control_channel(self): """Text context builder control channel.""" with pulse.build(self.backend): self.assertEqual(pulse.control_channels(0, 1)[0], pulse.ControlChannel(0)) class TestDirectivesV2(TestBuilderV2): """Test builder directives.""" def test_barrier_on_qubits(self): """Test barrier directive on qubits with backendV2. A part of qubits map of Mumbai 0 -- 1 -- 4 -- | | 2 """ with pulse.build(self.backend) as schedule: pulse.barrier(0, 1) reference = pulse.ScheduleBlock() reference += directives.RelativeBarrier( pulse.DriveChannel(0), pulse.DriveChannel(1), pulse.MeasureChannel(0), pulse.MeasureChannel(1), pulse.ControlChannel(0), pulse.ControlChannel(1), pulse.ControlChannel(2), pulse.ControlChannel(3), pulse.ControlChannel(4), pulse.ControlChannel(8), pulse.AcquireChannel(0), pulse.AcquireChannel(1), ) self.assertEqual(schedule, reference) class TestUtilitiesV2(TestBuilderV2): """Test builder utilities.""" def test_active_backend(self): """Test getting active builder backend.""" with pulse.build(self.backend): self.assertEqual(pulse.active_backend(), self.backend) def test_qubit_channels(self): """Test getting the qubit channels of the active builder's backend.""" with pulse.build(self.backend): qubit_channels = pulse.qubit_channels(0) self.assertEqual( qubit_channels, { pulse.DriveChannel(0), pulse.MeasureChannel(0), pulse.AcquireChannel(0), pulse.ControlChannel(0), pulse.ControlChannel(1), }, ) def test_active_transpiler_settings(self): """Test setting settings of active builder's transpiler.""" with pulse.build(self.backend): self.assertFalse(pulse.active_transpiler_settings()) with pulse.transpiler_settings(test_setting=1): self.assertEqual(pulse.active_transpiler_settings()["test_setting"], 1) def test_active_circuit_scheduler_settings(self): """Test setting settings of active builder's circuit scheduler.""" with pulse.build(self.backend): self.assertFalse(pulse.active_circuit_scheduler_settings()) with pulse.circuit_scheduler_settings(test_setting=1): self.assertEqual(pulse.active_circuit_scheduler_settings()["test_setting"], 1) def test_num_qubits(self): """Test builder utility to get number of qubits with backendV2.""" with pulse.build(self.backend): self.assertEqual(pulse.num_qubits(), 27) def test_samples_to_seconds(self): """Test samples to time with backendV2""" target = self.backend.target target.dt = 0.1 with pulse.build(self.backend): time = pulse.samples_to_seconds(100) self.assertTrue(isinstance(time, float)) self.assertEqual(pulse.samples_to_seconds(100), 10) def test_samples_to_seconds_array(self): """Test samples to time (array format) with backendV2.""" target = self.backend.target target.dt = 0.1 with pulse.build(self.backend): samples = np.array([100, 200, 300]) times = pulse.samples_to_seconds(samples) self.assertTrue(np.issubdtype(times.dtype, np.floating)) np.testing.assert_allclose(times, np.array([10, 20, 30])) def test_seconds_to_samples(self): """Test time to samples with backendV2""" target = self.backend.target target.dt = 0.1 with pulse.build(self.backend): samples = pulse.seconds_to_samples(10) self.assertTrue(isinstance(samples, int)) self.assertEqual(pulse.seconds_to_samples(10), 100) def test_seconds_to_samples_array(self): """Test time to samples (array format) with backendV2.""" target = self.backend.target target.dt = 0.1 with pulse.build(self.backend): times = np.array([10, 20, 30]) samples = pulse.seconds_to_samples(times) self.assertTrue(np.issubdtype(samples.dtype, np.integer)) np.testing.assert_allclose(pulse.seconds_to_samples(times), np.array([100, 200, 300])) class TestMacrosV2(TestBuilderV2): """Test builder macros with backendV2.""" def test_macro(self): """Test builder macro decorator.""" @pulse.macro def nested(a): pulse.play(pulse.Gaussian(100, a, 20), pulse.drive_channel(0)) return a * 2 @pulse.macro def test(): pulse.play(pulse.Constant(100, 1.0), pulse.drive_channel(0)) output = nested(0.5) return output with pulse.build(self.backend) as schedule: output = test() self.assertEqual(output, 0.5 * 2) reference = pulse.Schedule() reference += pulse.Play(pulse.Constant(100, 1.0), pulse.DriveChannel(0)) reference += pulse.Play(pulse.Gaussian(100, 0.5, 20), pulse.DriveChannel(0)) self.assertScheduleEqual(schedule, reference) def test_measure(self): """Test utility function - measure with backendV2.""" with pulse.build(self.backend) as schedule: reg = pulse.measure(0) self.assertEqual(reg, pulse.MemorySlot(0)) reference = macros.measure(qubits=[0], backend=self.backend, meas_map=self.backend.meas_map) self.assertScheduleEqual(schedule, reference) def test_measure_multi_qubits(self): """Test utility function - measure with multi qubits with backendV2.""" with pulse.build(self.backend) as schedule: regs = pulse.measure([0, 1]) self.assertListEqual(regs, [pulse.MemorySlot(0), pulse.MemorySlot(1)]) reference = macros.measure( qubits=[0, 1], backend=self.backend, meas_map=self.backend.meas_map ) self.assertScheduleEqual(schedule, reference) def test_measure_all(self): """Test utility function - measure with backendV2..""" with pulse.build(self.backend) as schedule: regs = pulse.measure_all() self.assertEqual(regs, [pulse.MemorySlot(i) for i in range(self.backend.num_qubits)]) reference = macros.measure_all(self.backend) self.assertScheduleEqual(schedule, reference) def test_delay_qubit(self): """Test delaying on a qubit macro.""" with pulse.build(self.backend) as schedule: pulse.delay_qubits(10, 0) d0 = pulse.DriveChannel(0) m0 = pulse.MeasureChannel(0) a0 = pulse.AcquireChannel(0) u0 = pulse.ControlChannel(0) u1 = pulse.ControlChannel(1) reference = pulse.Schedule() reference += instructions.Delay(10, d0) reference += instructions.Delay(10, m0) reference += instructions.Delay(10, a0) reference += instructions.Delay(10, u0) reference += instructions.Delay(10, u1) self.assertScheduleEqual(schedule, reference) def test_delay_qubits(self): """Test delaying on multiple qubits with backendV2 to make sure we don't insert delays twice.""" with pulse.build(self.backend) as schedule: pulse.delay_qubits(10, 0, 1) d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) m0 = pulse.MeasureChannel(0) m1 = pulse.MeasureChannel(1) a0 = pulse.AcquireChannel(0) a1 = pulse.AcquireChannel(1) u0 = pulse.ControlChannel(0) u1 = pulse.ControlChannel(1) u2 = pulse.ControlChannel(2) u3 = pulse.ControlChannel(3) u4 = pulse.ControlChannel(4) u8 = pulse.ControlChannel(8) reference = pulse.Schedule() reference += instructions.Delay(10, d0) reference += instructions.Delay(10, d1) reference += instructions.Delay(10, m0) reference += instructions.Delay(10, m1) reference += instructions.Delay(10, a0) reference += instructions.Delay(10, a1) reference += instructions.Delay(10, u0) reference += instructions.Delay(10, u1) reference += instructions.Delay(10, u2) reference += instructions.Delay(10, u3) reference += instructions.Delay(10, u4) reference += instructions.Delay(10, u8) self.assertScheduleEqual(schedule, reference)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for layouts of timeline drawer.""" import qiskit from qiskit.test import QiskitTestCase from qiskit.visualization.timeline import layouts class TestBitArrange(QiskitTestCase): """Tests for layout.bit_arrange.""" def setUp(self) -> None: """Setup.""" super().setUp() qregs = qiskit.QuantumRegister(3) cregs = qiskit.ClassicalRegister(3) self.regs = list(qregs) + list(cregs) def test_qreg_creg_ascending(self): """Test qreg_creg_ascending layout function.""" sorted_regs = layouts.qreg_creg_ascending(self.regs) ref_regs = [ self.regs[0], self.regs[1], self.regs[2], self.regs[3], self.regs[4], self.regs[5], ] self.assertListEqual(sorted_regs, ref_regs) def test_qreg_creg_descending(self): """Test qreg_creg_descending layout function.""" sorted_regs = layouts.qreg_creg_descending(self.regs) ref_regs = [ self.regs[2], self.regs[1], self.regs[0], self.regs[5], self.regs[4], self.regs[3], ] self.assertListEqual(sorted_regs, ref_regs) class TestAxisMap(QiskitTestCase): """Tests for layout.time_axis_map.""" def test_time_map_in_dt(self): """Test time_map_in_dt layout function.""" axis_config = layouts.time_map_in_dt(time_window=(-100, 500)) self.assertEqual(axis_config.window, (-100, 500)) self.assertEqual(axis_config.label, "System cycle time (dt)") ref_map = {0: "0", 100: "100", 200: "200", 300: "300", 400: "400", 500: "500"} self.assertDictEqual(axis_config.axis_map, ref_map)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/benkoehlL/Qiskit_Playground
benkoehlL
from qiskit import IBMQ from qiskit import * #provider = IBMQ.enable_account(<INSERT_IBM_QUANTUM_EXPERIENCE_TOKEN>) qc = QuantumCircuit(2,2) qc.h(0) qc.cx(0,1) qc.measure(1,0) backend = IBMQ.get_backend('ibmq_qasm_simulator', hub=None) job=execute(qc, backend, shots=1000) result = job.result() print(result.get_counts())
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# You can set a color for all the bars. from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_paulivec qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = Statevector(qc) plot_state_paulivec(state, color='midnightblue', title="New PauliVec plot")
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests evaluator of auxiliary operators for algorithms.""" from __future__ import annotations import unittest from typing import Tuple from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np from ddt import ddt, data from qiskit_algorithms.list_or_dict import ListOrDict from qiskit.quantum_info.operators.base_operator import BaseOperator from qiskit_algorithms import estimate_observables from qiskit.primitives import Estimator from qiskit.quantum_info import Statevector, SparsePauliOp from qiskit import QuantumCircuit from qiskit.circuit.library import EfficientSU2 from qiskit.opflow import PauliSumOp from qiskit.utils import algorithm_globals @ddt class TestObservablesEvaluator(QiskitAlgorithmsTestCase): """Tests evaluator of auxiliary operators for algorithms.""" def setUp(self): super().setUp() self.seed = 50 algorithm_globals.random_seed = self.seed self.threshold = 1e-8 def get_exact_expectation( self, ansatz: QuantumCircuit, observables: ListOrDict[BaseOperator | PauliSumOp] ): """ Calculates the exact expectation to be used as an expected result for unit tests. """ if isinstance(observables, dict): observables_list = list(observables.values()) else: observables_list = observables # the exact value is a list of (mean, (variance, shots)) where we expect 0 variance and # 0 shots exact = [ (Statevector(ansatz).expectation_value(observable), {}) for observable in observables_list ] if isinstance(observables, dict): return dict(zip(observables.keys(), exact)) return exact def _run_test( self, expected_result: ListOrDict[Tuple[complex, complex]], quantum_state: QuantumCircuit, decimal: int, observables: ListOrDict[BaseOperator | PauliSumOp], estimator: Estimator, ): result = estimate_observables(estimator, quantum_state, observables, None, self.threshold) if isinstance(observables, dict): np.testing.assert_equal(list(result.keys()), list(expected_result.keys())) means = [element[0] for element in result.values()] expected_means = [element[0] for element in expected_result.values()] np.testing.assert_array_almost_equal(means, expected_means, decimal=decimal) vars_and_shots = [element[1] for element in result.values()] expected_vars_and_shots = [element[1] for element in expected_result.values()] np.testing.assert_array_equal(vars_and_shots, expected_vars_and_shots) else: means = [element[0] for element in result] expected_means = [element[0] for element in expected_result] np.testing.assert_array_almost_equal(means, expected_means, decimal=decimal) vars_and_shots = [element[1] for element in result] expected_vars_and_shots = [element[1] for element in expected_result] np.testing.assert_array_equal(vars_and_shots, expected_vars_and_shots) @data( [ PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]), PauliSumOp.from_list([("II", 2.0)]), ], [ PauliSumOp.from_list([("ZZ", 2.0)]), ], { "op1": PauliSumOp.from_list([("II", 2.0)]), "op2": PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]), }, { "op1": PauliSumOp.from_list([("ZZ", 2.0)]), }, [], {}, ) def test_estimate_observables(self, observables: ListOrDict[BaseOperator | PauliSumOp]): """Tests evaluator of auxiliary operators for algorithms.""" ansatz = EfficientSU2(2) parameters = np.array( [1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0], dtype=float, ) bound_ansatz = ansatz.bind_parameters(parameters) states = bound_ansatz expected_result = self.get_exact_expectation(bound_ansatz, observables) estimator = Estimator() decimal = 6 self._run_test( expected_result, states, decimal, observables, estimator, ) def test_estimate_observables_zero_op(self): """Tests if a zero operator is handled correctly.""" ansatz = EfficientSU2(2) parameters = np.array( [1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0], dtype=float, ) bound_ansatz = ansatz.bind_parameters(parameters) state = bound_ansatz estimator = Estimator() observables = [SparsePauliOp(["XX", "YY"]), 0] result = estimate_observables(estimator, state, observables, None, self.threshold) expected_result = [(0.015607318055509564, {}), (0.0, {})] means = [element[0] for element in result] expected_means = [element[0] for element in expected_result] np.testing.assert_array_almost_equal(means, expected_means, decimal=0.01) vars_and_shots = [element[1] for element in result] expected_vars_and_shots = [element[1] for element in expected_result] np.testing.assert_array_equal(vars_and_shots, expected_vars_and_shots) def test_estimate_observables_shots(self): """Tests that variances and shots are returned properly.""" ansatz = EfficientSU2(2) parameters = np.array( [1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0], dtype=float, ) bound_ansatz = ansatz.bind_parameters(parameters) state = bound_ansatz estimator = Estimator(options={"shots": 2048}) with self.assertWarns(DeprecationWarning): observables = [PauliSumOp.from_list([("ZZ", 2.0)])] result = estimate_observables(estimator, state, observables, None, self.threshold) exact_result = self.get_exact_expectation(bound_ansatz, observables) expected_result = [(exact_result[0][0], {"variance": 1.0898, "shots": 2048})] means = [element[0] for element in result] expected_means = [element[0] for element in expected_result] np.testing.assert_array_almost_equal(means, expected_means, decimal=0.01) vars_and_shots = [element[1] for element in result] expected_vars_and_shots = [element[1] for element in expected_result] for computed, expected in zip(vars_and_shots, expected_vars_and_shots): self.assertAlmostEqual(computed.pop("variance"), expected.pop("variance"), 2) self.assertEqual(computed.pop("shots"), expected.pop("shots")) if __name__ == "__main__": unittest.main()
https://github.com/QC-Hub/Examples
QC-Hub
from qiskit.providers.ibmq import least_busy from qiskit import IBMQ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute #IBMQ.save_account("Account id") APItoken="APItoken" config = { "url": 'https://quantumexperience.ng.bluemix.net/api'} #IBMQ.backends() #Search for available quantum machines IBMQ.load_accounts() print("Available backends") print(IBMQ.backends()) large_enough_devices = IBMQ.backends(filters=lambda x : x.configuration().n_qubits >3 and not x.configuration().simulator) backend = least_busy(large_enough_devices) print(backend) print("The best backend is "+ backend.name()) #Creating quantum circuits q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q,c) m = QuantumCircuit(q,c) qc.h(q) qc.cx(q[0],q[1]) m.measure(q,c) t = qc + m #Executing the quantum circuits in a real quantum computer job = execute(t,backend,shots=1000) counts = job.result().get_counts(t) print(counts)
https://github.com/xtophe388/QISKIT
xtophe388
import sys, getpass try: sys.path.append("../../") # go to parent dir import Qconfig qx_config = { "APItoken": Qconfig.APItoken, "url": Qconfig.config['url']} print('Qconfig loaded from %s.' % Qconfig.__file__) except: APItoken = getpass.getpass('Please input your token and hit enter: ') qx_config = { "APItoken": APItoken, "url":"https://quantumexperience.ng.bluemix.net/api"} print('Qconfig.py not found in qiskit-tutorial directory; Qconfig loaded using user input.') # useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np from pprint import pprint # importing QISKit from qiskit import QuantumProgram, QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import available_backends, execute, register, least_busy # import basic plot tools from qiskit.tools.visualization import plot_histogram, circuit_drawer backend = 'local_qasm_simulator' # run on local simulator by default # Uncomment the following lines to run on a real device # register(qx_config['APItoken'], qx_config['url']) # backend = least_busy(available_backends({'simulator': False, 'local': False})) # print("the best backend is " + backend) zero = np.array([[1],[0]]) one = np.array([[0],[1]]) X = np.array([[0,1],[1,0]]) print(np.dot(X,zero)) print(np.dot(X,one)) # Creating registers qr = QuantumRegister(1) cr = ClassicalRegister(1) # Quantum circuit ground qc_ground = QuantumCircuit(qr, cr) qc_ground.measure(qr[0], cr[0]) # Quantum circuit excited qc_excited = QuantumCircuit(qr, cr) qc_excited.x(qr) qc_excited.measure(qr[0], cr[0]) circuit_drawer(qc_ground) circuit_drawer(qc_excited) circuits = [qc_ground, qc_excited] job = execute(circuits, backend) result = job.result() plot_histogram(result.get_counts(qc_ground)) plot_histogram(result.get_counts(qc_excited)) # Quantum circuit superposition qc_superposition = QuantumCircuit(qr, cr) qc_superposition.h(qr) qc_superposition.measure(qr[0], cr[0]) circuit_drawer(qc_superposition) job = execute(qc_superposition, backend) result = job.result() plot_histogram(result.get_counts(qc_superposition)) # Quantum circuit two Hadamards qc_twohadamard = QuantumCircuit(qr, cr) qc_twohadamard.h(qr) qc_twohadamard.barrier() qc_twohadamard.h(qr) qc_twohadamard.measure(qr[0], cr[0]) circuit_drawer(qc_twohadamard) job = execute(qc_twohadamard, backend) result = job.result() plot_histogram(result.get_counts(qc_twohadamard)) state_overlap = lambda state1, state2: np.absolute(np.dot(state1.conj().T,state2))**2 Hadamard = np.array([[1,1],[1,-1]],dtype=complex)/np.sqrt(2) psi1 = np.dot(Hadamard,zero) P0 = state_overlap(zero,psi1) P1 = state_overlap(one,psi1) plot_histogram({'0' : P0.item(0), '1' : P1.item(0)}) print(np.dot(Hadamard,zero)) print(np.dot(Hadamard,one)) # Creating registers q2 = QuantumRegister(2) c2 = ClassicalRegister(2) # quantum circuit to make an entangled bell state bell = QuantumCircuit(q2, c2) bell.h(q2[0]) bell.cx(q2[0], q2[1]) # quantum circuit to measure q0 in the standard basis measureIZ = QuantumCircuit(q2, c2) measureIZ.measure(q2[0], c2[0]) bellIZ = bell+measureIZ # quantum circuit to measure q0 in the superposition basis measureIX = QuantumCircuit(q2, c2) measureIX.h(q2[0]) measureIX.measure(q2[0], c2[0]) bellIX = bell+measureIX # quantum circuit to measure q1 in the standard basis measureZI = QuantumCircuit(q2, c2) measureZI.measure(q2[1], c2[1]) bellZI = bell+measureZI # quantum circuit to measure q1 in the superposition basis measureXI = QuantumCircuit(q2, c2) measureXI.h(q2[1]) measureXI.measure(q2[1], c2[1]) bellXI = bell+measureXI # quantum circuit to measure q in the standard basis measureZZ = QuantumCircuit(q2, c2) measureZZ.measure(q2[0], c2[0]) measureZZ.measure(q2[1], c2[1]) bellZZ = bell+measureZZ # quantum circuit to measure q in the superposition basis measureXX = QuantumCircuit(q2, c2) measureXX.h(q2[0]) measureXX.h(q2[1]) measureXX.measure(q2[0], c2[0]) measureXX.measure(q2[1], c2[1]) bellXX = bell+measureXX circuit_drawer(bellIZ) circuit_drawer(bellIX) circuit_drawer(bellZI) circuit_drawer(bellXI) circuit_drawer(bellZZ) circuit_drawer(bellXX) circuits = [bellIZ,bellIX,bellZI,bellXI,bellZZ,bellXX] job = execute(circuits, backend) result = job.result() plot_histogram(result.get_counts(bellIZ)) result.get_data(bellIZ) plot_histogram(result.get_counts(bellIX)) plot_histogram(result.get_counts(bellZI)) plot_histogram(result.get_counts(bellXI)) plot_histogram(result.get_counts(bellZZ)) plot_histogram(result.get_counts(bellXX)) # quantum circuit to make a mixed state mixed1 = QuantumCircuit(q2, c2) mixed2 = QuantumCircuit(q2, c2) mixed2.x(q2) mixed1.measure(q2[0], c2[0]) mixed1.measure(q2[1], c2[1]) mixed2.measure(q2[0], c2[0]) mixed2.measure(q2[1], c2[1]) circuit_drawer(mixed1) circuit_drawer(mixed2) mixed_state = [mixed1,mixed2] job = execute(mixed_state, backend) result = job.result() counts1 = result.get_counts(mixed_state[0]) counts2 = result.get_counts(mixed_state[1]) from collections import Counter ground = Counter(counts1) excited = Counter(counts2) plot_histogram(ground+excited)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Operator from qiskit.transpiler.passes import UnitarySynthesis circuit = QuantumCircuit(1) circuit.rx(0.8, 0) unitary = Operator(circuit).data unitary_circ = QuantumCircuit(1) unitary_circ.unitary(unitary, [0]) synth = UnitarySynthesis(basis_gates=["h", "s"], method="sk") out = synth(unitary_circ) out.draw('mpl')
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=missing-docstring,invalid-name,no-member,broad-except # pylint: disable=no-else-return, attribute-defined-outside-init # pylint: disable=import-error from qiskit_experiments.library import StateTomography import qiskit class StateTomographyBench: params = [2, 3, 4, 5] param_names = ["n_qubits"] version = "0.3.0" timeout = 120.0 def setup(self, _): self.qasm_backend = qiskit.BasicAer.get_backend("qasm_simulator") def time_state_tomography_bell(self, n_qubits): meas_qubits = [n_qubits - 2, n_qubits - 1] qr_full = qiskit.QuantumRegister(n_qubits) bell = qiskit.QuantumCircuit(qr_full) bell.h(qr_full[meas_qubits[0]]) bell.cx(qr_full[meas_qubits[0]], qr_full[meas_qubits[1]]) qst_exp = StateTomography(bell, measurement_qubits=meas_qubits) expdata = qst_exp.run(self.qasm_backend, shots=5000).block_for_results() expdata.analysis_results("state") expdata.analysis_results("state_fidelity") def time_state_tomography_cat(self, n_qubits): qr = qiskit.QuantumRegister(n_qubits, "qr") circ = qiskit.QuantumCircuit(qr, name="cat") circ.h(qr[0]) for i in range(1, n_qubits): circ.cx(qr[0], qr[i]) qst_exp = StateTomography(circ) expdata = qst_exp.run(self.qasm_backend, shots=5000).block_for_results() expdata.analysis_results("state") expdata.analysis_results("state_fidelity")
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/1chooo/Quantum-Oracle
1chooo
from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector qc = QuantumCircuit(3) qc.x(0) qc.y(1) qc.z(2) print(qc) qc.draw("mpl") state = Statevector.from_instruction(qc) state.draw('bloch')
https://github.com/nahumsa/Introduction-to-IBM_Qiskit
nahumsa
#initialization import matplotlib.pyplot as plt import numpy as np import math # importing Qiskit from qiskit import IBMQ, Aer, transpile, assemble from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister # import basic plot tools from qiskit.visualization import plot_histogram qpe = QuantumCircuit(4, 3) qpe.x(3) #Apply Hadamard gate for qubit in range(3): qpe.h(qubit) qpe.draw() repetitions = 1 for counting_qubit in range(3): for i in range(repetitions): qpe.cp(math.pi/4, counting_qubit, 3); # This is CU # we use 2*pi*(1/theta) repetitions *= 2 qpe.draw() def qft_dagger(qc, n): """n-qubit QFTdagger the first n qubits in circ""" # Don't forget the Swaps! for qubit in range(n//2): qc.swap(qubit, n-qubit-1) for j in range(n): for m in range(j): qc.cp(-math.pi/float(2**(j-m)), m, j) qc.h(j) qpe.barrier() # Apply inverse QFT qft_dagger(qpe, 3) # Measure qpe.barrier() for n in range(3): qpe.measure(n,n) qpe.draw() aer_sim = Aer.get_backend('aer_simulator') shots = 2048 t_qpe = transpile(qpe, aer_sim) qobj = assemble(t_qpe, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) # Create and set up circuit qpe2 = QuantumCircuit(4, 3) # Apply H-Gates to counting qubits: for qubit in range(3): qpe2.h(qubit) # Prepare our eigenstate |psi>: qpe2.x(3) # Do the controlled-U operations: angle = 2*math.pi/3 repetitions = 1 for counting_qubit in range(3): for i in range(repetitions): qpe2.cp(angle, counting_qubit, 3); repetitions *= 2 # Do the inverse QFT: qft_dagger(qpe2, 3) # Measure of course! for n in range(3): qpe2.measure(n,n) qpe2.draw() # Let's see the results! aer_sim = Aer.get_backend('aer_simulator') shots = 4096 t_qpe2 = transpile(qpe2, aer_sim) qobj = assemble(t_qpe2, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) # Create and set up circuit qpe3 = QuantumCircuit(6, 5) # Apply H-Gates to counting qubits: for qubit in range(5): qpe3.h(qubit) # Prepare our eigenstate |psi>: qpe3.x(5) # Do the controlled-U operations: angle = 2*math.pi/3 repetitions = 1 for counting_qubit in range(5): for i in range(repetitions): qpe3.cp(angle, counting_qubit, 5); repetitions *= 2 # Do the inverse QFT: qft_dagger(qpe3, 5) # Measure of course! qpe3.barrier() for n in range(5): qpe3.measure(n,n) qpe3.draw() # Let's see the results! aer_sim = Aer.get_backend('aer_simulator') shots = 4096 t_qpe3 = transpile(qpe3, aer_sim) qobj = assemble(t_qpe3, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/oracleagent/qSHA256
oracleagent
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer from qiskit.circuit.library import XGate, RZGate, CXGate, CCXGate, U2Gate def quantum_xor(circuit, a, b, output): """Quantum XOR gate using CNOTs.""" circuit.cx(a, output) circuit.cx(b, output) def quantum_and(circuit, a, b, output, ancilla): """Quantum AND gate using Toffoli gate.""" circuit.ccx(a, b, ancilla) circuit.cx(ancilla, output) circuit.reset(ancilla) def right_rotate(circuit, qubits, rotation): """Performs a right rotation on a register.""" for _ in range(rotation): circuit.swap(qubits[0], qubits[-1]) qubits.insert(0, qubits.pop()) def quantum_adder(circuit, a, b, output, carry): """Quantum full-adder for bitwise addition.""" for i in range(len(a)): quantum_xor(circuit, a[i], b[i], output[i]) # Implementing carry is a complex process and would involve more auxiliary qubits def initialize_constants(circuit, qubits): """Initializes SHA-256 constants into the first part of a quantum register.""" # SHA-256 constants, first 32 bits of the fractional parts of the square roots of the first 8 primes constants = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 ] for idx, const in enumerate(constants): for bit_pos in range(32): if const & (1 << bit_pos): circuit.x(qubits[idx*32 + bit_pos]) def main_compression_loop(circuit, message_schedule, working_vars): # Implements the main loop of SHA-256 with quantum gates. for i in range(64): # Ch, Maj, sum0, sum1 are functions that need quantum implementations # These are placeholders and would be implemented similarly to the example functions above pass def sha256_quantum(): """Constructs a full SHA-256 quantum circuit.""" # For simplicity, assume a single 512-bit message block num_qubits = 8 * 32 + 512 # 8x32 for initial hash values, 512 for message schedule qr = QuantumRegister(num_qubits, 'qr') cr = ClassicalRegister(256, 'cr') # Output is 256 bits circuit = QuantumCircuit(qr, cr) # Initialize constants and hash values initialize_constants(circuit, qr[:8*32]) # Initial hash values # Message schedule would be loaded here # Main compression loop main_compression_loop(circuit, qr[8*32:], qr[:8*32]) # Measure the output hash into classical bits circuit.measure(qr[:256], cr) return circuit circuit = sha256_quantum() simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=simulator, shots=1).result() counts = result.get_counts() print(counts)
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
hub=qc-spring-22-2, group=group-5 and project=recPrYILNAOsYMWIV
https://github.com/hephaex/Quantum-Computing-Awesome-List
hephaex
from qiskit import QuantumCircuit, execute, Aer from qiskit.visualization import plot_histogram, plot_bloch_vector from math import sqrt, pi %config InlineBackend.figure_format = 'svg' qc = QuantumCircuit(1) initialize_state = [1,0] qc.initialize(initialize_state, 0) qc.draw() backend = Aer.get_backend('statevector_simulator') result = execute(qc, backend).result() out_state = result.get_statevector() print(out_state) qc.measure_all() qc.draw() counts = execute(qc, backend).result().get_counts() plot_histogram(counts) initial_state = [1/sqrt(3), complex(0, sqrt(2)/sqrt(3))] qc = QuantumCircuit(1) qc.initialize(initial_state, 0) state = execute(qc, backend).result().get_statevector() print(state) count = execute(qc, backend).result().get_counts() plot_histogram(count) qc = QuantumCircuit(1) # Redefine qc initial_state = [0.+1.j/sqrt(2),1/sqrt(2)+0.j] qc.initialize(initial_state, [0]) qc.draw() qc.measure_all() qc.draw() state = execute(qc,backend).result().get_statevector() print("State of Measured Qubit = " + str(state)) from qiskit_textbook.widgets import plot_bloch_vector_spherical coords = [pi/2,0,1] # [Theta, Phi, Radius] plot_bloch_vector_spherical(coords)
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
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/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import * # Create a Quantum Circuit acting on a quantum register of three qubits circ = QuantumCircuit(3) # Add a H gate on qubit $q_{0}$, putting this qubit in superposition. circ.h(0) # Add a CX (CNOT) gate on control qubit $q_{0}$ and target qubit $q_{1}$, putting # the qubits in a Bell state. circ.cx(0, 1) # Add a CX (CNOT) gate on control qubit $q_{0}$ and target qubit $q_{2}$, putting # the qubits in a GHZ state. circ.cx(0, 2) circ.draw('mpl') # Import Aer from qiskit import Aer # Run the quantum circuit on a statevector simulator backend backend = Aer.get_backend('statevector_simulator') # Create a Quantum Program for execution job = backend.run(circ) result = job.result() outputstate = result.get_statevector(circ, decimals=3) print(outputstate) from qiskit.visualization import plot_state_city plot_state_city(outputstate) # Run the quantum circuit on a unitary simulator backend backend = Aer.get_backend('unitary_simulator') job = backend.run(circ) result = job.result() # Show the results print(result.get_unitary(circ, decimals=3)) # Create a Quantum Circuit meas = QuantumCircuit(3, 3) meas.barrier(range(3)) # map the quantum measurement to the classical bits meas.measure(range(3), range(3)) # The Qiskit circuit object supports composition using # the compose method. circ.add_register(meas.cregs[0]) qc = circ.compose(meas) #drawing the circuit qc.draw() # Use Aer's qasm_simulator backend_sim = Aer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator. # We've set the number of repeats of the circuit # to be 1024, which is the default. job_sim = backend_sim.run(transpile(qc, backend_sim), shots=1024) # Grab the results from the job. result_sim = job_sim.result() counts = result_sim.get_counts(qc) print(counts) from qiskit.visualization import plot_histogram plot_histogram(counts) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/msramalho/Teach-Me-Quantum
msramalho
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute # Choose the drawer you like best: from qiskit.tools.visualization import matplotlib_circuit_drawer as draw #from qiskit.tools.visualization import circuit_drawer as draw from qiskit import IBMQ IBMQ.load_accounts() # make sure you have setup your token locally to use this %matplotlib inline import matplotlib.pyplot as plt def show_results(D): # D is a dictionary with classical bits as keys and count as value # example: D = {'000': 497, '001': 527} plt.bar(range(len(D)), list(D.values()), align='center') plt.xticks(range(len(D)), list(D.keys())) plt.show() from qiskit import Aer # See a list of available local simulators print("Aer backends: ", Aer.backends()) # see a list of available remote backends (these are freely given by IBM) print("IBMQ Backends: ", IBMQ.backends()) # execute circuit and either display a histogram of the results def execute_locally(qc, draw_circuit=False): # Compile and run the Quantum circuit on a simulator backend backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) result_sim = job_sim.result() result_counts = result_sim.get_counts(qc) # Print the results print("simulation: ", result_sim, result_counts) if draw_circuit: # draw the circuit draw(qc) else: # or show the results show_results(result_counts) from qiskit.backends.ibmq import least_busy import time # Compile and run on a real device backend def execute_remotely(qc, draw_circuit=False): if draw_circuit: # draw the circuit draw(qc) try: # select least busy available device and execute. least_busy_device = least_busy(IBMQ.backends(simulator=False)) print("Running on current least busy device: ", least_busy_device) # running the job job_exp = execute(qc, backend=least_busy_device, shots=1024, max_credits=10) lapse, interval = 0, 10 while job_exp.status().name != 'DONE': print('Status @ {} seconds'.format(interval * lapse)) print(job_exp.status()) time.sleep(interval) lapse += 1 print(job_exp.status()) exp_result = job_exp.result() result_counts = exp_result.get_counts(qc) # Show the results print("experiment: ", exp_result, result_counts) if not draw_circuit: # show the results show_results(result_counts) except: print("All devices are currently unavailable.") def new_circuit(size): # Create a Quantum Register with size qubits qr = QuantumRegister(size) # Create a Classical Register with size bits cr = ClassicalRegister(size) # Create a Quantum Circuit acting on the qr and cr register return qr, cr, QuantumCircuit(qr, cr) # create the circuit # H gate on qubit 0 # measure the qubits # create the circuit # H gate on qubit 0 # X gate on qubit 1 # measure the qubits # create the circuit execute_remotely(circuit)
https://github.com/abbarreto/qiskit2
abbarreto
%run init.ipynb from qiskit import * nshots = 8192 IBMQ.load_account() provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main') device = provider.get_backend('ibmq_bogota') simulator = Aer.get_backend('qasm_simulator') from qiskit.visualization import plot_histogram from qiskit.tools.monitor import job_monitor from qiskit.quantum_info import state_fidelity cos(pi/8), sin(pi/8) U = (1/sqrt(2))*Matrix([[1,1],[1,-1]]); V1 = Matrix([[1,0],[0,1]]); V2 = V1 D1 = Matrix([[cos(pi/8),0],[0,cos(pi/8)]]); D2 = Matrix([[sin(pi/8),0],[0,sin(pi/8)]]) U, U*U.T, D1, D2 M1 = V1*D1*U; M2 = V2*D2*U; M1, M2 M1*M1, M2*M2, M1*M1 + M2*M2 # não são projetores, mas são operadores de medida 2*float((1/4)*(1+1/sqrt(2))), 2*float((1/4)*(1-1/sqrt(2))) qr = QuantumRegister(2); cr = ClassicalRegister(1); qc = QuantumCircuit(qr, cr) qc.h(qr[0]); qc.x(qr[0]); qc.cry(math.pi/4, 0, 1); qc.x(qr[0]); qc.cry(math.pi/4, 0, 1) # V1=V2=I qc.measure(1,0) qc.draw(output = 'mpl') job_sim = execute(qc, backend = simulator, shots = nshots) job_exp = execute(qc, backend = device, shots = nshots) job_monitor(job_exp) plot_histogram([job_sim.result().get_counts(), job_exp.result().get_counts()], legend = ['sim', 'exp']) def U(xi, et, ga): return Matrix([[(cos(xi)+1j*sin(xi))*cos(ga), (cos(et)+1j*sin(et))*sin(ga)], [-(cos(et)-1j*sin(et))*sin(ga), (cos(xi)-1j*sin(xi))*cos(ga)]]) xi, et, ga = symbols('xi eta gamma'); U(xi, et, ga) def D1(th, ph): return Matrix([[cos(th/2),0],[0,cos(ph/2)]]) def D2(th, ph): return Matrix([[sin(th/2),0],[0,sin(ph/2)]]) th,ph = symbols('theta phi'); D1(th, ph), D2(th, ph) xi1,et1,ga1,xi2,et2,ga2,xi3,et3,ga3 = symbols('xi_1 eta_1 gamma_1 xi_2 eta_2 gamma_2 xi_3 eta_3 gamma_3') simplify(U(xi1,et1,ga1)*D1(th,ph)*U(xi2,et2,ga2) - (1/2)*sqrt(1+1/sqrt(2))*Matrix([[1,1],[1,-1]])) simplify(U(xi3,et3,ga3)*D2(th,ph)*U(xi2,et2,ga2) - (1/2)*sqrt(1+1/sqrt(2))*Matrix([[1,1],[1,-1]])) cos(pi/3), sin(pi/3), cos(2*pi/3), sin(2*pi/3) M1 = sqrt(2/3)*Matrix([[1,0],[0,0]]) M2 = (1/(4*sqrt(6)))*Matrix([[1,sqrt(3)],[sqrt(3),3]]) M3 = (1/(4*sqrt(6)))*Matrix([[1,-sqrt(3)],[-sqrt(3),3]]) M1,M2,M3 M1.T*M1 + M2.T*M2 + M3.T*M3 M1 = sqrt(2/3.)*Matrix([[1,0],[0,0]]); M2 = sqrt(2/3.)*(1/4)*Matrix([[1,sqrt(3.)],[sqrt(3.),3]]) M3 = sqrt(2/3.)*(1/4)*Matrix([[1,-sqrt(3.)],[-sqrt(3.),3]]) M1, M2, M3 M1.T*M1 + M2.T*M2 + M3.T*M3 2/3, 1/6, 2/3+2*(1/6) #th1 = acos(sqrt(2/3)); ph1 = pi; th2 = pi/2; ph2 = pi/2 D11 = Matrix([[sqrt(2/3),0],[0,0]]) D21 = Matrix([[sqrt(1/3),0],[0,1]]) D12 = Matrix([[1/sqrt(2),0],[0,1/sqrt(2)]]) D22 = Matrix([[1/sqrt(2),0],[0,1/sqrt(2)]]) U = Matrix([[1,0],[0,1]]) V11 = Matrix([[1,0],[0,1]]) V21 = (1/sqrt(2))*Matrix([[1,1],[-1,1]]) V12 = (1/2)*Matrix([[1,-sqrt(3)],[sqrt(3),1]]) V22 = -(1/2)*Matrix([[sqrt(3),-1],[1,sqrt(3)]]) M1 = V11*D11*U np.array(M1).astype(np.float64), np.array(Matrix([[sqrt(2/3),0],[0,0]])).astype(np.float64) M2 = V12*D12*V21*D21*U np.array(M2).astype(np.float64), np.array((1/4)*sqrt(2/3)*Matrix([[1,sqrt(3)],[sqrt(3),3]])).astype(np.float64) # não é o resultado que precisamos M3 = V22*D22*V21*D21*U np.array(M3).astype(np.float64), np.array((1/4)*sqrt(2/3)*Matrix([[1,-sqrt(3)],[-sqrt(3),3]])).astype(np.float64) # não é o resultado que precisamos np.array(M1.T*M1 + M2.T*M2 + M3.T*M3).astype(np.float64) # esta ok a relacao de completeza cos(pi/3), sin(pi/3), cos(pi/6) def qc_ry(th): qr = QuantumRegister(1); qc = QuantumCircuit(qr, name = 'RY') qc.ry(th, 0) return qc def qc_u(th,ph,lb): qr = QuantumRegister(1); qc = QuantumCircuit(qr, name = 'U') qc.u(th,ph,lb, 0) return qc qr = QuantumRegister(3); cr = ClassicalRegister(2); qc = QuantumCircuit(qr, cr) # U = I qc.x(qr[0]); qc.cry(math.acos(math.sqrt(2/3)), 0, 1); qc.x(qr[0]); qc.cry(math.pi/2, 0, 1) # V11 = I qc.cu(math.pi/2,math.pi,math.pi,0, 1,0) qc.barrier() qc_ry_ = qc_ry(0); ccry = qc_ry_.to_gate().control(2) # cria a ctrl-ctrl-RY qc.x(0); qc.append(ccry, [0,1,2]); qc.x(0) qc_ry_ = qc_ry(math.pi/2); ccry = qc_ry_.to_gate().control(2) qc.append(ccry, [0,1,2]) # os primeiros sao o controle, os ultimos sao o target qc.x(2) qc_u_ = qc_u(2*math.pi/3,0,0); ccu = qc_u_.to_gate().control(2) qc.append(ccu, [1,2,0]) qc.x(2) qc_u_ = qc_u(4*math.pi/3,0,0); ccu = qc_u_.to_gate().control(2) qc.append(ccu, [1,2,0]) qc.barrier() qc.measure(1,0); qc.measure(2,1) qc.draw(output = 'mpl') qc.decompose().draw(output = 'mpl') job_sim = execute(qc, backend = simulator, shots = nshots) job_exp = execute(qc, backend = device, shots = nshots) job_monitor(job_exp) plot_histogram([job_sim.result().get_counts(), job_exp.result().get_counts()], legend = ['sim', 'exp']) # sequencia: 000 001 010 011 100 101 110 111 = 0 1 2 3 4 5 6 7 Phi_ACD = [math.sqrt(2/3), (1/4)*math.sqrt(2/3), (1/4)*math.sqrt(2/3), 0, 0, (1/4)*math.sqrt(2), -(1/4)*math.sqrt(2), 0] qr = QuantumRegister(3); cr = ClassicalRegister(2); qc = QuantumCircuit(qr,cr) qc.initialize(Phi_ACD, [qr[2],qr[1],qr[0]]) qc.draw(output='mpl') backend = BasicAer.get_backend('statevector_simulator') job = backend.run(transpile(qc, backend)) qc_state = job.result().get_statevector(qc) qc_state sqrt(2/3), 0.25*sqrt(2/3), 0.25*sqrt(2.) state_fidelity(Phi_ACD,qc_state) qc.measure([1,2],[0,1]) qc.draw(output='mpl') job_sim = execute(qc, backend = simulator, shots = nshots) job_exp = execute(qc, backend = device, shots = nshots) job_monitor(job_exp) # tava dando errado o resultado. Me parece que na inicializacao a ordem dos qubits foi trocada plot_histogram([job_sim.result().get_counts(), job_exp.result().get_counts()], legend = ['sim', 'exp']) # sequencia: 000 001 010 011 100 101 110 111 = 0 1 2 3 4 5 6 7 Phi_ACD = [1/math.sqrt(2), 1/(2*math.sqrt(2)), 0, 1/(2*math.sqrt(2)), 0, 1/(2*math.sqrt(2)), 0, -1/(2*math.sqrt(2))] qr = QuantumRegister(3); cr = ClassicalRegister(2); qc = QuantumCircuit(qr,cr) qc.initialize(Phi_ACD, [qr[2],qr[1],qr[0]]) qc.measure([1,2],[0,1]) qc.draw(output='mpl') qc.decompose().decompose().decompose().decompose().decompose().draw(output='mpl') job_sim = execute(qc, backend = simulator, shots = nshots) job_exp = execute(qc, backend = device, shots = nshots) job_monitor(job_exp) plot_histogram([job_sim.result().get_counts(), job_exp.result().get_counts()], legend = ['sim', 'exp']) qr = QuantumRegister(4); cr = ClassicalRegister(3); qc = QuantumCircuit(qr, cr) # U = I qc.x(qr[0]); qc.cry(math.acos(math.sqrt(2/3)), 0, 1); qc.x(qr[0]); qc.cry(math.pi/2, 0, 1) # V11 = I qc.cu(math.pi/2,math.pi,math.pi,0, 1,0) qc.barrier() qc_ry_ = qc_ry(0); ccry = qc_ry_.to_gate().control(2) # cria a ctrl-ctrl-RY qc.x(0); qc.append(ccry, [0,1,2]); qc.x(0) qc_ry_ = qc_ry(math.pi/2); ccry = qc_ry_.to_gate().control(2) qc.append(ccry, [0,1,2]) # os primeiros sao o controle, os ultimos sao o target qc.x(2) qc_u_ = qc_u(2*math.pi/3,0,0); ccu = qc_u_.to_gate().control(2) qc.append(ccu, [1,2,0]) qc.x(2) qc_u_ = qc_u(4*math.pi/3,0,0); ccu = qc_u_.to_gate().control(2) qc.append(ccu, [1,2,0]) qc.barrier() qc_ry_ = qc_ry(math.pi); cccry = qc_ry_.to_gate().control(3) # cria a ctrl-ctrl-ctrl-RY qc.x(0); qc.append(cccry, [0,1,2,3]); qc.x(0) qc_ry_ = qc_ry(math.pi/2); cccry = qc_ry_.to_gate().control(3) qc.append(cccry, [0,1,2,3]) qc_u_ = qc_u(math.pi,0,0); cccu = qc_u_.to_gate().control(3) qc.x(3); qc.append(cccu, [3,2,1,0]); qc.x(3) qc.append(cccu, [3,2,1,0]) qc_u_ = qc_u(math.pi/3,0,0); cccu = qc_u_.to_gate().control(3) qc.barrier() qc.measure(1,0); qc.measure(2,1); qc.measure(3,2) qc.draw(output = 'mpl') qc.decompose().draw(output = 'mpl') %run init.ipynb # 2 element 1-qubit povm (Yordanov) M1 = (1/2)*Matrix([[1,0],[0,sqrt(3)]]); M2 = M1 M1, M2 M1.T*M1 + M2.T*M2 # 3 element 1-qubit povm (Yordanov) M1 = sqrt(2/3)*Matrix([[1,0],[0,0]]) M2 = (1/(4*sqrt(6)))*Matrix([[1,sqrt(3)],[sqrt(3),1]]) M3 = (1/(4*sqrt(6)))*Matrix([[1,-sqrt(3)],[-sqrt(3),1]]) M1,M2,M3 M1.T*M1 + M2.T*M2 + M3.T*M3 # 2-element 1-qubit POVM (Douglas) M1 = (1/(2*sqrt(2)))*Matrix([[1,0],[sqrt(3),2]]) M2 = (1/(2*sqrt(2)))*Matrix([[1,0],[-sqrt(3),2]]) M1,M2 M1.T*M1 + M2.T*M2
https://github.com/ankitkmisra/Quantum-Computing-and-Cryptography
ankitkmisra
from qiskit import * from qiskit.tools.jupyter import * from qiskit.visualization import * import matplotlib.pyplot as plotter import numpy as np from IPython.display import display, Math, Latex %matplotlib inline # Loading your IBM Q account(s) provider = IBMQ.load_account() qr = QuantumRegister(3) crz = ClassicalRegister(1) crx = ClassicalRegister(2) # we will need seperates registers for using 'c_if' later. qc = QuantumCircuit(qr,crz,crx) qc.x(0) qc.h(0) # 'psi' can't be unknown to us as we are creating it here. Let us take '-' state as our 'psi' # We will verify later if the '-' is been teleported. qc.h(1) qc.cx(1,2) # creating a bell state qc.barrier() # Use barrier to separate steps, everything till this barrier is just intialisation. qc.cx(0,1) # '0' and '1' are with Alice and '2' is with Bob. # psi_1 prepared. qc.h(0) # psi_2 prepared. qc.barrier() qc.measure(0,0) qc.measure(1,1) qc.draw (output = 'mpl') qc.x(2).c_if(crx,1) # 'c_if' compares a classical register with a value (either 0 or 1) and performs the qc.z(2).c_if(crz,1) # operation if they are equal. qc.draw('mpl') # be careful of the order of applying X and Z! qc.h(2) qc.measure(2,crx[1]) 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) # the output should be '1xx' if the teleportation is successful. # Refer to above cell for a detailed explanation of the strategy. qc1 = QuantumCircuit(2, 2) # Preparing Alice's Bell state: \beta_{00} qc1.h(0) qc1.cx(0, 1) # Skyler's mischief: # Suppose for this example that she applied Pauli-Y. # You can change 'y' to 'x' or 'z' in the following line for other cases. qc1.y(0) # Alice's strategy: qc1.cx(0, 1) qc1.h(0) qc1.measure(0, 0) qc1.measure(1, 1) qc1.draw('mpl') 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(qc1) print(counts) if '10' in counts: print('Skyler used Pauli-X!') if '11' in counts: print('Skyler used Pauli-Y!') if '01' in counts: print('Skyler used Pauli-Z!') plot_histogram(counts)
https://github.com/scaleway/qiskit-scaleway
scaleway
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for Sampler.""" import unittest import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.circuit.library import RealAmplitudes from qiskit.exceptions import QiskitError from qiskit.extensions.unitary import UnitaryGate from qiskit.primitives import Sampler, SamplerResult from qiskit.providers import JobStatus, JobV1 from qiskit.test import QiskitTestCase class TestSampler(QiskitTestCase): """Test Sampler""" def setUp(self): super().setUp() hadamard = QuantumCircuit(1, 1, name="Hadamard") hadamard.h(0) hadamard.measure(0, 0) bell = QuantumCircuit(2, name="Bell") bell.h(0) bell.cx(0, 1) bell.measure_all() self._circuit = [hadamard, bell] self._target = [ {0: 0.5, 1: 0.5}, {0: 0.5, 3: 0.5, 1: 0, 2: 0}, ] self._pqc = RealAmplitudes(num_qubits=2, reps=2) self._pqc.measure_all() self._pqc2 = RealAmplitudes(num_qubits=2, reps=3) self._pqc2.measure_all() self._pqc_params = [[0.0] * 6, [1.0] * 6] self._pqc_target = [{0: 1}, {0: 0.0148, 1: 0.3449, 2: 0.0531, 3: 0.5872}] self._theta = [ [0, 1, 1, 2, 3, 5], [1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4, 5, 6, 7], ] def _generate_circuits_target(self, indices): if isinstance(indices, list): circuits = [self._circuit[j] for j in indices] target = [self._target[j] for j in indices] else: raise ValueError(f"invalid index {indices}") return circuits, target def _generate_params_target(self, indices): if isinstance(indices, int): params = self._pqc_params[indices] target = self._pqc_target[indices] elif isinstance(indices, list): params = [self._pqc_params[j] for j in indices] target = [self._pqc_target[j] for j in indices] else: raise ValueError(f"invalid index {indices}") return params, target def _compare_probs(self, prob, target): if not isinstance(prob, list): prob = [prob] if not isinstance(target, list): target = [target] self.assertEqual(len(prob), len(target)) for p, targ in zip(prob, target): for key, t_val in targ.items(): if key in p: self.assertAlmostEqual(p[key], t_val, places=1) else: self.assertAlmostEqual(t_val, 0, places=1) def test_sampler_run(self): """Test Sampler.run().""" bell = self._circuit[1] sampler = Sampler() job = sampler.run(circuits=[bell]) self.assertIsInstance(job, JobV1) result = job.result() self.assertIsInstance(result, SamplerResult) # print([q.binary_probabilities() for q in result.quasi_dists]) self._compare_probs(result.quasi_dists, self._target[1]) def test_sample_run_multiple_circuits(self): """Test Sampler.run() with multiple circuits.""" # executes three Bell circuits # Argument `parameters` is optional. bell = self._circuit[1] sampler = Sampler() result = sampler.run([bell, bell, bell]).result() # print([q.binary_probabilities() for q in result.quasi_dists]) self._compare_probs(result.quasi_dists[0], self._target[1]) self._compare_probs(result.quasi_dists[1], self._target[1]) self._compare_probs(result.quasi_dists[2], self._target[1]) def test_sampler_run_with_parameterized_circuits(self): """Test Sampler.run() with parameterized circuits.""" # parameterized circuit pqc = self._pqc pqc2 = self._pqc2 theta1, theta2, theta3 = self._theta sampler = Sampler() result = sampler.run([pqc, pqc, pqc2], [theta1, theta2, theta3]).result() # result of pqc(theta1) prob1 = { "00": 0.1309248462975777, "01": 0.3608720796028448, "10": 0.09324865232050054, "11": 0.41495442177907715, } self.assertDictAlmostEqual(result.quasi_dists[0].binary_probabilities(), prob1) # result of pqc(theta2) prob2 = { "00": 0.06282290651933871, "01": 0.02877144385576705, "10": 0.606654494132085, "11": 0.3017511554928094, } self.assertDictAlmostEqual(result.quasi_dists[1].binary_probabilities(), prob2) # result of pqc2(theta3) prob3 = { "00": 0.1880263994380416, "01": 0.6881971261189544, "10": 0.09326232720582443, "11": 0.030514147237179892, } self.assertDictAlmostEqual(result.quasi_dists[2].binary_probabilities(), prob3) def test_run_1qubit(self): """test for 1-qubit cases""" qc = QuantumCircuit(1) qc.measure_all() qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() sampler = Sampler() result = sampler.run([qc, qc2]).result() self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 2) for i in range(2): keys, values = zip(*sorted(result.quasi_dists[i].items())) self.assertTupleEqual(keys, (i,)) np.testing.assert_allclose(values, [1]) def test_run_2qubit(self): """test for 2-qubit cases""" qc0 = QuantumCircuit(2) qc0.measure_all() qc1 = QuantumCircuit(2) qc1.x(0) qc1.measure_all() qc2 = QuantumCircuit(2) qc2.x(1) qc2.measure_all() qc3 = QuantumCircuit(2) qc3.x([0, 1]) qc3.measure_all() sampler = Sampler() result = sampler.run([qc0, qc1, qc2, qc3]).result() self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 4) for i in range(4): keys, values = zip(*sorted(result.quasi_dists[i].items())) self.assertTupleEqual(keys, (i,)) np.testing.assert_allclose(values, [1]) def test_run_single_circuit(self): """Test for single circuit case.""" sampler = Sampler() with self.subTest("No parameter"): circuit = self._circuit[1] target = self._target[1] param_vals = [None, [], [[]], np.array([]), np.array([[]])] for val in param_vals: with self.subTest(f"{circuit.name} w/ {val}"): result = sampler.run(circuit, val).result() self._compare_probs(result.quasi_dists, target) self.assertEqual(len(result.metadata), 1) with self.subTest("One parameter"): circuit = QuantumCircuit(1, 1, name="X gate") param = Parameter("x") circuit.ry(param, 0) circuit.measure(0, 0) target = [{1: 1}] param_vals = [ [np.pi], [[np.pi]], np.array([np.pi]), np.array([[np.pi]]), [np.array([np.pi])], ] for val in param_vals: with self.subTest(f"{circuit.name} w/ {val}"): result = sampler.run(circuit, val).result() self._compare_probs(result.quasi_dists, target) self.assertEqual(len(result.metadata), 1) with self.subTest("More than one parameter"): circuit = self._pqc target = [self._pqc_target[0]] param_vals = [ self._pqc_params[0], [self._pqc_params[0]], np.array(self._pqc_params[0]), np.array([self._pqc_params[0]]), [np.array(self._pqc_params[0])], ] for val in param_vals: with self.subTest(f"{circuit.name} w/ {val}"): result = sampler.run(circuit, val).result() self._compare_probs(result.quasi_dists, target) self.assertEqual(len(result.metadata), 1) def test_run_reverse_meas_order(self): """test for sampler with reverse measurement order""" x = Parameter("x") y = Parameter("y") qc = QuantumCircuit(3, 3) qc.rx(x, 0) qc.rx(y, 1) qc.x(2) qc.measure(0, 2) qc.measure(1, 1) qc.measure(2, 0) sampler = Sampler() result = sampler.run([qc] * 2, [[0, 0], [np.pi / 2, 0]]).result() self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 2) # qc({x: 0, y: 0}) keys, values = zip(*sorted(result.quasi_dists[0].items())) self.assertTupleEqual(keys, (1,)) np.testing.assert_allclose(values, [1]) # qc({x: pi/2, y: 0}) keys, values = zip(*sorted(result.quasi_dists[1].items())) self.assertTupleEqual(keys, (1, 5)) np.testing.assert_allclose(values, [0.5, 0.5]) def test_run_errors(self): """Test for errors with run method""" qc1 = QuantumCircuit(1) qc1.measure_all() qc2 = RealAmplitudes(num_qubits=1, reps=1) qc2.measure_all() qc3 = QuantumCircuit(1) qc4 = QuantumCircuit(1, 1) sampler = Sampler() with self.subTest("set parameter values to a non-parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([qc1], [[1e2]]) with self.subTest("missing all parameter values for a parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([qc2], [[]]) with self.subTest("missing some parameter values for a parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([qc2], [[1e2]]) with self.subTest("too many parameter values for a parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([qc2], [[1e2]] * 100) with self.subTest("no classical bits"): with self.assertRaises(ValueError): _ = sampler.run([qc3], [[]]) with self.subTest("no measurement"): with self.assertRaises(QiskitError): # The following raises QiskitError because this check is located in # `Sampler._preprocess_circuit` _ = sampler.run([qc4], [[]]) def test_run_empty_parameter(self): """Test for empty parameter""" n = 5 qc = QuantumCircuit(n, n - 1) qc.measure(range(n - 1), range(n - 1)) sampler = Sampler() with self.subTest("one circuit"): result = sampler.run([qc], shots=1000).result() self.assertEqual(len(result.quasi_dists), 1) for q_d in result.quasi_dists: quasi_dist = {k: v for k, v in q_d.items() if v != 0.0} self.assertDictEqual(quasi_dist, {0: 1.0}) self.assertEqual(len(result.metadata), 1) with self.subTest("two circuits"): result = sampler.run([qc, qc], shots=1000).result() self.assertEqual(len(result.quasi_dists), 2) for q_d in result.quasi_dists: quasi_dist = {k: v for k, v in q_d.items() if v != 0.0} self.assertDictEqual(quasi_dist, {0: 1.0}) self.assertEqual(len(result.metadata), 2) def test_run_numpy_params(self): """Test for numpy array as parameter values""" qc = RealAmplitudes(num_qubits=2, reps=2) qc.measure_all() k = 5 params_array = np.random.rand(k, qc.num_parameters) params_list = params_array.tolist() params_list_array = list(params_array) sampler = Sampler() target = sampler.run([qc] * k, params_list).result() with self.subTest("ndarrary"): result = sampler.run([qc] * k, params_array).result() self.assertEqual(len(result.metadata), k) for i in range(k): self.assertDictEqual(result.quasi_dists[i], target.quasi_dists[i]) with self.subTest("list of ndarray"): result = sampler.run([qc] * k, params_list_array).result() self.assertEqual(len(result.metadata), k) for i in range(k): self.assertDictEqual(result.quasi_dists[i], target.quasi_dists[i]) def test_run_with_shots_option(self): """test with shots option.""" params, target = self._generate_params_target([1]) sampler = Sampler() result = sampler.run( circuits=[self._pqc], parameter_values=params, shots=1024, seed=15 ).result() self._compare_probs(result.quasi_dists, target) def test_run_with_shots_option_none(self): """test with shots=None option. Seed is ignored then.""" sampler = Sampler() result_42 = sampler.run( [self._pqc], parameter_values=[[0, 1, 1, 2, 3, 5]], shots=None, seed=42 ).result() result_15 = sampler.run( [self._pqc], parameter_values=[[0, 1, 1, 2, 3, 5]], shots=None, seed=15 ).result() self.assertDictAlmostEqual(result_42.quasi_dists, result_15.quasi_dists) def test_run_shots_result_size(self): """test with shots option to validate the result size""" n = 10 shots = 100 qc = QuantumCircuit(n) qc.h(range(n)) qc.measure_all() sampler = Sampler() result = sampler.run(qc, [], shots=shots, seed=42).result() self.assertEqual(len(result.quasi_dists), 1) self.assertLessEqual(len(result.quasi_dists[0]), shots) self.assertAlmostEqual(sum(result.quasi_dists[0].values()), 1.0) def test_primitive_job_status_done(self): """test primitive job's status""" bell = self._circuit[1] sampler = Sampler() job = sampler.run(circuits=[bell]) _ = job.result() self.assertEqual(job.status(), JobStatus.DONE) def test_options(self): """Test for options""" with self.subTest("init"): sampler = Sampler(options={"shots": 3000}) self.assertEqual(sampler.options.get("shots"), 3000) with self.subTest("set_options"): sampler.set_options(shots=1024, seed=15) self.assertEqual(sampler.options.get("shots"), 1024) self.assertEqual(sampler.options.get("seed"), 15) with self.subTest("run"): params, target = self._generate_params_target([1]) result = sampler.run([self._pqc], parameter_values=params).result() self._compare_probs(result.quasi_dists, target) self.assertEqual(result.quasi_dists[0].shots, 1024) def test_circuit_with_unitary(self): """Test for circuit with unitary gate.""" gate = UnitaryGate(np.eye(2)) circuit = QuantumCircuit(1) circuit.append(gate, [0]) circuit.measure_all() sampler = Sampler() sampler_result = sampler.run([circuit]).result() self.assertDictAlmostEqual(sampler_result.quasi_dists[0], {0: 1, 1: 0}) if __name__ == "__main__": unittest.main()
https://github.com/zapatacomputing/qe-qiskit
zapatacomputing
################################################################################ # © Copyright 2021 Zapata Computing Inc. ################################################################################ import json import os import subprocess import unittest import numpy as np import qiskit.providers.aer.noise as AerNoise from qeqiskit.noise.basic import ( create_amplitude_damping_noise, get_kraus_matrices_from_ibm_noise_model, ) from qeqiskit.utils import ( load_qiskit_noise_model, save_kraus_operators, save_qiskit_noise_model, ) from zquantum.core.utils import load_noise_model, save_noise_model class TestQiskitUtils(unittest.TestCase): def setUp(self): self.T_1 = 10e-7 self.t_step = 10e-9 def test_save_qiskit_noise_model(self): # Given noise_model = AerNoise.NoiseModel() coherent_error = np.asarray( [ np.asarray( [0.87758256 - 0.47942554j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j] ), np.asarray( [0.0 + 0.0j, 0.87758256 + 0.47942554j, 0.0 + 0.0j, 0.0 + 0.0j] ), np.asarray( [0.0 + 0.0j, 0.0 + 0.0j, 0.87758256 + 0.47942554j, 0.0 + 0.0j] ), np.asarray( [0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.87758256 - 0.47942554j] ), ] ) noise_model.add_quantum_error( AerNoise.coherent_unitary_error(coherent_error), ["cx"], [0, 1] ) filename = "noise_model.json" # When save_qiskit_noise_model(noise_model, filename) # Then with open("noise_model.json", "r") as f: data = json.loads(f.read()) self.assertEqual(data["module_name"], "qeqiskit.utils") self.assertEqual(data["function_name"], "load_qiskit_noise_model") self.assertIsInstance(data["data"], dict) # Cleanup subprocess.run(["rm", "noise_model.json"]) def test_noise_model_io_using_core_functions(self): # Given noise_model = AerNoise.NoiseModel() coherent_error = np.asarray( [ np.asarray( [0.87758256 - 0.47942554j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j] ), np.asarray( [0.0 + 0.0j, 0.87758256 + 0.47942554j, 0.0 + 0.0j, 0.0 + 0.0j] ), np.asarray( [0.0 + 0.0j, 0.0 + 0.0j, 0.87758256 + 0.47942554j, 0.0 + 0.0j] ), np.asarray( [0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.87758256 - 0.47942554j] ), ] ) noise_model.add_quantum_error( AerNoise.coherent_unitary_error(coherent_error), ["cx"], [0, 1] ) noise_model_data = noise_model.to_dict(serializable=True) module_name = "qeqiskit.utils" function_name = "load_qiskit_noise_model" filename = "noise_model.json" # When save_noise_model(noise_model_data, module_name, function_name, filename) new_noise_model = load_noise_model(filename) # Then self.assertEqual( noise_model.to_dict(serializable=True), new_noise_model.to_dict(serializable=True), ) # Cleanup subprocess.run(["rm", "noise_model.json"]) def test_save_kraus_operators(self): noise_model = create_amplitude_damping_noise(self.T_1, self.t_step) kraus_dict = get_kraus_matrices_from_ibm_noise_model(noise_model) save_kraus_operators(kraus_dict, "kraus_operators.json") # Cleanup os.remove("kraus_operators.json")
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ A collection of functions that decide the layout of an output image. See :py:mod:`~qiskit.visualization.timeline.types` for more info on the required data. There are 2 types of layout functions in this module. 1. layout.bit_arrange In this stylesheet entry the input data is a list of `types.Bits` and returns a sorted list of `types.Bits`. The function signature of the layout is restricted to: ```python def my_layout(bits: List[types.Bits]) -> List[types.Bits]: # your code here: sort input bits and return list of bits ``` 2. layout.time_axis_map In this stylesheet entry the input data is `Tuple[int, int]` that represents horizontal axis limit of the output image. The layout function returns `types.HorizontalAxis` data which is consumed by the plotter API to make horizontal axis. The function signature of the layout is restricted to: ```python def my_layout(time_window: Tuple[int, int]) -> types.HorizontalAxis: # your code here: create and return axis config ``` Arbitrary layout function satisfying the above format can be accepted. """ import warnings from typing import List, Tuple import numpy as np from qiskit import circuit from qiskit.visualization.exceptions import VisualizationError from qiskit.visualization.timeline import types def qreg_creg_ascending(bits: List[types.Bits]) -> List[types.Bits]: """Sort bits by ascending order. Bit order becomes Q0, Q1, ..., Cl0, Cl1, ... Args: bits: List of bits to sort. Returns: Sorted bits. """ qregs = [] cregs = [] for bit in bits: if isinstance(bit, circuit.Qubit): qregs.append(bit) elif isinstance(bit, circuit.Clbit): cregs.append(bit) else: raise VisualizationError(f"Unknown bit {bit} is provided.") with warnings.catch_warnings(): warnings.simplefilter("ignore") qregs = sorted(qregs, key=lambda x: x.index, reverse=False) cregs = sorted(cregs, key=lambda x: x.index, reverse=False) return qregs + cregs def qreg_creg_descending(bits: List[types.Bits]) -> List[types.Bits]: """Sort bits by descending order. Bit order becomes Q_N, Q_N-1, ..., Cl_N, Cl_N-1, ... Args: bits: List of bits to sort. Returns: Sorted bits. """ qregs = [] cregs = [] for bit in bits: if isinstance(bit, circuit.Qubit): qregs.append(bit) elif isinstance(bit, circuit.Clbit): cregs.append(bit) else: raise VisualizationError(f"Unknown bit {bit} is provided.") qregs = sorted(qregs, key=lambda x: x.index, reverse=True) cregs = sorted(cregs, key=lambda x: x.index, reverse=True) return qregs + cregs def time_map_in_dt(time_window: Tuple[int, int]) -> types.HorizontalAxis: """Layout function for the horizontal axis formatting. Generate equispaced 6 horizontal axis ticks. Args: time_window: Left and right edge of this graph. Returns: Axis formatter object. """ # shift time axis t0, t1 = time_window # axis label axis_loc = np.linspace(max(t0, 0), t1, 6) axis_label = axis_loc.copy() # consider time resolution label = "System cycle time (dt)" formatted_label = [f"{val:.0f}" for val in axis_label] return types.HorizontalAxis( window=(t0, t1), axis_map=dict(zip(axis_loc, formatted_label)), label=label )
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# You may need to trust this notebook before the button below works from IPython.display import HTML HTML('''<script> code_show=true; function code_toggle() { if (code_show){ $('div.input').hide(); } else { $('div.input').show(); } code_show = !code_show } $( document ).ready(code_toggle); </script> <form action="javascript:code_toggle()"><input type="submit" value="Click here to toggle on/off the raw code."></form>''') def cplayer_output(strategy, inp): if(strategy == 1): return inp elif(strategy == 2): return abs(inp-1) elif(strategy == 3): return 1 elif(strategy == 4): return 0 else: print("INVALID choice") return 100 # Pick Alice's classical strategy A_st = int(input('select the classical strategy for Alice, input 1,2,3 or 4 to pick one of the strategies listed above ')) # Pick Bob's classical strategy B_st = int(input('select the classical strategy for Bob, input 1,2,3 or 4 to pick one of the strategies listed above ')) # useful packages import numpy as np import random as rand # fixes the numbers of games to be played N=100 # initializes counters used to keep track of the numbers of games won and played by Alice an Bob cont_win = 0 # counts games won cont_tot = 0 # counts games played # play the game N times for i in range(N): # generates two random input from the refree, x and y, to be given to Alice and Bob random_num1 = rand.random() # first random number random_num2 = rand.random() # second random number if(random_num1 >= 1/2): # converts the first random number to 0 or 1 x = 0 else: x = 1 if(random_num2 >= 1/2): # converts the second random number to 0 or 1 y = 0 else: y = 1 # generates Alice's and Bob's output a = cplayer_output(A_st, x) # Alice's output b = cplayer_output(B_st, y) # Bob's output # check if the condition for winning the game is met if(x*y == a^b): cont_win += 1 # increase thes won games' counter if the condition to win the game is met cont_tot += 1 # increases the played games' counter Prob_win = cont_win/cont_tot # winning probability print('Alice and Bob won the game with probability: ', Prob_win*100, '%') def qAlice_output(strategy, inp): if(strategy == 1): return 0 elif(strategy == 2): return rand.uniform(0,2*np.pi) elif(strategy == 3): if(inp == 0): return 0 elif(inp == 1): return np.pi/2 else: print("INVALID choice") return 100 def qBob_output(strategy, inp): if(strategy == 1): return 0 elif(strategy == 2): return rand.uniform(0,2*np.pi) elif(strategy == 3): if(inp == 0): return np.pi/4 elif(inp == 1): return -np.pi/4 else: print("INVALID choice") return 100 # Alice's strategy qA_st = int(input('select the quantum strategy for Alice, input 1,2 or 3 to pick one of the strategies listed above: ')) # Bob's strategy qB_st = int(input('select the quantum strategy for Bob, input 1,2 or 3 to pick one of the strategies listed above: ')) # import packages from qiskit import * import numpy as np import random as rand # set parameters of the quantum run of the game shots = 1 # set how many times the circuit is run, accumulating statistics about the measurement outcomes backend = 'local_qasm_simulator' # set the machine where the quantum circuit is to be run #fixes the numbers of games to be played N=100 # initializes counters used to keep track of the numbers of games won and played by Alice an Bob cont_win = 0 # counts games won cont_tot = 0 # counts games played #play N games for i in range(N): #creates quantum program, which allows to specify the details of the circuit like the register and the gates used Q_program = QuantumProgram() # creates registers for qubits and bits q = Q_program.create_quantum_register('q', 2) # creates a quantum register, it specifies the qubits which are going to be used for the program c = Q_program.create_classical_register('c', 2) # creates a classical register, the results of the measurement of the qubits are stored here # creates quantum circuit, to write a quantum algorithm we will add gates to the circuit game = Q_program.create_circuit('game', [q], [c]) # These gates prepare the entangled Bell pair to be shared by Alice and Bob as part of their quantum strategy # Alice will have qubit 0 and Bob will have qubit 1 game.h(q[0]) # Hadamard gate on qubit 0 game.cx(q[0],q[1]) # CNOT gate on qubit 1 controlled by qubit 0 # generates two random input from the refree, x and y, to be given to Alice and Bob random_num1 = rand.random() # first random number random_num2 = rand.random() # second random number if(random_num1 >= 1/2): # converts the first random number to 0 or 1 x = 0 else: x = 1 if(random_num2 >= 1/2): # converts the second random number to 0 or 1 y = 0 else: y = 1 # The main part of Alice and Bob quantum strategy is to fix different rotation angles for their qubit according to the input x,y theta = qAlice_output(qA_st, x) # fixes Alice's rotation for her qubit phi = qBob_output(qB_st, y) # fixes Bob's rotation for his qubit # The following gates rotate Alice's qubit and Bob's qubit game.ry(theta,q[0]) #rotates Alice's qubit of an angle theta game.ry(phi,q[1]) ##rotates Bob's qubit of an angle phi # These gates are used to measure the value of the qubits game.measure(q[0], c[0]) # measure Alice's qubit and stores the result in a classical bit game.measure(q[1], c[1]) # measure Bob's qubit and stores the result in a classical bit # Assemble the gates in the circuit circuits = ['game'] # assemble circuit # executes circuit and store the output of the measurements result = Q_program.execute(circuits, backend=backend, shots=shots, wait=10, timeout=240) data = result.get_counts('game') # extract the outcomes and their statistics from the result of the execution # reads the result of the measurements of the quantum system for outcomes in data.keys(): out = outcomes # converts the result of the measurements contained in the classical register as string '00', '01', '10', '11', # which are the answers of Alice(a) and Bob (b), from a 'string' type to 'integer' type if(out == '00'): a = 0 b = 0 if(out == '01'): a = 1 b = 0 if(out == '10'): a = 0 b = 1 if(out == '11'): a = 1 b = 1 # check if the condition for winning the game is met if(x*y == a^b): cont_win += 1 # increase thes won games' counter if the condition to win the game is met cont_tot += 1 # increases the played games' counter qProb_win = cont_win/cont_tot print('Alice and Bob won the game with probability: ', qProb_win*100, '%') if Prob_win > qProb_win : print("The classical strategy gave Alice and Bob higher chances of winning") else: print("The quantum strategy gave Alice and Bob higher chances of winning")
https://github.com/Kairos-T/QRNG
Kairos-T
from flask import Flask, render_template, request, jsonify from qiskit import QuantumCircuit, Aer, transpile, assemble import matplotlib.pyplot as plt from io import BytesIO import base64 import numpy as np from scipy import stats app = Flask(__name__) # Global variables number_counts = {} total_generated = 0 def generate_random_number(min_value, max_value): global total_generated if min_value > max_value: raise ValueError( "Invalid range: Minimum value should be less than or equal to the maximum value") num_bits = len(bin(max_value)) - 2 circuit = QuantumCircuit(num_bits, num_bits) circuit.h(range(num_bits)) circuit.measure(range(num_bits), range(num_bits)) backend = Aer.get_backend('qasm_simulator') result = backend.run( assemble(transpile(circuit, backend=backend))).result() counts = result.get_counts(circuit) random_number = int(list(counts.keys())[0], 2) # Ensure that the generated number is within the specified range random_number = min(max(random_number, min_value), max_value) # Update the count of the generated number in the dictionary number_counts[random_number] = number_counts.get(random_number, 0) + 1 total_generated += 1 return random_number def generate_numbers(min_value, max_value, num_samples=1): global total_generated if min_value > max_value: raise ValueError( "Invalid range: Minimum value should be less than or equal to the maximum value") num_bits = len(bin(max_value)) - 2 backend = Aer.get_backend('qasm_simulator') generated_numbers = [] for _ in range(num_samples): circuit = QuantumCircuit(num_bits, num_bits) circuit.h(range(num_bits)) circuit.measure(range(num_bits), range(num_bits)) result = backend.run( assemble(transpile(circuit, backend=backend))).result() counts = result.get_counts(circuit) random_number = int(list(counts.keys())[0], 2) # Ensure that the generated number is within the specified range random_number = min(max(random_number, min_value), max_value) # Update the count of the generated number in the dictionary number_counts[random_number] = number_counts.get(random_number, 0) + 1 total_generated += 1 generated_numbers.append(random_number) return generated_numbers def remove_outliers(data, z_threshold=3): z_scores = np.abs(stats.zscore(data)) outliers = np.where(z_scores > z_threshold)[0] cleaned_data = [data[i] for i in range(len(data)) if i not in outliers] return cleaned_data def plot_bar_chart(remove_outliers_flag=False): global number_counts data_keys = list(number_counts.keys()) data_values = list(number_counts.values()) if remove_outliers_flag: cleaned_data = remove_outliers(data_values) number_counts = {key: value for key, value in zip(data_keys, cleaned_data)} data_values = cleaned_data data_keys = data_keys[:len(data_values)] plt.bar(data_keys, data_values) plt.xlabel('Number') plt.ylabel('Occurrences') plt.title('Distribution of Numbers') plt.grid(axis='y') img = BytesIO() plt.savefig(img, format='png') img.seek(0) plt.close() return base64.b64encode(img.getvalue()).decode() @app.route('/', methods=['GET', 'POST']) def home(): random_number = None error_message = None if request.method == 'POST': try: min_value = int(request.form['min_value']) max_value = int(request.form['max_value']) if 'generate_100' in request.form: generated_numbers = generate_numbers( min_value, max_value, num_samples=100) return render_template('index.html', generated_numbers=generated_numbers, number_counts=number_counts, total_generated=total_generated) else: random_number = generate_random_number(min_value, max_value) except ValueError as e: error_message = str(e) return render_template('index.html', random_number=random_number, number_counts=number_counts, total_generated=total_generated, error_message=error_message) @app.route('/generate_100_numbers', methods=['POST']) def generate_100_numbers_route(): try: min_value = int(request.form['min_value']) max_value = int(request.form['max_value']) generated_numbers = generate_numbers( min_value, max_value, num_samples=100) return render_template('index.html', generated_numbers=generated_numbers, number_counts=number_counts, total_generated=total_generated) except ValueError as e: return jsonify({'error': str(e)}) @app.route('/clear') def clear_numbers(): global number_counts, total_generated number_counts = {} total_generated = 0 return render_template('index.html', random_number=None, number_counts=number_counts, total_generated=total_generated) @app.route('/generate_graph', methods=['GET', 'POST']) def generate_graph(): remove_outliers_flag = False if request.method == 'POST' and 'remove_outliers' in request.form: remove_outliers_flag = True plot = plot_bar_chart(remove_outliers_flag) return render_template('index.html', plot=plot, random_number=None, number_counts=number_counts, total_generated=total_generated) if __name__ == '__main__': app.run(debug=True)
https://github.com/JouziP/MQITE
JouziP
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 13 12:40:38 2022 @author: pejmanjouzdani """ # # from SimulateMQITE.log_config import logger import pandas as pd import numpy as np from qiskit import QuantumCircuit from MultiQubitGate.functions import multiqubit from BasicFunctions.functions import getBinary from Phase.PhaseFunctions.computeAmplFromShots import computeAmplFromShots class Phase: ##### CONSTRUCTOR def __init__(self, df_ampl, nspins, circ_U, Q, significant_figures, shots, machine_precision=10, j_ref=None, gamma= np.pi/10): #### static # self.amplObj = amplObj self.nspins = nspins self.circ_U = circ_U ## the U_t circuit self.Q = Q # the Q Pauli string given in form of an array of 0,...,3 self.significant_figures = significant_figures # significant_figures self.shots = shots # self.machine_precision = machine_precision self.df_ampl = df_ampl# |c_j| in U^QU|0>=\sum_j c_j|j> self.gamma= gamma if j_ref==None: #### choose the ref j_ref = np.random.randint(0, 2**nspins) while j_ref in self.df_ampl.index: j_ref = np.random.randint(0, 2**nspins) else: pass self.j_ref = j_ref ##### OVERWRITING () OPERATOR def __call__(self, TestLevel=0): self.getImagPart() self.getRealPart() ##### TURN C_J TO Y_J def getY(self, delta): ''' uses the c_j^(r) and imag to compute the y_j_r and imaginary ''' NotImplemented try: ## <0| U^ Q U |0> Q_expect = self.df_ampl.loc[0]['|c_j|'].real except: Q_expect = 0 ### norm norm = 1- 2*delta * Q_expect + delta ** 2 ### to avoid devision by zero error _epsilon = 10**(-1 * 2 * self.significant_figures) ### the actual parameters y_j c_j_times_delta_real = self.c_real * -( delta / (norm + _epsilon) ) c_j_times_delta_imag = self.c_imag * -( delta / (norm + _epsilon) ) params_real_plus_imag = -c_j_times_delta_real.values + 1j*c_j_times_delta_imag.values ## -y_j^(re) + 1j * y_j^(im) self.yj_parameters = pd.DataFrame(params_real_plus_imag, columns=['y_j'], index = self.c_real.index) ## -y_j^(r) ### delta * cj the otput that will be passed to update circuit delta_times_cj = c_j_times_delta_real.values + 1j*c_j_times_delta_imag.values ## delta * ( c_j ) self.delta_times_cj = pd.DataFrame(delta_times_cj, columns=['delta_times_cj'], index = self.c_real.index) # remove 0 --> double check try: self.delta_times_cj = self.delta_times_cj.drop(index=0) except: pass ### j_list and delta_times_cj_values j_list = self.delta_times_cj.loc[self.delta_times_cj['delta_times_cj']!=0].index delta_times_cj_values = self.delta_times_cj.loc[j_list] #### returns list of js and list of delta*cj's return [ j_list.tolist(), delta_times_cj_values.values.T.tolist()[0] ] ##### Q. COMPUTE IMAG PART OF C_J def getImagPart(self,): circ_adj_for_imag_part = self.getImagPart_base_circ(self.nspins, self.circ_U, self.Q, self.j_ref, self.gamma) #################### for each j2 The T_{j_ref -> j2} is different indexs = self.df_ampl.index ### the observed bit strings from shots; j's m1s = self.getMsImag(indexs, self.j_ref, self.nspins, circ_adj_for_imag_part, self.shots, self.significant_figures ) c2_2s = self.getC2s(indexs, self.df_ampl, self.significant_figures) c_imag = self.getComponent(c2_2s, m1s, self.gamma) c_imag = pd.DataFrame(c_imag, index= indexs).round(self.significant_figures) c_imag.columns=[ 'c_imag_sim' ] # ### m1s = pd.DataFrame(m1s, index= indexs) m1s.columns=[ 'm1s-imag-sim' ] c2_2s = pd.DataFrame(c2_2s, index= indexs) c2_2s.columns=[ 'c2^2' ] ### attribute to the obj self.c_imag = c_imag self.m1s_from_imag = m1s self.c2_2power2__imag = c2_2s ##### Q. COMPUTE REAL PART OF C_J def getRealPart(self,): circ_adj_for_real_part = self.getRealPart_base_circ(self.nspins, self.circ_U, self.Q, self.j_ref, self.gamma) #################### for each j2 The T_{j_ref -> j2} is different indexs = self.df_ampl.index ### the observed bit strings from shots; j's m1s = self.getMsReal(indexs, self.j_ref, self.nspins, circ_adj_for_real_part, self.shots, self.significant_figures ) c2_2s = self.getC2s(indexs, self.df_ampl, self.significant_figures) c_real = self.getComponent(c2_2s, m1s, self.gamma) c_real = pd.DataFrame(c_real, index= indexs).round(self.significant_figures) c_real.columns=[ 'c_real_sim' ] # ### m1s = pd.DataFrame(m1s, index= indexs) m1s.columns=[ 'm1s-real-sim' ] c2_2s = pd.DataFrame(c2_2s, index= indexs) c2_2s.columns=[ 'c2^2' ] ### attribute to the obj self.c_real = c_real self.m1s_from_real = m1s self.c2_2power2__real = c2_2s ########################################### TOOLKIT @staticmethod def getComponent(c2_2s, m1s, gamma): component = lambda m_ref, c2_2 : (m_ref - (1/4) * c2_2 *\ (np.cos(gamma/2)**2) - (1/4)*(np.sin(gamma/2))**2 )/\ ((-1/2) * np.cos(gamma/2) * np.sin(gamma/2)) return list(map(component, m1s, c2_2s)) @staticmethod def getC2s(indexs, df_ampl, significant_figures): c2_2s = [] for j2 in indexs: #### amplitude from shots c2 = df_ampl['|c_j|'][j2] #### c2_2 = c2**2 ### |c_j|^2 c2_2 = np.round(c2_2, significant_figures) ### collect results c2_2s.append(c2_2) return c2_2s @staticmethod def getMsReal(indexs, j_ref, nspins, circ_adj, shots, significant_figures): m1s = [] for j2 in indexs: circ_uhu_adj = Phase.getRealPart_ref_circ(j_ref, j2, nspins, circ_adj) #### from shots m_ref = computeAmplFromShots(circ_uhu_adj, shots, j_ref) #### m_ref = np.round(m_ref, significant_figures) ### collect results m1s.append(m_ref) return m1s @staticmethod def getMsImag(indexs, j_ref, nspins, circ_adj, shots, significant_figures): m1s = [] for j2 in indexs: circ_uhu_adj = Phase.getImagPart_ref_circ(j_ref, j2, nspins, circ_adj) #### from shots m_ref = computeAmplFromShots(circ_uhu_adj, shots, j_ref) #### m_ref = np.round(m_ref, significant_figures) ### collect results m1s.append(m_ref) return m1s @staticmethod def computeAmplFromShots(circ_uhu_adj, shots, j_ref): return computeAmplFromShots(circ_uhu_adj, shots, j_ref) @staticmethod def getImagPart_base_circ(nspins, circ_U , Q, j_ref, gamma = np.pi/10): circ_adj = QuantumCircuit(nspins+1) circ_adj.ry(gamma, qubit=-1) ### R_gamma circ_adj.x(qubit=-1) ### X ### U ### attaches U to the q=1 ... q=n qubits, while q=0 is the ancillary circ_adj = circ_adj.compose(QuantumCircuit.copy(circ_U) ) ### control-Q ; Ancillary - n target for (q,o) in enumerate(Q): if o==1: circ_adj.cx(-1, q) if o==2: circ_adj.cy(-1, q) if o==3: circ_adj.cz(-1, q) ### U^ circ_adj = circ_adj.compose(QuantumCircuit.copy(circ_U).inverse()) ### control-P_{0 j_ref} circ_adj.x(qubit=nspins) J1 = list(getBinary(j_ref, nspins)) + [0] for (q,o) in enumerate(J1): if o==1: circ_adj.cx(nspins, q) circ_adj.x(nspins) ### H on ancillary circ_adj.h(nspins) return circ_adj @staticmethod def getImagPart_ref_circ(j_ref, j2,nspins, circ_adj): #### T Gate p_12_int = j2^j_ref ## operator P_12 = getBinary(p_12_int, nspins).tolist()+[0] #bitstring array of p12 mult_gate, op_count = multiqubit(P_12, np.pi/4) # turned into T gate circ_uhu_adj = circ_adj.compose( mult_gate ) #add to the circuit return circ_uhu_adj @staticmethod def getRealPart_ref_circ(j_ref, j2, nspins, circ_adj): #### T Gate p_12_int = j2^j_ref ## operator P_12 = getBinary(p_12_int, nspins).tolist()+[0] #bitstring array of p12 mult_gate, op_count = multiqubit(P_12, np.pi/4) # turned into T gate circ_uhu_adj = circ_adj.compose( mult_gate ) #add to the circuit return circ_uhu_adj @staticmethod def getRealPart_base_circ(nspins, circ_U , Q, j_ref, gamma = np.pi/10): circ_adj = QuantumCircuit(nspins+1) circ_adj.ry(gamma, qubit=-1) ### R_gamma circ_adj.x(qubit=-1) ### X ### U ### attaches U to the q=1 ... q=n qubits, while q=0 is the ancillary circ_adj = circ_adj.compose(QuantumCircuit.copy(circ_U) ) ### control-Q ; Ancillary - n target for (q,o) in enumerate(Q): if o==1: circ_adj.cx(-1, q) if o==2: circ_adj.cy(-1, q) if o==3: circ_adj.cz(-1, q) ### U^ circ_adj = circ_adj.compose(QuantumCircuit.copy(circ_U).inverse()) ### control-P_{0 j_ref} circ_adj.x(qubit=nspins) J1 = list(getBinary(j_ref, nspins)) + [0] for (q,o) in enumerate(J1): if o==1: circ_adj.cx(nspins, q) circ_adj.x(nspins) ### S and H on ancillary circ_adj.s(-1) circ_adj.h(nspins) return circ_adj
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeAuckland backend = FakeAuckland() ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) ghz.draw(output='mpl')
https://github.com/VedDharkar/IBM_QISKIT_EXAM_C1000-112
VedDharkar
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit import * # Loading your IBM Q account(s) #provider = IBMQ.load_account() q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.x(q[0]) qc.measure(q, c) #To convert into qasm use:- qc.qasm(formatted=True, filename='my_circuit.qasm') #To get circuit from qasm file use:- qc = QuantumCircuit.from_qasm_file('my_circuit.qam')
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # ============================================================================= """Test QGT.""" import unittest from ddt import ddt, data import numpy as np from qiskit import QuantumCircuit from qiskit_algorithms.gradients import DerivativeType, LinCombQGT, ReverseQGT from qiskit.circuit import Parameter from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Estimator from qiskit.test import QiskitTestCase from .logging_primitives import LoggingEstimator @ddt class TestQGT(QiskitTestCase): """Test QGT""" def setUp(self): super().setUp() self.estimator = Estimator() @data(LinCombQGT, ReverseQGT) def test_qgt_derivative_type(self, qgt_type): """Test QGT derivative_type""" args = () if qgt_type == ReverseQGT else (self.estimator,) qgt = qgt_type(*args, derivative_type=DerivativeType.REAL) a, b = Parameter("a"), Parameter("b") qc = QuantumCircuit(1) qc.h(0) qc.rz(a, 0) qc.rx(b, 0) param_list = [[np.pi / 4, 0], [np.pi / 2, np.pi / 4]] correct_values = [ np.array([[1, 0.707106781j], [-0.707106781j, 0.5]]) / 4, np.array([[1, 1j], [-1j, 1]]) / 4, ] # test real derivative with self.subTest("Test with DerivativeType.REAL"): qgt.derivative_type = DerivativeType.REAL for i, param in enumerate(param_list): qgt_result = qgt.run([qc], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], correct_values[i].real, atol=1e-3) # test imaginary derivative with self.subTest("Test with DerivativeType.IMAG"): qgt.derivative_type = DerivativeType.IMAG for i, param in enumerate(param_list): qgt_result = qgt.run([qc], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], correct_values[i].imag, atol=1e-3) # test real + imaginary derivative with self.subTest("Test with DerivativeType.COMPLEX"): qgt.derivative_type = DerivativeType.COMPLEX for i, param in enumerate(param_list): qgt_result = qgt.run([qc], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], correct_values[i], atol=1e-3) @data(LinCombQGT, ReverseQGT) def test_qgt_phase_fix(self, qgt_type): """Test the phase-fix argument in a QGT calculation""" args = () if qgt_type == ReverseQGT else (self.estimator,) qgt = qgt_type(*args, phase_fix=False) # create the circuit a, b = Parameter("a"), Parameter("b") qc = QuantumCircuit(1) qc.h(0) qc.rz(a, 0) qc.rx(b, 0) param_list = [[np.pi / 4, 0], [np.pi / 2, np.pi / 4]] correct_values = [ np.array([[1, 0.707106781j], [-0.707106781j, 1]]) / 4, np.array([[1, 1j], [-1j, 1]]) / 4, ] # test real derivative with self.subTest("Test phase fix with DerivativeType.REAL"): qgt.derivative_type = DerivativeType.REAL for i, param in enumerate(param_list): qgt_result = qgt.run([qc], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], correct_values[i].real, atol=1e-3) # test imaginary derivative with self.subTest("Test phase fix with DerivativeType.IMAG"): qgt.derivative_type = DerivativeType.IMAG for i, param in enumerate(param_list): qgt_result = qgt.run([qc], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], correct_values[i].imag, atol=1e-3) # test real + imaginary derivative with self.subTest("Test phase fix with DerivativeType.COMPLEX"): qgt.derivative_type = DerivativeType.COMPLEX for i, param in enumerate(param_list): qgt_result = qgt.run([qc], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], correct_values[i], atol=1e-3) @data(LinCombQGT, ReverseQGT) def test_qgt_coefficients(self, qgt_type): """Test the derivative option of QGT""" args = () if qgt_type == ReverseQGT else (self.estimator,) qgt = qgt_type(*args, derivative_type=DerivativeType.REAL) qc = RealAmplitudes(num_qubits=2, reps=1) qc.rz(qc.parameters[0].exp() + 2 * qc.parameters[1], 0) qc.rx(3.0 * qc.parameters[2] + qc.parameters[3].sin(), 1) # test imaginary derivative param_list = [ [np.pi / 4 for param in qc.parameters], [np.pi / 2 for param in qc.parameters], ] correct_values = ( np.array( [ [ [5.707309, 4.2924833, 1.5295868, 0.1938604], [4.2924833, 4.9142136, 0.75, 0.8838835], [1.5295868, 0.75, 3.4430195, 0.0758252], [0.1938604, 0.8838835, 0.0758252, 1.1357233], ], [ [1.0, 0.0, 1.0, 0.0], [0.0, 1.0, 0.0, 0.0], [1.0, 0.0, 10.0, -0.0], [0.0, 0.0, -0.0, 1.0], ], ] ) / 4 ) for i, param in enumerate(param_list): qgt_result = qgt.run([qc], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], correct_values[i], atol=1e-3) @data(LinCombQGT, ReverseQGT) def test_qgt_parameters(self, qgt_type): """Test the QGT with specified parameters""" args = () if qgt_type == ReverseQGT else (self.estimator,) qgt = qgt_type(*args, derivative_type=DerivativeType.REAL) a = Parameter("a") b = Parameter("b") qc = QuantumCircuit(1) qc.rx(a, 0) qc.ry(b, 0) param_values = [np.pi / 4, np.pi / 4] qgt_result = qgt.run([qc], [param_values], [[a]]).result().qgts np.testing.assert_allclose(qgt_result[0], [[1 / 4]], atol=1e-3) with self.subTest("Test with different parameter orders"): c = Parameter("c") qc2 = QuantumCircuit(1) qc2.rx(a, 0) qc2.rz(b, 0) qc2.rx(c, 0) param_values = [np.pi / 4, np.pi / 4, np.pi / 4] params = [[a, b, c], [c, b, a], [a, c], [b, a]] expected = [ np.array( [ [0.25, 0.0, 0.1767767], [0.0, 0.125, -0.08838835], [0.1767767, -0.08838835, 0.1875], ] ), np.array( [ [0.1875, -0.08838835, 0.1767767], [-0.08838835, 0.125, 0.0], [0.1767767, 0.0, 0.25], ] ), np.array([[0.25, 0.1767767], [0.1767767, 0.1875]]), np.array([[0.125, 0.0], [0.0, 0.25]]), ] for i, param in enumerate(params): qgt_result = qgt.run([qc2], [param_values], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], expected[i], atol=1e-3) @data(LinCombQGT, ReverseQGT) def test_qgt_multi_arguments(self, qgt_type): """Test the QGT for multiple arguments""" args = () if qgt_type == ReverseQGT else (self.estimator,) qgt = qgt_type(*args, derivative_type=DerivativeType.REAL) a = Parameter("a") b = Parameter("b") qc = QuantumCircuit(1) qc.rx(a, 0) qc.ry(b, 0) qc2 = QuantumCircuit(1) qc2.rx(a, 0) qc2.ry(b, 0) param_list = [[np.pi / 4], [np.pi / 2]] correct_values = [[[1 / 4]], [[1 / 4, 0], [0, 0]]] param_list = [[np.pi / 4, np.pi / 4], [np.pi / 2, np.pi / 2]] qgt_results = qgt.run([qc, qc2], param_list, [[a], None]).result().qgts for i, _ in enumerate(param_list): np.testing.assert_allclose(qgt_results[i], correct_values[i], atol=1e-3) @data(LinCombQGT, ReverseQGT) def test_qgt_validation(self, qgt_type): """Test estimator QGT's validation""" args = () if qgt_type == ReverseQGT else (self.estimator,) qgt = qgt_type(*args) a = Parameter("a") qc = QuantumCircuit(1) qc.rx(a, 0) parameter_values = [[np.pi / 4]] with self.subTest("assert number of circuits does not match"): with self.assertRaises(ValueError): qgt.run([qc, qc], parameter_values) with self.subTest("assert number of parameter values does not match"): with self.assertRaises(ValueError): qgt.run([qc], [[np.pi / 4], [np.pi / 2]]) with self.subTest("assert number of parameters does not match"): with self.assertRaises(ValueError): qgt.run([qc], parameter_values, parameters=[[a], [a]]) def test_options(self): """Test QGT's options""" a = Parameter("a") qc = QuantumCircuit(1) qc.rx(a, 0) estimator = Estimator(options={"shots": 100}) with self.subTest("estimator"): qgt = LinCombQGT(estimator) options = qgt.options result = qgt.run([qc], [[1]]).result() self.assertEqual(result.options.get("shots"), 100) self.assertEqual(options.get("shots"), 100) with self.subTest("QGT init"): qgt = LinCombQGT(estimator, options={"shots": 200}) result = qgt.run([qc], [[1]]).result() options = qgt.options self.assertEqual(result.options.get("shots"), 200) self.assertEqual(options.get("shots"), 200) with self.subTest("QGT update"): qgt = LinCombQGT(estimator, options={"shots": 200}) qgt.update_default_options(shots=100) options = qgt.options result = qgt.run([qc], [[1]]).result() self.assertEqual(result.options.get("shots"), 100) self.assertEqual(options.get("shots"), 100) with self.subTest("QGT run"): qgt = LinCombQGT(estimator, options={"shots": 200}) result = qgt.run([qc], [[0]], shots=300).result() options = qgt.options self.assertEqual(result.options.get("shots"), 300) self.assertEqual(options.get("shots"), 200) def test_operations_preserved(self): """Test non-parameterized instructions are preserved and not unrolled.""" x, y = Parameter("x"), Parameter("y") circuit = QuantumCircuit(2) circuit.initialize([0.5, 0.5, 0.5, 0.5]) # this should remain as initialize circuit.crx(x, 0, 1) # this should get unrolled circuit.ry(y, 0) values = [np.pi / 2, np.pi] expect = np.diag([0.25, 0.5]) / 4 ops = [] def operations_callback(op): ops.append(op) estimator = LoggingEstimator(operations_callback=operations_callback) qgt = LinCombQGT(estimator, derivative_type=DerivativeType.REAL) job = qgt.run([circuit], [values]) result = job.result() with self.subTest(msg="assert initialize is preserved"): self.assertTrue(all("initialize" in ops_i[0].keys() for ops_i in ops)) with self.subTest(msg="assert result is correct"): np.testing.assert_allclose(result.qgts[0], expect, atol=1e-5) if __name__ == "__main__": unittest.main()
https://github.com/peiyong-addwater/Hackathon-QNLP
peiyong-addwater
import collections import pickle import warnings warnings.filterwarnings("ignore") import os from random import shuffle import re import spacy from discopy.tensor import Tensor from discopy import Word from discopy.rigid import Functor import seaborn as sns import pandas as pd import matplotlib.pyplot as plt import numpy as np from numpy import random, unique from lambeq import AtomicType, IQPAnsatz, remove_cups, NumpyModel, spiders_reader from lambeq import BobcatParser, TreeReader, cups_reader, DepCCGParser from lambeq import Dataset from lambeq import QuantumTrainer, SPSAOptimizer from lambeq import TketModel from lambeq import SpacyTokeniser from pytket.extensions.qiskit import AerBackend from nltk.tokenize import sent_tokenize, word_tokenize from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer, PorterStemmer from nltk import pos_tag, ne_chunk from nltk.chunk import tree2conlltags import seaborn as sns import matplotlib.pyplot as plt from collections import Counter import nltk nltk.download('stopwords') nltk.download('punkt') nltk.download('wordnet') nltk.download('averaged_perceptron_tagger') nltk.download('maxent_ne_chunker') nltk.download('words') nltk.download('omw-1.4') pd.set_option('display.width', 1000) pd.options.display.max_colwidth=80 print(os.getcwd()) warnings.filterwarnings("ignore") os.environ["TOKENIZERS_PARALLELISM"] = "false" spacy.load('en_core_web_sm') MAX_LENGTH = 5 BATCH_SIZE = 30 EPOCHS = 100 SEED = 0 random.seed(SEED) def get_sent_length(sent): if type(sent) is not str: return 9999999 word_list = sent.split(" ") return len(word_list) columns = ["Id","Entity","Target","Text"] data = pd.read_csv(os.path.join(os.getcwd(),"data/twitter_training.csv"), names=columns,header=None) #data = data.sample(frac=1).reset_index(drop=True) data_val = pd.read_csv(os.path.join(os.getcwd(), "data/twitter_validation.csv"), names=columns,header=None) #data_val = data.sample(frac=1).reset_index(drop=True) df_train = data[["Text","Target"]] df_train = df_train.loc[(df_train["Target"]=='Positive') | (df_train["Target"]=='Negative') & (df_train["Text"]!=np.nan)&(df_train["Text"].map(get_sent_length)<=MAX_LENGTH)] df_train= df_train.drop_duplicates() df_val = data_val[['Text', 'Target']] df_val = df_val.loc[(df_val['Target'] == 'Positive') | (df_val['Target'] == 'Negative') & (df_val["Text"]!=np.nan)&(df_val["Text"].map(get_sent_length)<=MAX_LENGTH)] text_cleaning_re = "@\S+|https?:\S+|http?:\S|[^A-Za-z0-9]+" emoji_pattern = re.compile("[" u"\U0001F600-\U0001F64F" # emoticons u"\U0001F300-\U0001F5FF" # symbols & pictographs u"\U0001F680-\U0001F6FF" # transport & map symbols u"\U0001F1E0-\U0001F1FF" # flags (iOS) "]+", flags=re.UNICODE) def preprocess(text): text = re.sub(text_cleaning_re, ' ', str(text).lower()).strip() without_emoji = emoji_pattern.sub(r'', text) tokens = word_tokenize(str(without_emoji).replace("'", "").lower()) # Remove Puncs without_punc = [w for w in tokens if w.isalpha()] # Lemmatize text_len = [WordNetLemmatizer().lemmatize(t) for t in without_punc] # Stem text_cleaned = [PorterStemmer().stem(w) for w in text_len] return " ".join(text_cleaned) df_train["Text"]= df_train["Text"].str.replace("im","i am") df_train["Text"]= df_train["Text"].str.replace("it's","it is") df_train["Text"]= df_train["Text"].str.replace("you're","you are") df_train["Text"]= df_train["Text"].str.replace("hasn't","has not") df_train["Text"]= df_train["Text"].str.replace("haven't","have not") df_train["Text"]= df_train["Text"].str.replace("don't","do not") df_train["Text"]= df_train["Text"].str.replace("doesn't","does not") df_train["Text"]= df_train["Text"].str.replace("won't","will not") df_train["Text"]= df_train["Text"].str.replace("shouldn't","should not") df_train["Text"]= df_train["Text"].str.replace("can't","can not") df_train["Text"]= df_train["Text"].str.replace("couldn't","could not") df_val["Text"] = df_val["Text"].str.replace("im","i am") df_val["Text"]= df_val["Text"].str.replace("it's","it is") df_val["Text"]= df_val["Text"].str.replace("you're","you are") df_val["Text"]= df_val["Text"].str.replace("hasn't","has not") df_val["Text"]= df_val["Text"].str.replace("haven't","have not") df_val["Text"] = df_val["Text"].str.replace("don't","do not") df_val["Text"] = df_val["Text"].str.replace("doesn't","does not") df_val["Text"] = df_val["Text"].str.replace("won't","will not") df_val["Text"] = df_val["Text"].str.replace("shouldn't","should not") df_val["Text"] = df_val["Text"].str.replace("can't","can not") df_val["Text"] = df_val["Text"].str.replace("couldn't","could not") df_train["Text"] = df_train["Text"].apply(preprocess) df_val["Text"] = df_val["Text"].apply(preprocess) df_train = df_train.dropna() df_val = df_val.dropna() negative_train_df = df_train.loc[df_train["Target"]=="Negative"] positive_train_df = df_train.loc[df_train["Target"]=='Positive'] if len(positive_train_df)>=len(negative_train_df): positive_train_df = positive_train_df.head(len(negative_train_df)) else: negative_train_df = negative_train_df.head(len(positive_train_df)) negative_val_df = df_val.loc[df_val['Target'] == 'Negative'] positive_val_df = df_val.loc[df_val['Target'] == 'Positive'] if len(positive_val_df)>=len(negative_val_df): positive_val_df = positive_val_df.head(len(negative_val_df)) else: negative_val_df = negative_val_df.head(len(positive_val_df)) df_train = pd.concat([positive_train_df, negative_train_df]) df_val = pd.concat([positive_val_df, negative_val_df]) # Positive sentiment to [0,1], negative sentiment to [1,0] sentiment_train = [] sentiment_val = [] for i in df_train["Target"]: if i == "Positive": sentiment_train.append([0,1]) else: sentiment_train.append([1,0]) df_train["Sentiment"] = sentiment_train for i in df_val["Target"]: if i == "Positive": sentiment_val.append([0,1]) else: sentiment_val.append([1,0]) df_val["Sentiment"] = sentiment_val df_train.info() df_val.info() df_train.head() df_val.head() sns.countplot(x = "Target", data = df_train) sns.countplot(x = "Target", data = df_val) train_data_all, train_label_all = df_train["Text"].tolist(), df_train["Sentiment"].tolist() dev_data, dev_labels = df_val["Text"].tolist(), df_val["Sentiment"].tolist() data = train_data_all+dev_data labels = train_label_all+dev_labels pairs = [] for c in zip(labels, data): if len(c[1]) != 0 and len(c[1].split(" "))<=5: pairs.append(c) random.seed(0) random.shuffle(pairs) N_EXAMPLES = len(pairs) print("Total: {}".format(N_EXAMPLES)) TRAIN_RATIO_INDEX = 0.8 TEST_RATIO_INDEX = TRAIN_RATIO_INDEX + 0.1 DEV_RATIO_INDEX = TEST_RATIO_INDEX + 0.1 train_labels, train_data = zip(*pairs[:round(N_EXAMPLES * TRAIN_RATIO_INDEX)]) dev_labels, dev_data = zip(*pairs[round(N_EXAMPLES * TRAIN_RATIO_INDEX):round(N_EXAMPLES * TEST_RATIO_INDEX)]) test_labels, test_data = zip(*pairs[round(N_EXAMPLES * TEST_RATIO_INDEX):round(N_EXAMPLES * DEV_RATIO_INDEX)]) print("Data selected for train: {}\nData selected for test: {}\nData selected for dev: {}".format(len(train_data), len(test_data), len(dev_data))) # Function for replacing low occuring word(s) with <unk> token def replace(box): if isinstance(box, Word) and dataset.count(box.name) < 1: return Word('unk', box.cod, box.dom) return box tokeniser = SpacyTokeniser() train_data = tokeniser.tokenise_sentences(train_data) dev_data = tokeniser.tokenise_sentences(dev_data) test_data = tokeniser.tokenise_sentences(test_data) for i in range(len(train_data)): train_data[i] = ' '.join(train_data[i]) for i in range(len(dev_data)): dev_data[i] = ' '.join(dev_data[i]) for i in range(len(test_data)): test_data[i] = ' '.join(test_data[i]) # training set words (with repetition) train_data_string = ' '.join(train_data) train_data_list = train_data_string.split(' ') # validation set words (with repetition) dev_data_string = ' '.join(dev_data) dev_data_list = dev_data_string.split(' ') # test set words (with repetition) test_data_string = ' '.join(test_data) test_data_list = test_data_string.split(' ') # dataset words (with repetition) dataset = train_data_list + dev_data_list + test_data_list # list of all unique words in the dataset unique_words = unique(dataset) # frequency for each unique word counter = collections.Counter(dataset) #print(counter) replace_functor = Functor(ob=lambda x: x, ar=replace) # parser = BobcatParser(verbose='text') print(BobcatParser.available_models()) parser = spiders_reader #parser = DepCCGParser() #parser = cups_reader raw_train_diagrams = [] new_train_labels = [] raw_dev_diagrams = [] new_dev_labels = [] raw_test_diagrams = [] new_test_labels = [] for sent, label in zip(train_data, train_labels): try: diag = parser.sentence2diagram(sent) raw_train_diagrams.append(diag) new_train_labels.append(label) except: print("Cannot be parsed in train: {}".format(sent)) for sent, label in zip(dev_data, dev_labels): try: diag = parser.sentence2diagram(sent) raw_dev_diagrams.append(diag) new_dev_labels.append(label) except: print("Cannot be parsed in dev: {}".format(sent)) for sent, label in zip(test_data, test_labels): try: diag = parser.sentence2diagram(sent) raw_test_diagrams.append(diag) new_test_labels.append(label) except: print("Cannot be parsed in test: {}".format(sent)) train_labels = new_train_labels dev_labels = new_dev_labels test_labels = new_test_labels # # Tokenizing low occuring words in each dataset for i in range(len(raw_train_diagrams)): raw_train_diagrams[i] = replace_functor(raw_train_diagrams[i]) for i in range(len(raw_dev_diagrams)): raw_dev_diagrams[i] = replace_functor(raw_dev_diagrams[i]) for i in range(len(raw_test_diagrams)): raw_test_diagrams[i] = replace_functor(raw_test_diagrams[i]) # sample sentence diagram (entry 1) raw_train_diagrams[0].draw() # merging all diagrams into one for checking the new words raw_all_diagrams = raw_train_diagrams + raw_dev_diagrams + raw_test_diagrams # removing cups (after performing top-to-bottom scan of the word diagrams) train_diagrams = [remove_cups(diagram) for diagram in raw_train_diagrams] dev_diagrams = [remove_cups(diagram) for diagram in raw_dev_diagrams] test_diagrams = [remove_cups(diagram) for diagram in raw_test_diagrams] # sample sentence diagram (entry 1) train_diagrams[0].draw() ansatz = IQPAnsatz({AtomicType.NOUN: 1, AtomicType.SENTENCE: 1, AtomicType.PREPOSITIONAL_PHRASE: 1, AtomicType.NOUN_PHRASE:1, AtomicType.CONJUNCTION:1}, n_layers=1, n_single_qubit_params=3) # train/test circuits train_circuits = [ansatz(diagram) for diagram in train_diagrams] dev_circuits = [ansatz(diagram) for diagram in dev_diagrams] test_circuits = [ansatz(diagram) for diagram in test_diagrams] # sample circuit diagram train_circuits[0].draw(figsize=(9, 12)) all_circuits = train_circuits + dev_circuits + test_circuits model = NumpyModel.from_diagrams(all_circuits, use_jit=True) loss = lambda y_hat, y: -np.sum(y * np.log(y_hat)) / len(y) # binary cross-entropy loss acc = lambda y_hat, y: np.sum(np.round(y_hat) == y) / len(y) / 2 # half due to double-counting trainer = QuantumTrainer( model, loss_function=loss, epochs=EPOCHS, optimizer=SPSAOptimizer, optim_hyperparams={'a': 0.2, 'c': 0.06, 'A':0.01*EPOCHS}, evaluate_functions={'acc': acc}, evaluate_on_train=True, verbose = 'text', seed=0 ) train_dataset = Dataset( train_circuits, train_labels, batch_size=BATCH_SIZE) val_dataset = Dataset(dev_circuits, dev_labels, shuffle=False) trainer.fit(train_dataset, val_dataset, logging_step=12) fig, ((ax_tl, ax_tr), (ax_bl, ax_br)) = plt.subplots(2, 2, sharex=True, sharey='row', figsize=(10, 6)) ax_tl.set_title('Training set') ax_tr.set_title('Development set') ax_bl.set_xlabel('Iterations') ax_br.set_xlabel('Iterations') ax_bl.set_ylabel('Accuracy') ax_tl.set_ylabel('Loss') colours = iter(plt.rcParams['axes.prop_cycle'].by_key()['color']) ax_tl.plot(trainer.train_epoch_costs, color=next(colours)) ax_bl.plot(trainer.train_results['acc'], color=next(colours)) ax_tr.plot(trainer.val_costs, color=next(colours)) ax_br.plot(trainer.val_results['acc'], color=next(colours)) test_acc = acc(model(test_circuits), test_labels) print('Test accuracy:', test_acc)
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. # pylint: disable=missing-function-docstring """ Tests for the default UnitarySynthesis transpiler pass. """ from test import combine import unittest import numpy as np from ddt import ddt, data from qiskit import transpile from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeVigo, FakeMumbaiFractionalCX, FakeBelemV2 from qiskit.providers.fake_provider.fake_backend_v2 import FakeBackendV2, FakeBackend5QV2 from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit.library import QuantumVolume from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit.transpiler.passes import UnitarySynthesis from qiskit.quantum_info.operators import Operator from qiskit.quantum_info.random import random_unitary from qiskit.transpiler import PassManager, CouplingMap, Target, InstructionProperties from qiskit.transpiler.exceptions import TranspilerError from qiskit.exceptions import QiskitError from qiskit.transpiler.passes import ( Collect2qBlocks, ConsolidateBlocks, Optimize1qGates, SabreLayout, Unroll3qOrMore, CheckMap, BarrierBeforeFinalMeasurements, SabreSwap, TrivialLayout, ) from qiskit.circuit.library import ( IGate, CXGate, RZGate, RXGate, SXGate, XGate, iSwapGate, ECRGate, UGate, ZGate, RYYGate, RZZGate, RXXGate, ) from qiskit.circuit import Measure from qiskit.circuit.controlflow import IfElseOp from qiskit.circuit import Parameter, Gate @ddt class TestUnitarySynthesis(QiskitTestCase): """Test UnitarySynthesis pass.""" def test_empty_basis_gates(self): """Verify when basis_gates is None, we do not synthesize unitaries.""" qc = QuantumCircuit(3) op_1q = random_unitary(2, seed=0) op_2q = random_unitary(4, seed=0) op_3q = random_unitary(8, seed=0) qc.unitary(op_1q.data, [0]) qc.unitary(op_2q.data, [0, 1]) qc.unitary(op_3q.data, [0, 1, 2]) out = UnitarySynthesis(basis_gates=None, min_qubits=2)(qc) self.assertEqual(out.count_ops(), {"unitary": 3}) @data( ["u3", "cx"], ["u1", "u2", "u3", "cx"], ["rx", "ry", "rxx"], ["rx", "rz", "iswap"], ["u3", "rx", "rz", "cz", "iswap"], ) def test_two_qubit_synthesis_to_basis(self, basis_gates): """Verify two qubit unitaries are synthesized to match basis gates.""" bell = QuantumCircuit(2) bell.h(0) bell.cx(0, 1) bell_op = Operator(bell) qc = QuantumCircuit(2) qc.unitary(bell_op, [0, 1]) dag = circuit_to_dag(qc) out = UnitarySynthesis(basis_gates).run(dag) self.assertTrue(set(out.count_ops()).issubset(basis_gates)) def test_two_qubit_synthesis_to_directional_cx_from_gate_errors(self): """Verify two qubit unitaries are synthesized to match basis gates.""" # TODO: should make check more explicit e.g. explicitly set gate # direction in test instead of using specific fake backend backend = FakeVigo() conf = backend.configuration() qr = QuantumRegister(2) coupling_map = CouplingMap(conf.coupling_map) triv_layout_pass = TrivialLayout(coupling_map) qc = QuantumCircuit(qr) qc.unitary(random_unitary(4, seed=12), [0, 1]) unisynth_pass = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=None, backend_props=backend.properties(), pulse_optimize=True, natural_direction=False, ) pm = PassManager([triv_layout_pass, unisynth_pass]) qc_out = pm.run(qc) unisynth_pass_nat = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=None, backend_props=backend.properties(), pulse_optimize=True, natural_direction=True, ) pm_nat = PassManager([triv_layout_pass, unisynth_pass_nat]) qc_out_nat = pm_nat.run(qc) self.assertEqual(Operator(qc), Operator(qc_out)) self.assertEqual(Operator(qc), Operator(qc_out_nat)) def test_swap_synthesis_to_directional_cx(self): """Verify two qubit unitaries are synthesized to match basis gates.""" # TODO: should make check more explicit e.g. explicitly set gate # direction in test instead of using specific fake backend backend = FakeVigo() conf = backend.configuration() qr = QuantumRegister(2) coupling_map = CouplingMap(conf.coupling_map) triv_layout_pass = TrivialLayout(coupling_map) qc = QuantumCircuit(qr) qc.swap(qr[0], qr[1]) unisynth_pass = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=None, backend_props=backend.properties(), pulse_optimize=True, natural_direction=False, ) pm = PassManager([triv_layout_pass, unisynth_pass]) qc_out = pm.run(qc) unisynth_pass_nat = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=None, backend_props=backend.properties(), pulse_optimize=True, natural_direction=True, ) pm_nat = PassManager([triv_layout_pass, unisynth_pass_nat]) qc_out_nat = pm_nat.run(qc) self.assertEqual(Operator(qc), Operator(qc_out)) self.assertEqual(Operator(qc), Operator(qc_out_nat)) def test_two_qubit_synthesis_to_directional_cx_multiple_registers(self): """Verify two qubit unitaries are synthesized to match basis gates across multiple registers.""" # TODO: should make check more explicit e.g. explicitly set gate # direction in test instead of using specific fake backend backend = FakeVigo() conf = backend.configuration() qr0 = QuantumRegister(1) qr1 = QuantumRegister(1) coupling_map = CouplingMap(conf.coupling_map) triv_layout_pass = TrivialLayout(coupling_map) qc = QuantumCircuit(qr0, qr1) qc.unitary(random_unitary(4, seed=12), [qr0[0], qr1[0]]) unisynth_pass = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=None, backend_props=backend.properties(), pulse_optimize=True, natural_direction=False, ) pm = PassManager([triv_layout_pass, unisynth_pass]) qc_out = pm.run(qc) unisynth_pass_nat = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=None, backend_props=backend.properties(), pulse_optimize=True, natural_direction=True, ) pm_nat = PassManager([triv_layout_pass, unisynth_pass_nat]) qc_out_nat = pm_nat.run(qc) self.assertEqual(Operator(qc), Operator(qc_out)) self.assertEqual(Operator(qc), Operator(qc_out_nat)) def test_two_qubit_synthesis_to_directional_cx_from_coupling_map(self): """Verify natural cx direction is used when specified in coupling map.""" # TODO: should make check more explicit e.g. explicitly set gate # direction in test instead of using specific fake backend backend = FakeVigo() conf = backend.configuration() qr = QuantumRegister(2) coupling_map = CouplingMap([[0, 1], [1, 2], [1, 3], [3, 4]]) triv_layout_pass = TrivialLayout(coupling_map) qc = QuantumCircuit(qr) qc.unitary(random_unitary(4, seed=12), [0, 1]) unisynth_pass = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=coupling_map, backend_props=backend.properties(), pulse_optimize=True, natural_direction=False, ) pm = PassManager([triv_layout_pass, unisynth_pass]) qc_out = pm.run(qc) unisynth_pass_nat = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=coupling_map, backend_props=backend.properties(), pulse_optimize=True, natural_direction=True, ) pm_nat = PassManager([triv_layout_pass, unisynth_pass_nat]) qc_out_nat = pm_nat.run(qc) # the decomposer defaults to the [1, 0] direction but the coupling # map specifies a [0, 1] direction. Check that this is respected. self.assertTrue( all(((qr[1], qr[0]) == instr.qubits for instr in qc_out.get_instructions("cx"))) ) self.assertTrue( all(((qr[0], qr[1]) == instr.qubits for instr in qc_out_nat.get_instructions("cx"))) ) self.assertEqual(Operator(qc), Operator(qc_out)) self.assertEqual(Operator(qc), Operator(qc_out_nat)) def test_two_qubit_synthesis_to_directional_cx_from_coupling_map_natural_none(self): """Verify natural cx direction is used when specified in coupling map when natural_direction is None.""" # TODO: should make check more explicit e.g. explicitly set gate # direction in test instead of using specific fake backend backend = FakeVigo() conf = backend.configuration() qr = QuantumRegister(2) coupling_map = CouplingMap([[0, 1], [1, 2], [1, 3], [3, 4]]) triv_layout_pass = TrivialLayout(coupling_map) qc = QuantumCircuit(qr) qc.unitary(random_unitary(4, seed=12), [0, 1]) unisynth_pass = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=coupling_map, backend_props=backend.properties(), pulse_optimize=True, natural_direction=False, ) pm = PassManager([triv_layout_pass, unisynth_pass]) qc_out = pm.run(qc) unisynth_pass_nat = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=coupling_map, backend_props=backend.properties(), pulse_optimize=True, natural_direction=None, ) pm_nat = PassManager([triv_layout_pass, unisynth_pass_nat]) qc_out_nat = pm_nat.run(qc) # the decomposer defaults to the [1, 0] direction but the coupling # map specifies a [0, 1] direction. Check that this is respected. self.assertTrue( all(((qr[1], qr[0]) == instr.qubits for instr in qc_out.get_instructions("cx"))) ) self.assertTrue( all(((qr[0], qr[1]) == instr.qubits for instr in qc_out_nat.get_instructions("cx"))) ) self.assertEqual(Operator(qc), Operator(qc_out)) self.assertEqual(Operator(qc), Operator(qc_out_nat)) def test_two_qubit_synthesis_to_directional_cx_from_coupling_map_natural_false(self): """Verify natural cx direction is used when specified in coupling map when natural_direction is None.""" # TODO: should make check more explicit e.g. explicitly set gate # direction in test instead of using specific fake backend backend = FakeVigo() conf = backend.configuration() qr = QuantumRegister(2) coupling_map = CouplingMap([[0, 1], [1, 2], [1, 3], [3, 4]]) triv_layout_pass = TrivialLayout(coupling_map) qc = QuantumCircuit(qr) qc.unitary(random_unitary(4, seed=12), [0, 1]) unisynth_pass = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=coupling_map, backend_props=backend.properties(), pulse_optimize=True, natural_direction=False, ) pm = PassManager([triv_layout_pass, unisynth_pass]) qc_out = pm.run(qc) unisynth_pass_nat = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=coupling_map, backend_props=backend.properties(), pulse_optimize=True, natural_direction=False, ) pm_nat = PassManager([triv_layout_pass, unisynth_pass_nat]) qc_out_nat = pm_nat.run(qc) # the decomposer defaults to the [1, 0] direction but the coupling # map specifies a [0, 1] direction. Check that this is respected. self.assertTrue( all(((qr[1], qr[0]) == instr.qubits for instr in qc_out.get_instructions("cx"))) ) self.assertTrue( all(((qr[1], qr[0]) == instr.qubits for instr in qc_out_nat.get_instructions("cx"))) ) self.assertEqual(Operator(qc), Operator(qc_out)) self.assertEqual(Operator(qc), Operator(qc_out_nat)) def test_two_qubit_synthesis_not_pulse_optimal(self): """Verify not attempting pulse optimal decomposition when pulse_optimize==False.""" backend = FakeVigo() conf = backend.configuration() qr = QuantumRegister(2) coupling_map = CouplingMap([[0, 1], [1, 2], [1, 3], [3, 4]]) triv_layout_pass = TrivialLayout(coupling_map) qc = QuantumCircuit(qr) qc.unitary(random_unitary(4, seed=12), [0, 1]) unisynth_pass = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=coupling_map, backend_props=backend.properties(), pulse_optimize=False, natural_direction=True, ) pm = PassManager([triv_layout_pass, unisynth_pass]) qc_out = pm.run(qc) if isinstance(qc_out, QuantumCircuit): num_ops = qc_out.count_ops() else: num_ops = qc_out[0].count_ops() self.assertIn("sx", num_ops) self.assertGreaterEqual(num_ops["sx"], 16) def test_two_qubit_pulse_optimal_true_raises(self): """Verify raises if pulse optimal==True but cx is not in the backend basis.""" backend = FakeVigo() conf = backend.configuration() # this assumes iswawp pulse optimal decomposition doesn't exist conf.basis_gates = [gate if gate != "cx" else "iswap" for gate in conf.basis_gates] qr = QuantumRegister(2) coupling_map = CouplingMap([[0, 1], [1, 2], [1, 3], [3, 4]]) triv_layout_pass = TrivialLayout(coupling_map) qc = QuantumCircuit(qr) qc.unitary(random_unitary(4, seed=12), [0, 1]) unisynth_pass = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=coupling_map, backend_props=backend.properties(), pulse_optimize=True, natural_direction=True, ) pm = PassManager([triv_layout_pass, unisynth_pass]) with self.assertRaises(QiskitError): pm.run(qc) def test_two_qubit_natural_direction_true_duration_fallback(self): """Verify not attempting pulse optimal decomposition when pulse_optimize==False.""" # this assumes iswawp pulse optimal decomposition doesn't exist backend = FakeVigo() conf = backend.configuration() # conf.basis_gates = [gate if gate != "cx" else "iswap" for gate in conf.basis_gates] qr = QuantumRegister(2) coupling_map = CouplingMap([[0, 1], [1, 0], [1, 2], [1, 3], [3, 4]]) triv_layout_pass = TrivialLayout(coupling_map) qc = QuantumCircuit(qr) qc.unitary(random_unitary(4, seed=12), [0, 1]) unisynth_pass = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=coupling_map, backend_props=backend.properties(), pulse_optimize=True, natural_direction=True, ) pm = PassManager([triv_layout_pass, unisynth_pass]) qc_out = pm.run(qc) self.assertTrue( all(((qr[0], qr[1]) == instr.qubits for instr in qc_out.get_instructions("cx"))) ) def test_two_qubit_natural_direction_true_gate_length_raises(self): """Verify not attempting pulse optimal decomposition when pulse_optimize==False.""" # this assumes iswawp pulse optimal decomposition doesn't exist backend = FakeVigo() conf = backend.configuration() for _, nduv in backend.properties()._gates["cx"].items(): nduv["gate_length"] = (4e-7, nduv["gate_length"][1]) nduv["gate_error"] = (7e-3, nduv["gate_error"][1]) qr = QuantumRegister(2) coupling_map = CouplingMap([[0, 1], [1, 0], [1, 2], [1, 3], [3, 4]]) triv_layout_pass = TrivialLayout(coupling_map) qc = QuantumCircuit(qr) qc.unitary(random_unitary(4, seed=12), [0, 1]) unisynth_pass = UnitarySynthesis( basis_gates=conf.basis_gates, backend_props=backend.properties(), pulse_optimize=True, natural_direction=True, ) pm = PassManager([triv_layout_pass, unisynth_pass]) with self.assertRaises(TranspilerError): pm.run(qc) def test_two_qubit_pulse_optimal_none_optimal(self): """Verify pulse optimal decomposition when pulse_optimize==None.""" # this assumes iswawp pulse optimal decomposition doesn't exist backend = FakeVigo() conf = backend.configuration() qr = QuantumRegister(2) coupling_map = CouplingMap([[0, 1], [1, 2], [1, 3], [3, 4]]) triv_layout_pass = TrivialLayout(coupling_map) qc = QuantumCircuit(qr) qc.unitary(random_unitary(4, seed=12), [0, 1]) unisynth_pass = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=coupling_map, backend_props=backend.properties(), pulse_optimize=None, natural_direction=True, ) pm = PassManager([triv_layout_pass, unisynth_pass]) qc_out = pm.run(qc) if isinstance(qc_out, QuantumCircuit): num_ops = qc_out.count_ops() else: num_ops = qc_out[0].count_ops() self.assertIn("sx", num_ops) self.assertLessEqual(num_ops["sx"], 12) def test_two_qubit_pulse_optimal_none_no_raise(self): """Verify pulse optimal decomposition when pulse_optimize==None doesn't raise when pulse optimal decomposition unknown.""" # this assumes iswawp pulse optimal decomposition doesn't exist backend = FakeVigo() conf = backend.configuration() conf.basis_gates = [gate if gate != "cx" else "iswap" for gate in conf.basis_gates] qr = QuantumRegister(2) coupling_map = CouplingMap([[0, 1], [1, 2], [1, 3], [3, 4]]) triv_layout_pass = TrivialLayout(coupling_map) qc = QuantumCircuit(qr) qc.unitary(random_unitary(4, seed=12), [0, 1]) unisynth_pass = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=coupling_map, backend_props=backend.properties(), pulse_optimize=None, natural_direction=True, ) pm = PassManager([triv_layout_pass, unisynth_pass]) try: qc_out = pm.run(qc) except QiskitError: self.fail("pulse_optimize=None raised exception unexpectedly") if isinstance(qc_out, QuantumCircuit): num_ops = qc_out.count_ops() else: num_ops = qc_out[0].count_ops() self.assertIn("sx", num_ops) self.assertLessEqual(num_ops["sx"], 14) def test_qv_natural(self): """check that quantum volume circuit compiles for natural direction""" qv64 = QuantumVolume(5, seed=15) def construct_passmanager(basis_gates, coupling_map, synthesis_fidelity, pulse_optimize): seed = 2 _map = [SabreLayout(coupling_map, max_iterations=2, seed=seed)] _unroll3q = Unroll3qOrMore() _swap_check = CheckMap(coupling_map) _swap = [ BarrierBeforeFinalMeasurements(), SabreSwap(coupling_map, heuristic="lookahead", seed=seed), ] _optimize = [ Collect2qBlocks(), ConsolidateBlocks(basis_gates=basis_gates), UnitarySynthesis( basis_gates, synthesis_fidelity, coupling_map, pulse_optimize=pulse_optimize, natural_direction=True, ), Optimize1qGates(basis_gates), ] pm = PassManager() pm.append(_map) # map to hardware by inserting swaps pm.append(_unroll3q) pm.append(_swap_check) pm.append(_swap) pm.append(_optimize) return pm coupling_map = CouplingMap([[0, 1], [1, 2], [3, 2], [3, 4], [5, 4]]) basis_gates = ["rz", "sx", "cx"] pm1 = construct_passmanager( basis_gates=basis_gates, coupling_map=coupling_map, synthesis_fidelity=0.99, pulse_optimize=True, ) pm2 = construct_passmanager( basis_gates=basis_gates, coupling_map=coupling_map, synthesis_fidelity=0.99, pulse_optimize=False, ) qv64_1 = pm1.run(qv64.decompose()) qv64_2 = pm2.run(qv64.decompose()) edges = [list(edge) for edge in coupling_map.get_edges()] self.assertTrue( all( [qv64_1.qubits.index(qubit) for qubit in instr.qubits] in edges for instr in qv64_1.get_instructions("cx") ) ) self.assertEqual(Operator(qv64_1), Operator(qv64_2)) @data(1, 2, 3) def test_coupling_map_transpile(self, opt): """test natural_direction works with transpile/execute""" qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.append(random_unitary(4, seed=1), [0, 1]) circ_01 = transpile( circ, basis_gates=["rz", "sx", "cx"], optimization_level=opt, coupling_map=[[0, 1]] ) circ_10 = transpile( circ, basis_gates=["rz", "sx", "cx"], optimization_level=opt, coupling_map=[[1, 0]] ) circ_01_index = {qubit: index for index, qubit in enumerate(circ_01.qubits)} circ_10_index = {qubit: index for index, qubit in enumerate(circ_10.qubits)} self.assertTrue( all( ( (1, 0) == (circ_10_index[instr.qubits[0]], circ_10_index[instr.qubits[1]]) for instr in circ_10.get_instructions("cx") ) ) ) self.assertTrue( all( ( (0, 1) == (circ_01_index[instr.qubits[0]], circ_01_index[instr.qubits[1]]) for instr in circ_01.get_instructions("cx") ) ) ) @combine( opt_level=[0, 1, 2, 3], bidirectional=[True, False], dsc=( "test natural_direction works with transpile using opt_level {opt_level} on" " target with multiple 2q gates with bidirectional={bidirectional}" ), name="opt_level_{opt_level}_bidirectional_{bidirectional}", ) def test_coupling_map_transpile_with_backendv2(self, opt_level, bidirectional): backend = FakeBackend5QV2(bidirectional) qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.append(random_unitary(4, seed=1), [0, 1]) circ_01 = transpile( circ, backend=backend, optimization_level=opt_level, layout_method="trivial" ) circ_01_index = {qubit: index for index, qubit in enumerate(circ_01.qubits)} self.assertGreaterEqual(len(circ_01.get_instructions("cx")), 1) for instr in circ_01.get_instructions("cx"): self.assertEqual( (0, 1), (circ_01_index[instr.qubits[0]], circ_01_index[instr.qubits[1]]) ) @data(1, 2, 3) def test_coupling_map_unequal_durations(self, opt): """Test direction with transpile/execute with backend durations.""" qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.append(random_unitary(4, seed=1), [1, 0]) backend = FakeVigo() tqc = transpile( circ, backend=backend, optimization_level=opt, translation_method="synthesis", layout_method="trivial", ) tqc_index = {qubit: index for index, qubit in enumerate(tqc.qubits)} self.assertTrue( all( ( (0, 1) == (tqc_index[instr.qubits[0]], tqc_index[instr.qubits[1]]) for instr in tqc.get_instructions("cx") ) ) ) @combine( opt_level=[0, 1, 2, 3], bidirectional=[True, False], dsc=( "Test direction with transpile using opt_level {opt_level} on" " target with multiple 2q gates with bidirectional={bidirectional}" "direction [0, 1] is lower error and should be picked." ), name="opt_level_{opt_level}_bidirectional_{bidirectional}", ) def test_coupling_unequal_duration_with_backendv2(self, opt_level, bidirectional): qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.append(random_unitary(4, seed=1), [1, 0]) backend = FakeBackend5QV2(bidirectional) tqc = transpile( circ, backend=backend, optimization_level=opt_level, translation_method="synthesis", layout_method="trivial", ) tqc_index = {qubit: index for index, qubit in enumerate(tqc.qubits)} self.assertGreaterEqual(len(tqc.get_instructions("cx")), 1) for instr in tqc.get_instructions("cx"): self.assertEqual((0, 1), (tqc_index[instr.qubits[0]], tqc_index[instr.qubits[1]])) @combine( opt_level=[0, 1, 2, 3], dsc=( "Test direction with transpile using opt_level {opt_level} on" " target with multiple 2q gates" ), name="opt_level_{opt_level}", ) def test_non_overlapping_kak_gates_with_backendv2(self, opt_level): qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.append(random_unitary(4, seed=1), [1, 0]) backend = FakeBackendV2() tqc = transpile( circ, backend=backend, optimization_level=opt_level, translation_method="synthesis", layout_method="trivial", ) tqc_index = {qubit: index for index, qubit in enumerate(tqc.qubits)} self.assertGreaterEqual(len(tqc.get_instructions("ecr")), 1) for instr in tqc.get_instructions("ecr"): self.assertEqual((1, 0), (tqc_index[instr.qubits[0]], tqc_index[instr.qubits[1]])) def test_fractional_cx_with_backendv2(self): """Test fractional CX gets used if present in target.""" qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.append(random_unitary(4, seed=1), [0, 1]) backend = FakeMumbaiFractionalCX() synth_pass = UnitarySynthesis(target=backend.target) tqc = synth_pass(circ) tqc_index = {qubit: index for index, qubit in enumerate(tqc.qubits)} self.assertGreaterEqual(len(tqc.get_instructions("rzx")), 1) for instr in tqc.get_instructions("rzx"): self.assertEqual((0, 1), (tqc_index[instr.qubits[0]], tqc_index[instr.qubits[1]])) @combine( opt_level=[0, 1, 2, 3], dsc=( "Test direction with transpile using opt_level {opt_level} on" "target with multiple 2q gates available in reverse direction" ), name="opt_level_{opt_level}", ) def test_reverse_direction(self, opt_level): target = Target(2) target.add_instruction(CXGate(), {(0, 1): InstructionProperties(error=1.2e-6)}) target.add_instruction(ECRGate(), {(0, 1): InstructionProperties(error=1.2e-7)}) target.add_instruction( UGate(Parameter("theta"), Parameter("phi"), Parameter("lam")), {(0,): None, (1,): None} ) qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.append(random_unitary(4, seed=1), [1, 0]) tqc = transpile( circ, target=target, optimization_level=opt_level, translation_method="synthesis", layout_method="trivial", ) tqc_index = {qubit: index for index, qubit in enumerate(tqc.qubits)} self.assertGreaterEqual(len(tqc.get_instructions("ecr")), 1) for instr in tqc.get_instructions("ecr"): self.assertEqual((0, 1), (tqc_index[instr.qubits[0]], tqc_index[instr.qubits[1]])) @combine( opt_level=[0, 1, 2, 3], dsc=("Test controlled but not supercontrolled basis"), name="opt_level_{opt_level}", ) def test_controlled_basis(self, opt_level): target = Target(2) target.add_instruction(RYYGate(np.pi / 8), {(0, 1): InstructionProperties(error=1.2e-6)}) target.add_instruction( UGate(Parameter("theta"), Parameter("phi"), Parameter("lam")), {(0,): None, (1,): None} ) qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.append(random_unitary(4, seed=1), [1, 0]) tqc = transpile( circ, target=target, optimization_level=opt_level, translation_method="synthesis", layout_method="trivial", ) self.assertGreaterEqual(len(tqc.get_instructions("ryy")), 1) self.assertEqual(Operator(tqc), Operator(circ)) def test_approximation_controlled(self): target = Target(2) target.add_instruction(RZZGate(np.pi / 10), {(0, 1): InstructionProperties(error=0.006)}) target.add_instruction(RXXGate(np.pi / 3), {(0, 1): InstructionProperties(error=0.01)}) target.add_instruction( UGate(Parameter("theta"), Parameter("phi"), Parameter("lam")), {(0,): InstructionProperties(error=0.001), (1,): InstructionProperties(error=0.002)}, ) circ = QuantumCircuit(2) circ.append(random_unitary(4, seed=7), [1, 0]) dag = circuit_to_dag(circ) dag_100 = UnitarySynthesis(target=target, approximation_degree=1.0).run(dag) dag_99 = UnitarySynthesis(target=target, approximation_degree=0.99).run(dag) self.assertGreaterEqual(dag_100.depth(), dag_99.depth()) self.assertEqual(Operator(dag_to_circuit(dag_100)), Operator(circ)) def test_if_simple(self): """Test a simple if statement.""" basis_gates = {"u", "cx"} qr = QuantumRegister(2) cr = ClassicalRegister(2) qc_uni = QuantumCircuit(2) qc_uni.h(0) qc_uni.cx(0, 1) qc_uni_mat = Operator(qc_uni) qc_true_body = QuantumCircuit(2) qc_true_body.unitary(qc_uni_mat, [0, 1]) qc = QuantumCircuit(qr, cr) qc.if_test((cr, 1), qc_true_body, [0, 1], []) dag = circuit_to_dag(qc) cdag = UnitarySynthesis(basis_gates=basis_gates).run(dag) cqc = dag_to_circuit(cdag) cbody = cqc.data[0].operation.params[0] self.assertEqual(cbody.count_ops().keys(), basis_gates) self.assertEqual(qc_uni_mat, Operator(cbody)) def test_nested_control_flow(self): """Test unrolling nested control flow blocks.""" qr = QuantumRegister(2) cr = ClassicalRegister(1) qc_uni1 = QuantumCircuit(2) qc_uni1.swap(0, 1) qc_uni1_mat = Operator(qc_uni1) qc = QuantumCircuit(qr, cr) with qc.for_loop(range(3)): with qc.while_loop((cr, 0)): qc.unitary(qc_uni1_mat, [0, 1]) dag = circuit_to_dag(qc) cdag = UnitarySynthesis(basis_gates=["u", "cx"]).run(dag) cqc = dag_to_circuit(cdag) cbody = cqc.data[0].operation.params[2].data[0].operation.params[0] self.assertEqual(cbody.count_ops().keys(), {"u", "cx"}) self.assertEqual(qc_uni1_mat, Operator(cbody)) def test_mapping_control_flow(self): """Test that inner dags use proper qubit mapping.""" qr = QuantumRegister(3, "q") qc = QuantumCircuit(qr) # Create target that supports CX only between 0 and 2. fake_target = Target() fake_target.add_instruction(CXGate(), {(0, 2): None}) fake_target.add_instruction( UGate(Parameter("t"), Parameter("p"), Parameter("l")), { (0,): None, (1,): None, (2,): None, }, ) qc_uni1 = QuantumCircuit(2) qc_uni1.swap(0, 1) qc_uni1_mat = Operator(qc_uni1) loop_body = QuantumCircuit(2) loop_body.unitary(qc_uni1_mat, [0, 1]) # Loop body uses qubits 0 and 2, mapped to 0 and 1 in the block. # If synthesis doesn't handle recursive mapping, it'll incorrectly # look for a CX on (0, 1) instead of on (0, 2). qc.for_loop((0,), None, loop_body, [0, 2], []) dag = circuit_to_dag(qc) UnitarySynthesis(basis_gates=["u", "cx"], target=fake_target).run(dag) def test_single_qubit_with_target(self): """Test input circuit with only 1q works with target.""" qc = QuantumCircuit(1) qc.append(ZGate(), [qc.qubits[0]]) dag = circuit_to_dag(qc) unitary_synth_pass = UnitarySynthesis(target=FakeBelemV2().target) result_dag = unitary_synth_pass.run(dag) result_qc = dag_to_circuit(result_dag) self.assertEqual(qc, result_qc) def test_single_qubit_identity_with_target(self): """Test input single qubit identity works with target.""" qc = QuantumCircuit(1) qc.unitary([[1.0, 0.0], [0.0, 1.0]], 0) dag = circuit_to_dag(qc) unitary_synth_pass = UnitarySynthesis(target=FakeBelemV2().target) result_dag = unitary_synth_pass.run(dag) result_qc = dag_to_circuit(result_dag) self.assertEqual(result_qc, QuantumCircuit(1)) def test_unitary_synthesis_with_ideal_and_variable_width_ops(self): """Test unitary synthesis works with a target that contains ideal and variadic ops.""" qc = QuantumCircuit(2) qc.unitary(np.eye(4), [0, 1]) dag = circuit_to_dag(qc) target = FakeBelemV2().target target.add_instruction(IfElseOp, name="if_else") target.add_instruction(ZGate()) target.add_instruction(ECRGate()) unitary_synth_pass = UnitarySynthesis(target=target) result_dag = unitary_synth_pass.run(dag) result_qc = dag_to_circuit(result_dag) self.assertEqual(result_qc, QuantumCircuit(2)) def test_unitary_synthesis_custom_gate_target(self): qc = QuantumCircuit(2) qc.unitary(np.eye(4), [0, 1]) dag = circuit_to_dag(qc) class CustomGate(Gate): """Custom Opaque Gate""" def __init__(self): super().__init__("custom", 2, []) target = Target(num_qubits=2) target.add_instruction( UGate(Parameter("t"), Parameter("p"), Parameter("l")), {(0,): None, (1,): None} ) target.add_instruction(CustomGate(), {(0, 1): None, (1, 0): None}) unitary_synth_pass = UnitarySynthesis(target=target) result_dag = unitary_synth_pass.run(dag) result_qc = dag_to_circuit(result_dag) self.assertEqual(result_qc, qc) def test_default_does_not_fail_on_no_syntheses(self): qc = QuantumCircuit(1) qc.unitary(np.eye(2), [0]) pass_ = UnitarySynthesis(["unknown", "gates"]) self.assertEqual(qc, pass_(qc)) def test_iswap_no_cx_synthesis_succeeds(self): """Test basis set with iswap but no cx can synthesize a circuit""" target = Target() theta = Parameter("theta") i_props = { (0,): InstructionProperties(duration=35.5e-9, error=0.000413), (1,): InstructionProperties(duration=35.5e-9, error=0.000502), } target.add_instruction(IGate(), i_props) rz_props = { (0,): InstructionProperties(duration=0, error=0), (1,): InstructionProperties(duration=0, error=0), } target.add_instruction(RZGate(theta), rz_props) sx_props = { (0,): InstructionProperties(duration=35.5e-9, error=0.000413), (1,): InstructionProperties(duration=35.5e-9, error=0.000502), } target.add_instruction(SXGate(), sx_props) x_props = { (0,): InstructionProperties(duration=35.5e-9, error=0.000413), (1,): InstructionProperties(duration=35.5e-9, error=0.000502), } target.add_instruction(XGate(), x_props) iswap_props = { (0, 1): InstructionProperties(duration=519.11e-9, error=0.01201), (1, 0): InstructionProperties(duration=554.66e-9, error=0.01201), } target.add_instruction(iSwapGate(), iswap_props) measure_props = { (0,): InstructionProperties(duration=5.813e-6, error=0.0751), (1,): InstructionProperties(duration=5.813e-6, error=0.0225), } target.add_instruction(Measure(), measure_props) qc = QuantumCircuit(2) cxmat = Operator(CXGate()).to_matrix() qc.unitary(cxmat, [0, 1]) unitary_synth_pass = UnitarySynthesis(target=target) dag = circuit_to_dag(qc) result_dag = unitary_synth_pass.run(dag) result_qc = dag_to_circuit(result_dag) self.assertTrue(np.allclose(Operator(result_qc.to_gate()).to_matrix(), cxmat)) def test_parameterized_basis_gate_in_target(self): """Test synthesis with parameterized RXX gate.""" theta = Parameter("θ") lam = Parameter("λ") target = Target(num_qubits=2) target.add_instruction(RZGate(lam)) target.add_instruction(RXGate(theta)) target.add_instruction(RXXGate(theta)) qc = QuantumCircuit(2) qc.cp(np.pi / 2, 0, 1) qc_transpiled = transpile(qc, target=target, optimization_level=3, seed_transpiler=42) opcount = qc_transpiled.count_ops() self.assertTrue(set(opcount).issubset({"rz", "rx", "rxx"})) self.assertTrue(np.allclose(Operator(qc_transpiled), Operator(qc))) if __name__ == "__main__": unittest.main()
https://github.com/avkhadiev/schwinger-vqe
avkhadiev
#Assign these values as per your requirements. global min_qubits,max_qubits,skip_qubits,max_circuits,num_shots,Noise_Inclusion min_qubits=1 max_qubits=3 skip_qubits=1 max_circuits=3 num_shots=1000 use_XX_YY_ZZ_gates = True Noise_Inclusion = False saveplots = False Memory_utilization_plot = True Type_of_Simulator = "built_in" #Inputs are "built_in" or "FAKE" or "FAKEV2" backend_name = "FakeGuadalupeV2" #Can refer to the README files for the available backends gate_counts_plots = True #Change your Specification of Simulator in Declaring Backend Section #By Default : built_in -> qasm_simulator and FAKE -> FakeSantiago() and FAKEV2 -> FakeSantiagoV2() import numpy as np import os,json from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, execute import time import matplotlib.pyplot as plt # Import from Qiskit Aer noise module from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError,pauli_error, depolarizing_error, thermal_relaxation_error,reset_error) # Benchmark Name benchmark_name = "Hamiltonian Simulation" # Selection of basis gate set for transpilation # Note: selector 1 is a hardware agnostic gate set basis_selector = 1 basis_gates_array = [ [], ['rx', 'ry', 'rz', 'cx'], # a common basis set, default ['cx', 'rz', 'sx', 'x'], # IBM default basis set ['rx', 'ry', 'rxx'], # IonQ default basis set ['h', 'p', 'cx'], # another common basis set ['u', 'cx'] # general unitaries basis gates ] np.random.seed(0) num_gates = 0 depth = 0 def get_QV(backend): import json # Assuming backend.conf_filename is the filename and backend.dirname is the directory path conf_filename = backend.dirname + "/" + backend.conf_filename # Open the JSON file with open(conf_filename, 'r') as file: # Load the JSON data data = json.load(file) # Extract the quantum_volume parameter QV = data.get('quantum_volume', None) return QV def checkbackend(backend_name,Type_of_Simulator): if Type_of_Simulator == "built_in": available_backends = [] for i in Aer.backends(): available_backends.append(i.name) if backend_name in available_backends: platform = backend_name return platform else: print(f"incorrect backend name or backend not available. Using qasm_simulator by default !!!!") print(f"available backends are : {available_backends}") platform = "qasm_simulator" return platform elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2": import qiskit.providers.fake_provider as fake_backends if hasattr(fake_backends,backend_name) is True: print(f"Backend {backend_name} is available for type {Type_of_Simulator}.") backend_class = getattr(fake_backends,backend_name) backend_instance = backend_class() return backend_instance else: print(f"Backend {backend_name} is not available or incorrect for type {Type_of_Simulator}. Executing with FakeSantiago!!!") if Type_of_Simulator == "FAKEV2": backend_class = getattr(fake_backends,"FakeSantiagoV2") else: backend_class = getattr(fake_backends,"FakeSantiago") backend_instance = backend_class() return backend_instance if Type_of_Simulator == "built_in": platform = checkbackend(backend_name,Type_of_Simulator) #By default using "Qasm Simulator" backend = Aer.get_backend(platform) QV_=None print(f"{platform} device is capable of running {backend.num_qubits}") print(f"backend version is {backend.backend_version}") elif Type_of_Simulator == "FAKE": basis_selector = 0 backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.properties().backend_name +"-"+ backend.properties().backend_version #Replace this string with the backend Provider's name as this is used for Plotting. max_qubits=backend.configuration().n_qubits print(f"{platform} device is capable of running {backend.configuration().n_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") elif Type_of_Simulator == "FAKEV2": basis_selector = 0 if "V2" not in backend_name: backend_name = backend_name+"V2" backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.name +"-" +backend.backend_version max_qubits=backend.num_qubits print(f"{platform} device is capable of running {backend.num_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") else: print("Enter valid Simulator.....") # saved circuits and subcircuits for display QC_ = None XX_ = None YY_ = None ZZ_ = None XXYYZZ_ = None # import precalculated data to compare against filename = os.path.join("precalculated_data.json") with open(filename, 'r') as file: data = file.read() precalculated_data = json.loads(data) ############### Circuit Definition def HamiltonianSimulation(n_spins, K, t, w, h_x, h_z): ''' Construct a Qiskit circuit for Hamiltonian Simulation :param n_spins:The number of spins to simulate :param K: The Trotterization order :param t: duration of simulation :return: return a Qiskit circuit for this Hamiltonian ''' num_qubits = n_spins secret_int = f"{K}-{t}" # allocate qubits qr = QuantumRegister(n_spins); cr = ClassicalRegister(n_spins); qc = QuantumCircuit(qr, cr, name=f"hamsim-{num_qubits}-{secret_int}") tau = t / K # start with initial state of 1010101... for k in range(0, n_spins, 2): qc.x(qr[k]) qc.barrier() # loop over each trotter step, adding gates to the circuit defining the hamiltonian for k in range(K): # the Pauli spin vector product [qc.rx(2 * tau * w * h_x[i], qr[i]) for i in range(n_spins)] [qc.rz(2 * tau * w * h_z[i], qr[i]) for i in range(n_spins)] qc.barrier() # Basic implementation of exp(i * t * (XX + YY + ZZ)) if _use_XX_YY_ZZ_gates: # XX operator on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(xx_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # YY operator on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(yy_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # ZZ operation on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(zz_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # Use an optimal XXYYZZ combined operator # See equation 1 and Figure 6 in https://arxiv.org/pdf/quant-ph/0308006.pdf else: # optimized XX + YY + ZZ operator on each pair of qubits in linear chain for j in range(2): for i in range(j % 2, n_spins - 1, 2): qc.append(xxyyzz_opt_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) qc.barrier() # measure all the qubits used in the circuit for i_qubit in range(n_spins): qc.measure(qr[i_qubit], cr[i_qubit]) # save smaller circuit example for display global QC_ if QC_ == None or n_spins <= 6: if n_spins < 9: QC_ = qc return qc ############### XX, YY, ZZ Gate Implementations # Simple XX gate on q0 and q1 with angle 'tau' def xx_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="xx_gate") qc.h(qr[0]) qc.h(qr[1]) qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.h(qr[1]) # save circuit example for display global XX_ XX_ = qc return qc # Simple YY gate on q0 and q1 with angle 'tau' def yy_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="yy_gate") qc.s(qr[0]) qc.s(qr[1]) qc.h(qr[0]) qc.h(qr[1]) qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.h(qr[1]) qc.sdg(qr[0]) qc.sdg(qr[1]) # save circuit example for display global YY_ YY_ = qc return qc # Simple ZZ gate on q0 and q1 with angle 'tau' def zz_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="zz_gate") qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) # save circuit example for display global ZZ_ ZZ_ = qc return qc # Optimal combined XXYYZZ gate (with double coupling) on q0 and q1 with angle 'tau' def xxyyzz_opt_gate(tau): alpha = tau; beta = tau; gamma = tau qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="xxyyzz_opt") qc.rz(3.1416/2, qr[1]) qc.cx(qr[1], qr[0]) qc.rz(3.1416*gamma - 3.1416/2, qr[0]) qc.ry(3.1416/2 - 3.1416*alpha, qr[1]) qc.cx(qr[0], qr[1]) qc.ry(3.1416*beta - 3.1416/2, qr[1]) qc.cx(qr[1], qr[0]) qc.rz(-3.1416/2, qr[0]) # save circuit example for display global XXYYZZ_ XXYYZZ_ = qc return qc # Create an empty noise model noise_parameters = NoiseModel() if Type_of_Simulator == "built_in": # Add depolarizing error to all single qubit gates with error rate 0.05% and to all two qubit gates with error rate 0.5% depol_one_qb_error = 0.05 depol_two_qb_error = 0.005 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_two_qb_error, 2), ['cx']) # Add amplitude damping error to all single qubit gates with error rate 0.0% and to all two qubit gates with error rate 0.0% amp_damp_one_qb_error = 0.0 amp_damp_two_qb_error = 0.0 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_two_qb_error, 2), ['cx']) # Add reset noise to all single qubit resets reset_to_zero_error = 0.005 reset_to_one_error = 0.005 noise_parameters.add_all_qubit_quantum_error(reset_error(reset_to_zero_error, reset_to_one_error),["reset"]) # Add readout error p0given1_error = 0.000 p1given0_error = 0.000 error_meas = ReadoutError([[1 - p1given0_error, p1given0_error], [p0given1_error, 1 - p0given1_error]]) noise_parameters.add_all_qubit_readout_error(error_meas) #print(noise_parameters) elif Type_of_Simulator == "FAKE"or"FAKEV2": noise_parameters = NoiseModel.from_backend(backend) #print(noise_parameters) ### Analysis methods to be expanded and eventually compiled into a separate analysis.py file import math, functools def hellinger_fidelity_with_expected(p, q): """ p: result distribution, may be passed as a counts distribution q: the expected distribution to be compared against References: `Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_ Qiskit Hellinger Fidelity Function """ p_sum = sum(p.values()) q_sum = sum(q.values()) if q_sum == 0: print("ERROR: polarization_fidelity(), expected distribution is invalid, all counts equal to 0") return 0 p_normed = {} for key, val in p.items(): p_normed[key] = val/p_sum # if p_sum != 0: # p_normed[key] = val/p_sum # else: # p_normed[key] = 0 q_normed = {} for key, val in q.items(): q_normed[key] = val/q_sum total = 0 for key, val in p_normed.items(): if key in q_normed.keys(): total += (np.sqrt(val) - np.sqrt(q_normed[key]))**2 del q_normed[key] else: total += val total += sum(q_normed.values()) # in some situations (error mitigation) this can go negative, use abs value if total < 0: print(f"WARNING: using absolute value in fidelity calculation") total = abs(total) dist = np.sqrt(total)/np.sqrt(2) fidelity = (1-dist**2)**2 return fidelity def polarization_fidelity(counts, correct_dist, thermal_dist=None): """ Combines Hellinger fidelity and polarization rescaling into fidelity calculation used in every benchmark counts: the measurement outcomes after `num_shots` algorithm runs correct_dist: the distribution we expect to get for the algorithm running perfectly thermal_dist: optional distribution to pass in distribution from a uniform superposition over all states. If `None`: generated as `uniform_dist` with the same qubits as in `counts` returns both polarization fidelity and the hellinger fidelity Polarization from: `https://arxiv.org/abs/2008.11294v1` """ num_measured_qubits = len(list(correct_dist.keys())[0]) #print(num_measured_qubits) counts = {k.zfill(num_measured_qubits): v for k, v in counts.items()} # calculate hellinger fidelity between measured expectation values and correct distribution hf_fidelity = hellinger_fidelity_with_expected(counts,correct_dist) # to limit cpu and memory utilization, skip noise correction if more than 16 measured qubits if num_measured_qubits > 16: return { 'fidelity':hf_fidelity, 'hf_fidelity':hf_fidelity } # if not provided, generate thermal dist based on number of qubits if thermal_dist == None: thermal_dist = uniform_dist(num_measured_qubits) # set our fidelity rescaling value as the hellinger fidelity for a depolarized state floor_fidelity = hellinger_fidelity_with_expected(thermal_dist, correct_dist) # rescale fidelity result so uniform superposition (random guessing) returns fidelity # rescaled to 0 to provide a better measure of success of the algorithm (polarization) new_floor_fidelity = 0 fidelity = rescale_fidelity(hf_fidelity, floor_fidelity, new_floor_fidelity) return { 'fidelity':fidelity, 'hf_fidelity':hf_fidelity } ## Uniform distribution function commonly used def rescale_fidelity(fidelity, floor_fidelity, new_floor_fidelity): """ Linearly rescales our fidelities to allow comparisons of fidelities across benchmarks fidelity: raw fidelity to rescale floor_fidelity: threshold fidelity which is equivalent to random guessing new_floor_fidelity: what we rescale the floor_fidelity to Ex, with floor_fidelity = 0.25, new_floor_fidelity = 0.0: 1 -> 1; 0.25 -> 0; 0.5 -> 0.3333; """ rescaled_fidelity = (1-new_floor_fidelity)/(1-floor_fidelity) * (fidelity - 1) + 1 # ensure fidelity is within bounds (0, 1) if rescaled_fidelity < 0: rescaled_fidelity = 0.0 if rescaled_fidelity > 1: rescaled_fidelity = 1.0 return rescaled_fidelity def uniform_dist(num_state_qubits): dist = {} for i in range(2**num_state_qubits): key = bin(i)[2:].zfill(num_state_qubits) dist[key] = 1/(2**num_state_qubits) return dist from matplotlib.patches import Rectangle import matplotlib.cm as cm from matplotlib.colors import ListedColormap, LinearSegmentedColormap, Normalize from matplotlib.patches import Circle ############### Color Map functions # Create a selection of colormaps from which to choose; default to custom_spectral cmap_spectral = plt.get_cmap('Spectral') cmap_greys = plt.get_cmap('Greys') cmap_blues = plt.get_cmap('Blues') cmap_custom_spectral = None # the default colormap is the spectral map cmap = cmap_spectral cmap_orig = cmap_spectral # current cmap normalization function (default None) cmap_norm = None default_fade_low_fidelity_level = 0.16 default_fade_rate = 0.7 # Specify a normalization function here (default None) def set_custom_cmap_norm(vmin, vmax): global cmap_norm if vmin == vmax or (vmin == 0.0 and vmax == 1.0): print("... setting cmap norm to None") cmap_norm = None else: print(f"... setting cmap norm to [{vmin}, {vmax}]") cmap_norm = Normalize(vmin=vmin, vmax=vmax) # Remake the custom spectral colormap with user settings def set_custom_cmap_style( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): #print("... set custom map style") global cmap, cmap_custom_spectral, cmap_orig cmap_custom_spectral = create_custom_spectral_cmap( fade_low_fidelity_level=fade_low_fidelity_level, fade_rate=fade_rate) cmap = cmap_custom_spectral cmap_orig = cmap_custom_spectral # Create the custom spectral colormap from the base spectral def create_custom_spectral_cmap( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): # determine the breakpoint from the fade level num_colors = 100 breakpoint = round(fade_low_fidelity_level * num_colors) # get color list for spectral map spectral_colors = [cmap_spectral(v/num_colors) for v in range(num_colors)] #print(fade_rate) # create a list of colors to replace those below the breakpoint # and fill with "faded" color entries (in reverse) low_colors = [0] * breakpoint #for i in reversed(range(breakpoint)): for i in range(breakpoint): # x is index of low colors, normalized 0 -> 1 x = i / breakpoint # get color at this index bc = spectral_colors[i] r0 = bc[0] g0 = bc[1] b0 = bc[2] z0 = bc[3] r_delta = 0.92 - r0 #print(f"{x} {bc} {r_delta}") # compute saturation and greyness ratio sat_ratio = 1 - x #grey_ratio = 1 - x ''' attempt at a reflective gradient if i >= breakpoint/2: xf = 2*(x - 0.5) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (yf + 0.5) else: xf = 2*(0.5 - x) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (0.5 - yf) ''' grey_ratio = 1 - math.pow(x, 1/fade_rate) #print(f" {xf} {yf} ") #print(f" {sat_ratio} {grey_ratio}") r = r0 + r_delta * sat_ratio g_delta = r - g0 b_delta = r - b0 g = g0 + g_delta * grey_ratio b = b0 + b_delta * grey_ratio #print(f"{r} {g} {b}\n") low_colors[i] = (r,g,b,z0) #print(low_colors) # combine the faded low colors with the regular spectral cmap to make a custom version cmap_custom_spectral = ListedColormap(low_colors + spectral_colors[breakpoint:]) #spectral_colors = [cmap_custom_spectral(v/10) for v in range(10)] #for i in range(10): print(spectral_colors[i]) #print("") return cmap_custom_spectral # Make the custom spectral color map the default on module init set_custom_cmap_style() # Arrange the stored annotations optimally and add to plot def anno_volumetric_data(ax, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True): # sort all arrays by the x point of the text (anno_offs) global x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos all_annos = sorted(zip(x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos)) x_anno_offs = [a for a,b,c,d,e in all_annos] y_anno_offs = [b for a,b,c,d,e in all_annos] anno_labels = [c for a,b,c,d,e in all_annos] x_annos = [d for a,b,c,d,e in all_annos] y_annos = [e for a,b,c,d,e in all_annos] #print(f"{x_anno_offs}") #print(f"{y_anno_offs}") #print(f"{anno_labels}") for i in range(len(anno_labels)): x_anno = x_annos[i] y_anno = y_annos[i] x_anno_off = x_anno_offs[i] y_anno_off = y_anno_offs[i] label = anno_labels[i] if i > 0: x_delta = abs(x_anno_off - x_anno_offs[i - 1]) y_delta = abs(y_anno_off - y_anno_offs[i - 1]) if y_delta < 0.7 and x_delta < 2: y_anno_off = y_anno_offs[i] = y_anno_offs[i - 1] - 0.6 #x_anno_off = x_anno_offs[i] = x_anno_offs[i - 1] + 0.1 ax.annotate(label, xy=(x_anno+0.0, y_anno+0.1), arrowprops=dict(facecolor='black', shrink=0.0, width=0.5, headwidth=4, headlength=5, edgecolor=(0.8,0.8,0.8)), xytext=(x_anno_off + labelpos[0], y_anno_off + labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='baseline', color=(0.2,0.2,0.2), clip_on=True) if saveplots == True: plt.savefig("VolumetricPlotSample.jpg") # Plot one group of data for volumetric presentation def plot_volumetric_data(ax, w_data, d_data, f_data, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True, w_max=18, do_label=False, do_border=True, x_size=1.0, y_size=1.0, zorder=1, offset_flag=False, max_depth=0, suppress_low_fidelity=False): # since data may come back out of order, save point at max y for annotation i_anno = 0 x_anno = 0 y_anno = 0 # plot data rectangles low_fidelity_count = True last_y = -1 k = 0 # determine y-axis dimension for one pixel to use for offset of bars that start at 0 (_, dy) = get_pixel_dims(ax) # do this loop in reverse to handle the case where earlier cells are overlapped by later cells for i in reversed(range(len(d_data))): x = depth_index(d_data[i], depth_base) y = float(w_data[i]) f = f_data[i] # each time we star a new row, reset the offset counter # DEVNOTE: this is highly specialized for the QA area plots, where there are 8 bars # that represent time starting from 0 secs. We offset by one pixel each and center the group if y != last_y: last_y = y; k = 3 # hardcoded for 8 cells, offset by 3 #print(f"{i = } {x = } {y = }") if max_depth > 0 and d_data[i] > max_depth: #print(f"... excessive depth (2), skipped; w={y} d={d_data[i]}") break; # reject cells with low fidelity if suppress_low_fidelity and f < suppress_low_fidelity_level: if low_fidelity_count: break else: low_fidelity_count = True # the only time this is False is when doing merged gradation plots if do_border == True: # this case is for an array of x_sizes, i.e. each box has different width if isinstance(x_size, list): # draw each of the cells, with no offset if not offset_flag: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size[i], y_size=y_size, zorder=zorder)) # use an offset for y value, AND account for x and width to draw starting at 0 else: ax.add_patch(box_at((x/2 + x_size[i]/4), y + k*dy, f, type=type, fill=fill, x_size=x+ x_size[i]/2, y_size=y_size, zorder=zorder)) # this case is for only a single cell else: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size, y_size=y_size)) # save the annotation point with the largest y value if y >= y_anno: x_anno = x y_anno = y i_anno = i # move the next bar down (if using offset) k -= 1 # if no data rectangles plotted, no need for a label if x_anno == 0 or y_anno == 0: return x_annos.append(x_anno) y_annos.append(y_anno) anno_dist = math.sqrt( (y_anno - 1)**2 + (x_anno - 1)**2 ) # adjust radius of annotation circle based on maximum width of apps anno_max = 10 if w_max > 10: anno_max = 14 if w_max > 14: anno_max = 18 scale = anno_max / anno_dist # offset of text from end of arrow if scale > 1: x_anno_off = scale * x_anno - x_anno - 0.5 y_anno_off = scale * y_anno - y_anno else: x_anno_off = 0.7 y_anno_off = 0.5 x_anno_off += x_anno y_anno_off += y_anno # print(f"... {xx} {yy} {anno_dist}") x_anno_offs.append(x_anno_off) y_anno_offs.append(y_anno_off) anno_labels.append(label) if do_label: ax.annotate(label, xy=(x_anno+labelpos[0], y_anno+labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='bottom', color=(0.2,0.2,0.2)) x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # init arrays to hold annotation points for label spreading def vplot_anno_init (): global x_annos, y_annos, x_anno_offs, y_anno_offs, anno_labels x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # Number of ticks on volumetric depth axis max_depth_log = 22 # average transpile factor between base QV depth and our depth based on results from QV notebook QV_transpile_factor = 12.7 # format a number using K,M,B,T for large numbers, optionally rounding to 'digits' decimal places if num > 1 # (sign handling may be incorrect) def format_number(num, digits=0): if isinstance(num, str): num = float(num) num = float('{:.3g}'.format(abs(num))) sign = '' metric = {'T': 1000000000000, 'B': 1000000000, 'M': 1000000, 'K': 1000, '': 1} for index in metric: num_check = num / metric[index] if num_check >= 1: num = round(num_check, digits) sign = index break numstr = f"{str(num)}" if '.' in numstr: numstr = numstr.rstrip('0').rstrip('.') return f"{numstr}{sign}" # Return the color associated with the spcific value, using color map norm def get_color(value): # if there is a normalize function installed, scale the data if cmap_norm: value = float(cmap_norm(value)) if cmap == cmap_spectral: value = 0.05 + value*0.9 elif cmap == cmap_blues: value = 0.00 + value*1.0 else: value = 0.0 + value*0.95 return cmap(value) # Return the x and y equivalent to a single pixel for the given plot axis def get_pixel_dims(ax): # transform 0 -> 1 to pixel dimensions pixdims = ax.transData.transform([(0,1),(1,0)])-ax.transData.transform((0,0)) xpix = pixdims[1][0] ypix = pixdims[0][1] #determine x- and y-axis dimension for one pixel dx = (1 / xpix) dy = (1 / ypix) return (dx, dy) ############### Helper functions # return the base index for a circuit depth value # take the log in the depth base, and add 1 def depth_index(d, depth_base): if depth_base <= 1: return d if d == 0: return 0 return math.log(d, depth_base) + 1 # draw a box at x,y with various attributes def box_at(x, y, value, type=1, fill=True, x_size=1.0, y_size=1.0, alpha=1.0, zorder=1): value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Rectangle((x - (x_size/2), y - (y_size/2)), x_size, y_size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.5*y_size, zorder=zorder) # draw a circle at x,y with various attributes def circle_at(x, y, value, type=1, fill=True): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Circle((x, y), size/2, alpha = 0.7, # DEVNOTE: changed to 0.7 from 0.5, to handle only one cell edgecolor = ec, facecolor = fc, fill=fill, lw=0.5) def box4_at(x, y, value, type=1, fill=True, alpha=1.0): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.3,0.3,0.3) ec = fc return Rectangle((x - size/8, y - size/2), size/4, size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.1) # Draw a Quantum Volume rectangle with specified width and depth, and grey-scale value def qv_box_at(x, y, qv_width, qv_depth, value, depth_base): #print(f"{qv_width} {qv_depth} {depth_index(qv_depth, depth_base)}") return Rectangle((x - 0.5, y - 0.5), depth_index(qv_depth, depth_base), qv_width, edgecolor = (value,value,value), facecolor = (value,value,value), fill=True, lw=1) def bkg_box_at(x, y, value=0.9): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (value,value,value), fill=True, lw=0.5) def bkg_empty_box_at(x, y): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (1.0,1.0,1.0), fill=True, lw=0.5) # Plot the background for the volumetric analysis def plot_volumetric_background(max_qubits=11, QV=32, depth_base=2, suptitle=None, avail_qubits=0, colorbar_label="Avg Result Fidelity"): if suptitle == None: suptitle = f"Volumetric Positioning\nCircuit Dimensions and Fidelity Overlaid on Quantum Volume = {QV}" QV0 = QV qv_estimate = False est_str = "" if QV == 0: # QV = 0 indicates "do not draw QV background or label" QV = 2048 elif QV < 0: # QV < 0 indicates "add est. to label" QV = -QV qv_estimate = True est_str = " (est.)" if avail_qubits > 0 and max_qubits > avail_qubits: max_qubits = avail_qubits max_width = 13 if max_qubits > 11: max_width = 18 if max_qubits > 14: max_width = 20 if max_qubits > 16: max_width = 24 if max_qubits > 24: max_width = 33 #print(f"... {avail_qubits} {max_qubits} {max_width}") plot_width = 6.8 plot_height = 0.5 + plot_width * (max_width / max_depth_log) #print(f"... {plot_width} {plot_height}") # define matplotlib figure and axis; use constrained layout to fit colorbar to right fig, ax = plt.subplots(figsize=(plot_width, plot_height), constrained_layout=True) plt.suptitle(suptitle) plt.xlim(0, max_depth_log) plt.ylim(0, max_width) # circuit depth axis (x axis) xbasis = [x for x in range(1,max_depth_log)] xround = [depth_base**(x-1) for x in xbasis] xlabels = [format_number(x) for x in xround] ax.set_xlabel('Circuit Depth') ax.set_xticks(xbasis) plt.xticks(xbasis, xlabels, color='black', rotation=45, ha='right', va='top', rotation_mode="anchor") # other label options #plt.xticks(xbasis, xlabels, color='black', rotation=-60, ha='left') #plt.xticks(xbasis, xlabels, color='black', rotation=-45, ha='left', va='center', rotation_mode="anchor") # circuit width axis (y axis) ybasis = [y for y in range(1,max_width)] yround = [1,2,3,4,5,6,7,8,10,12,15] # not used now ylabels = [str(y) for y in yround] # not used now #ax.set_ylabel('Circuit Width (Number of Qubits)') ax.set_ylabel('Circuit Width') ax.set_yticks(ybasis) #create simple line plot (not used right now) #ax.plot([0, 10],[0, 10]) log2QV = math.log2(QV) QV_width = log2QV QV_depth = log2QV * QV_transpile_factor # show a quantum volume rectangle of QV = 64 e.g. (6 x 6) if QV0 != 0: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.87, depth_base)) else: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.91, depth_base)) # the untranspiled version is commented out - we do not show this by default # also show a quantum volume rectangle un-transpiled # ax.add_patch(qv_box_at(1, 1, QV_width, QV_width, 0.80, depth_base)) # show 2D array of volumetric cells based on this QV_transpiled # DEVNOTE: we use +1 only to make the visuals work; s/b without # Also, the second arg of the min( below seems incorrect, needs correction maxprod = (QV_width + 1) * (QV_depth + 1) for w in range(1, min(max_width, round(QV) + 1)): # don't show VB squares if width greater than known available qubits if avail_qubits != 0 and w > avail_qubits: continue i_success = 0 for d in xround: # polarization factor for low circuit widths maxtest = maxprod / ( 1 - 1 / (2**w) ) # if circuit would fail here, don't draw box if d > maxtest: continue if w * d > maxtest: continue # guess for how to capture how hardware decays with width, not entirely correct # # reduce maxtext by a factor of number of qubits > QV_width # # just an approximation to account for qubit distances # if w > QV_width: # over = w - QV_width # maxtest = maxtest / (1 + (over/QV_width)) # draw a box at this width and depth id = depth_index(d, depth_base) # show vb rectangles; if not showing QV, make all hollow (or less dark) if QV0 == 0: #ax.add_patch(bkg_empty_box_at(id, w)) ax.add_patch(bkg_box_at(id, w, 0.95)) else: ax.add_patch(bkg_box_at(id, w, 0.9)) # save index of last successful depth i_success += 1 # plot empty rectangle after others d = xround[i_success] id = depth_index(d, depth_base) ax.add_patch(bkg_empty_box_at(id, w)) # Add annotation showing quantum volume if QV0 != 0: t = ax.text(max_depth_log - 2.0, 1.5, f"QV{est_str}={QV}", size=12, horizontalalignment='right', verticalalignment='center', color=(0.2,0.2,0.2), bbox=dict(boxstyle="square,pad=0.3", fc=(.9,.9,.9), ec="grey", lw=1)) # add colorbar to right of plot plt.colorbar(cm.ScalarMappable(cmap=cmap), cax=None, ax=ax, shrink=0.6, label=colorbar_label, panchor=(0.0, 0.7)) return ax # Function to calculate circuit depth def calculate_circuit_depth(qc): # Calculate the depth of the circuit depth = qc.depth() return depth def calculate_transpiled_depth(qc,basis_selector): # use either the backend or one of the basis gate sets if basis_selector == 0: qc = transpile(qc, backend) else: basis_gates = basis_gates_array[basis_selector] qc = transpile(qc, basis_gates=basis_gates, seed_transpiler=0) transpiled_depth = qc.depth() return transpiled_depth,qc def plot_fidelity_data(fidelity_data, Hf_fidelity_data, title): avg_fidelity_means = [] avg_Hf_fidelity_means = [] avg_num_qubits_values = list(fidelity_data.keys()) # Calculate the average fidelity and Hamming fidelity for each unique number of qubits for num_qubits in avg_num_qubits_values: avg_fidelity = np.average(fidelity_data[num_qubits]) avg_fidelity_means.append(avg_fidelity) avg_Hf_fidelity = np.mean(Hf_fidelity_data[num_qubits]) avg_Hf_fidelity_means.append(avg_Hf_fidelity) return avg_fidelity_means,avg_Hf_fidelity_means list_of_gates = [] def list_of_standardgates(): import qiskit.circuit.library as lib from qiskit.circuit import Gate import inspect # List all the attributes of the library module gate_list = dir(lib) # Filter out non-gate classes (like functions, variables, etc.) gates = [gate for gate in gate_list if isinstance(getattr(lib, gate), type) and issubclass(getattr(lib, gate), Gate)] # Get method names from QuantumCircuit circuit_methods = inspect.getmembers(QuantumCircuit, inspect.isfunction) method_names = [name for name, _ in circuit_methods] # Map gate class names to method names gate_to_method = {} for gate in gates: gate_class = getattr(lib, gate) class_name = gate_class.__name__.replace('Gate', '').lower() # Normalize class name for method in method_names: if method == class_name or method == class_name.replace('cr', 'c-r'): gate_to_method[gate] = method break # Add common operations that are not strictly gates additional_operations = { 'Measure': 'measure', 'Barrier': 'barrier', } gate_to_method.update(additional_operations) for k,v in gate_to_method.items(): list_of_gates.append(v) def update_counts(gates,custom_gates): operations = {} for key, value in gates.items(): operations[key] = value for key, value in custom_gates.items(): if key in operations: operations[key] += value else: operations[key] = value return operations def get_gate_counts(gates,custom_gate_defs): result = gates.copy() # Iterate over the gate counts in the quantum circuit for gate, count in gates.items(): if gate in custom_gate_defs: custom_gate_ops = custom_gate_defs[gate] # Multiply custom gate operations by the count of the custom gate in the circuit for _ in range(count): result = update_counts(result, custom_gate_ops) # Remove the custom gate entry as we have expanded it del result[gate] return result dict_of_qc = dict() custom_gates_defs = dict() # Function to count operations recursively def count_operations(qc): dict_of_qc.clear() circuit_traverser(qc) operations = dict() operations = dict_of_qc[qc.name] del dict_of_qc[qc.name] # print("operations :",operations) # print("dict_of_qc :",dict_of_qc) for keys in operations.keys(): if keys not in list_of_gates: for k,v in dict_of_qc.items(): if k in operations.keys(): custom_gates_defs[k] = v operations=get_gate_counts(operations,custom_gates_defs) custom_gates_defs.clear() return operations def circuit_traverser(qc): dict_of_qc[qc.name]=dict(qc.count_ops()) for i in qc.data: if str(i.operation.name) not in list_of_gates: qc_1 = i.operation.definition circuit_traverser(qc_1) def get_memory(): import resource usage = resource.getrusage(resource.RUSAGE_SELF) max_mem = usage.ru_maxrss/1024 #in MB return max_mem def analyzer(num_qubits): # we have precalculated the correct distribution that a perfect quantum computer will return # it is stored in the json file we import at the top of the code correct_dist = precalculated_data[f"Qubits - {num_qubits}"] return correct_dist num_state_qubits=1 #(default) not exposed to users def run (min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, use_XX_YY_ZZ_gates = use_XX_YY_ZZ_gates): creation_times = [] elapsed_times = [] quantum_times = [] circuit_depths = [] transpiled_depths = [] fidelity_data = {} Hf_fidelity_data = {} numckts = [] mem_usage = [] algorithmic_1Q_gate_counts = [] algorithmic_2Q_gate_counts = [] transpiled_1Q_gate_counts = [] transpiled_2Q_gate_counts = [] print(f"{benchmark_name} Benchmark Program - {platform}") #defining all the standard gates supported by qiskit in a list if gate_counts_plots == True: list_of_standardgates() # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even skip_qubits = max(1, skip_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") global _use_XX_YY_ZZ_gates _use_XX_YY_ZZ_gates = use_XX_YY_ZZ_gates if _use_XX_YY_ZZ_gates: print("... using unoptimized XX YY ZZ gates") global max_ckts max_ckts = max_circuits global min_qbits,max_qbits,skp_qubits min_qbits = min_qubits max_qbits = max_qubits skp_qubits = skip_qubits print(f"min, max qubits = {min_qubits} {max_qubits}") # Execute Benchmark Program N times for multiple circuit sizes for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): fidelity_data[num_qubits] = [] Hf_fidelity_data[num_qubits] = [] # reset random seed np.random.seed(0) # determine number of circuits to execute for this group num_circuits = max(1, max_circuits) print(f"Executing [{num_circuits}] circuits with num_qubits = {num_qubits}") numckts.append(num_circuits) # parameters of simulation #### CANNOT BE MODIFIED W/O ALSO MODIFYING PRECALCULATED DATA ######### w = precalculated_data['w'] # strength of disorder k = precalculated_data['k'] # Trotter error. # A large Trotter order approximates the Hamiltonian evolution better. # But a large Trotter order also means the circuit is deeper. # For ideal or noise-less quantum circuits, k >> 1 gives perfect hamiltonian simulation. t = precalculated_data['t'] # time of simulation ####################################################################### for circuit_id in range(num_circuits): print("*********************************************") print(f"qc of {num_qubits} qubits for circuit_id: {circuit_id}") #creation of Quantum Circuit. ts = time.time() h_x = precalculated_data['h_x'][:num_qubits] # precalculated random numbers between [-1, 1] h_z = precalculated_data['h_z'][:num_qubits] qc = HamiltonianSimulation(num_qubits, K=k, t=t, w=w, h_x= h_x, h_z=h_z) #creation time creation_time = time.time() - ts creation_times.append(creation_time) print(f"creation time = {creation_time*1000} ms") # Calculate gate count for the algorithmic circuit (excluding barriers and measurements) if gate_counts_plots == True: operations = count_operations(qc) n1q = 0; n2q = 0 if operations != None: for key, value in operations.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c") or key.startswith("mc"): n2q += value else: n1q += value algorithmic_1Q_gate_counts.append(n1q) algorithmic_2Q_gate_counts.append(n2q) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc=qc.decompose() #print(qc) # Calculate circuit depth depth = calculate_circuit_depth(qc) circuit_depths.append(depth) # Calculate transpiled circuit depth transpiled_depth,qc = calculate_transpiled_depth(qc,basis_selector) transpiled_depths.append(transpiled_depth) #print(qc) print(f"Algorithmic Depth = {depth} and Normalized Depth = {transpiled_depth}") if gate_counts_plots == True: # Calculate gate count for the transpiled circuit (excluding barriers and measurements) tr_ops = qc.count_ops() #print("tr_ops = ",tr_ops) tr_n1q = 0; tr_n2q = 0 if tr_ops != None: for key, value in tr_ops.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c"): tr_n2q += value else: tr_n1q += value transpiled_1Q_gate_counts.append(tr_n1q) transpiled_2Q_gate_counts.append(tr_n2q) print(f"Algorithmic 1Q gates = {n1q} ,Algorithmic 2Q gates = {n2q}") print(f"Normalized 1Q gates = {tr_n1q} ,Normalized 2Q gates = {tr_n2q}") #execution if Type_of_Simulator == "built_in": #To check if Noise is required if Noise_Inclusion == True: noise_model = noise_parameters else: noise_model = None ts = time.time() job = execute(qc, backend, shots=num_shots, noise_model=noise_model) elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2" : ts = time.time() job = backend.run(qc,shots=num_shots, noise_model=noise_parameters) #retrieving the result result = job.result() #print(result) #calculating elapsed time elapsed_time = time.time() - ts elapsed_times.append(elapsed_time) # Calculate quantum processing time quantum_time = result.time_taken quantum_times.append(quantum_time) print(f"Elapsed time = {elapsed_time*1000} ms and Quantum Time = {quantum_time*1000} ms") #counts in result object counts = result.get_counts() #Correct distribution to compare with counts correct_dist = analyzer(num_qubits) #fidelity calculation comparision of counts and correct_dist fidelity_dict = polarization_fidelity(counts, correct_dist) fidelity_data[num_qubits].append(fidelity_dict['fidelity']) Hf_fidelity_data[num_qubits].append(fidelity_dict['hf_fidelity']) #maximum memory utilization (if required) if Memory_utilization_plot == True: max_mem = get_memory() print(f"Maximum Memory Utilized: {max_mem} MB") mem_usage.append(max_mem) print("*********************************************") ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") if _use_XX_YY_ZZ_gates: print("\nXX, YY, ZZ =") print(XX_); print(YY_); print(ZZ_) else: print("\nXXYYZZ_opt =") print(XXYYZZ_) return (creation_times, elapsed_times, quantum_times, circuit_depths, transpiled_depths, fidelity_data, Hf_fidelity_data, numckts , algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) # Execute the benchmark program, accumulate metrics, and calculate circuit depths (creation_times, elapsed_times, quantum_times, circuit_depths,transpiled_depths, fidelity_data, Hf_fidelity_data, numckts, algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) = run() # Define the range of qubits for the x-axis num_qubits_range = range(min_qbits, max_qbits+1,skp_qubits) print("num_qubits_range =",num_qubits_range) # Calculate average creation time, elapsed time, quantum processing time, and circuit depth for each number of qubits avg_creation_times = [] avg_elapsed_times = [] avg_quantum_times = [] avg_circuit_depths = [] avg_transpiled_depths = [] avg_1Q_algorithmic_gate_counts = [] avg_2Q_algorithmic_gate_counts = [] avg_1Q_Transpiled_gate_counts = [] avg_2Q_Transpiled_gate_counts = [] max_memory = [] start = 0 for num in numckts: avg_creation_times.append(np.mean(creation_times[start:start+num])) avg_elapsed_times.append(np.mean(elapsed_times[start:start+num])) avg_quantum_times.append(np.mean(quantum_times[start:start+num])) avg_circuit_depths.append(np.mean(circuit_depths[start:start+num])) avg_transpiled_depths.append(np.mean(transpiled_depths[start:start+num])) if gate_counts_plots == True: avg_1Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_1Q_gate_counts[start:start+num]))) avg_2Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_2Q_gate_counts[start:start+num]))) avg_1Q_Transpiled_gate_counts.append(int(np.mean(transpiled_1Q_gate_counts[start:start+num]))) avg_2Q_Transpiled_gate_counts.append(int(np.mean(transpiled_2Q_gate_counts[start:start+num]))) if Memory_utilization_plot == True:max_memory.append(np.max(mem_usage[start:start+num])) start += num # Calculate the fidelity data avg_f, avg_Hf = plot_fidelity_data(fidelity_data, Hf_fidelity_data, "Fidelity Comparison") # Plot histograms for average creation time, average elapsed time, average quantum processing time, and average circuit depth versus the number of qubits # Add labels to the bars def autolabel(rects,ax,str='{:.3f}',va='top',text_color="black"): for rect in rects: height = rect.get_height() ax.annotate(str.format(height), # Formatting to two decimal places xy=(rect.get_x() + rect.get_width() / 2, height / 2), xytext=(0, 0), textcoords="offset points", ha='center', va=va,color=text_color,rotation=90) bar_width = 0.3 # Determine the number of subplots and their arrangement if Memory_utilization_plot and gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6, ax7) = plt.subplots(7, 1, figsize=(18, 30)) # Plotting for both memory utilization and gate counts # ax1, ax2, ax3, ax4, ax5, ax6, ax7 are available elif Memory_utilization_plot: fig, (ax1, ax2, ax3, ax6, ax7) = plt.subplots(5, 1, figsize=(18, 30)) # Plotting for memory utilization only # ax1, ax2, ax3, ax6, ax7 are available elif gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6, 1, figsize=(18, 30)) # Plotting for gate counts only # ax1, ax2, ax3, ax4, ax5, ax6 are available else: fig, (ax1, ax2, ax3, ax6) = plt.subplots(4, 1, figsize=(18, 30)) # Default plotting # ax1, ax2, ax3, ax6 are available fig.suptitle(f"General Benchmarks : {platform} - {benchmark_name}", fontsize=16) for i in range(len(avg_creation_times)): #converting seconds to milli seconds by multiplying 1000 avg_creation_times[i] *= 1000 ax1.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax1.bar(num_qubits_range, avg_creation_times, color='deepskyblue') autolabel(ax1.patches, ax1) ax1.set_xlabel('Number of Qubits') ax1.set_ylabel('Average Creation Time (ms)') ax1.set_title('Average Creation Time vs Number of Qubits',fontsize=14) ax2.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) for i in range(len(avg_elapsed_times)): #converting seconds to milli seconds by multiplying 1000 avg_elapsed_times[i] *= 1000 for i in range(len(avg_quantum_times)): #converting seconds to milli seconds by multiplying 1000 avg_quantum_times[i] *= 1000 Elapsed= ax2.bar(np.array(num_qubits_range) - bar_width / 2, avg_elapsed_times, width=bar_width, color='cyan', label='Elapsed Time') Quantum= ax2.bar(np.array(num_qubits_range) + bar_width / 2, avg_quantum_times,width=bar_width, color='deepskyblue',label ='Quantum Time') autolabel(Elapsed,ax2,str='{:.1f}') autolabel(Quantum,ax2,str='{:.1f}') ax2.set_xlabel('Number of Qubits') ax2.set_ylabel('Average Time (ms)') ax2.set_title('Average Time vs Number of Qubits') ax2.legend() ax3.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized = ax3.bar(np.array(num_qubits_range) - bar_width / 2, avg_transpiled_depths, color='cyan', label='Normalized Depth', width=bar_width) # Adjust width here Algorithmic = ax3.bar(np.array(num_qubits_range) + bar_width / 2,avg_circuit_depths, color='deepskyblue', label='Algorithmic Depth', width=bar_width) # Adjust width here autolabel(Normalized,ax3,str='{:.2f}') autolabel(Algorithmic,ax3,str='{:.2f}') ax3.set_xlabel('Number of Qubits') ax3.set_ylabel('Average Circuit Depth') ax3.set_title('Average Circuit Depth vs Number of Qubits') ax3.legend() if gate_counts_plots == True: ax4.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_1Q_counts = ax4.bar(np.array(num_qubits_range) - bar_width / 2, avg_1Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_1Q_counts = ax4.bar(np.array(num_qubits_range) + bar_width / 2, avg_1Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_1Q_counts,ax4,str='{}') autolabel(Algorithmic_1Q_counts,ax4,str='{}') ax4.set_xlabel('Number of Qubits') ax4.set_ylabel('Average 1-Qubit Gate Counts') ax4.set_title('Average 1-Qubit Gate Counts vs Number of Qubits') ax4.legend() ax5.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_2Q_counts = ax5.bar(np.array(num_qubits_range) - bar_width / 2, avg_2Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_2Q_counts = ax5.bar(np.array(num_qubits_range) + bar_width / 2, avg_2Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_2Q_counts,ax5,str='{}') autolabel(Algorithmic_2Q_counts,ax5,str='{}') ax5.set_xlabel('Number of Qubits') ax5.set_ylabel('Average 2-Qubit Gate Counts') ax5.set_title('Average 2-Qubit Gate Counts vs Number of Qubits') ax5.legend() ax6.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Hellinger = ax6.bar(np.array(num_qubits_range) - bar_width / 2, avg_Hf, width=bar_width, label='Hellinger Fidelity',color='cyan') # Adjust width here Normalized = ax6.bar(np.array(num_qubits_range) + bar_width / 2, avg_f, width=bar_width, label='Normalized Fidelity', color='deepskyblue') # Adjust width here autolabel(Hellinger,ax6,str='{:.2f}') autolabel(Normalized,ax6,str='{:.2f}') ax6.set_xlabel('Number of Qubits') ax6.set_ylabel('Average Value') ax6.set_title("Fidelity Comparison") ax6.legend() if Memory_utilization_plot == True: ax7.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax7.bar(num_qubits_range, max_memory, color='turquoise', width=bar_width, label="Memory Utilizations") autolabel(ax7.patches, ax7) ax7.set_xlabel('Number of Qubits') ax7.set_ylabel('Maximum Memory Utilized (MB)') ax7.set_title('Memory Utilized vs Number of Qubits',fontsize=14) plt.tight_layout(rect=[0, 0, 1, 0.96]) if saveplots == True: plt.savefig("ParameterPlotsSample.jpg") plt.show() # Quantum Volume Plot Suptitle = f"Volumetric Positioning - {platform}" appname=benchmark_name if QV_ == None: QV=2048 else: QV=QV_ depth_base =2 ax = plot_volumetric_background(max_qubits=max_qbits, QV=QV,depth_base=depth_base, suptitle=Suptitle, colorbar_label="Avg Result Fidelity") w_data = num_qubits_range # determine width for circuit w_max = 0 for i in range(len(w_data)): y = float(w_data[i]) w_max = max(w_max, y) d_tr_data = avg_transpiled_depths f_data = avg_f plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=True,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max) anno_volumetric_data(ax, depth_base,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False)
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')