repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
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. """DAGFixedPoint pass testing""" import unittest from qiskit.transpiler.passes import DAGFixedPoint from qiskit import QuantumRegister, QuantumCircuit from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase class TestFixedPointPass(QiskitTestCase): """Tests for PropertySet methods.""" def test_empty_dag_true(self): """Test the dag fixed point of an empty dag.""" circuit = QuantumCircuit() dag = circuit_to_dag(circuit) pass_ = DAGFixedPoint() pass_.run(dag) self.assertFalse(pass_.property_set["dag_fixed_point"]) pass_.run(dag) self.assertTrue(pass_.property_set["dag_fixed_point"]) def test_nonempty_dag_false(self): """Test the dag false fixed point of a non-empty dag.""" qr = QuantumRegister(2) circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) dag = circuit_to_dag(circuit) pass_ = DAGFixedPoint() pass_.run(dag) self.assertFalse(pass_.property_set["dag_fixed_point"]) dag.remove_all_ops_named("h") pass_.run(dag) self.assertFalse(pass_.property_set["dag_fixed_point"]) if __name__ == "__main__": unittest.main()
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": ### added x gate ### qc.x(qubit) qc.x(qubit) if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) qc.h(1) return qc
https://github.com/magn5452/QiskitQaoa
magn5452
import numpy as np from matplotlib import pyplot as plt from qiskit import QuantumCircuit, Aer, transpile, assemble from qiskit.circuit import Gate from qiskit.circuit import Parameter from qiskit.extensions import UnitaryGate, HamiltonianGate from qiskit.providers.aer import StatevectorSimulator from qiskit.visualization import plot_histogram from qiskit_nature.operators.second_quantization import SpinOp from VehicleRouting.standard.concretization.CircuitPlotter import MPLCircuitPlotter beta = Parameter('beta') spinop = SpinOp([("++--", 1),("--++", 1)]) print(spinop.to_matrix()) gate = HamiltonianGate(spinop.to_matrix(), np.pi/2, label="Gate") qc = QuantumCircuit(4) qc.h(0) qc.h(1) qc.h(2) qc.h(3) qc.append(gate, [0,1,2,3]) backend = StatevectorSimulator(precision='double') transpiled = transpile(qc, backend=backend) transpiled.draw('mpl') result = backend.run(transpiled).result() counts = result.get_counts() print(result) print(counts) plot_histogram(counts) circuit_plotter = MPLCircuitPlotter() circuit_plotter.plot(qc) plt.show()
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import Aer, QuantumCircuit from qiskit.circuit.library import PhaseEstimation qc= QuantumCircuit(3,3) # dummy unitary circuit unitary_circuit = QuantumCircuit(1) unitary_circuit.h(0) # QPE qc.append(PhaseEstimation(2, unitary_circuit), list(range(3))) qc.measure(list(range(3)), list(range(3))) backend = Aer.get_backend('qasm_simulator') result = backend.run(qc, shots = 8192).result()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests pulse function samplers.""" import numpy as np from qiskit.test import QiskitTestCase import qiskit.pulse.commands as commands import qiskit.pulse.samplers as samplers def linear(times: np.ndarray, m: float, b: float = 0.1) -> np.ndarray: """Linear test function Args: times: Input times. m: Slope. b: Intercept Returns: np.ndarray """ return m*times+b class TestSampler(QiskitTestCase): """Test continuous pulse function samplers.""" def test_left_sampler(self): """Test left sampler.""" m = 0.1 b = 0.1 duration = 2 left_linear_pulse_fun = samplers.left(linear) reference = np.array([0.1, 0.2], dtype=np.complex) pulse = left_linear_pulse_fun(duration, m=m, b=b) self.assertIsInstance(pulse, commands.SamplePulse) np.testing.assert_array_almost_equal(pulse.samples, reference) def test_right_sampler(self): """Test right sampler.""" m = 0.1 b = 0.1 duration = 2 right_linear_pulse_fun = samplers.right(linear) reference = np.array([0.2, 0.3], dtype=np.complex) pulse = right_linear_pulse_fun(duration, m=m, b=b) self.assertIsInstance(pulse, commands.SamplePulse) np.testing.assert_array_almost_equal(pulse.samples, reference) def test_midpoint_sampler(self): """Test midpoint sampler.""" m = 0.1 b = 0.1 duration = 2 midpoint_linear_pulse_fun = samplers.midpoint(linear) reference = np.array([0.15, 0.25], dtype=np.complex) pulse = midpoint_linear_pulse_fun(duration, m=m, b=b) self.assertIsInstance(pulse, commands.SamplePulse) np.testing.assert_array_almost_equal(pulse.samples, reference) def test_sampler_name(self): """Test that sampler setting of pulse name works.""" m = 0.1 b = 0.1 duration = 2 left_linear_pulse_fun = samplers.left(linear) pulse = left_linear_pulse_fun(duration, m=m, b=b, name='test') self.assertIsInstance(pulse, commands.SamplePulse) self.assertEqual(pulse.name, 'test') def test_default_arg_sampler(self): """Test that default arguments work with sampler.""" m = 0.1 duration = 2 left_linear_pulse_fun = samplers.left(linear) reference = np.array([0.1, 0.2], dtype=np.complex) pulse = left_linear_pulse_fun(duration, m=m) self.assertIsInstance(pulse, commands.SamplePulse) np.testing.assert_array_almost_equal(pulse.samples, reference)
https://github.com/sebasmos/QuantumVE
sebasmos
#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, transpile, schedule from qiskit.visualization.pulse_v2 import draw from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() qc = transpile(qc, FakeBoeblingen(), layout_method='trivial') sched = schedule(qc, FakeBoeblingen()) draw(sched, backend=FakeBoeblingen())
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit # Create a circuit with a register of three qubits circ = QuantumCircuit(3) # H gate on qubit 0, putting this qubit in a superposition of |0> + |1>. circ.h(0) # A CX (CNOT) gate on control qubit 0 and target qubit 1 generating a Bell state. circ.cx(0, 1) # CX (CNOT) gate on control qubit 0 and target qubit 2 resulting in a GHZ state. circ.cx(0, 2) # Draw the circuit circ.draw('mpl')
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """A module for visualizing device coupling maps.""" import math from typing import List import numpy as np from qiskit.exceptions import MissingOptionalLibraryError, QiskitError from qiskit.providers.backend import BackendV2 from qiskit.tools.visualization import HAS_MATPLOTLIB, VisualizationError from qiskit.visualization.utils import matplotlib_close_if_inline def plot_gate_map( backend, figsize=None, plot_directed=False, label_qubits=True, qubit_size=None, line_width=4, font_size=None, qubit_color=None, qubit_labels=None, line_color=None, font_color="w", ax=None, filename=None, qubit_coordinates=None, ): """Plots the gate map of a device. Args: backend (BaseBackend): The backend instance that will be used to plot the device gate map. figsize (tuple): Output figure size (wxh) in inches. plot_directed (bool): Plot directed coupling map. label_qubits (bool): Label the qubits. qubit_size (float): Size of qubit marker. line_width (float): Width of lines. font_size (int): Font size of qubit labels. qubit_color (list): A list of colors for the qubits qubit_labels (list): A list of qubit labels line_color (list): A list of colors for each line from coupling_map. font_color (str): The font color for the qubit labels. ax (Axes): A Matplotlib axes instance. filename (str): file path to save image to. Returns: Figure: A Matplotlib figure instance. Raises: QiskitError: if tried to pass a simulator, or if the backend is None, but one of num_qubits, mpl_data, or cmap is None. MissingOptionalLibraryError: if matplotlib not installed. Example: .. jupyter-execute:: :hide-code: :hide-output: from qiskit.test.ibmq_mock import mock_get_backend mock_get_backend('FakeVigo') .. jupyter-execute:: from qiskit import QuantumCircuit, execute, IBMQ from qiskit.visualization import plot_gate_map %matplotlib inline provider = IBMQ.load_account() accountProvider = IBMQ.get_provider(hub='ibm-q') backend = accountProvider.get_backend('ibmq_vigo') plot_gate_map(backend) """ if not HAS_MATPLOTLIB: raise MissingOptionalLibraryError( libname="Matplotlib", name="plot_gate_map", pip_install="pip install matplotlib", ) if isinstance(backend, BackendV2): pass elif backend.configuration().simulator: raise QiskitError("Requires a device backend, not simulator.") qubit_coordinates_map = {} qubit_coordinates_map[1] = [[0, 0]] qubit_coordinates_map[5] = [[1, 0], [0, 1], [1, 1], [1, 2], [2, 1]] qubit_coordinates_map[7] = [[0, 0], [0, 1], [0, 2], [1, 1], [2, 0], [2, 1], [2, 2]] qubit_coordinates_map[20] = [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [1, 0], [1, 1], [1, 2], [1, 3], [1, 4], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [3, 0], [3, 1], [3, 2], [3, 3], [3, 4], ] qubit_coordinates_map[15] = [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [1, 7], [1, 6], [1, 5], [1, 4], [1, 3], [1, 2], [1, 1], [1, 0], ] qubit_coordinates_map[16] = [ [1, 0], [1, 1], [2, 1], [3, 1], [1, 2], [3, 2], [0, 3], [1, 3], [3, 3], [4, 3], [1, 4], [3, 4], [1, 5], [2, 5], [3, 5], [1, 6], ] qubit_coordinates_map[27] = [ [1, 0], [1, 1], [2, 1], [3, 1], [1, 2], [3, 2], [0, 3], [1, 3], [3, 3], [4, 3], [1, 4], [3, 4], [1, 5], [2, 5], [3, 5], [1, 6], [3, 6], [0, 7], [1, 7], [3, 7], [4, 7], [1, 8], [3, 8], [1, 9], [2, 9], [3, 9], [3, 10], ] qubit_coordinates_map[28] = [ [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [1, 2], [1, 6], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7], [2, 8], [3, 0], [3, 4], [3, 8], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [4, 7], [4, 8], ] qubit_coordinates_map[53] = [ [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [1, 2], [1, 6], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7], [2, 8], [3, 0], [3, 4], [3, 8], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [4, 7], [4, 8], [5, 2], [5, 6], [6, 0], [6, 1], [6, 2], [6, 3], [6, 4], [6, 5], [6, 6], [6, 7], [6, 8], [7, 0], [7, 4], [7, 8], [8, 0], [8, 1], [8, 2], [8, 3], [8, 4], [8, 5], [8, 6], [8, 7], [8, 8], [9, 2], [9, 6], ] qubit_coordinates_map[65] = [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [0, 7], [0, 8], [0, 9], [1, 0], [1, 4], [1, 8], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7], [2, 8], [2, 9], [2, 10], [3, 2], [3, 6], [3, 10], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [4, 7], [4, 8], [4, 9], [4, 10], [5, 0], [5, 4], [5, 8], [6, 0], [6, 1], [6, 2], [6, 3], [6, 4], [6, 5], [6, 6], [6, 7], [6, 8], [6, 9], [6, 10], [7, 2], [7, 6], [7, 10], [8, 1], [8, 2], [8, 3], [8, 4], [8, 5], [8, 6], [8, 7], [8, 8], [8, 9], [8, 10], ] if isinstance(backend, BackendV2): num_qubits = backend.num_qubits coupling_map = backend.plot_coupling_map else: config = backend.configuration() num_qubits = config.n_qubits coupling_map = config.coupling_map # don't reference dictionary if provided as a parameter if qubit_coordinates is None: qubit_coordinates = qubit_coordinates_map.get(num_qubits) # try to adjust num_qubits to match the next highest hardcoded grid size if qubit_coordinates is None: if any([num_qubits < key for key in qubit_coordinates_map.keys()]): num_qubits_roundup = max(qubit_coordinates_map.keys()) for key in qubit_coordinates_map.keys(): if key < num_qubits_roundup and key > num_qubits: num_qubits_roundup = key qubit_coordinates = qubit_coordinates_map.get(num_qubits_roundup) return plot_coupling_map( num_qubits, qubit_coordinates, coupling_map, figsize, plot_directed, label_qubits, qubit_size, line_width, font_size, qubit_color, qubit_labels, line_color, font_color, ax, filename, ) def plot_coupling_map( num_qubits: int, qubit_coordinates: List[List[int]], coupling_map: List[List[int]], figsize=None, plot_directed=False, label_qubits=True, qubit_size=None, line_width=4, font_size=None, qubit_color=None, qubit_labels=None, line_color=None, font_color="w", ax=None, filename=None, ): """Plots an arbitrary coupling map of qubits (embedded in a plane). Args: num_qubits (int): The number of qubits defined and plotted. qubit_coordinates (List[List[int]]): A list of two-element lists, with entries of each nested list being the planar coordinates in a 0-based square grid where each qubit is located. coupling_map (List[List[int]]): A list of two-element lists, with entries of each nested list being the qubit numbers of the bonds to be plotted. figsize (tuple): Output figure size (wxh) in inches. plot_directed (bool): Plot directed coupling map. label_qubits (bool): Label the qubits. qubit_size (float): Size of qubit marker. line_width (float): Width of lines. font_size (int): Font size of qubit labels. qubit_color (list): A list of colors for the qubits qubit_labels (list): A list of qubit labels line_color (list): A list of colors for each line from coupling_map. font_color (str): The font color for the qubit labels. ax (Axes): A Matplotlib axes instance. filename (str): file path to save image to. Returns: Figure: A Matplotlib figure instance. Raises: MissingOptionalLibraryError: if matplotlib not installed. QiskitError: If length of qubit labels does not match number of qubits. Example: .. jupyter-execute:: from qiskit.visualization import plot_coupling_map %matplotlib inline num_qubits = 8 coupling_map = [[0, 1], [1, 2], [2, 3], [3, 5], [4, 5], [5, 6], [2, 4], [6, 7]] qubit_coordinates = [[0, 1], [1, 1], [1, 0], [1, 2], [2, 0], [2, 2], [2, 1], [3, 1]] plot_coupling_map(num_qubits, coupling_map, qubit_coordinates) """ if not HAS_MATPLOTLIB: raise MissingOptionalLibraryError( libname="Matplotlib", name="plot_coupling_map", pip_install="pip install matplotlib", ) import matplotlib.patches as mpatches import matplotlib.pyplot as plt input_axes = False if ax: input_axes = True if font_size is None: font_size = 12 if qubit_size is None: qubit_size = 24 if num_qubits > 20: qubit_size = 28 font_size = 10 if qubit_labels is None: qubit_labels = list(range(num_qubits)) else: if len(qubit_labels) != num_qubits: raise QiskitError("Length of qubit labels does not equal number of qubits.") if qubit_coordinates is not None: grid_data = qubit_coordinates else: if not input_axes: fig, ax = plt.subplots(figsize=(5, 5)) ax.axis("off") if filename: fig.savefig(filename) return fig x_max = max(d[1] for d in grid_data) y_max = max(d[0] for d in grid_data) max_dim = max(x_max, y_max) if figsize is None: if num_qubits == 1 or (x_max / max_dim > 0.33 and y_max / max_dim > 0.33): figsize = (5, 5) else: figsize = (9, 3) if ax is None: fig, ax = plt.subplots(figsize=figsize) ax.axis("off") # set coloring if qubit_color is None: qubit_color = ["#648fff"] * num_qubits if line_color is None: line_color = ["#648fff"] * len(coupling_map) if coupling_map else [] # Add lines for couplings if num_qubits != 1: for ind, edge in enumerate(coupling_map): is_symmetric = False if edge[::-1] in coupling_map: is_symmetric = True y_start = grid_data[edge[0]][0] x_start = grid_data[edge[0]][1] y_end = grid_data[edge[1]][0] x_end = grid_data[edge[1]][1] if is_symmetric: if y_start == y_end: x_end = (x_end - x_start) / 2 + x_start elif x_start == x_end: y_end = (y_end - y_start) / 2 + y_start else: x_end = (x_end - x_start) / 2 + x_start y_end = (y_end - y_start) / 2 + y_start ax.add_artist( plt.Line2D( [x_start, x_end], [-y_start, -y_end], color=line_color[ind], linewidth=line_width, zorder=0, ) ) if plot_directed: dx = x_end - x_start dy = y_end - y_start if is_symmetric: x_arrow = x_start + dx * 0.95 y_arrow = -y_start - dy * 0.95 dx_arrow = dx * 0.01 dy_arrow = -dy * 0.01 head_width = 0.15 else: x_arrow = x_start + dx * 0.5 y_arrow = -y_start - dy * 0.5 dx_arrow = dx * 0.2 dy_arrow = -dy * 0.2 head_width = 0.2 ax.add_patch( mpatches.FancyArrow( x_arrow, y_arrow, dx_arrow, dy_arrow, head_width=head_width, length_includes_head=True, edgecolor=None, linewidth=0, facecolor=line_color[ind], zorder=1, ) ) # Add circles for qubits for var, idx in enumerate(grid_data): # add check if num_qubits had been rounded up if var >= num_qubits: break _idx = [idx[1], -idx[0]] ax.add_artist( mpatches.Ellipse( _idx, qubit_size / 48, qubit_size / 48, # This is here so that the changes color=qubit_color[var], zorder=1, ) ) # to how qubits are plotted does if label_qubits: # not affect qubit size kwarg. ax.text( *_idx, s=qubit_labels[var], horizontalalignment="center", verticalalignment="center", color=font_color, size=font_size, weight="bold", ) ax.set_xlim([-1, x_max + 1]) ax.set_ylim([-(y_max + 1), 1]) ax.set_aspect("equal") if not input_axes: matplotlib_close_if_inline(fig) if filename: fig.savefig(filename) return fig return None def plot_circuit_layout(circuit, backend, view="virtual", qubit_coordinates=None): """Plot the layout of a circuit transpiled for a given target backend. Args: circuit (QuantumCircuit): Input quantum circuit. backend (BaseBackend): Target backend. view (str): Layout view: either 'virtual' or 'physical'. Returns: Figure: A matplotlib figure showing layout. Raises: QiskitError: Invalid view type given. VisualizationError: Circuit has no layout attribute. Example: .. jupyter-execute:: :hide-code: :hide-output: from qiskit.test.ibmq_mock import mock_get_backend mock_get_backend('FakeVigo') .. jupyter-execute:: import numpy as np from qiskit import QuantumCircuit, IBMQ, transpile from qiskit.visualization import plot_histogram, plot_gate_map, plot_circuit_layout from qiskit.tools.monitor import job_monitor import matplotlib.pyplot as plt %matplotlib inline IBMQ.load_account() ghz = QuantumCircuit(3, 3) ghz.h(0) for idx in range(1,3): ghz.cx(0,idx) ghz.measure(range(3), range(3)) provider = IBMQ.get_provider(hub='ibm-q') backend = provider.get_backend('ibmq_vigo') new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3) plot_circuit_layout(new_circ_lv3, backend) """ if circuit._layout is None: raise QiskitError("Circuit has no layout. Perhaps it has not been transpiled.") if isinstance(backend, BackendV2): num_qubits = backend.num_qubits else: num_qubits = backend.configuration().n_qubits qubits = [] qubit_labels = [None] * num_qubits bit_locations = { bit: {"register": register, "index": index} for register in circuit._layout.get_registers() for index, bit in enumerate(register) } for index, qubit in enumerate(circuit._layout.get_virtual_bits()): if qubit not in bit_locations: bit_locations[qubit] = {"register": None, "index": index} if view == "virtual": for key, val in circuit._layout.get_virtual_bits().items(): bit_register = bit_locations[key]["register"] if bit_register is None or bit_register.name != "ancilla": qubits.append(val) qubit_labels[val] = bit_locations[key]["index"] elif view == "physical": for key, val in circuit._layout.get_physical_bits().items(): bit_register = bit_locations[val]["register"] if bit_register is None or bit_register.name != "ancilla": qubits.append(key) qubit_labels[key] = key else: raise VisualizationError("Layout view must be 'virtual' or 'physical'.") qcolors = ["#648fff"] * num_qubits for k in qubits: qcolors[k] = "k" if isinstance(backend, BackendV2): cmap = backend.plot_coupling_map else: cmap = backend.configuration().coupling_map lcolors = ["#648fff"] * len(cmap) for idx, edge in enumerate(cmap): if edge[0] in qubits and edge[1] in qubits: lcolors[idx] = "k" fig = plot_gate_map( backend, qubit_color=qcolors, qubit_labels=qubit_labels, line_color=lcolors, qubit_coordinates=qubit_coordinates, ) return fig def plot_error_map(backend, figsize=(12, 9), show_title=True): """Plots the error map of a given backend. Args: backend (IBMQBackend): Given backend. figsize (tuple): Figure size in inches. show_title (bool): Show the title or not. Returns: Figure: A matplotlib figure showing error map. Raises: VisualizationError: Input is not IBMQ backend. VisualizationError: The backend does not provide gate errors for the 'sx' gate. MissingOptionalLibraryError: If seaborn is not installed Example: .. jupyter-execute:: :hide-code: :hide-output: from qiskit.test.ibmq_mock import mock_get_backend mock_get_backend('FakeVigo') .. jupyter-execute:: from qiskit import QuantumCircuit, execute, IBMQ from qiskit.visualization import plot_error_map %matplotlib inline IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = provider.get_backend('ibmq_vigo') plot_error_map(backend) """ try: import seaborn as sns except ImportError as ex: raise MissingOptionalLibraryError( libname="seaborn", name="plot_error_map", pip_install="pip install seaborn", ) from ex if not HAS_MATPLOTLIB: raise MissingOptionalLibraryError( libname="Matplotlib", name="plot_error_map", pip_install="pip install matplotlib", ) import matplotlib import matplotlib.pyplot as plt from matplotlib import gridspec, ticker color_map = sns.cubehelix_palette(reverse=True, as_cmap=True) props = backend.properties().to_dict() config = backend.configuration().to_dict() num_qubits = config["n_qubits"] # sx error rates single_gate_errors = [0] * num_qubits for gate in props["gates"]: if gate["gate"] == "sx": _qubit = gate["qubits"][0] for param in gate["parameters"]: if param["name"] == "gate_error": single_gate_errors[_qubit] = param["value"] break else: raise VisualizationError( f"Backend '{backend}' did not supply an error for the 'sx' gate." ) # Convert to percent single_gate_errors = 100 * np.asarray(single_gate_errors) avg_1q_err = np.mean(single_gate_errors) single_norm = matplotlib.colors.Normalize( vmin=min(single_gate_errors), vmax=max(single_gate_errors) ) q_colors = [color_map(single_norm(err)) for err in single_gate_errors] cmap = config["coupling_map"] directed = False line_colors = [] if cmap: directed = False if num_qubits < 20: for edge in cmap: if [edge[1], edge[0]] not in cmap: directed = True break cx_errors = [] for line in cmap: for item in props["gates"]: if item["qubits"] == line: cx_errors.append(item["parameters"][0]["value"]) break else: continue # Convert to percent cx_errors = 100 * np.asarray(cx_errors) avg_cx_err = np.mean(cx_errors) cx_norm = matplotlib.colors.Normalize(vmin=min(cx_errors), vmax=max(cx_errors)) line_colors = [color_map(cx_norm(err)) for err in cx_errors] # Measurement errors read_err = [] for qubit in range(num_qubits): for item in props["qubits"][qubit]: if item["name"] == "readout_error": read_err.append(item["value"]) read_err = 100 * np.asarray(read_err) avg_read_err = np.mean(read_err) max_read_err = np.max(read_err) fig = plt.figure(figsize=figsize) gridspec.GridSpec(nrows=2, ncols=3) grid_spec = gridspec.GridSpec( 12, 12, height_ratios=[1] * 11 + [0.5], width_ratios=[2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2], ) left_ax = plt.subplot(grid_spec[2:10, :1]) main_ax = plt.subplot(grid_spec[:11, 1:11]) right_ax = plt.subplot(grid_spec[2:10, 11:]) bleft_ax = plt.subplot(grid_spec[-1, :5]) if cmap: bright_ax = plt.subplot(grid_spec[-1, 7:]) qubit_size = 28 if num_qubits <= 5: qubit_size = 20 plot_gate_map( backend, qubit_color=q_colors, line_color=line_colors, qubit_size=qubit_size, line_width=5, plot_directed=directed, ax=main_ax, ) main_ax.axis("off") main_ax.set_aspect(1) if cmap: single_cb = matplotlib.colorbar.ColorbarBase( bleft_ax, cmap=color_map, norm=single_norm, orientation="horizontal" ) tick_locator = ticker.MaxNLocator(nbins=5) single_cb.locator = tick_locator single_cb.update_ticks() single_cb.update_ticks() bleft_ax.set_title(f"H error rate (%) [Avg. = {round(avg_1q_err, 3)}]") if cmap is None: bleft_ax.axis("off") bleft_ax.set_title(f"H error rate (%) = {round(avg_1q_err, 3)}") if cmap: cx_cb = matplotlib.colorbar.ColorbarBase( bright_ax, cmap=color_map, norm=cx_norm, orientation="horizontal" ) tick_locator = ticker.MaxNLocator(nbins=5) cx_cb.locator = tick_locator cx_cb.update_ticks() bright_ax.set_title(f"CNOT error rate (%) [Avg. = {round(avg_cx_err, 3)}]") if num_qubits < 10: num_left = num_qubits num_right = 0 else: num_left = math.ceil(num_qubits / 2) num_right = num_qubits - num_left left_ax.barh(range(num_left), read_err[:num_left], align="center", color="#DDBBBA") left_ax.axvline(avg_read_err, linestyle="--", color="#212121") left_ax.set_yticks(range(num_left)) left_ax.set_xticks([0, round(avg_read_err, 2), round(max_read_err, 2)]) left_ax.set_yticklabels([str(kk) for kk in range(num_left)], fontsize=12) left_ax.invert_yaxis() left_ax.set_title("Readout Error (%)", fontsize=12) for spine in left_ax.spines.values(): spine.set_visible(False) if num_right: right_ax.barh( range(num_left, num_qubits), read_err[num_left:], align="center", color="#DDBBBA", ) right_ax.axvline(avg_read_err, linestyle="--", color="#212121") right_ax.set_yticks(range(num_left, num_qubits)) right_ax.set_xticks([0, round(avg_read_err, 2), round(max_read_err, 2)]) right_ax.set_yticklabels( [str(kk) for kk in range(num_left, num_qubits)], fontsize=12 ) right_ax.invert_yaxis() right_ax.invert_xaxis() right_ax.yaxis.set_label_position("right") right_ax.yaxis.tick_right() right_ax.set_title("Readout Error (%)", fontsize=12) else: right_ax.axis("off") for spine in right_ax.spines.values(): spine.set_visible(False) if show_title: fig.suptitle(f"{backend.name()} Error Map", fontsize=24, y=0.9) matplotlib_close_if_inline(fig) return fig
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.pulse_v2 import draw from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() qc = transpile(qc, FakeBoeblingen(), layout_method='trivial') sched = schedule(qc, FakeBoeblingen()) draw(sched, backend=FakeBoeblingen())
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=invalid-name """Tests for generator of timeline drawer.""" import qiskit from qiskit.test import QiskitTestCase from qiskit.visualization.timeline import generators, types, stylesheet from qiskit.circuit import library, Delay class TestGates(QiskitTestCase): """Tests for generator.gates.""" def setUp(self) -> None: """Setup.""" super().setUp() self.qubit = list(qiskit.QuantumRegister(1))[0] self.u1 = types.ScheduledGate( t0=100, operand=library.U1Gate(0), duration=0, bits=[self.qubit], bit_position=0 ) self.u3 = types.ScheduledGate( t0=100, operand=library.U3Gate(0, 0, 0), duration=20, bits=[self.qubit], bit_position=0 ) self.delay = types.ScheduledGate( t0=100, operand=Delay(20), duration=20, bits=[self.qubit], bit_position=0 ) style = stylesheet.QiskitTimelineStyle() self.formatter = style.formatter def test_gen_sched_gate_with_finite_duration(self): """Test test_gen_sched_gate generator with finite duration gate.""" drawing_obj = generators.gen_sched_gate(self.u3, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.BoxType.SCHED_GATE.value)) self.assertListEqual(list(drawing_obj.xvals), [100, 120]) self.assertListEqual( list(drawing_obj.yvals), [-0.5 * self.formatter["box_height.gate"], 0.5 * self.formatter["box_height.gate"]], ) self.assertListEqual(drawing_obj.bits, [self.qubit]) ref_meta = { "name": "u3", "label": "n/a", "bits": str(self.qubit.register.name), "t0": 100, "duration": 20, "unitary": "[[1.+0.j 0.-0.j]\n [0.+0.j 1.+0.j]]", "parameters": "0, 0, 0", } self.assertDictEqual(ref_meta, drawing_obj.meta) ref_styles = { "zorder": self.formatter["layer.gate"], "facecolor": self.formatter["color.gates"]["u3"], "alpha": self.formatter["alpha.gate"], "linewidth": self.formatter["line_width.gate"], } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_sched_gate_with_zero_duration(self): """Test test_gen_sched_gate generator with zero duration gate.""" drawing_obj = generators.gen_sched_gate(self.u1, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.SymbolType.FRAME.value)) self.assertListEqual(list(drawing_obj.xvals), [100]) self.assertListEqual(list(drawing_obj.yvals), [0]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, self.formatter["unicode_symbol.frame_change"]) self.assertEqual(drawing_obj.latex, self.formatter["latex_symbol.frame_change"]) ref_styles = { "zorder": self.formatter["layer.frame_change"], "color": self.formatter["color.gates"]["u1"], "size": self.formatter["text_size.frame_change"], "va": "center", "ha": "center", } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_sched_gate_with_delay(self): """Test test_gen_sched_gate generator with delay.""" drawing_obj = generators.gen_sched_gate(self.delay, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.BoxType.DELAY.value)) def test_gen_full_gate_name_with_finite_duration(self): """Test gen_full_gate_name generator with finite duration gate.""" drawing_obj = generators.gen_full_gate_name(self.u3, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value)) self.assertListEqual(list(drawing_obj.xvals), [110.0]) self.assertListEqual(list(drawing_obj.yvals), [0.0]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, "u3(0.00, 0.00, 0.00)[20]") ref_latex = "{name}(0.00, 0.00, 0.00)[20]".format( name=self.formatter["latex_symbol.gates"]["u3"] ) self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { "zorder": self.formatter["layer.gate_name"], "color": self.formatter["color.gate_name"], "size": self.formatter["text_size.gate_name"], "va": "center", "ha": "center", } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_full_gate_name_with_zero_duration(self): """Test gen_full_gate_name generator with zero duration gate.""" drawing_obj = generators.gen_full_gate_name(self.u1, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value)) self.assertListEqual(list(drawing_obj.xvals), [100.0]) self.assertListEqual(list(drawing_obj.yvals), [self.formatter["label_offset.frame_change"]]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, "u1(0.00)") ref_latex = "{name}(0.00)".format(name=self.formatter["latex_symbol.gates"]["u1"]) self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { "zorder": self.formatter["layer.gate_name"], "color": self.formatter["color.gate_name"], "size": self.formatter["text_size.gate_name"], "va": "bottom", "ha": "center", } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_full_gate_name_with_delay(self): """Test gen_full_gate_name generator with delay.""" drawing_obj = generators.gen_full_gate_name(self.delay, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.DELAY.value)) def test_gen_short_gate_name_with_finite_duration(self): """Test gen_short_gate_name generator with finite duration gate.""" drawing_obj = generators.gen_short_gate_name(self.u3, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value)) self.assertListEqual(list(drawing_obj.xvals), [110.0]) self.assertListEqual(list(drawing_obj.yvals), [0.0]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, "u3") ref_latex = "{name}".format(name=self.formatter["latex_symbol.gates"]["u3"]) self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { "zorder": self.formatter["layer.gate_name"], "color": self.formatter["color.gate_name"], "size": self.formatter["text_size.gate_name"], "va": "center", "ha": "center", } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_short_gate_name_with_zero_duration(self): """Test gen_short_gate_name generator with zero duration gate.""" drawing_obj = generators.gen_short_gate_name(self.u1, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value)) self.assertListEqual(list(drawing_obj.xvals), [100.0]) self.assertListEqual(list(drawing_obj.yvals), [self.formatter["label_offset.frame_change"]]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, "u1") ref_latex = "{name}".format(name=self.formatter["latex_symbol.gates"]["u1"]) self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { "zorder": self.formatter["layer.gate_name"], "color": self.formatter["color.gate_name"], "size": self.formatter["text_size.gate_name"], "va": "bottom", "ha": "center", } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_short_gate_name_with_delay(self): """Test gen_short_gate_name generator with delay.""" drawing_obj = generators.gen_short_gate_name(self.delay, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.DELAY.value)) class TestTimeslot(QiskitTestCase): """Tests for generator.bits.""" def setUp(self) -> None: """Setup.""" super().setUp() self.qubit = list(qiskit.QuantumRegister(1))[0] style = stylesheet.QiskitTimelineStyle() self.formatter = style.formatter def test_gen_timeslot(self): """Test gen_timeslot generator.""" drawing_obj = generators.gen_timeslot(self.qubit, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.BoxType.TIMELINE.value)) self.assertListEqual( list(drawing_obj.xvals), [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT] ) self.assertListEqual( list(drawing_obj.yvals), [ -0.5 * self.formatter["box_height.timeslot"], 0.5 * self.formatter["box_height.timeslot"], ], ) self.assertListEqual(drawing_obj.bits, [self.qubit]) ref_styles = { "zorder": self.formatter["layer.timeslot"], "alpha": self.formatter["alpha.timeslot"], "linewidth": self.formatter["line_width.timeslot"], "facecolor": self.formatter["color.timeslot"], } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_bit_name(self): """Test gen_bit_name generator.""" drawing_obj = generators.gen_bit_name(self.qubit, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.BIT_NAME.value)) self.assertListEqual(list(drawing_obj.xvals), [types.AbstractCoordinate.LEFT]) self.assertListEqual(list(drawing_obj.yvals), [0]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, str(self.qubit.register.name)) ref_latex = r"{{\rm {register}}}_{{{index}}}".format( register=self.qubit.register.prefix, index=self.qubit.index ) self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { "zorder": self.formatter["layer.bit_name"], "color": self.formatter["color.bit_name"], "size": self.formatter["text_size.bit_name"], "va": "center", "ha": "right", } self.assertDictEqual(ref_styles, drawing_obj.styles) class TestBarrier(QiskitTestCase): """Tests for generator.barriers.""" def setUp(self) -> None: """Setup.""" super().setUp() self.qubits = list(qiskit.QuantumRegister(3)) self.barrier = types.Barrier(t0=100, bits=self.qubits, bit_position=1) style = stylesheet.QiskitTimelineStyle() self.formatter = style.formatter def test_gen_barrier(self): """Test gen_barrier generator.""" drawing_obj = generators.gen_barrier(self.barrier, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LineType.BARRIER.value)) self.assertListEqual(list(drawing_obj.xvals), [100, 100]) self.assertListEqual(list(drawing_obj.yvals), [-0.5, 0.5]) self.assertListEqual(drawing_obj.bits, [self.qubits[1]]) ref_styles = { "alpha": self.formatter["alpha.barrier"], "zorder": self.formatter["layer.barrier"], "linewidth": self.formatter["line_width.barrier"], "linestyle": self.formatter["line_style.barrier"], "color": self.formatter["color.barrier"], } self.assertDictEqual(ref_styles, drawing_obj.styles) class TestGateLink(QiskitTestCase): """Tests for generator.gate_links.""" def setUp(self) -> None: """Setup.""" super().setUp() self.qubits = list(qiskit.QuantumRegister(2)) self.gate_link = types.GateLink(t0=100, opname="cx", bits=self.qubits) style = stylesheet.QiskitTimelineStyle() self.formatter = style.formatter def gen_bit_link(self): """Test gen_bit_link generator.""" drawing_obj = generators.gen_gate_link(self.gate_link, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LineType.GATE_LINK.value)) self.assertListEqual(list(drawing_obj.xvals), [100]) self.assertListEqual(list(drawing_obj.yvals), [0]) self.assertListEqual(drawing_obj.bits, self.qubits) ref_styles = { "alpha": self.formatter["alpha.bit_link"], "zorder": self.formatter["layer.bit_link"], "linewidth": self.formatter["line_width.bit_link"], "linestyle": self.formatter["line_style.bit_link"], "color": self.formatter["color.gates"]["cx"], } self.assertDictEqual(ref_styles, drawing_obj.styles)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit.quantumcircuitdata import CircuitInstruction from qiskit.circuit import Measure from qiskit.circuit.library import HGate, CXGate qr = QuantumRegister(2) cr = ClassicalRegister(2) instructions = [ CircuitInstruction(HGate(), [qr[0]], []), CircuitInstruction(CXGate(), [qr[0], qr[1]], []), CircuitInstruction(Measure(), [qr[0]], [cr[0]]), CircuitInstruction(Measure(), [qr[1]], [cr[1]]), ] circuit = QuantumCircuit.from_instructions(instructions) circuit.draw("mpl")
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
PabloMartinezAngerosa
from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost from utils import mapeo_grafo import qiskit import numpy as np import networkx as nx import matplotlib.pyplot as plt from collections import defaultdict from operator import itemgetter from scipy.optimize import minimize from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble from qiskit.quantum_info import Statevector from qiskit.aqua.algorithms import NumPyEigensolver from qiskit.quantum_info import Pauli from qiskit.aqua.operators import op_converter from qiskit.aqua.operators import WeightedPauliOperator from qiskit.visualization import plot_histogram from qiskit.providers.aer.extensions.snapshot_statevector import * import json import csv # Gloabal _lambda variable _LAMBDA = 10 _SHOTS = 10000 _UNIFORM_CONVERGENCE_SAMPLE = [] # returns the bit index for an alpha and j def bit(i_city, l_time, num_cities): return i_city * num_cities + l_time # e^(cZZ) def append_zz_term(qc, q_i, q_j, gamma, constant_term): qc.cx(q_i, q_j) qc.rz(2*gamma*constant_term,q_j) qc.cx(q_i, q_j) # e^(cZ) def append_z_term(qc, q_i, gamma, constant_term): qc.rz(2*gamma*constant_term, q_i) # e^(cX) def append_x_term(qc,qi,beta): qc.rx(-2*beta, qi) def get_not_edge_in(G): N = G.number_of_nodes() not_edge = [] for i in range(N): for j in range(N): if i != j: buffer_tupla = (i,j) in_edges = False for edge_i, edge_j in G.edges(): if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)): in_edges = True if in_edges == False: not_edge.append((i, j)) return not_edge def get_classical_simplified_z_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # z term # z_classic_term = [0] * N**2 # first term for l in range(N): for i in range(N): z_il_index = bit(i, l, N) z_classic_term[z_il_index] += -1 * _lambda # second term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_jl z_jl_index = bit(j, l, N) z_classic_term[z_jl_index] += _lambda / 2 # third term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_ij z_ij_index = bit(i, j, N) z_classic_term[z_ij_index] += _lambda / 2 # fourth term not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 4 # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) z_classic_term[z_jlplus_index] += _lambda / 4 # fifthy term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) z_classic_term[z_il_index] += weight_ij / 4 # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) z_classic_term[z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) z_classic_term[z_il_index] += weight_ji / 4 # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) z_classic_term[z_jlplus_index] += weight_ji / 4 return z_classic_term def get_classical_simplified_zz_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # zz term # zz_classic_term = [[0] * N**2 for i in range(N**2) ] # first term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) # z_jl z_jl_index = bit(j, l, N) zz_classic_term[z_il_index][z_jl_index] += _lambda / 2 # second term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) # z_ij z_ij_index = bit(i, j, N) zz_classic_term[z_il_index][z_ij_index] += _lambda / 2 # third term not_edge = get_not_edge_in(G) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4 # fourth term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4 return zz_classic_term def get_classical_simplified_hamiltonian(G, _lambda): # z term # z_classic_term = get_classical_simplified_z_term(G, _lambda) # zz term # zz_classic_term = get_classical_simplified_zz_term(G, _lambda) return z_classic_term, zz_classic_term def get_cost_circuit(G, gamma, _lambda): N = G.number_of_nodes() N_square = N**2 qc = QuantumCircuit(N_square,N_square) z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda) # z term for i in range(N_square): if z_classic_term[i] != 0: append_z_term(qc, i, gamma, z_classic_term[i]) # zz term for i in range(N_square): for j in range(N_square): if zz_classic_term[i][j] != 0: append_zz_term(qc, i, j, gamma, zz_classic_term[i][j]) return qc def get_mixer_operator(G,beta): N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) for n in range(N**2): append_x_term(qc, n, beta) return qc def invert_counts(counts): return {k[::-1] :v for k,v in counts.items()} def get_QAOA_circuit(G, beta, gamma, _lambda): assert(len(beta)==len(gamma)) N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) # init min mix state qc.h(range(N**2)) p = len(beta) for i in range(p): qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda)) qc = qc.compose(get_mixer_operator(G, beta[i])) qc.barrier(range(N**2)) qc.snapshot_statevector("final_state") qc.measure(range(N**2),range(N**2)) return qc def tsp_obj(x, G): # obtenemos el valor evaluado en f(x_1, x_2,... x_n) z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _LAMBDA) cost = 0 # z term for index in range(len(x)): z = (int(x[index]) * 2 ) -1 cost += z_classic_term[index] * z ## zz term for i in range(len(x)): z_1 = (int(x[i]) * 2 ) -1 for j in range(len(x)): z_2 = (int(x[j]) * 2 ) -1 cost += zz_classic_term[i][j] * z_1 * z_1 return cost # Sample expectation value def compute_tsp_energy(counts, G): energy = 0 get_counts = 0 total_counts = 0 for meas, meas_count in counts.items(): obj_for_meas = tsp_obj(meas, G) energy += obj_for_meas*meas_count total_counts += meas_count return energy/total_counts # Sample expectation value def compute_tsp_energy_2(counts, G): energy = 0 get_counts = 0 total_counts = 0 for meas, meas_count in counts.items(): obj_for_meas = tsp_obj_2(meas, G, _LAMBDA) energy += obj_for_meas*meas_count total_counts += meas_count mean = energy/total_counts return mean def tsp_obj_2(x, G,_lambda): # obtenemos el valor evaluado en f(x_1, x_2,... x_n) not_edge = get_not_edge_in(G) N = G.number_of_nodes() tsp_cost=0 #Distancia weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # x_il x_il_index = bit(edge_i, l, N) # x_jlplus l_plus = (l+1) % N x_jlplus_index = bit(edge_j, l_plus, N) tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij # add order term because G.edges() do not include order tuples # # x_i'l x_il_index = bit(edge_j, l, N) # x_j'lplus x_jlplus_index = bit(edge_i, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji #Constraint 1 for l in range(N): penal1 = 1 for i in range(N): x_il_index = bit(i, l, N) penal1 -= int(x[x_il_index]) tsp_cost += _lambda * penal1**2 #Contstraint 2 for i in range(N): penal2 = 1 for l in range(N): x_il_index = bit(i, l, N) penal2 -= int(x[x_il_index]) tsp_cost += _lambda*penal2**2 #Constraint 3 for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # x_il x_il_index = bit(i, l, N) # x_j(l+1) l_plus = (l+1) % N x_jlplus_index = bit(j, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda return tsp_cost def get_black_box_objective(G,p): backend = Aer.get_backend('qasm_simulator') def f(theta): beta = theta[:p] gamma = theta[p:] _lambda = _LAMBDA # get global _lambda qc = get_QAOA_circuit(G, beta, gamma, _LAMBDA) counts = execute(qc, backend, seed_simulator=10, shots=_SHOTS).result().get_counts() return compute_tsp_energy(invert_counts(counts),G) return f def get_black_box_objective_2(G,p): backend = Aer.get_backend('qasm_simulator') sim = Aer.get_backend('aer_simulator') def f(theta): beta = theta[:p] gamma = theta[p:] #print(beta) _lambda = _LAMBDA # get global _lambda qc = get_QAOA_circuit(G, beta, gamma, _LAMBDA) #print(beta) result = execute(qc, backend, seed_simulator=10, shots=_SHOTS).result() final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0] state_vector = Statevector(final_state_vector) probabilities = state_vector.probabilities() # expected value #print("prob-dict") #print(state_vector.probabilities_dict()) probabilities_states = invert_counts(state_vector.probabilities_dict()) expected_value = 0 for state,probability in probabilities_states.items(): # get cost from state cost = tsp_obj_2(state, G, _LAMBDA) expected_value += cost*probability #print(probabilities) counts = result.get_counts() #qc.save_statevector() # Tell simulator to save statevector #qobj = assemble(qc) # Create a Qobj from the circuit for the simulator to run #state_vector = sim.run(qobj).result().get_statevector() #state_vector = Statevector(state_vector) #probabilities = state_vector.probabilities() mean = compute_tsp_energy_2(invert_counts(counts),G) global _UNIFORM_CONVERGENCE_SAMPLE _UNIFORM_CONVERGENCE_SAMPLE.append({ "beta" : beta, "gamma" : gamma, "counts" : counts, "mean" : mean, "probabilities" : probabilities, "expected_value" : expected_value }) return mean return f def compute_tsp_min_energy_2(counts, G): energy = 0 get_counts = 0 total_counts = 0 min = 1000000000000000000000 index = 0 min_meas = "" for meas, meas_count in counts.items(): index = index + 1 obj_for_meas = tsp_obj_2(meas, G, _LAMBDA) if obj_for_meas < min: min = obj_for_meas min_meas = meas return index, min, min_meas def compute_tsp_min_energy_1(counts, G): energy = 0 get_counts = 0 total_counts = 0 min = 1000000000000000000000 index = 0 min_meas = "" for meas, meas_count in counts.items(): index = index + 1 obj_for_meas = tsp_obj(meas, G) if obj_for_meas < min: min = obj_for_meas min_meas = meas return index, min, min_meas def test_counts_2(counts, G): mean_energy2 = compute_tsp_energy_2(invert_counts(counts),G) cantidad, min, min_meas = compute_tsp_min_energy_2(invert_counts(counts),G) print("*************************") print("En el algoritmo 2 (Marina) el valor esperado como resultado es " + str(mean_energy2)) print("El valor minimo de todos los evaluados es " + str(min) + " se evaluaron un total de " + str(cantidad)) print("El vector minimo es " + min_meas) def test_counts_1(counts, G): mean_energy1 = compute_tsp_energy(invert_counts(counts),G) cantidad, min, min_meas = compute_tsp_min_energy_1(invert_counts(counts),G) print("*************************") print("En el algoritmo 1 (Pablo) el valor esperado como resultado es " + str(mean_energy1)) print("El valor minimo de todos los evaluados es " + str(min) + " se evaluaron un total de " + str(cantidad)) print("El vector minimo es " + min_meas) def test_solution(grafo=None, p=7): global _UNIFORM_CONVERGENCE_SAMPLE _UNIFORM_CONVERGENCE_SAMPLE = [] if grafo == None: cantidad_ciudades = 2 pesos, conexiones = None, None mejor_camino = None while not mejor_camino: pesos, conexiones = rand_graph(cantidad_ciudades) mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False) G = mapeo_grafo(conexiones, pesos) print(mejor_costo) print(mejor_camino) print(G.edges()) print(G.nodes()) else: G = grafo # beta [0,pi], gamma [0, 2pi] # create bounds for beta [0,pi] bounds = [] intial_random = [] for i in range(p): bounds.append((0, np.pi)) intial_random.append(np.random.uniform(0,np.pi)) # create bounds for gamma [0,2*pi] for i in range(p): bounds.append((0, np.pi * 2)) intial_random.append(np.random.uniform(0,2*np.pi)) init_point = np.array(intial_random) # Pablo Solutions #obj = get_black_box_objective(G,p) #res_sample_1 = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True}) #print(res_sample_1) # Marina Solutions obj = get_black_box_objective_2(G,p) res_sample_2 = minimize(obj, init_point, method="COBYLA", options={"maxiter":2500,"disp":True}) print(res_sample_2) #theta_1 = res_sample_1.x theta_2 = res_sample_2.x #beta = theta_1[:p] #gamma = theta_1[p:] #_lambda = _LAMBDA # get global _lambda #qc = get_QAOA_circuit(G, beta, gamma, _LAMBDA) #backend = Aer.get_backend('qasm_simulator') #job_1 = execute(qc, backend, shots=_SHOTS) #resutls_1 = job_1.result().get_counts() #test_counts_1(resutls_1, G) beta = theta_2[:p] gamma = theta_2[p:] _lambda = _LAMBDA # get global _lambda qc = get_QAOA_circuit(G, beta, gamma, _LAMBDA) backend = Aer.get_backend('qasm_simulator') job_2 = execute(qc, backend, shots=_SHOTS) resutls_2 = job_2.result().get_counts() test_counts_2(resutls_2, G) #print( _UNIFORM_CONVERGENCE_SAMPLE) return job_2, G, _UNIFORM_CONVERGENCE_SAMPLE def create_multiple_p_mismo_grafo(): header = ['p', 'state', 'probability', 'mean'] length_p = 10 with open('qaoa_multiple_p.csv', 'w', encoding='UTF8') as f: writer = csv.writer(f) # write the header writer.writerow(header) first_p = False UNIFORM_CONVERGENCE_SAMPLE = [] for p in range(length_p): p = p+1 if first_p == False: job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(p=p) first_p = True else: job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(grafo=G, p=p) # Sort the JSON data based on the value of the brand key UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["mean"]) mean = UNIFORM_CONVERGENCE_SAMPLE[0]["mean"] print(mean) state = 0 for probability in UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"]: state += 1 writer.writerow([p,state, probability,mean]) def create_multiple_p_mismo_grafo_multiples_instanncias(): header = ['instance','p','distance', 'mean'] length_p = 4 length_instances = 10 with open('qaoa_multiple_p_distance.csv', 'w', encoding='UTF8') as f: writer = csv.writer(f) # write the header writer.writerow(header) instance_index = 0 for instance in range(length_instances): instance_index += 1 first_p = False UNIFORM_CONVERGENCE_P = [] UNIFORM_CONVERGENCE_SAMPLE = [] for p in range(length_p): p = p+1 print("p es igual " + str(p)) if first_p == False: print("Vuelve a llamar a test_solution") job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(p=p) first_p = True else: job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(grafo=G, p=p) # Sort the JSON data based on the value of the brand key UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["expected_value"]) convergence_min = UNIFORM_CONVERGENCE_SAMPLE[0] UNIFORM_CONVERGENCE_P.append({ "mean":convergence_min["expected_value"], "probabilities": convergence_min["probabilities"] }) print("expected value min con p =" + str(p) + " : " + str(convergence_min["expected_value"])) cauchy_function_nk = UNIFORM_CONVERGENCE_P[len(UNIFORM_CONVERGENCE_P) - 1] p_index = 0 for p_state in UNIFORM_CONVERGENCE_P: p_index += 1 print(p_index) mean = p_state["mean"] #print(p_state) print("expected value min") print(mean) distance_p_cauchy_function_nk = np.max(np.abs(cauchy_function_nk["probabilities"] - p_state["probabilities"])) writer.writerow([instance_index, p_index, distance_p_cauchy_function_nk, mean]) if __name__ == '__main__': #create_multiple_p_mismo_grafo() create_multiple_p_mismo_grafo_multiples_instanncias() def defult_init(): cantidad_ciudades = 2 pesos, conexiones = None, None mejor_camino = None while not mejor_camino: pesos, conexiones = rand_graph(cantidad_ciudades) mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False) G = mapeo_grafo(conexiones, pesos) print(mejor_costo) print(mejor_camino) print(G.edges()) print(G.nodes()) print("labels") labels = nx.get_edge_attributes(G,'weight') #z_term, zz_term = get_classical_simplified_hamiltonian(G, 1) #print("z term") #print(z_term) #print("*****************") #print("zz term") #print(zz_term) #print(get_QAOA_circuit(G, beta = [2,3], gamma = [4,5], _lambda = 1)) p = 5 obj = get_black_box_objective(G,p) init_point = np.array([0.8,2.2,0.83,2.15,0.37,2.4,6.1,2.2,3.8,6.1]) #res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True}) #print(res_sample) # Marina Solutions obj = get_black_box_objective_2(G,p) res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True}) print(res_sample) theta_2 = [0.72685401, 2.15678239, 0.86389827, 2.19403121, 0.26916675, 2.19832144, 7.06651453, 3.20333137, 3.81301611, 6.08893568] theta_1 = [0.90644898, 2.15994212, 1.8609325 , 2.14042604, 1.49126214, 2.4127999, 6.10529434, 2.18238732, 3.84056674, 6.07097744] beta = theta_1[:p] gamma = theta_1[p:] _lambda = _LAMBDA # get global _lambda qc = get_QAOA_circuit(G, beta, gamma, _LAMBDA) backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend) print(plot_histogram(job.result().get_counts(), color='midnightblue', title="New Histogram")) beta = theta_2[:p] gamma = theta_2[p:] _lambda = _LAMBDA # get global _lambda qc = get_QAOA_circuit(G, beta, gamma, _LAMBDA) backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend) print(plot_histogram(job.result().get_counts(), color='midnightblue', title="New Histogram"))
https://github.com/abbarreto/qiskit2
abbarreto
%run init.ipynb rx,ry,rz = symbols('r_x r_y r_z') rho1qb = (1/2)*(id(2) + rx*pauli(1) + ry*pauli(2) + rz*pauli(3)) rho1qb pI,pX,pZ,pY = symbols('p_I p_X p_Z p_Y') K0 = sqrt(pI)*id(2); K1 = sqrt(pX)*pauli(1); K2 = sqrt(pZ)*pauli(3); K3 = sqrt(pY)*pauli(2) rho_p = K0*rho1qb*K0 + K1*rho1qb*K1 + K2*rho1qb*K2 + K3*rho1qb*K3 simplify(rho_p) p = symbols('p') pI = (1+3*p)/4; pX = (1-p)/4; pY = pX; pZ = pX rho_p = K0*rho1qb*K0 + K1*rho1qb*K1 + K2*rho1qb*K2 + K3*rho1qb*K3 simplify(rho_p) import numpy as np from matplotlib import pyplot as plt p = np.arange(0,1.1,0.1) # PD channel C = np.sqrt(1-p) plt.plot(p,C) plt.show() from sympy import * N,p = symbols('N p') K0 = sqrt(1-N)*Matrix([[1,0],[0,sqrt(1-p)]]) K1 = sqrt(1-N)*Matrix([[0,sqrt(p)],[0,0]]) K2 = sqrt(N)*Matrix([[sqrt(1-p),0],[0,1]]) K3 = sqrt(N)*Matrix([[0,0],[sqrt(p),0]]) #K0 r00,r01,r10,r11 = symbols('r_{00} r_{01} r_{10} r_{11}')#; r00 rho = Matrix([[r00,r01],[r10,r11]])#; rho rho_gad = K0*rho*K0 + K1*rho*K1.T + K2*rho*K2 + K3*rho*K3.T simplify(rho_gad)
https://github.com/rubenandrebarreiro/summer-school-on-quantum-computing-software-for-near-term-quantum-devices-2020
rubenandrebarreiro
#initialization import matplotlib.pyplot as plt %matplotlib inline import numpy as np import math # importing Qiskit from qiskit import IBMQ, BasicAer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute # import basic plot tools from qiskit.tools.visualization import plot_histogram def cz(circuit,qr): circuit.h(qr[1]) circuit.cx(qr[0],qr[1]) circuit.h(qr[1]) qr2 = QuantumRegister(2) czCircuit = QuantumCircuit(qr2) cz(czCircuit,qr2) czCircuit.draw(output="mpl") def ccz(circuit,qr): circuit.h(qr[2]) # ccx is the Toffoli gate circuit.ccx(qr[0], qr[1], qr[2]) circuit.h(qr[2]) qr3 = QuantumRegister(3) cczCircuit = QuantumCircuit(qr3) ccz(cczCircuit,qr3) cczCircuit.draw(output="mpl") def cccz(circuit,qr): pi = math.pi circuit.cu1(pi/4,qr[0],qr[3]) circuit.cx(qr[0], qr[1]) circuit.cu1(-pi/4, qr[1],qr[3]) circuit.cx(qr[0], qr[1]) circuit.cu1(pi/4, qr[1],qr[3]) circuit.cx(qr[1], qr[2]) circuit.cu1(-pi/4, qr[2],qr[3]) circuit.cx(qr[0], qr[2]) circuit.cu1(pi/4, qr[2],qr[3]) circuit.cx(qr[1], qr[2]) circuit.cu1(-pi/4, qr[2],qr[3]) circuit.cx(qr[0], qr[2]) circuit.cu1(pi/4, qr[2],qr[3]) qr4 = QuantumRegister(4) ccczCircuit = QuantumCircuit(qr4) cccz(ccczCircuit,qr4) ccczCircuit.draw(output="mpl") def n_controlled_Z(circuit, qr): """Implement a Z gate with multiple controls""" if (len(qr) > 4): raise ValueError('The controlled Z with more than 3 controls is not implemented') # This is the case n = 2 (1 control + 1 target qubit) elif (len(qr) == 2): cz(circuit,qr) # This is the case n = 3 (2 control + 1 target qubit) elif (len(qr) == 3): ccz(circuit,qr) # This is the case n = 4 (3 control + 1 target qubit) elif (len(qr) == 4): cccz(circuit,qr) def phase_oracle(circuit,qr,element): # element is an array that defines the searched element, for example, element = [0,1,0,1] n = len(element) for j,x in enumerate(element): if (x == 0): circuit.x(qr[j]) n_controlled_Z(circuit,qr) for j,x in enumerate(element): if (x == 0): circuit.x(qr[j]) def inversion_about_average(circuit, register, n): """Apply inversion about the average step of Grover's algorithm.""" circuit.h(register) circuit.x(register) n_controlled_Z(circuit, qr) circuit.x(register) circuit.h(register) #Let's plot it! qr = QuantumRegister(4) qAverage = QuantumCircuit(qr) inversion_about_average(qAverage, qr, 4) qAverage.draw(output='mpl')
https://github.com/tanishabassan/QAOA-Maxcut
tanishabassan
import numpy as np from matplotlib import pyplot as plt from qiskit import Aer from qiskit.visualization import plot_histogram from scipy.optimize import minimize from VehicleRouting.standard.factories.MaxCutFactories import TwoConnectedMaxCutFactory from VehicleRouting.standard.problems.MaxCutProblem import MaxCutProblem from VehicleRouting.functions.functionsMaxCut import get_expectation, get_execute_circuit, create_qaoa_circuit from VehicleRouting.standard.plotter.GraphPlotter import GraphPlotter number_of_vertices = 4 problem_factory = TwoConnectedMaxCutFactory() problem = MaxCutProblem(problem_factory) plotter = GraphPlotter(problem) plotter.plot_problem() graph = problem.get_graph() expectation = get_expectation(graph, p=1) # Returns a function to be optimized p = 4 expectation = get_execute_circuit(graph) # Optimize initial_parameter = np.ones(2 * p) optimization_method = 'COBYLA' optimization_object = minimize(expectation, initial_parameter, method=optimization_method) print(optimization_object) backend = Aer.get_backend('aer_simulator') backend.shots = 2 ^ 12 # Create Circuit with Optimized Parameters optimized_parameters = optimization_object.x qc_res = create_qaoa_circuit(graph, optimized_parameters) qc_res.draw(output="mpl") counts = backend.run(qc_res, seed_simulator=10).result().get_counts() print(counts) plot_histogram(counts) plt.show()
https://github.com/jvscursulim/qamp_fall22_project
jvscursulim
import matplotlib.pyplot as plt from neqr import NEQR from qiskit import execute from qiskit.providers.aer.backends import AerSimulator from qiskit.quantum_info import Statevector from skimage import data from skimage.color import rgb2gray from skimage.transform import resize neqr_class = NEQR() backend = AerSimulator() shots = 2**14 astro_pic = resize(data.astronaut(), (32,32)) gray_astro_pic = rgb2gray(astro_pic) plt.imshow(gray_astro_pic, cmap="gray") qc_gray = neqr_class.image_quantum_circuit(image=gray_astro_pic, measurements=True) counts = backend.run(qc_gray, shots=shots).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=gray_astro_pic.shape) plt.imshow(image, cmap="gray") qc_gray = neqr_class.image_quantum_circuit(image=gray_astro_pic) qc_gray.x(qubit=qc_gray.qregs[0]) qc_gray.measure(qubit=qc_gray.qregs[0], cbit=qc_gray.cregs[0]) qc_gray.measure(qubit=qc_gray.qregs[1], cbit=qc_gray.cregs[1]) counts = backend.run(qc_gray, shots=shots).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=gray_astro_pic.shape) plt.imshow(image, cmap="gray") qc_gray = neqr_class.image_quantum_circuit(image=gray_astro_pic) qc_gray.x(qubit=qc_gray.qregs[1][:int(qc_gray.qregs[1].size/2)]) qc_gray.measure(qubit=qc_gray.qregs[0], cbit=qc_gray.cregs[0]) qc_gray.measure(qubit=qc_gray.qregs[1], cbit=qc_gray.cregs[1]) counts = backend.run(qc_gray, shots=shots).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=gray_astro_pic.shape) plt.imshow(image, cmap="gray") qc_gray = neqr_class.image_quantum_circuit(image=gray_astro_pic) qc_gray.x(qubit=qc_gray.qregs[1][int(qc_gray.qregs[1].size/2):]) qc_gray.measure(qubit=qc_gray.qregs[0], cbit=qc_gray.cregs[0]) qc_gray.measure(qubit=qc_gray.qregs[1], cbit=qc_gray.cregs[1]) counts = backend.run(qc_gray, shots=shots).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=gray_astro_pic.shape) plt.imshow(image, cmap="gray") qc_gray = neqr_class.image_quantum_circuit(image=gray_astro_pic) qc_gray.x(qubit=qc_gray.qregs[1]) qc_gray.measure(qubit=qc_gray.qregs[0], cbit=qc_gray.cregs[0]) qc_gray.measure(qubit=qc_gray.qregs[1], cbit=qc_gray.cregs[1]) counts = backend.run(qc_gray, shots=shots).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=gray_astro_pic.shape) plt.imshow(image, cmap="gray") qc_gray = neqr_class.image_quantum_circuit(image=gray_astro_pic) qc_gray.x(qubit=qc_gray.qregs[0]) qc_gray.x(qubit=qc_gray.qregs[1]) qc_gray.measure(qubit=qc_gray.qregs[0], cbit=qc_gray.cregs[0]) qc_gray.measure(qubit=qc_gray.qregs[1], cbit=qc_gray.cregs[1]) counts = backend.run(qc_gray, shots=shots).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=gray_astro_pic.shape) plt.imshow(image, cmap="gray") gray_astro_pic_full_size = rgb2gray(data.astronaut()) qc_gray = neqr_class.image_quantum_circuit(image=gray_astro_pic_full_size, measurements=True) print(f"Number of qubits: {qc_gray.qregs[0].size + qc_gray.qregs[1].size}") print(f"Circuit size: {qc_gray.size()}") print(f"Circuit depth: {qc_gray.depth()}") print(f"Circuit ops: {qc_gray.count_ops()}") plt.imshow(gray_astro_pic_full_size, cmap="gray") plt.imshow(astro_pic) qc_rgb = neqr_class.image_quantum_circuit(image=astro_pic, measurements=True) counts = backend.run(qc_rgb, shots=shots*4).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=astro_pic.shape) plt.imshow(image) qc_rgb = neqr_class.image_quantum_circuit(image=astro_pic) qc_rgb.x(qubit=qc_rgb.qregs[1][:int(qc_rgb.qregs[1].size/2)]) qc_rgb.measure(qubit=qc_rgb.qregs[0], cbit=qc_rgb.cregs[0]) qc_rgb.measure(qubit=qc_rgb.qregs[1], cbit=qc_rgb.cregs[1]) qc_rgb.measure(qubit=qc_rgb.qregs[2], cbit=qc_rgb.cregs[2]) counts = backend.run(qc_rgb, shots=shots*4).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=astro_pic.shape) plt.imshow(image) qc_rgb = neqr_class.image_quantum_circuit(image=astro_pic) qc_rgb.x(qubit=qc_rgb.qregs[1][int(qc_rgb.qregs[1].size/2):]) qc_rgb.measure(qubit=qc_rgb.qregs[0], cbit=qc_rgb.cregs[0]) qc_rgb.measure(qubit=qc_rgb.qregs[1], cbit=qc_rgb.cregs[1]) qc_rgb.measure(qubit=qc_rgb.qregs[2], cbit=qc_rgb.cregs[2]) counts = backend.run(qc_rgb, shots=shots*4).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=astro_pic.shape) plt.imshow(image) qc_rgb = neqr_class.image_quantum_circuit(image=astro_pic) qc_rgb.x(qubit=qc_rgb.qregs[1]) qc_rgb.measure(qubit=qc_rgb.qregs[0], cbit=qc_rgb.cregs[0]) qc_rgb.measure(qubit=qc_rgb.qregs[1], cbit=qc_rgb.cregs[1]) qc_rgb.measure(qubit=qc_rgb.qregs[2], cbit=qc_rgb.cregs[2]) counts = backend.run(qc_rgb, shots=shots*4).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=astro_pic.shape) plt.imshow(image) qc_rgb = neqr_class.image_quantum_circuit(image=astro_pic) qc_rgb.x(qubit=qc_rgb.qregs[0]) qc_rgb.measure(qubit=qc_rgb.qregs[0], cbit=qc_rgb.cregs[0]) qc_rgb.measure(qubit=qc_rgb.qregs[1], cbit=qc_rgb.cregs[1]) qc_rgb.measure(qubit=qc_rgb.qregs[2], cbit=qc_rgb.cregs[2]) counts = backend.run(qc_rgb, shots=shots*4).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=astro_pic.shape) plt.imshow(image) qc_rgb = neqr_class.image_quantum_circuit(image=astro_pic) qc_rgb.x(qubit=qc_rgb.qregs[2]) for i in range(8): qc_rgb.mct(control_qubits=qc_rgb.qregs[2], target_qubit=qc_rgb.qregs[0][i]) qc_rgb.x(qubit=qc_rgb.qregs[2]) qc_rgb.measure(qubit=qc_rgb.qregs[0], cbit=qc_rgb.cregs[0]) qc_rgb.measure(qubit=qc_rgb.qregs[1], cbit=qc_rgb.cregs[1]) qc_rgb.measure(qubit=qc_rgb.qregs[2], cbit=qc_rgb.cregs[2]) counts = backend.run(qc_rgb, shots=shots*4).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=astro_pic.shape) plt.imshow(image) qc_rgb = neqr_class.image_quantum_circuit(image=astro_pic) qc_rgb.x(qubit=qc_rgb.qregs[2][1]) for i in range(8): qc_rgb.mct(control_qubits=qc_rgb.qregs[2], target_qubit=qc_rgb.qregs[0][i]) qc_rgb.x(qubit=qc_rgb.qregs[2][1]) qc_rgb.measure(qubit=qc_rgb.qregs[0], cbit=qc_rgb.cregs[0]) qc_rgb.measure(qubit=qc_rgb.qregs[1], cbit=qc_rgb.cregs[1]) qc_rgb.measure(qubit=qc_rgb.qregs[2], cbit=qc_rgb.cregs[2]) counts = backend.run(qc_rgb, shots=shots*4).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=astro_pic.shape) plt.imshow(image) qc_rgb = neqr_class.image_quantum_circuit(image=astro_pic) qc_rgb.x(qubit=qc_rgb.qregs[2][0]) for i in range(8): qc_rgb.mct(control_qubits=qc_rgb.qregs[2], target_qubit=qc_rgb.qregs[0][i]) qc_rgb.x(qubit=qc_rgb.qregs[2][0]) qc_rgb.measure(qubit=qc_rgb.qregs[0], cbit=qc_rgb.cregs[0]) qc_rgb.measure(qubit=qc_rgb.qregs[1], cbit=qc_rgb.cregs[1]) qc_rgb.measure(qubit=qc_rgb.qregs[2], cbit=qc_rgb.cregs[2]) counts = backend.run(qc_rgb, shots=shots*4).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=astro_pic.shape) plt.imshow(image) qc_rgb = neqr_class.image_quantum_circuit(image=astro_pic) qc_rgb.x(qubit=qc_rgb.qregs[0]) qc_rgb.x(qubit=qc_rgb.qregs[1]) qc_rgb.measure(qubit=qc_rgb.qregs[0], cbit=qc_rgb.cregs[0]) qc_rgb.measure(qubit=qc_rgb.qregs[1], cbit=qc_rgb.cregs[1]) qc_rgb.measure(qubit=qc_rgb.qregs[2], cbit=qc_rgb.cregs[2]) counts = backend.run(qc_rgb, shots=shots*4).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=astro_pic.shape) plt.imshow(image) cat = data.cat() cat_gray_resized = resize(rgb2gray(cat), (int(cat.shape[0]/10), int(cat.shape[1]/10))) plt.imshow(cat_gray_resized, cmap="gray") qc_gray = neqr_class.image_quantum_circuit(image=cat_gray_resized, measurements=True) counts = backend.run(qc_gray, shots=shots).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=cat_gray_resized.shape) plt.imshow(image, cmap="gray") print(f"Number of qubits: {qc_gray.qregs[0].size + qc_gray.qregs[1].size}") print(f"Circuit size: {qc_gray.size()}") print(f"Circuit depth: {qc_gray.depth()}") print(f"Circuit ops: {qc_gray.count_ops()}")
https://github.com/urwin419/QiskitChecker
urwin419
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": ### removed z gate ### pass return qc def decode_message(qc): ### removed cx gate ### qc.h(1) return qc
https://github.com/jenglick/scipy22-qiskit-runtime-tutorial
jenglick
# Import the module needed to access Qiskit Runtime from qiskit_ibm_runtime import QiskitRuntimeService # Save account on disk. # QiskitRuntimeService.save_account(channel="ibm_quantum", token=<IBM Quantum API token>) # Load your IBM Quantum account or enable the account if it's not previously saved. service = QiskitRuntimeService(channel="ibm_quantum") # service = QiskitRuntimeService(channel="ibm_quantum", token=<IBM Quantum API token>) # Specify the backend name. options = {"backend_name": "ibmq_qasm_simulator"} job = service.run( program_id="hello-world", options=options, inputs={}, ) # Get the job result - this is blocking and control may not return immediately. result = job.result() print(result) from qiskit.circuit.library import RealAmplitudes pqc = RealAmplitudes(num_qubits=2, reps=2) pqc.measure_all() print(f"The circuit has {pqc.num_parameters} parameters") pqc.decompose().draw() # You can also check the backend configuration and properties. # Backend configuration contains (mostly) static information about the backend. # Backend properties contains dynamic information about the backend. backend = service.least_busy(simulator=False, min_num_qubits=5) print(f"Backend {backend.name} has {backend.configuration().num_qubits} qubits.") print(f"T1 value for qubit 0 is {backend.properties().t1(0)}s") # In this workshop we will be using the simulator. backend = "ibmq_qasm_simulator" from qiskit_ibm_runtime import Sampler # Use a context manager to open a session. with Sampler(circuits=pqc, service=service, options={"backend": backend}) as sampler: pass with Sampler(circuits=pqc, service=service, options={"backend": backend}) as sampler: result = sampler(circuits=[0], parameter_values=[[0, 1, 1, 2, 3, 5]]) print(result) from qiskit.circuit.library import EfficientSU2 pqc2 = EfficientSU2(num_qubits=2, reps=1) pqc2.measure_all() print(f"The circuit has {pqc2.num_parameters} parameters") pqc2.decompose().draw() from qiskit_ibm_runtime import Sampler theta1 = [0, 1, 1, 2, 3, 5] theta2 = [1, 2, 3, 4, 5, 6] theta3 = [0, 1, 2, 3, 4, 5, 6, 7] with Sampler(circuits=[pqc, pqc2], service=service, options={"backend": backend}) as sampler: result = sampler(circuits=[0], parameter_values=[theta1], shots=2000) print(f"Result from circuit 0 with parameter {theta1}: {result}\n") result = sampler(circuits=[0, 0], parameter_values=[theta1, theta2]) print(f"Result from circuit 0 with parameters {theta1, theta2}: {result}\n") result = sampler(circuits=[0, 1], parameter_values=[theta1, theta3]) print(f"Result from circuits 0, 1 with parameters {theta1, theta2}: {result}") from qiskit.circuit import Parameter, QuantumCircuit # Create a custom parameterized circuit. theta = Parameter('θ') qc = QuantumCircuit(1) qc.rx(theta, 0) qc.measure_all() qc.draw() from math import pi from qiskit_ibm_runtime import Sampler theta_val = 0.25*pi with Sampler(circuits=[qc], service=service, options={"backend": backend}) as sampler: result = sampler(circuits=[0], parameter_values=[[theta_val]], shots=100) while result.quasi_dists[0].get('1', 0) < 0.5: print(f"Result is {result.quasi_dists} when using theta {theta_val}") theta_val += (result.quasi_dists[0].get('1', 0.25)*pi) result = sampler(circuits=[0], parameter_values=[[theta_val]], shots=100) print(f"All done. Result is {result.quasi_dists} when using theta {theta_val}") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Naphann/Solving-TSP-Grover
Naphann
#initialization import matplotlib.pyplot as plt %matplotlib inline import numpy as np # importing Qiskit from qiskit import IBMQ, BasicAer, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute # import basic plot tools from qiskit.tools.visualization import plot_histogram provider = IBMQ.load_account() #functions # def OR(a, b, k): # # enter qubit numbers here # """ function does the equivalent of a classical OR between nodes a and b and stores the result in k """ # qc.barrier(q) # qc.cx(q[a], q[k]) # qc.barrier(q) # qc.x(q[a]) # qc.barrier(q) # qc.ccx(q[a], q[b], q[k]) # qc.barrier(q) # qc.x(q[a]) # qc.barrier(q) def OR(qubit_1, qubit_2, k): # enter qubit numbers here """ function does the equivalent of a classical OR between qubit numbers a and b and stores the result in qubit number k """ qc.barrier(q) qc.x(q[qubit_1]) qc.x(q[qubit_2]) qc.barrier(q) qc.ccx(q[qubit_1], q[qubit_2], q[k]) qc.x(q[k]) qc.barrier(q) qc.x(q[qubit_1]) qc.x(q[qubit_2]) qc.barrier(q) def are_not_equal(a_0, b_0, k): # enter node numbers here. For example, a is node 0, b is node 1 and c is node 2 """ function outputs 1 if nodes a and b are not the same. Node numbering starts from 0 as in the problem statement. k is the qubit number where the output is XOR-ed. qubit numbering also starts from 0 """ qc.barrier(q) qc.cx(q[2*a_0], q[2*b_0]) qc.cx(q[(2*a_0) + 1], q[(2*b_0) + 1]) OR(2*b_0, (2*b_0)+1, k) qc.cx(q[2*a_0], q[2*b_0]) qc.cx(q[(2*a_0) + 1], q[(2*b_0) + 1]) qc.barrier(q) # number of nodes n = 4 def initialize_oracle_part(n): t = 2*(n-1) qc.h(q[0:t]) qc.barrier(q) are_not_equal(0, 1, 6) # node a and b are not equal are_not_equal(0, 2, 7) are_not_equal(1, 2, 8) qc.barrier(q) qc.mct([q[6], q[7], q[8]], q[10],[q[9]]) # answer is stored in 10. please keep 9 a clean qubit, it's used as ancilla here qc.barrier(q) are_not_equal(0, 1, 6) # node a and b are not equal are_not_equal(0, 2, 7) are_not_equal(1, 2, 8) qubit_num = 20 # max is 32 if you're using the simulator q = QuantumRegister(qubit_num) c = ClassicalRegister(14) qc = QuantumCircuit(q, c) initialize_oracle_part(4) qc.draw(output='mpl')
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test circuits with variable parameters.""" import unittest import cmath import math import copy import pickle from operator import add, mul, sub, truediv from test import combine import numpy from ddt import data, ddt, named_data import qiskit import qiskit.circuit.library as circlib from qiskit.circuit.library.standard_gates.rz import RZGate from qiskit import BasicAer, ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.circuit import Gate, Instruction, Parameter, ParameterExpression, ParameterVector from qiskit.circuit.parametertable import ParameterReferences, ParameterTable, ParameterView from qiskit.circuit.exceptions import CircuitError from qiskit.compiler import assemble, transpile from qiskit.execute_function import execute from qiskit import pulse from qiskit.quantum_info import Operator from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeOurense from qiskit.tools import parallel_map def raise_if_parameter_table_invalid(circuit): """Validates the internal consistency of a ParameterTable and its containing QuantumCircuit. Intended for use in testing. Raises: CircuitError: if QuantumCircuit and ParameterTable are inconsistent. """ table = circuit._parameter_table # Assert parameters present in circuit match those in table. circuit_parameters = { parameter for instruction in circuit._data for param in instruction.operation.params for parameter in param.parameters if isinstance(param, ParameterExpression) } table_parameters = set(table._table.keys()) if circuit_parameters != table_parameters: raise CircuitError( "Circuit/ParameterTable Parameter mismatch. " "Circuit parameters: {}. " "Table parameters: {}.".format(circuit_parameters, table_parameters) ) # Assert parameter locations in table are present in circuit. circuit_instructions = [instr.operation for instr in circuit._data] for parameter, instr_list in table.items(): for instr, param_index in instr_list: if instr not in circuit_instructions: raise CircuitError(f"ParameterTable instruction not present in circuit: {instr}.") if not isinstance(instr.params[param_index], ParameterExpression): raise CircuitError( "ParameterTable instruction does not have a " "ParameterExpression at param_index {}: {}." "".format(param_index, instr) ) if parameter not in instr.params[param_index].parameters: raise CircuitError( "ParameterTable instruction parameters does " "not match ParameterTable key. Instruction " "parameters: {} ParameterTable key: {}." "".format(instr.params[param_index].parameters, parameter) ) # Assert circuit has no other parameter locations other than those in table. for instruction in circuit._data: for param_index, param in enumerate(instruction.operation.params): if isinstance(param, ParameterExpression): parameters = param.parameters for parameter in parameters: if (instruction.operation, param_index) not in table[parameter]: raise CircuitError( "Found parameterized instruction not " "present in table. Instruction: {} " "param_index: {}".format(instruction.operation, param_index) ) @ddt class TestParameters(QiskitTestCase): """Test Parameters.""" def test_gate(self): """Test instantiating gate with variable parameters""" theta = Parameter("θ") theta_gate = Gate("test", 1, params=[theta]) self.assertEqual(theta_gate.name, "test") self.assertIsInstance(theta_gate.params[0], Parameter) def test_compile_quantum_circuit(self): """Test instantiating gate with variable parameters""" theta = Parameter("θ") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta, qr) backend = BasicAer.get_backend("qasm_simulator") qc_aer = transpile(qc, backend) self.assertIn(theta, qc_aer.parameters) def test_duplicate_name_on_append(self): """Test adding a second parameter object with the same name fails.""" param_a = Parameter("a") param_a_again = Parameter("a") qc = QuantumCircuit(1) qc.rx(param_a, 0) self.assertRaises(CircuitError, qc.rx, param_a_again, 0) def test_get_parameters(self): """Test instantiating gate with variable parameters""" from qiskit.circuit.library.standard_gates.rx import RXGate theta = Parameter("θ") qr = QuantumRegister(1) qc = QuantumCircuit(qr) rxg = RXGate(theta) qc.append(rxg, [qr[0]], []) vparams = qc._parameter_table self.assertEqual(len(vparams), 1) self.assertIs(theta, next(iter(vparams))) self.assertEqual(rxg, next(iter(vparams[theta]))[0]) def test_get_parameters_by_index(self): """Test getting parameters by index""" x = Parameter("x") y = Parameter("y") z = Parameter("z") v = ParameterVector("v", 3) qc = QuantumCircuit(1) qc.rx(x, 0) qc.rz(z, 0) qc.ry(y, 0) qc.u(*v, 0) self.assertEqual(x, qc.parameters[3]) self.assertEqual(y, qc.parameters[4]) self.assertEqual(z, qc.parameters[5]) for i, vi in enumerate(v): self.assertEqual(vi, qc.parameters[i]) def test_bind_parameters_anonymously(self): """Test setting parameters by insertion order anonymously""" phase = Parameter("phase") x = Parameter("x") y = Parameter("y") z = Parameter("z") v = ParameterVector("v", 3) qc = QuantumCircuit(1, global_phase=phase) qc.rx(x, 0) qc.rz(z, 0) qc.ry(y, 0) qc.u(*v, 0) params = [0.1 * i for i in range(len(qc.parameters))] order = [phase] + v[:] + [x, y, z] param_dict = dict(zip(order, params)) for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): bqc_anonymous = getattr(qc, assign_fun)(params) bqc_list = getattr(qc, assign_fun)(param_dict) self.assertEqual(bqc_anonymous, bqc_list) def test_bind_parameters_allow_unknown(self): """Test binding parameters allowing unknown parameters.""" a = Parameter("a") b = Parameter("b") c = a.bind({a: 1, b: 1}, allow_unknown_parameters=True) self.assertEqual(c, a.bind({a: 1})) @data(QuantumCircuit.assign_parameters, QuantumCircuit.bind_parameters) def test_bind_parameters_custom_definition_global_phase(self, assigner): """Test that a custom gate with a parametrised `global_phase` is assigned correctly.""" x = Parameter("x") custom = QuantumCircuit(1, global_phase=x).to_gate() base = QuantumCircuit(1) base.append(custom, [0], []) test = Operator(assigner(base, {x: math.pi})) expected = Operator(numpy.array([[-1, 0], [0, -1]])) self.assertEqual(test, expected) def test_bind_half_single_precision(self): """Test binding with 16bit and 32bit floats.""" phase = Parameter("phase") x = Parameter("x") y = Parameter("y") z = Parameter("z") v = ParameterVector("v", 3) for i in (numpy.float16, numpy.float32): with self.subTest(float_type=i): expr = (v[0] * (x + y + z) + phase) - (v[2] * v[1]) params = numpy.array([0.1 * j for j in range(8)], dtype=i) order = [phase] + v[:] + [x, y, z] param_dict = dict(zip(order, params)) bound_value = expr.bind(param_dict) self.assertAlmostEqual(float(bound_value), 0.09, delta=1e-4) def test_parameter_order(self): """Test the parameters are sorted by name but parameter vector order takes precedence. This means that the following set of parameters {a, z, x[0], x[1], x[2], x[3], x[10], x[11]} will be sorted as [a, x[0], x[1], x[2], x[3], x[10], x[11], z] """ a, b, some_name, z = (Parameter(name) for name in ["a", "b", "some_name", "z"]) x = ParameterVector("x", 12) a_vector = ParameterVector("a_vector", 15) qc = QuantumCircuit(2) qc.p(z, 0) for i, x_i in enumerate(reversed(x)): qc.rx(x_i, i % 2) qc.cry(a, 0, 1) qc.crz(some_name, 1, 0) for v_i in a_vector[::2]: qc.p(v_i, 0) for v_i in a_vector[1::2]: qc.p(v_i, 1) qc.p(b, 0) expected_order = [a] + a_vector[:] + [b, some_name] + x[:] + [z] actual_order = qc.parameters self.assertListEqual(expected_order, list(actual_order)) @data(True, False) def test_parameter_order_compose(self, front): """Test the parameter order is correctly maintained upon composing circuits.""" x = Parameter("x") y = Parameter("y") qc1 = QuantumCircuit(1) qc1.p(x, 0) qc2 = QuantumCircuit(1) qc2.rz(y, 0) order = [x, y] composed = qc1.compose(qc2, front=front) self.assertListEqual(list(composed.parameters), order) def test_parameter_order_append(self): """Test the parameter order is correctly maintained upon appending circuits.""" x = Parameter("x") y = Parameter("y") qc1 = QuantumCircuit(1) qc1.p(x, 0) qc2 = QuantumCircuit(1) qc2.rz(y, 0) qc1.append(qc2, [0]) self.assertListEqual(list(qc1.parameters), [x, y]) def test_parameter_order_composing_nested_circuit(self): """Test the parameter order after nesting circuits and instructions.""" x = ParameterVector("x", 5) inner = QuantumCircuit(1) inner.rx(x[0], [0]) mid = QuantumCircuit(2) mid.p(x[1], 1) mid.append(inner, [0]) mid.p(x[2], 0) mid.append(inner, [0]) outer = QuantumCircuit(2) outer.compose(mid, inplace=True) outer.ryy(x[3], 0, 1) outer.compose(inner, inplace=True) outer.rz(x[4], 0) order = [x[0], x[1], x[2], x[3], x[4]] self.assertListEqual(list(outer.parameters), order) def test_is_parameterized(self): """Test checking if a gate is parameterized (bound/unbound)""" from qiskit.circuit.library.standard_gates.h import HGate from qiskit.circuit.library.standard_gates.rx import RXGate theta = Parameter("θ") rxg = RXGate(theta) self.assertTrue(rxg.is_parameterized()) theta_bound = theta.bind({theta: 3.14}) rxg = RXGate(theta_bound) self.assertFalse(rxg.is_parameterized()) h_gate = HGate() self.assertFalse(h_gate.is_parameterized()) def test_fix_variable(self): """Test setting a variable to a constant value""" theta = Parameter("θ") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta, qr) qc.u(0, theta, 0, qr) # test for both `bind_parameters` and `assign_parameters` for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): bqc = getattr(qc, assign_fun)({theta: 0.5}) self.assertEqual(float(bqc.data[0].operation.params[0]), 0.5) self.assertEqual(float(bqc.data[1].operation.params[1]), 0.5) bqc = getattr(qc, assign_fun)({theta: 0.6}) self.assertEqual(float(bqc.data[0].operation.params[0]), 0.6) self.assertEqual(float(bqc.data[1].operation.params[1]), 0.6) def test_multiple_parameters(self): """Test setting multiple parameters""" theta = Parameter("θ") x = Parameter("x") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta, qr) qc.u(0, theta, x, qr) self.assertEqual(qc.parameters, {theta, x}) def test_multiple_named_parameters(self): """Test setting multiple named/keyword argument based parameters""" theta = Parameter(name="θ") x = Parameter(name="x") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta, qr) qc.u(0, theta, x, qr) self.assertEqual(theta.name, "θ") self.assertEqual(qc.parameters, {theta, x}) @named_data( ["int", 2, int], ["float", 2.5, float], ["float16", numpy.float16(2.5), float], ["float32", numpy.float32(2.5), float], ["float64", numpy.float64(2.5), float], ) def test_circuit_assignment_to_numeric(self, value, type_): """Test binding a numeric value to a circuit instruction""" x = Parameter("x") qc = QuantumCircuit(1) qc.append(Instruction("inst", 1, 0, [x]), (0,)) qc.assign_parameters({x: value}, inplace=True) bound = qc.data[0].operation.params[0] self.assertIsInstance(bound, type_) self.assertEqual(bound, value) def test_partial_binding(self): """Test that binding a subset of circuit parameters returns a new parameterized circuit.""" theta = Parameter("θ") x = Parameter("x") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta, qr) qc.u(0, theta, x, qr) # test for both `bind_parameters` and `assign_parameters` for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): pqc = getattr(qc, assign_fun)({theta: 2}) self.assertEqual(pqc.parameters, {x}) self.assertEqual(float(pqc.data[0].operation.params[0]), 2) self.assertEqual(float(pqc.data[1].operation.params[1]), 2) @data(True, False) def test_mixed_binding(self, inplace): """Test we can bind a mixed dict with Parameter objects and floats.""" theta = Parameter("θ") x, new_x = Parameter("x"), Parameter("new_x") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta, qr) qc.u(0, theta, x, qr) pqc = qc.assign_parameters({theta: 2, x: new_x}, inplace=inplace) if inplace: self.assertEqual(qc.parameters, {new_x}) else: self.assertEqual(pqc.parameters, {new_x}) def test_expression_partial_binding(self): """Test that binding a subset of expression parameters returns a new parameterized circuit.""" theta = Parameter("θ") phi = Parameter("phi") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta + phi, qr) # test for both `bind_parameters` and `assign_parameters` for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): pqc = getattr(qc, assign_fun)({theta: 2}) self.assertEqual(pqc.parameters, {phi}) self.assertTrue(isinstance(pqc.data[0].operation.params[0], ParameterExpression)) self.assertEqual(str(pqc.data[0].operation.params[0]), "phi + 2") fbqc = getattr(pqc, assign_fun)({phi: 1.0}) self.assertEqual(fbqc.parameters, set()) self.assertIsInstance(fbqc.data[0].operation.params[0], float) self.assertEqual(float(fbqc.data[0].operation.params[0]), 3) def test_two_parameter_expression_binding(self): """Verify that for a circuit with parameters theta and phi that we can correctly assign theta to -phi. """ theta = Parameter("theta") phi = Parameter("phi") qc = QuantumCircuit(1) qc.rx(theta, 0) qc.ry(phi, 0) self.assertEqual(len(qc._parameter_table[theta]), 1) self.assertEqual(len(qc._parameter_table[phi]), 1) qc.assign_parameters({theta: -phi}, inplace=True) self.assertEqual(len(qc._parameter_table[phi]), 2) def test_expression_partial_binding_zero(self): """Verify that binding remains possible even if a previous partial bind would reduce the expression to zero. """ theta = Parameter("theta") phi = Parameter("phi") qc = QuantumCircuit(1) qc.p(theta * phi, 0) # test for both `bind_parameters` and `assign_parameters` for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): pqc = getattr(qc, assign_fun)({theta: 0}) self.assertEqual(pqc.parameters, {phi}) self.assertTrue(isinstance(pqc.data[0].operation.params[0], ParameterExpression)) self.assertEqual(str(pqc.data[0].operation.params[0]), "0") fbqc = getattr(pqc, assign_fun)({phi: 1}) self.assertEqual(fbqc.parameters, set()) self.assertIsInstance(fbqc.data[0].operation.params[0], int) self.assertEqual(float(fbqc.data[0].operation.params[0]), 0) def test_raise_if_assigning_params_not_in_circuit(self): """Verify binding parameters which are not present in the circuit raises an error.""" x = Parameter("x") y = Parameter("y") z = ParameterVector("z", 3) qr = QuantumRegister(1) qc = QuantumCircuit(qr) # test for both `bind_parameters` and `assign_parameters` for assign_fun in ["bind_parameters", "assign_parameters"]: qc = QuantumCircuit(qr) with self.subTest(assign_fun=assign_fun): qc.p(0.1, qr[0]) self.assertRaises(CircuitError, getattr(qc, assign_fun), {x: 1}) qc.p(x, qr[0]) self.assertRaises(CircuitError, getattr(qc, assign_fun), {x: 1, y: 2}) qc.p(z[1], qr[0]) self.assertRaises(CircuitError, getattr(qc, assign_fun), {z: [3, 4, 5]}) self.assertRaises(CircuitError, getattr(qc, assign_fun), {"a_str": 6}) self.assertRaises(CircuitError, getattr(qc, assign_fun), {None: 7}) def test_gate_multiplicity_binding(self): """Test binding when circuit contains multiple references to same gate""" qc = QuantumCircuit(1) theta = Parameter("theta") gate = RZGate(theta) qc.append(gate, [0], []) qc.append(gate, [0], []) # test for both `bind_parameters` and `assign_parameters` for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): qc2 = getattr(qc, assign_fun)({theta: 1.0}) self.assertEqual(len(qc2._parameter_table), 0) for instruction in qc2.data: self.assertEqual(float(instruction.operation.params[0]), 1.0) def test_calibration_assignment(self): """That that calibration mapping and the schedules they map are assigned together.""" theta = Parameter("theta") circ = QuantumCircuit(3, 3) circ.append(Gate("rxt", 1, [theta]), [0]) circ.measure(0, 0) rxt_q0 = pulse.Schedule( pulse.Play( pulse.library.Gaussian(duration=128, sigma=16, amp=0.2 * theta / 3.14), pulse.DriveChannel(0), ) ) circ.add_calibration("rxt", [0], rxt_q0, [theta]) circ = circ.assign_parameters({theta: 3.14}) instruction = circ.data[0] cal_key = ( tuple(circ.find_bit(q).index for q in instruction.qubits), tuple(instruction.operation.params), ) self.assertEqual(cal_key, ((0,), (3.14,))) # Make sure that key from instruction data matches the calibrations dictionary self.assertIn(cal_key, circ.calibrations["rxt"]) sched = circ.calibrations["rxt"][cal_key] self.assertEqual(sched.instructions[0][1].pulse.amp, 0.2) def test_calibration_assignment_doesnt_mutate(self): """That that assignment doesn't mutate the original circuit.""" theta = Parameter("theta") circ = QuantumCircuit(3, 3) circ.append(Gate("rxt", 1, [theta]), [0]) circ.measure(0, 0) rxt_q0 = pulse.Schedule( pulse.Play( pulse.library.Gaussian(duration=128, sigma=16, amp=0.2 * theta / 3.14), pulse.DriveChannel(0), ) ) circ.add_calibration("rxt", [0], rxt_q0, [theta]) circ_copy = copy.deepcopy(circ) assigned_circ = circ.assign_parameters({theta: 3.14}) self.assertEqual(circ.calibrations, circ_copy.calibrations) self.assertNotEqual(assigned_circ.calibrations, circ.calibrations) def test_calibration_assignment_w_expressions(self): """That calibrations with multiple parameters are assigned correctly""" theta = Parameter("theta") sigma = Parameter("sigma") circ = QuantumCircuit(3, 3) circ.append(Gate("rxt", 1, [theta / 2, sigma]), [0]) circ.measure(0, 0) rxt_q0 = pulse.Schedule( pulse.Play( pulse.library.Gaussian(duration=128, sigma=4 * sigma, amp=0.2 * theta / 3.14), pulse.DriveChannel(0), ) ) circ.add_calibration("rxt", [0], rxt_q0, [theta / 2, sigma]) circ = circ.assign_parameters({theta: 3.14, sigma: 4}) instruction = circ.data[0] cal_key = ( tuple(circ.find_bit(q).index for q in instruction.qubits), tuple(instruction.operation.params), ) self.assertEqual(cal_key, ((0,), (3.14 / 2, 4))) # Make sure that key from instruction data matches the calibrations dictionary self.assertIn(cal_key, circ.calibrations["rxt"]) sched = circ.calibrations["rxt"][cal_key] self.assertEqual(sched.instructions[0][1].pulse.amp, 0.2) self.assertEqual(sched.instructions[0][1].pulse.sigma, 16) def test_substitution(self): """Test Parameter substitution (vs bind).""" alpha = Parameter("⍺") beta = Parameter("beta") schedule = pulse.Schedule(pulse.ShiftPhase(alpha, pulse.DriveChannel(0))) circ = QuantumCircuit(3, 3) circ.append(Gate("my_rz", 1, [alpha]), [0]) circ.add_calibration("my_rz", [0], schedule, [alpha]) circ = circ.assign_parameters({alpha: 2 * beta}) circ = circ.assign_parameters({beta: 1.57}) cal_sched = circ.calibrations["my_rz"][((0,), (3.14,))] self.assertEqual(float(cal_sched.instructions[0][1].phase), 3.14) def test_partial_assignment(self): """Expressions of parameters with partial assignment.""" alpha = Parameter("⍺") beta = Parameter("beta") gamma = Parameter("γ") phi = Parameter("ϕ") with pulse.build() as my_cal: pulse.set_frequency(alpha + beta, pulse.DriveChannel(0)) pulse.shift_frequency(gamma + beta, pulse.DriveChannel(0)) pulse.set_phase(phi, pulse.DriveChannel(1)) circ = QuantumCircuit(2, 2) circ.append(Gate("custom", 2, [alpha, beta, gamma, phi]), [0, 1]) circ.add_calibration("custom", [0, 1], my_cal, [alpha, beta, gamma, phi]) # Partial bind delta = 1e9 freq = 4.5e9 shift = 0.5e9 phase = 3.14 / 4 circ = circ.assign_parameters({alpha: freq - delta}) cal_sched = list(circ.calibrations["custom"].values())[0] self.assertEqual(cal_sched.instructions[0][1].frequency, freq - delta + beta) circ = circ.assign_parameters({beta: delta}) cal_sched = list(circ.calibrations["custom"].values())[0] self.assertEqual(float(cal_sched.instructions[0][1].frequency), freq) self.assertEqual(cal_sched.instructions[1][1].frequency, gamma + delta) circ = circ.assign_parameters({gamma: shift - delta}) cal_sched = list(circ.calibrations["custom"].values())[0] self.assertEqual(float(cal_sched.instructions[1][1].frequency), shift) self.assertEqual(cal_sched.instructions[2][1].phase, phi) circ = circ.assign_parameters({phi: phase}) cal_sched = list(circ.calibrations["custom"].values())[0] self.assertEqual(float(cal_sched.instructions[2][1].phase), phase) def test_circuit_generation(self): """Test creating a series of circuits parametrically""" theta = Parameter("θ") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta, qr) backend = BasicAer.get_backend("qasm_simulator") qc_aer = transpile(qc, backend) # generate list of circuits for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): circs = [] theta_list = numpy.linspace(0, numpy.pi, 20) for theta_i in theta_list: circs.append(getattr(qc_aer, assign_fun)({theta: theta_i})) qobj = assemble(circs) for index, theta_i in enumerate(theta_list): res = float(qobj.experiments[index].instructions[0].params[0]) self.assertTrue(math.isclose(res, theta_i), f"{res} != {theta_i}") def test_circuit_composition(self): """Test preservation of parameters when combining circuits.""" theta = Parameter("θ") qr = QuantumRegister(1) cr = ClassicalRegister(1) qc1 = QuantumCircuit(qr, cr) qc1.rx(theta, qr) phi = Parameter("phi") qc2 = QuantumCircuit(qr, cr) qc2.ry(phi, qr) qc2.h(qr) qc2.measure(qr, cr) qc3 = qc1.compose(qc2) self.assertEqual(qc3.parameters, {theta, phi}) def test_composite_instruction(self): """Test preservation of parameters via parameterized instructions.""" theta = Parameter("θ") qr1 = QuantumRegister(1, name="qr1") qc1 = QuantumCircuit(qr1) qc1.rx(theta, qr1) qc1.rz(numpy.pi / 2, qr1) qc1.ry(theta, qr1) gate = qc1.to_instruction() self.assertEqual(gate.params, [theta]) phi = Parameter("phi") qr2 = QuantumRegister(3, name="qr2") qc2 = QuantumCircuit(qr2) qc2.ry(phi, qr2[0]) qc2.h(qr2) qc2.append(gate, qargs=[qr2[1]]) self.assertEqual(qc2.parameters, {theta, phi}) def test_parameter_name_conflicts_raises(self): """Verify attempting to add different parameters with matching names raises an error.""" theta1 = Parameter("theta") theta2 = Parameter("theta") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.p(theta1, 0) self.assertRaises(CircuitError, qc.p, theta2, 0) def test_bind_ryrz_vector(self): """Test binding a list of floats to a ParameterVector""" qc = QuantumCircuit(4) depth = 4 theta = ParameterVector("θ", length=len(qc.qubits) * depth * 2) theta_iter = iter(theta) for _ in range(depth): for q in qc.qubits: qc.ry(next(theta_iter), q) qc.rz(next(theta_iter), q) for i, q in enumerate(qc.qubits[:-1]): qc.cx(qc.qubits[i], qc.qubits[i + 1]) qc.barrier() theta_vals = numpy.linspace(0, 1, len(theta)) * numpy.pi self.assertEqual(set(qc.parameters), set(theta.params)) for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): bqc = getattr(qc, assign_fun)({theta: theta_vals}) for instruction in bqc.data: if hasattr(instruction.operation, "params") and instruction.operation.params: self.assertIn(float(instruction.operation.params[0]), theta_vals) def test_compile_vector(self): """Test compiling a circuit with an unbound ParameterVector""" qc = QuantumCircuit(4) depth = 4 theta = ParameterVector("θ", length=len(qc.qubits) * depth * 2) theta_iter = iter(theta) for _ in range(depth): for q in qc.qubits: qc.ry(next(theta_iter), q) qc.rz(next(theta_iter), q) for i, q in enumerate(qc.qubits[:-1]): qc.cx(qc.qubits[i], qc.qubits[i + 1]) qc.barrier() backend = BasicAer.get_backend("qasm_simulator") qc_aer = transpile(qc, backend) for param in theta: self.assertIn(param, qc_aer.parameters) def test_instruction_ryrz_vector(self): """Test constructing a circuit from instructions with remapped ParameterVectors""" qubits = 5 depth = 4 ryrz = QuantumCircuit(qubits, name="ryrz") theta = ParameterVector("θ0", length=len(ryrz.qubits) * 2) theta_iter = iter(theta) for q in ryrz.qubits: ryrz.ry(next(theta_iter), q) ryrz.rz(next(theta_iter), q) cxs = QuantumCircuit(qubits - 1, name="cxs") for i, _ in enumerate(cxs.qubits[:-1:2]): cxs.cx(cxs.qubits[2 * i], cxs.qubits[2 * i + 1]) paramvecs = [] qc = QuantumCircuit(qubits) for i in range(depth): theta_l = ParameterVector(f"θ{i + 1}", length=len(ryrz.qubits) * 2) ryrz_inst = ryrz.to_instruction(parameter_map={theta: theta_l}) paramvecs += [theta_l] qc.append(ryrz_inst, qargs=qc.qubits) qc.append(cxs, qargs=qc.qubits[1:]) qc.append(cxs, qargs=qc.qubits[:-1]) qc.barrier() backend = BasicAer.get_backend("qasm_simulator") qc_aer = transpile(qc, backend) for vec in paramvecs: for param in vec: self.assertIn(param, qc_aer.parameters) @data("single", "vector") def test_parameter_equality_through_serialization(self, ptype): """Verify parameters maintain their equality after serialization.""" if ptype == "single": x1 = Parameter("x") x2 = Parameter("x") else: x1 = ParameterVector("x", 2)[0] x2 = ParameterVector("x", 2)[0] x1_p = pickle.loads(pickle.dumps(x1)) x2_p = pickle.loads(pickle.dumps(x2)) self.assertEqual(x1, x1_p) self.assertEqual(x2, x2_p) self.assertNotEqual(x1, x2_p) self.assertNotEqual(x2, x1_p) def test_binding_parameterized_circuits_built_in_multiproc(self): """Verify subcircuits built in a subprocess can still be bound.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/2429 num_processes = 4 qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit = QuantumCircuit(qr, cr) parameters = [Parameter(f"x{i}") for i in range(num_processes)] results = parallel_map( _construct_circuit, parameters, task_args=(qr,), num_processes=num_processes ) for qc in results: circuit.compose(qc, inplace=True) parameter_values = [{x: 1.0 for x in parameters}] qobj = assemble( circuit, backend=BasicAer.get_backend("qasm_simulator"), parameter_binds=parameter_values, ) self.assertEqual(len(qobj.experiments), 1) self.assertEqual(len(qobj.experiments[0].instructions), 4) self.assertTrue( all( len(inst.params) == 1 and isinstance(inst.params[0], float) and float(inst.params[0]) == 1 for inst in qobj.experiments[0].instructions ) ) def test_transpiling_multiple_parameterized_circuits(self): """Verify several parameterized circuits can be transpiled at once.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/2864 qr = QuantumRegister(1) qc1 = QuantumCircuit(qr) qc2 = QuantumCircuit(qr) theta = Parameter("theta") qc1.u(theta, 0, 0, qr[0]) qc2.u(theta, 3.14, 0, qr[0]) circuits = [qc1, qc2] job = execute( circuits, BasicAer.get_backend("unitary_simulator"), shots=512, parameter_binds=[{theta: 1}], ) self.assertTrue(len(job.result().results), 2) @data(0, 1, 2, 3) def test_transpile_across_optimization_levels(self, opt_level): """Verify parameterized circuits can be transpiled with all default pass managers.""" qc = QuantumCircuit(5, 5) theta = Parameter("theta") phi = Parameter("phi") qc.rx(theta, 0) qc.x(0) for i in range(5 - 1): qc.rxx(phi, i, i + 1) qc.measure(range(5 - 1), range(5 - 1)) transpile(qc, FakeOurense(), optimization_level=opt_level) def test_repeated_gates_to_dag_and_back(self): """Verify circuits with repeated parameterized gates can be converted to DAG and back, maintaining consistency of circuit._parameter_table.""" from qiskit.converters import circuit_to_dag, dag_to_circuit qr = QuantumRegister(1) qc = QuantumCircuit(qr) theta = Parameter("theta") qc.p(theta, qr[0]) double_qc = qc.compose(qc) test_qc = dag_to_circuit(circuit_to_dag(double_qc)) for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): bound_test_qc = getattr(test_qc, assign_fun)({theta: 1}) self.assertEqual(len(bound_test_qc.parameters), 0) def test_rebinding_instruction_copy(self): """Test rebinding a copied instruction does not modify the original.""" theta = Parameter("th") qc = QuantumCircuit(1) qc.rx(theta, 0) instr = qc.to_instruction() qc1 = QuantumCircuit(1) qc1.append(instr, [0]) for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): output1 = getattr(qc1, assign_fun)({theta: 0.1}).decompose() output2 = getattr(qc1, assign_fun)({theta: 0.2}).decompose() expected1 = QuantumCircuit(1) expected1.rx(0.1, 0) expected2 = QuantumCircuit(1) expected2.rx(0.2, 0) self.assertEqual(expected1, output1) self.assertEqual(expected2, output2) @combine(target_type=["gate", "instruction"], parameter_type=["numbers", "parameters"]) def test_decompose_propagates_bound_parameters(self, target_type, parameter_type): """Verify bind-before-decompose preserves bound values.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/2482 theta = Parameter("th") qc = QuantumCircuit(1) qc.rx(theta, 0) if target_type == "gate": inst = qc.to_gate() elif target_type == "instruction": inst = qc.to_instruction() qc2 = QuantumCircuit(1) qc2.append(inst, [0]) if parameter_type == "numbers": bound_qc2 = qc2.assign_parameters({theta: 0.5}) expected_parameters = set() expected_qc2 = QuantumCircuit(1) expected_qc2.rx(0.5, 0) else: phi = Parameter("ph") bound_qc2 = qc2.assign_parameters({theta: phi}) expected_parameters = {phi} expected_qc2 = QuantumCircuit(1) expected_qc2.rx(phi, 0) decomposed_qc2 = bound_qc2.decompose() with self.subTest(msg="testing parameters of initial circuit"): self.assertEqual(qc2.parameters, {theta}) with self.subTest(msg="testing parameters of bound circuit"): self.assertEqual(bound_qc2.parameters, expected_parameters) with self.subTest(msg="testing parameters of deep decomposed bound circuit"): self.assertEqual(decomposed_qc2.parameters, expected_parameters) with self.subTest(msg="testing deep decomposed circuit"): self.assertEqual(decomposed_qc2, expected_qc2) @combine(target_type=["gate", "instruction"], parameter_type=["numbers", "parameters"]) def test_decompose_propagates_deeply_bound_parameters(self, target_type, parameter_type): """Verify bind-before-decompose preserves deeply bound values.""" theta = Parameter("th") qc1 = QuantumCircuit(1) qc1.rx(theta, 0) if target_type == "gate": inst = qc1.to_gate() elif target_type == "instruction": inst = qc1.to_instruction() qc2 = QuantumCircuit(1) qc2.append(inst, [0]) if target_type == "gate": inst = qc2.to_gate() elif target_type == "instruction": inst = qc2.to_instruction() qc3 = QuantumCircuit(1) qc3.append(inst, [0]) if parameter_type == "numbers": bound_qc3 = qc3.assign_parameters({theta: 0.5}) expected_parameters = set() expected_qc3 = QuantumCircuit(1) expected_qc3.rx(0.5, 0) else: phi = Parameter("ph") bound_qc3 = qc3.assign_parameters({theta: phi}) expected_parameters = {phi} expected_qc3 = QuantumCircuit(1) expected_qc3.rx(phi, 0) deep_decomposed_qc3 = bound_qc3.decompose().decompose() with self.subTest(msg="testing parameters of initial circuit"): self.assertEqual(qc3.parameters, {theta}) with self.subTest(msg="testing parameters of bound circuit"): self.assertEqual(bound_qc3.parameters, expected_parameters) with self.subTest(msg="testing parameters of deep decomposed bound circuit"): self.assertEqual(deep_decomposed_qc3.parameters, expected_parameters) with self.subTest(msg="testing deep decomposed circuit"): self.assertEqual(deep_decomposed_qc3, expected_qc3) @data("gate", "instruction") def test_executing_parameterized_instruction_bound_early(self, target_type): """Verify bind-before-execute preserves bound values.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/2482 theta = Parameter("theta") sub_qc = QuantumCircuit(2) sub_qc.h(0) sub_qc.cx(0, 1) sub_qc.rz(theta, [0, 1]) sub_qc.cx(0, 1) sub_qc.h(0) if target_type == "gate": sub_inst = sub_qc.to_gate() elif target_type == "instruction": sub_inst = sub_qc.to_instruction() unbound_qc = QuantumCircuit(2, 1) unbound_qc.append(sub_inst, [0, 1], []) unbound_qc.measure(0, 0) for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): bound_qc = getattr(unbound_qc, assign_fun)({theta: numpy.pi / 2}) shots = 1024 job = execute(bound_qc, backend=BasicAer.get_backend("qasm_simulator"), shots=shots) self.assertDictAlmostEqual(job.result().get_counts(), {"1": shots}, 0.05 * shots) def test_num_parameters(self): """Test the num_parameters property.""" with self.subTest(msg="standard case"): theta = Parameter("θ") x = Parameter("x") qc = QuantumCircuit(1) qc.rx(theta, 0) qc.u(0, theta, x, 0) self.assertEqual(qc.num_parameters, 2) with self.subTest(msg="parameter vector"): params = ParameterVector("x", length=3) qc = QuantumCircuit(4) qc.rx(params[0], 2) qc.ry(params[1], 1) qc.rz(params[2], 3) self.assertEqual(qc.num_parameters, 3) with self.subTest(msg="no params"): qc = QuantumCircuit(1) qc.x(0) self.assertEqual(qc.num_parameters, 0) def test_execute_result_names(self): """Test unique names for list of parameter binds.""" theta = Parameter("θ") reps = 5 qc = QuantumCircuit(1, 1) qc.rx(theta, 0) qc.measure(0, 0) plist = [{theta: i} for i in range(reps)] simulator = BasicAer.get_backend("qasm_simulator") result = execute(qc, backend=simulator, parameter_binds=plist).result() result_names = {res.name for res in result.results} self.assertEqual(reps, len(result_names)) def test_to_instruction_after_inverse(self): """Verify converting an inverse generates a valid ParameterTable""" # ref: https://github.com/Qiskit/qiskit-terra/issues/4235 qc = QuantumCircuit(1) theta = Parameter("theta") qc.rz(theta, 0) inv_instr = qc.inverse().to_instruction() self.assertIsInstance(inv_instr, Instruction) def test_repeated_circuit(self): """Test repeating a circuit maintains the parameters.""" qc = QuantumCircuit(1) theta = Parameter("theta") qc.rz(theta, 0) rep = qc.repeat(3) self.assertEqual(rep.parameters, {theta}) def test_copy_after_inverse(self): """Verify circuit.inverse generates a valid ParameterTable.""" qc = QuantumCircuit(1) theta = Parameter("theta") qc.rz(theta, 0) inverse = qc.inverse() self.assertIn(theta, inverse.parameters) raise_if_parameter_table_invalid(inverse) def test_copy_after_reverse(self): """Verify circuit.reverse generates a valid ParameterTable.""" qc = QuantumCircuit(1) theta = Parameter("theta") qc.rz(theta, 0) reverse = qc.reverse_ops() self.assertIn(theta, reverse.parameters) raise_if_parameter_table_invalid(reverse) def test_copy_after_dot_data_setter(self): """Verify setting circuit.data generates a valid ParameterTable.""" qc = QuantumCircuit(1) theta = Parameter("theta") qc.rz(theta, 0) qc.data = [] self.assertEqual(qc.parameters, set()) raise_if_parameter_table_invalid(qc) def test_circuit_with_ufunc(self): """Test construction of circuit and binding of parameters after we apply universal functions.""" from math import pi phi = Parameter(name="phi") theta = Parameter(name="theta") qc = QuantumCircuit(2) qc.p(numpy.abs(-phi), 0) qc.p(numpy.cos(phi), 0) qc.p(numpy.sin(phi), 0) qc.p(numpy.tan(phi), 0) qc.rz(numpy.arccos(theta), 1) qc.rz(numpy.arctan(theta), 1) qc.rz(numpy.arcsin(theta), 1) qc.assign_parameters({phi: pi, theta: 1}, inplace=True) qc_ref = QuantumCircuit(2) qc_ref.p(pi, 0) qc_ref.p(-1, 0) qc_ref.p(0, 0) qc_ref.p(0, 0) qc_ref.rz(0, 1) qc_ref.rz(pi / 4, 1) qc_ref.rz(pi / 2, 1) self.assertEqual(qc, qc_ref) def test_compile_with_ufunc(self): """Test compiling of circuit with unbound parameters after we apply universal functions.""" from math import pi theta = ParameterVector("theta", length=7) qc = QuantumCircuit(7) qc.rx(numpy.abs(theta[0]), 0) qc.rx(numpy.cos(theta[1]), 1) qc.rx(numpy.sin(theta[2]), 2) qc.rx(numpy.tan(theta[3]), 3) qc.rx(numpy.arccos(theta[4]), 4) qc.rx(numpy.arctan(theta[5]), 5) qc.rx(numpy.arcsin(theta[6]), 6) # transpile to different basis transpiled = transpile(qc, basis_gates=["rz", "sx", "x", "cx"], optimization_level=0) for x in theta: self.assertIn(x, transpiled.parameters) bound = transpiled.bind_parameters({theta: [-1, pi, pi, pi, 1, 1, 1]}) expected = QuantumCircuit(7) expected.rx(1.0, 0) expected.rx(-1.0, 1) expected.rx(0.0, 2) expected.rx(0.0, 3) expected.rx(0.0, 4) expected.rx(pi / 4, 5) expected.rx(pi / 2, 6) expected = transpile(expected, basis_gates=["rz", "sx", "x", "cx"], optimization_level=0) self.assertEqual(expected, bound) def test_parametervector_resize(self): """Test the resize method of the parameter vector.""" vec = ParameterVector("x", 2) element = vec[1] # store an entry for instancecheck later on with self.subTest("shorten"): vec.resize(1) self.assertEqual(len(vec), 1) self.assertListEqual([param.name for param in vec], _paramvec_names("x", 1)) with self.subTest("enlargen"): vec.resize(3) self.assertEqual(len(vec), 3) # ensure we still have the same instance not a copy with the same name # this is crucial for adding parameters to circuits since we cannot use the same # name if the instance is not the same self.assertIs(element, vec[1]) self.assertListEqual([param.name for param in vec], _paramvec_names("x", 3)) def test_raise_if_sub_unknown_parameters(self): """Verify we raise if asked to sub a parameter not in self.""" x = Parameter("x") y = Parameter("y") z = Parameter("z") with self.assertRaisesRegex(CircuitError, "not present"): x.subs({y: z}) def test_sub_allow_unknown_parameters(self): """Verify we raise if asked to sub a parameter not in self.""" x = Parameter("x") y = Parameter("y") z = Parameter("z") subbed = x.subs({y: z}, allow_unknown_parameters=True) self.assertEqual(subbed, x) def _construct_circuit(param, qr): qc = QuantumCircuit(qr) qc.ry(param, qr[0]) return qc def _paramvec_names(prefix, length): return [f"{prefix}[{i}]" for i in range(length)] @ddt class TestParameterExpressions(QiskitTestCase): """Test expressions of Parameters.""" supported_operations = [add, sub, mul, truediv] def test_compare_to_value_when_bound(self): """Verify expression can be compared to a fixed value when fully bound.""" x = Parameter("x") bound_expr = x.bind({x: 2.3}) self.assertEqual(bound_expr, 2.3) def test_abs_function_when_bound(self): """Verify expression can be used with abs functions when bound.""" x = Parameter("x") xb_1 = x.bind({x: 2.0}) xb_2 = x.bind({x: 3.0 + 4.0j}) self.assertEqual(abs(xb_1), 2.0) self.assertEqual(abs(-xb_1), 2.0) self.assertEqual(abs(xb_2), 5.0) def test_abs_function_when_not_bound(self): """Verify expression can be used with abs functions when not bound.""" x = Parameter("x") y = Parameter("y") self.assertEqual(abs(x), abs(-x)) self.assertEqual(abs(x) * abs(y), abs(x * y)) self.assertEqual(abs(x) / abs(y), abs(x / y)) def test_cast_to_complex_when_bound(self): """Verify that the cast to complex works for bound objects.""" x = Parameter("x") y = Parameter("y") bound_expr = (x + y).bind({x: 1.0, y: 1j}) self.assertEqual(complex(bound_expr), 1 + 1j) def test_raise_if_cast_to_complex_when_not_fully_bound(self): """Verify raises if casting to complex and not fully bound.""" x = Parameter("x") y = Parameter("y") bound_expr = (x + y).bind({x: 1j}) with self.assertRaisesRegex(TypeError, "unbound parameters"): complex(bound_expr) def test_cast_to_float_when_bound(self): """Verify expression can be cast to a float when fully bound.""" x = Parameter("x") bound_expr = x.bind({x: 2.3}) self.assertEqual(float(bound_expr), 2.3) def test_cast_to_float_when_underlying_expression_bound(self): """Verify expression can be cast to a float when it still contains unbound parameters, but the underlying symbolic expression has a knowable value.""" x = Parameter("x") expr = x - x + 2.3 self.assertEqual(float(expr), 2.3) def test_cast_to_float_intermediate_complex_value(self): """Verify expression can be cast to a float when it is fully bound, but an intermediate part of the expression evaluation involved complex types. Sympy is generally more permissive than symengine here, and sympy's tends to be the expected behaviour for our users.""" x = Parameter("x") bound_expr = (x + 1.0 + 1.0j).bind({x: -1.0j}) self.assertEqual(float(bound_expr), 1.0) def test_cast_to_float_of_complex_fails(self): """Test that an attempt to produce a float from a complex value fails if there is an imaginary part, with a sensible error message.""" x = Parameter("x") bound_expr = (x + 1.0j).bind({x: 1.0}) with self.assertRaisesRegex(TypeError, "could not cast expression to float"): float(bound_expr) def test_raise_if_cast_to_float_when_not_fully_bound(self): """Verify raises if casting to float and not fully bound.""" x = Parameter("x") y = Parameter("y") bound_expr = (x + y).bind({x: 2.3}) with self.assertRaisesRegex(TypeError, "unbound parameters"): float(bound_expr) def test_cast_to_int_when_bound(self): """Verify expression can be cast to an int when fully bound.""" x = Parameter("x") bound_expr = x.bind({x: 2.3}) self.assertEqual(int(bound_expr), 2) def test_cast_to_int_when_bound_truncates_after_evaluation(self): """Verify expression can be cast to an int when fully bound, but truncated only after evaluation.""" x = Parameter("x") y = Parameter("y") bound_expr = (x + y).bind({x: 2.3, y: 0.8}) self.assertEqual(int(bound_expr), 3) def test_cast_to_int_when_underlying_expression_bound(self): """Verify expression can be cast to a int when it still contains unbound parameters, but the underlying symbolic expression has a knowable value.""" x = Parameter("x") expr = x - x + 2.3 self.assertEqual(int(expr), 2) def test_raise_if_cast_to_int_when_not_fully_bound(self): """Verify raises if casting to int and not fully bound.""" x = Parameter("x") y = Parameter("y") bound_expr = (x + y).bind({x: 2.3}) with self.assertRaisesRegex(TypeError, "unbound parameters"): int(bound_expr) def test_raise_if_sub_unknown_parameters(self): """Verify we raise if asked to sub a parameter not in self.""" x = Parameter("x") expr = x + 2 y = Parameter("y") z = Parameter("z") with self.assertRaisesRegex(CircuitError, "not present"): expr.subs({y: z}) def test_sub_allow_unknown_parameters(self): """Verify we raise if asked to sub a parameter not in self.""" x = Parameter("x") expr = x + 2 y = Parameter("y") z = Parameter("z") subbed = expr.subs({y: z}, allow_unknown_parameters=True) self.assertEqual(subbed, expr) def test_raise_if_subbing_in_parameter_name_conflict(self): """Verify we raise if substituting in conflicting parameter names.""" x = Parameter("x") y_first = Parameter("y") expr = x + y_first y_second = Parameter("y") # Replacing an existing name is okay. expr.subs({y_first: y_second}) with self.assertRaisesRegex(CircuitError, "Name conflict"): expr.subs({x: y_second}) def test_expressions_of_parameter_with_constant(self): """Verify operating on a Parameter with a constant.""" good_constants = [2, 1.3, 0, -1, -1.0, numpy.pi, 1j] x = Parameter("x") for op in self.supported_operations: for const in good_constants: expr = op(const, x) bound_expr = expr.bind({x: 2.3}) self.assertEqual(complex(bound_expr), op(const, 2.3)) # Division by zero will raise. Tested elsewhere. if const == 0 and op == truediv: continue # Repeat above, swapping position of Parameter and constant. expr = op(x, const) bound_expr = expr.bind({x: 2.3}) res = complex(bound_expr) expected = op(2.3, const) self.assertTrue(cmath.isclose(res, expected), f"{res} != {expected}") def test_complex_parameter_bound_to_real(self): """Test a complex parameter expression can be real if bound correctly.""" x, y = Parameter("x"), Parameter("y") with self.subTest("simple 1j * x"): qc = QuantumCircuit(1) qc.rx(1j * x, 0) bound = qc.bind_parameters({x: 1j}) ref = QuantumCircuit(1) ref.rx(-1, 0) self.assertEqual(bound, ref) with self.subTest("more complex expression"): qc = QuantumCircuit(1) qc.rx(0.5j * x - y * y + 2 * y, 0) bound = qc.bind_parameters({x: -4, y: 1j}) ref = QuantumCircuit(1) ref.rx(1, 0) self.assertEqual(bound, ref) def test_complex_angle_raises_when_not_supported(self): """Test parameters are validated when fully bound and errors are raised accordingly.""" x = Parameter("x") qc = QuantumCircuit(1) qc.r(x, 1j * x, 0) with self.subTest("binding x to 0 yields real parameters"): bound = qc.bind_parameters({x: 0}) ref = QuantumCircuit(1) ref.r(0, 0, 0) self.assertEqual(bound, ref) with self.subTest("binding x to 1 yields complex parameters"): # RGate does not support complex parameters with self.assertRaises(CircuitError): bound = qc.bind_parameters({x: 1}) def test_operating_on_a_parameter_with_a_non_float_will_raise(self): """Verify operations between a Parameter and a non-float will raise.""" bad_constants = ["1", numpy.Inf, numpy.NaN, None, {}, []] x = Parameter("x") for op in self.supported_operations: for const in bad_constants: with self.subTest(op=op, const=const): with self.assertRaises(TypeError): _ = op(const, x) with self.assertRaises(TypeError): _ = op(x, const) def test_expressions_division_by_zero(self): """Verify dividing a Parameter by 0, or binding 0 as a denominator raises.""" x = Parameter("x") with self.assertRaises(ZeroDivisionError): _ = x / 0 with self.assertRaises(ZeroDivisionError): _ = x / 0.0 expr = 2 / x with self.assertRaises(ZeroDivisionError): _ = expr.bind({x: 0}) with self.assertRaises(ZeroDivisionError): _ = expr.bind({x: 0.0}) def test_expressions_of_parameter_with_parameter(self): """Verify operating on two Parameters.""" x = Parameter("x") y = Parameter("y") for op in self.supported_operations: expr = op(x, y) partially_bound_expr = expr.bind({x: 2.3}) self.assertEqual(partially_bound_expr.parameters, {y}) fully_bound_expr = partially_bound_expr.bind({y: -numpy.pi}) self.assertEqual(fully_bound_expr.parameters, set()) self.assertEqual(float(fully_bound_expr), op(2.3, -numpy.pi)) bound_expr = expr.bind({x: 2.3, y: -numpy.pi}) self.assertEqual(bound_expr.parameters, set()) self.assertEqual(float(bound_expr), op(2.3, -numpy.pi)) def test_expressions_operation_order(self): """Verify ParameterExpressions respect order of operations.""" x = Parameter("x") y = Parameter("y") z = Parameter("z") # Parenthesis before multiplication/division expr = (x + y) * z bound_expr = expr.bind({x: 1, y: 2, z: 3}) self.assertEqual(float(bound_expr), 9) expr = x * (y + z) bound_expr = expr.bind({x: 1, y: 2, z: 3}) self.assertEqual(float(bound_expr), 5) # Multiplication/division before addition/subtraction expr = x + y * z bound_expr = expr.bind({x: 1, y: 2, z: 3}) self.assertEqual(float(bound_expr), 7) expr = x * y + z bound_expr = expr.bind({x: 1, y: 2, z: 3}) self.assertEqual(float(bound_expr), 5) def test_nested_expressions(self): """Verify ParameterExpressions can also be the target of operations.""" x = Parameter("x") y = Parameter("y") z = Parameter("z") expr1 = x * y expr2 = expr1 + z bound_expr2 = expr2.bind({x: 1, y: 2, z: 3}) self.assertEqual(float(bound_expr2), 5) def test_negated_expression(self): """Verify ParameterExpressions can be negated.""" x = Parameter("x") y = Parameter("y") z = Parameter("z") expr1 = -x + y expr2 = -expr1 * (-z) bound_expr2 = expr2.bind({x: 1, y: 2, z: 3}) self.assertEqual(float(bound_expr2), 3) def test_standard_cu3(self): """This tests parameter negation in standard extension gate cu3.""" from qiskit.circuit.library import CU3Gate x = Parameter("x") y = Parameter("y") z = Parameter("z") qc = qiskit.QuantumCircuit(2) qc.append(CU3Gate(x, y, z), [0, 1]) try: qc.decompose() except TypeError: self.fail("failed to decompose cu3 gate with negated parameter expression") def test_name_collision(self): """Verify Expressions of distinct Parameters of shared name raises.""" x = Parameter("p") y = Parameter("p") # Expression of the same Parameter are valid. _ = x + x _ = x - x _ = x * x _ = x / x with self.assertRaises(CircuitError): _ = x + y with self.assertRaises(CircuitError): _ = x - y with self.assertRaises(CircuitError): _ = x * y with self.assertRaises(CircuitError): _ = x / y @combine(target_type=["gate", "instruction"], order=["bind-decompose", "decompose-bind"]) def test_to_instruction_with_expression(self, target_type, order): """Test preservation of expressions via parameterized instructions. ┌───────┐┌──────────┐┌───────────┐ qr1_0: |0>┤ Rx(θ) ├┤ Rz(pi/2) ├┤ Ry(phi*θ) ├ └───────┘└──────────┘└───────────┘ ┌───────────┐ qr2_0: |0>───┤ Ry(delta) ├─── ┌──┴───────────┴──┐ qr2_1: |0>┤ Circuit0(phi,θ) ├ └─────────────────┘ qr2_2: |0>─────────────────── """ theta = Parameter("θ") phi = Parameter("phi") qr1 = QuantumRegister(1, name="qr1") qc1 = QuantumCircuit(qr1) qc1.rx(theta, qr1) qc1.rz(numpy.pi / 2, qr1) qc1.ry(theta * phi, qr1) if target_type == "gate": gate = qc1.to_gate() elif target_type == "instruction": gate = qc1.to_instruction() self.assertEqual(gate.params, [phi, theta]) delta = Parameter("delta") qr2 = QuantumRegister(3, name="qr2") qc2 = QuantumCircuit(qr2) qc2.ry(delta, qr2[0]) qc2.append(gate, qargs=[qr2[1]]) self.assertEqual(qc2.parameters, {delta, theta, phi}) binds = {delta: 1, theta: 2, phi: 3} expected_qc = QuantumCircuit(qr2) expected_qc.rx(2, 1) expected_qc.rz(numpy.pi / 2, 1) expected_qc.ry(3 * 2, 1) expected_qc.r(1, numpy.pi / 2, 0) if order == "bind-decompose": decomp_bound_qc = qc2.assign_parameters(binds).decompose() elif order == "decompose-bind": decomp_bound_qc = qc2.decompose().assign_parameters(binds) self.assertEqual(decomp_bound_qc.parameters, set()) self.assertEqual(decomp_bound_qc, expected_qc) @combine(target_type=["gate", "instruction"], order=["bind-decompose", "decompose-bind"]) def test_to_instruction_expression_parameter_map(self, target_type, order): """Test preservation of expressions via instruction parameter_map.""" theta = Parameter("θ") phi = Parameter("phi") qr1 = QuantumRegister(1, name="qr1") qc1 = QuantumCircuit(qr1) qc1.rx(theta, qr1) qc1.rz(numpy.pi / 2, qr1) qc1.ry(theta * phi, qr1) theta_p = Parameter("theta") phi_p = Parameter("phi") if target_type == "gate": gate = qc1.to_gate(parameter_map={theta: theta_p, phi: phi_p}) elif target_type == "instruction": gate = qc1.to_instruction(parameter_map={theta: theta_p, phi: phi_p}) self.assertListEqual(gate.params, [theta_p, phi_p]) delta = Parameter("delta") qr2 = QuantumRegister(3, name="qr2") qc2 = QuantumCircuit(qr2) qc2.ry(delta, qr2[0]) qc2.append(gate, qargs=[qr2[1]]) self.assertListEqual(list(qc2.parameters), [delta, phi_p, theta_p]) binds = {delta: 1, theta_p: 2, phi_p: 3} expected_qc = QuantumCircuit(qr2) expected_qc.rx(2, 1) expected_qc.rz(numpy.pi / 2, 1) expected_qc.ry(3 * 2, 1) expected_qc.r(1, numpy.pi / 2, 0) if order == "bind-decompose": decomp_bound_qc = qc2.assign_parameters(binds).decompose() elif order == "decompose-bind": decomp_bound_qc = qc2.decompose().assign_parameters(binds) self.assertEqual(decomp_bound_qc.parameters, set()) self.assertEqual(decomp_bound_qc, expected_qc) def test_binding_across_broadcast_instruction(self): """Bind a parameter which was included via a broadcast instruction.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/3008 theta = Parameter("θ") n = 5 qc = QuantumCircuit(n, 1) qc.h(0) for i in range(n - 1): qc.cx(i, i + 1) qc.barrier() qc.rz(theta, range(n)) qc.barrier() for i in reversed(range(n - 1)): qc.cx(i, i + 1) qc.h(0) qc.measure(0, 0) theta_range = numpy.linspace(0, 2 * numpy.pi, 128) circuits = [qc.assign_parameters({theta: theta_val}) for theta_val in theta_range] self.assertEqual(len(circuits), len(theta_range)) for theta_val, bound_circ in zip(theta_range, circuits): rz_gates = [ inst.operation for inst in bound_circ.data if isinstance(inst.operation, RZGate) ] self.assertEqual(len(rz_gates), n) self.assertTrue(all(float(gate.params[0]) == theta_val for gate in rz_gates)) def test_substituting_parameter_with_simple_expression(self): """Substitute a simple parameter expression for a parameter.""" x = Parameter("x") y = Parameter("y") sub_ = y / 2 updated_expr = x.subs({x: sub_}) expected = y / 2 self.assertEqual(updated_expr, expected) def test_substituting_parameter_with_compound_expression(self): """Substitute a simple parameter expression for a parameter.""" x = Parameter("x") y = Parameter("y") z = Parameter("z") sub_ = y * z updated_expr = x.subs({x: sub_}) expected = y * z self.assertEqual(updated_expr, expected) def test_substituting_simple_with_simple_expression(self): """Substitute a simple parameter expression in a parameter expression.""" x = Parameter("x") expr = x * x y = Parameter("y") sub_ = y / 2 updated_expr = expr.subs({x: sub_}) expected = y * y / 4 self.assertEqual(updated_expr, expected) def test_substituting_compound_expression(self): """Substitute a compound parameter expression in a parameter expression.""" x = Parameter("x") expr = x * x y = Parameter("y") z = Parameter("z") sub_ = y + z updated_expr = expr.subs({x: sub_}) expected = (y + z) * (y + z) self.assertEqual(updated_expr, expected) def test_conjugate(self): """Test calling conjugate on a ParameterExpression.""" x = Parameter("x") self.assertEqual((x.conjugate() + 1j), (x - 1j).conjugate()) @data( circlib.RGate, circlib.RXGate, circlib.RYGate, circlib.RZGate, circlib.RXXGate, circlib.RYYGate, circlib.RZXGate, circlib.RZZGate, circlib.CRXGate, circlib.CRYGate, circlib.CRZGate, circlib.XXPlusYYGate, ) def test_bound_gate_to_matrix(self, gate_class): """Test to_matrix works if previously free parameters are bound. The conversion might fail, if trigonometric functions such as cos are called on the parameters and the parameters are still of type ParameterExpression. """ num_parameters = 2 if gate_class == circlib.RGate else 1 params = list(range(1, 1 + num_parameters)) free_params = ParameterVector("th", num_parameters) gate = gate_class(*params) num_qubits = gate.num_qubits circuit = QuantumCircuit(num_qubits) circuit.append(gate_class(*free_params), list(range(num_qubits))) bound_circuit = circuit.assign_parameters({free_params: params}) numpy.testing.assert_array_almost_equal(Operator(bound_circuit).data, gate.to_matrix()) def test_parameter_expression_grad(self): """Verify correctness of ParameterExpression gradients.""" x = Parameter("x") y = Parameter("y") z = Parameter("z") with self.subTest(msg="first order gradient"): expr = (x + y) * z self.assertEqual(expr.gradient(x), z) self.assertEqual(expr.gradient(z), (x + y)) with self.subTest(msg="second order gradient"): expr = x * x self.assertEqual(expr.gradient(x), 2 * x) self.assertEqual(expr.gradient(x).gradient(x), 2) def test_bound_expression_is_real(self): """Test is_real on bound parameters.""" x = Parameter("x") self.assertEqual(x.is_real(), None) self.assertEqual((1j * x).is_real(), None) expr = 1j * x bound = expr.bind({x: 2}) self.assertEqual(bound.is_real(), False) bound = x.bind({x: 0 + 0j}) self.assertEqual(bound.is_real(), True) bound = x.bind({x: 0 + 1j}) self.assertEqual(bound.is_real(), False) bound = x.bind({x: 1 + 0j}) self.assertEqual(bound.is_real(), True) bound = x.bind({x: 1 + 1j}) self.assertEqual(bound.is_real(), False) class TestParameterEquality(QiskitTestCase): """Test equality of Parameters and ParameterExpressions.""" def test_parameter_equal_self(self): """Verify a parameter is equal to it self.""" theta = Parameter("theta") self.assertEqual(theta, theta) def test_parameter_not_equal_param_of_same_name(self): """Verify a parameter is not equal to a Parameter of the same name.""" theta1 = Parameter("theta") theta2 = Parameter("theta") self.assertNotEqual(theta1, theta2) def test_parameter_expression_equal_to_self(self): """Verify an expression is equal to itself.""" theta = Parameter("theta") expr = 2 * theta self.assertEqual(expr, expr) def test_parameter_expression_equal_to_identical(self): """Verify an expression is equal an identical expression.""" theta = Parameter("theta") expr1 = 2 * theta expr2 = 2 * theta self.assertEqual(expr1, expr2) def test_parameter_expression_equal_floats_to_ints(self): """Verify an expression with float and int is identical.""" theta = Parameter("theta") expr1 = 2.0 * theta expr2 = 2 * theta self.assertEqual(expr1, expr2) def test_parameter_expression_not_equal_if_params_differ(self): """Verify expressions not equal if parameters are different.""" theta1 = Parameter("theta") theta2 = Parameter("theta") expr1 = 2 * theta1 expr2 = 2 * theta2 self.assertNotEqual(expr1, expr2) def test_parameter_equal_to_identical_expression(self): """Verify parameters and ParameterExpressions can be equal if identical.""" theta = Parameter("theta") phi = Parameter("phi") expr = (theta + phi).bind({phi: 0}) self.assertEqual(expr, theta) self.assertEqual(theta, expr) def test_parameter_symbol_equal_after_ufunc(self): """Verfiy ParameterExpression phi and ParameterExpression cos(phi) have the same symbol map""" phi = Parameter("phi") cos_phi = numpy.cos(phi) self.assertEqual(phi._parameter_symbols, cos_phi._parameter_symbols) class TestParameterReferences(QiskitTestCase): """Test the ParameterReferences class.""" def test_equal_inst_diff_instance(self): """Different value equal instructions are treated as distinct.""" theta = Parameter("theta") gate1 = RZGate(theta) gate2 = RZGate(theta) self.assertIsNot(gate1, gate2) self.assertEqual(gate1, gate2) refs = ParameterReferences(((gate1, 0), (gate2, 0))) # test __contains__ self.assertIn((gate1, 0), refs) self.assertIn((gate2, 0), refs) gate_ids = {id(gate1), id(gate2)} self.assertEqual(gate_ids, {id(gate) for gate, _ in refs}) self.assertTrue(all(idx == 0 for _, idx in refs)) def test_pickle_unpickle(self): """Membership testing after pickle/unpickle.""" theta = Parameter("theta") gate1 = RZGate(theta) gate2 = RZGate(theta) self.assertIsNot(gate1, gate2) self.assertEqual(gate1, gate2) refs = ParameterReferences(((gate1, 0), (gate2, 0))) to_pickle = (gate1, refs) pickled = pickle.dumps(to_pickle) (gate1_new, refs_new) = pickle.loads(pickled) self.assertEqual(len(refs_new), len(refs)) self.assertNotIn((gate1, 0), refs_new) self.assertIn((gate1_new, 0), refs_new) def test_equal_inst_same_instance(self): """Referentially equal instructions are treated as same.""" theta = Parameter("theta") gate = RZGate(theta) refs = ParameterReferences(((gate, 0), (gate, 0))) self.assertIn((gate, 0), refs) self.assertEqual(len(refs), 1) self.assertIs(next(iter(refs))[0], gate) self.assertEqual(next(iter(refs))[1], 0) def test_extend_refs(self): """Extending references handles duplicates.""" theta = Parameter("theta") ref0 = (RZGate(theta), 0) ref1 = (RZGate(theta), 0) ref2 = (RZGate(theta), 0) refs = ParameterReferences((ref0,)) refs |= ParameterReferences((ref0, ref1, ref2, ref1, ref0)) self.assertEqual(refs, ParameterReferences((ref0, ref1, ref2))) def test_copy_param_refs(self): """Copy of parameter references is a shallow copy.""" theta = Parameter("theta") ref0 = (RZGate(theta), 0) ref1 = (RZGate(theta), 0) ref2 = (RZGate(theta), 0) ref3 = (RZGate(theta), 0) refs = ParameterReferences((ref0, ref1)) refs_copy = refs.copy() # Check same gate instances in copy gate_ids = {id(ref0[0]), id(ref1[0])} self.assertEqual({id(gate) for gate, _ in refs_copy}, gate_ids) # add new ref to original and check copy not modified refs.add(ref2) self.assertNotIn(ref2, refs_copy) self.assertEqual(refs_copy, ParameterReferences((ref0, ref1))) # add new ref to copy and check original not modified refs_copy.add(ref3) self.assertNotIn(ref3, refs) self.assertEqual(refs, ParameterReferences((ref0, ref1, ref2))) class TestParameterTable(QiskitTestCase): """Test the ParameterTable class.""" def test_init_param_table(self): """Parameter table init from mapping.""" p1 = Parameter("theta") p2 = Parameter("theta") ref0 = (RZGate(p1), 0) ref1 = (RZGate(p1), 0) ref2 = (RZGate(p2), 0) mapping = {p1: ParameterReferences((ref0, ref1)), p2: ParameterReferences((ref2,))} table = ParameterTable(mapping) # make sure editing mapping doesn't change `table` del mapping[p1] self.assertEqual(table[p1], ParameterReferences((ref0, ref1))) self.assertEqual(table[p2], ParameterReferences((ref2,))) def test_set_references(self): """References replacement by parameter key.""" p1 = Parameter("theta") ref0 = (RZGate(p1), 0) ref1 = (RZGate(p1), 0) table = ParameterTable() table[p1] = ParameterReferences((ref0, ref1)) self.assertEqual(table[p1], ParameterReferences((ref0, ref1))) table[p1] = ParameterReferences((ref1,)) self.assertEqual(table[p1], ParameterReferences((ref1,))) def test_set_references_from_iterable(self): """Parameter table init from iterable.""" p1 = Parameter("theta") ref0 = (RZGate(p1), 0) ref1 = (RZGate(p1), 0) ref2 = (RZGate(p1), 0) table = ParameterTable({p1: ParameterReferences((ref0, ref1))}) table[p1] = (ref2, ref1, ref0) self.assertEqual(table[p1], ParameterReferences((ref2, ref1, ref0))) class TestParameterView(QiskitTestCase): """Test the ParameterView object.""" def setUp(self): super().setUp() x, y, z = Parameter("x"), Parameter("y"), Parameter("z") self.params = [x, y, z] self.view1 = ParameterView([x, y]) self.view2 = ParameterView([y, z]) self.view3 = ParameterView([x]) def test_and(self): """Test __and__.""" self.assertEqual(self.view1 & self.view2, {self.params[1]}) def test_or(self): """Test __or__.""" self.assertEqual(self.view1 | self.view2, set(self.params)) def test_xor(self): """Test __xor__.""" self.assertEqual(self.view1 ^ self.view2, {self.params[0], self.params[2]}) def test_len(self): """Test __len__.""" self.assertEqual(len(self.view1), 2) def test_le(self): """Test __le__.""" self.assertTrue(self.view1 <= self.view1) self.assertFalse(self.view1 <= self.view3) def test_lt(self): """Test __lt__.""" self.assertTrue(self.view3 < self.view1) def test_ge(self): """Test __ge__.""" self.assertTrue(self.view1 >= self.view1) self.assertFalse(self.view3 >= self.view1) def test_gt(self): """Test __lt__.""" self.assertTrue(self.view1 > self.view3) def test_eq(self): """Test __eq__.""" self.assertTrue(self.view1 == self.view1) self.assertFalse(self.view3 == self.view1) def test_ne(self): """Test __eq__.""" self.assertTrue(self.view1 != self.view2) self.assertFalse(self.view3 != self.view3) if __name__ == "__main__": unittest.main()
https://github.com/ncitron/qiskit-hack
ncitron
class QuantComp: def __init__(qboard, classical): qboard.classical = classical def convert(cboard): ret = [] for i in range(len(cboard)): if cboard[i] == 1: hold = str(bin(i)) while(len(hold) < 7): hold = '0' + hold ret.append(hold) return ret def setup(array): tot = len(array) n = 7 s = [] for i in range(n-1): s.append(i) if tot > 8: rep = 2 elif tot > 4: rep = 3 elif tot == 4: rep = 4 elif tot == 3: rep = 5 elif tot == 2: rep = 6 else: rep = 8 return rep, n def build_oracle(circuit, solutions, n): for i in range(tot): temp = solutions[i] for j, yesno in enumerate(reversed(temp)): if yesno == '0': circuit.x(j) circuit.h(n-1) circuit.mct(s, n-1) circuit.h(n-1) for k, noyes in enumerate(reversed(temp)): if noyes == '0': circuit.x(k) def amplify(circuit, n): circuit.h(range(n)) circuit.x(range(n)) circuit.h(n-1) circuit.mct(s, n-1) circuit.h(n-1) circuit.x(range(n)) circuit.h(range(n)) def guess(): sol = convert(qboard.classical) rep, n = setup(sol) qc = QuantumCircuit(n) qc.h(range(n)) for i in range(rep): build_oracle(qc, sol, n) amplify(qc, n) qc.measure_all() simulator = Aer.get_backend('qasm_simulator') return execute(qc, backend = simulator, shots = 1).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/quantastica/qiskit-toaster
quantastica
from qiskit import Aer, QuantumCircuit, execute from qiskit.compiler import transpile, assemble from quantastica.qiskit_toaster import ToasterBackend import time import logging import os backend = ToasterBackend.get_backend("qasm_simulator") # backend = Aer.get_backend("qasm_simulator") default_options = { # "method": "statevector", # Force dense statevector method for benchmarks # "truncate_enable": False, # Disable unused qubit truncation for benchmarks # "max_parallel_threads": 1, # Disable OpenMP parallelization for benchmarks "toaster_optimization": 3 # optimization for qubit-toaster } # def _execute(circuit, backend_options=None): # experiment = transpile(circuit, backend) # qobj = assemble(experiment, shots=1) # qobj_aer = backend._format_qobj(qobj, backend_options, None) # return backend._controller(qobj_aer) def _execute(circuit, backend): job = execute(circuit, backend=backend) # job.result is needed in order to wait for results job.result() def native_execute(benchmark, circuit, backend_options=None): # experiment = transpile(circuit, backend) # qobj = assemble(experiment, shots=1) # qobj_aer = backend._format_qobj(qobj, backend_options, None) # benchmark(backend._controller, qobj_aer) benchmark(_execute, circuit, backend) def run_bench(benchmark, nqubits, gate, locs=(1,)): qc = QuantumCircuit(nqubits) getattr(qc, gate)(*locs) native_execute(benchmark, qc, default_options) def first_rotation(circuit, nqubits): circuit.rx(1.0, range(nqubits)) circuit.rz(1.0, range(nqubits)) return circuit def mid_rotation(circuit, nqubits): circuit.rz(1.0, range(nqubits)) circuit.rx(1.0, range(nqubits)) circuit.rz(1.0, range(nqubits)) return circuit def last_rotation(circuit, nqubits): circuit.rz(1.0, range(nqubits)) circuit.rx(1.0, range(nqubits)) return circuit def entangler(circuit, pairs): for a, b in pairs: circuit.cx(a, b) return circuit def generate_qcbm_circuit(nqubits, depth, pairs): circuit = QuantumCircuit(nqubits) first_rotation(circuit, nqubits) entangler(circuit, pairs) for k in range(depth - 1): mid_rotation(circuit, nqubits) entangler(circuit, pairs) last_rotation(circuit, nqubits) # circuit.measure_all() return circuit def test_qcbm(name, backend, nqubits, optimization_level=None): pairs = [(i, (i + 1) % nqubits) for i in range(nqubits)] circuit = generate_qcbm_circuit(nqubits, 9, pairs) with open("circuit.qasm", "w") as f: f.write(circuit.qasm()) t1 = time.time() # test = transpile(circuit, optimization_level=0) # qobj = assemble(circuit) # job = backend.run(qobj, backend_options=default_options) job = execute( circuit, backend=backend, backend_options=default_options, optimization_level=optimization_level, ) # job.result is needed in order to wait for results result = job.result() t2 = time.time() # print(result) # counts = result.get_counts(circuit) # print("Counts size: %d" % len(counts)) print(" %s time: %f" % (name, t2 - t1)) if __name__ == "__main__": logging.basicConfig( format="%(levelname)s %(asctime)s %(pathname)s - %(message)s", level=os.environ.get("LOGLEVEL", "CRITICAL"), ) N = int(os.environ.get("N", 20)) LOOPS = int(os.environ.get("LOOPS", 10)) for i in range(0, LOOPS): print("Iteration #%d (of %d)" % (i, LOOPS)) test_qcbm("AER", Aer.get_backend("qasm_simulator"), N, 0) test_qcbm( "TOASTER", ToasterBackend.get_backend("qasm_simulator"), N, 0 )
https://github.com/unif2/Quantum-Computing-Mentorship-Task-4-Code
unif2
import numpy as np from numpy import kron import qiskit as qk def decomposition(H): """Decompose any 4x4 Hermitian matrix into a sum of tensor products of two Pauli matrices """ identity = np.array([[1, 0],[ 0, 1]], dtype=np.complex128) x = np.array([[0, 1], [ 1, 0]], dtype=np.complex128) y = np.array([[0, -1j],[1j, 0]], dtype=np.complex128) z = np.array([[1, 0], [0, -1]], dtype=np.complex128) S = [identity, x, y, z] labels = ['I', 'sigma_x', 'sigma_y', 'sigma_z'] d = {'00': 'I product I', '01': 'I product sigma_x', '02': 'I product sigma_y', '03': 'I product sigma_z', '10': 'sigma_x product I', '11': 'sigma_x product sigma_x', '12': 'sigma_x product sigma_y', '13': 'sigma_x product sigma_z', '20': 'sigma_y product I', '21': 'sigma_y product sigma_x', '22': 'sigma_y product sigma_y', '23': 'sigma_y product sigma_z', '30': 'sigma_z product I', '31': 'sigma_z product sigma_x', '32': 'sigma_z product sigma_y', '33': 'sigma_z product sigma_z'} for i in range(4): for j in range(4): a_ij = 0.25 * np.dot(kron(S[i], S[j]), H).trace() if a_ij != 0.0: print(str(a_ij) + ' * ' + d[str(i)+str(j)]) H = np.array([[0,0,0,0],[0,-1,1,0],[0,1,-1,0],[0,0,0,0]]) decomposition(H) def prepare_state(theta, n=3): """ Prepare three 2-qubit states with 3 associated quantum registers, 3 associated classical registers, and 3 quantum circuits. We will prepare the state with the ansatz mentioned in the notes in which we act on the first qubit with the Hadamard operator, then with the R_z operator, then we act on the 2-qubit state with the CNOT gate, and then on the second qubit in each terms of the superposition with the sigma_x operator. After that, we will take the first circuit and act on each qubit with the R_y(pi/2) operator, and take the second circuit and act on each qubit with the R_x(-pi/2) operator as explained in the notes. We do this so that those qubits will be in the basis of eigenvectors of sigma_x and sigma_y as explained in the notes. We can measure the qubits in the other circuit as-is because we need the expectation value of sigma_z and the qubits are already in the computational basis. """ qr0 = qk.QuantumRegister(2) cr0 = qk.ClassicalRegister(2) qc0 = qk.QuantumCircuit(qr0,cr0) qr1 = qk.QuantumRegister(2) cr1 = qk.ClassicalRegister(2) qc1 = qk.QuantumCircuit(qr1,cr1) qr2 = qk.QuantumRegister(2) cr2 = qk.ClassicalRegister(2) qc2 = qk.QuantumCircuit(qr2,cr2) qregisters = [qr0,qr1,qr2] cregisters = [cr0,cr1,cr2] qcircuits = [qc0,qc1,qc2] for i in range(n): qcircuits[i].h(qregisters[i][0]) for i in range(n): qcircuits[i].rz(theta, qregisters[i][0]) for i in range(n): qcircuits[i].cx(qregisters[i][0], qregisters[i][1]) for i in range(n): qcircuits[i].x(qregisters[i][1]) qcircuits[0].ry((np.pi)/2, qregisters[0][0]) qcircuits[0].ry((np.pi)/2, qregisters[0][1]) qcircuits[1].rx(-(np.pi)/2, qregisters[1][0]) qcircuits[1].rx(-(np.pi)/2, qregisters[1][1]) return qregisters, cregisters, qcircuits qregisters, cregisters, qcircuits = prepare_state(np.pi, n=3) qcircuits[0].draw(output='mpl') qcircuits[1].draw(output='mpl') qcircuits[2].draw(output='mpl') def expectation(qcircuits, cregisters, qregisters, n_shots, n=3): """ For each circuit, execute and measure it using the classical simulator 5000 times as explained above. Multiply each of the three expectation values by 0.5, add them up, and subtract -0.5. Return the result. """ expect = -0.5 for i in range(n): qcircuits[i].measure(qregisters[i],cregisters[i]) qk.Aer.backends() sim = qk.Aer.get_backend('qasm_simulator') res = qk.execute(qcircuits[i], sim, shots=n_shots).result() counts = res.get_counts() sum = 0 for k,v in counts.items(): if k=='01' or k=='10': sum += (-1)*v/n_shots elif k=='00' or k=='11': sum += v/n_shots sum = 0.5*sum expect += sum return expect # Consider 100 values of theta, between 0 and Pi. This theta is the one used in state preparation. thetas = np.linspace(0, np.pi, 100) # For each theta, store the resulting expectation value in results results = [] # For each theta, find the expectation value for theta in thetas: qregisters, cregisters, qcircuits = prepare_state(theta, n=3) expect = expectation(qcircuits, cregisters, qregisters, 5000, n=3) results.append(expect) # Sort the results in ascending order. The first one is your minimum eigenvalue. results.sort() print("The minimum eigenvalue is: {}.".format(results[0])) from qiskit import IBMQ #IBMQ.delete_account() IBMQ.save_account('my IBM token', overwrite=True) IBMQ.load_account() provider = IBMQ.get_provider() procs=provider.backends(operational=True, simulator=False) from qiskit.tools.jupyter import * %qiskit_backend_overview from qiskit.tools import monitor backend = qk.providers.ibmq.least_busy([p for p in procs if len(p.properties().qubits) >= 2]) from qiskit.tools.monitor import backend_overview, backend_monitor backend_monitor(backend) def q_expectation(qcircuits, cregisters, qregisters, n_shots, n=3): """ For each circuit, execute and measure it using the classical simulator 5000 times as explained above. Multiply each of the three expectation values by 0.5, add them up, and subtract -0.5. Return the result. """ expect = -0.5 for i in range(n): qcircuits[i].measure(qregisters[i],cregisters[i]) qk.Aer.backends() sim = qk.Aer.get_backend('qasm_simulator') res = qk.execute(qcircuits[i], backend=backend, shots=n_shots).result() #mon = monitor.job_monitor(res) counts = res.get_counts() sum = 0 for k,v in counts.items(): if k=='01' or k=='10': sum += (-1)*v/n_shots elif k=='00' or k=='11': sum += v/n_shots sum = 0.5*sum expect += sum return expect # Consider 10 values of theta, between 0 and Pi. This theta is the one used in state preparation. thetas = np.linspace(0, np.pi, 10) # Use n_shots = 100 results = [] # For each theta, find the expectation value for theta in thetas: qregisters, cregisters, qcircuits = prepare_state(theta, n=3) expect = q_expectation(qcircuits, cregisters, qregisters, 100, n=3) results.append(expect) # Sort the results in ascending order. The first one is your minimum eigenvalue. results.sort() print("The minimum eigenvalue is: {}.".format(results[0])) # Use n_shots = 1000 results = [] # For each theta, find the expectation value for theta in thetas: qregisters, cregisters, qcircuits = prepare_state(theta, n=3) expect = q_expectation(qcircuits, cregisters, qregisters, 1000, n=3) results.append(expect) # Sort the results in ascending order. The first one is your minimum eigenvalue. results.sort() print("The minimum eigenvalue is: {}.".format(results[0])) # Use n_shots = 5000 results = [] # For each theta, find the expectation value for theta in thetas: qregisters, cregisters, qcircuits = prepare_state(theta, n=3) expect = q_expectation(qcircuits, cregisters, qregisters, 5000, n=3) results.append(expect) # Sort the results in ascending order. The first one is your minimum eigenvalue. results.sort() print("The minimum eigenvalue is: {}.".format(results[0])) # Use n_shots = 8192 = max allowed results = [] thetas = [np.pi] # For each theta, find the expectation value for theta in thetas: qregisters, cregisters, qcircuits = prepare_state(theta, n=3) expect = q_expectation(qcircuits, cregisters, qregisters, 8192, n=3) results.append(expect) # Sort the results in ascending order. The first one is your minimum eigenvalue. results.sort() print("The minimum eigenvalue is: {}.".format(results[0])) def decomposition(H): """Decompose any 4x4 Hermitian matrix into a sum of tensor products of two Pauli matrices """ A_ij = [] identity = np.array([[1, 0],[ 0, 1]], dtype=np.complex128) x = np.array([[0, 1], [ 1, 0]], dtype=np.complex128) y = np.array([[0, -1j],[1j, 0]], dtype=np.complex128) z = np.array([[1, 0], [0, -1]], dtype=np.complex128) S = [identity, x, y, z] labels = ['I', 'sigma_x', 'sigma_y', 'sigma_z'] d = {'00': 'I product I', '01': 'I product sigma_x', '02': 'I product sigma_y', '03': 'I product sigma_z', '10': 'sigma_x product I', '11': 'sigma_x product sigma_x', '12': 'sigma_x product sigma_y', '13': 'sigma_x product sigma_z', '20': 'sigma_y product I', '21': 'sigma_y product sigma_x', '22': 'sigma_y product sigma_y', '23': 'sigma_y product sigma_z', '30': 'sigma_z product I', '31': 'sigma_z product sigma_x', '32': 'sigma_z product sigma_y', '33': 'sigma_z product sigma_z'} for i in range(4): for j in range(4): a_ij = 0.25 * np.dot(kron(S[i], S[j]), H).trace() A_ij.append(a_ij) if a_ij != 0.0: print(str(a_ij) + ' * ' + d[str(i)+str(j)]) return np.asarray(A_ij).reshape(4,4) def prepare_state2(A, theta): qregisters = [] cregisters = [] qcircuits = [] identity = np.array([[1, 0],[ 0, 1]], dtype=np.complex128) x = np.array([[0, 1], [ 1, 0]], dtype=np.complex128) y = np.array([[0, -1j],[1j, 0]], dtype=np.complex128) z = np.array([[1, 0], [0, -1]], dtype=np.complex128) d = {} for i in range(4): for j in range(4): if A[i,j] != 0: if i !=0 and j!=0: qr = qk.QuantumRegister(2) cr = qk.ClassicalRegister(2) qc = qk.QuantumCircuit(qr,cr) qc.h(qr[0]) qc.rz(theta, qr[0]) qc.cx(qr[0], qr[1]) qc.x(qr[1]) if i==1: qc.ry((np.pi)/2, qr[0]) if i==2: qc.rx(-(np.pi)/2, qr[0]) if j==1: qc.ry((np.pi)/2, qr[1]) if j==2: qc.rx(-(np.pi)/2, qr[1]) qregisters.append(qr) cregisters.append(cr) qcircuits.append(qc) d[(i,j)] = [qregisters, cregisters, qcircuits] if i == 0 and j != 0: qr = qk.QuantumRegister(2) cr = qk.ClassicalRegister(2) qc = qk.QuantumCircuit(qr,cr) qc.h(qr[0]) qc.rz(theta, qr[0]) qc.cx(qr[0], qr[1]) qc.x(qr[1]) if j==1: qc.ry((np.pi)/2, qr[1]) if j==2: qc.rx(-(np.pi)/2, qr[1]) qregisters.append(qr) cregisters.append(cr) qcircuits.append(qc) d[(i,j)] = [qregisters, cregisters, qcircuits] if i != 0 and j == 0: qr = qk.QuantumRegister(2) cr = qk.ClassicalRegister(2) qc = qk.QuantumCircuit(qr,cr) qc.h(qr[0]) qc.rz(theta, qr[0]) qc.cx(qr[0], qr[1]) qc.x(qr[1]) if i==1: qc.ry((np.pi)/2, qr[0]) if i==2: qc.rx(-(np.pi)/2, qr[0]) qregisters.append(qr) cregisters.append(cr) qcircuits.append(qc) d[(i,j)] = [qregisters, cregisters, qcircuits] return d, A def expectation2(d, A, n_shots): """ For each circuit, execute and measure it using the classical simulator 5000 times as explained above. Return the result. """ expect = A[0,0] qk.Aer.backends() sim = qk.Aer.get_backend('qasm_simulator') for k,v in d.items(): for i in range(len(v[2])): v[2][i].measure(v[0][i],v[1][i]) res = qk.execute(v[2][i], sim, shots=n_shots).result() counts = res.get_counts() sum = 0 for m,n in counts.items(): if m=='01' or m=='10': sum += (-1)*n/n_shots elif m=='00' or m=='11': sum += n/n_shots sum = A[k[0],k[1]]*sum expect += sum return expect thetas = np.linspace(0, np.pi, 100) H = np.array([[0,0,0,0],[0,-1,1,0],[0,1,-1,0],[0,0,0,0]]) A = decomposition(H) # For each theta, store the resulting expectation value in results results = [] # For each theta, find the expectation value for theta in thetas: d, A = prepare_state2(A, theta) expect = expectation2(d, A, 5000) results.append(expect) # Sort the results in ascending order. The first one is your minimum eigenvalue. results.sort() print("The minimum eigenvalue is: {}.".format(results[0])) # -5??!! Maybe I missed something in my logic. Will continue to look into this. :-)
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. """ Divide-and-conquer state preparation https://doi.org/10.1038/s41598-021-85474-1 https://arxiv.org/abs/2108.10182 """ from math import log2 from qiskit import QuantumCircuit from qclib.gates.initialize import Initialize from qclib.state_preparation.util.state_tree_preparation import ( Amplitude, state_decomposition, ) from qclib.state_preparation.util.angle_tree_preparation import create_angles_tree from qclib.state_preparation.util.tree_register import add_register from qclib.state_preparation.util.tree_walk import bottom_up class DcspInitialize(Initialize): """ A divide-and-conquer algorithm for quantum state preparation https://doi.org/10.1038/s41598-021-85474-1 This class implements a state preparation gate. """ def __init__(self, params, label=None): """ Parameters ---------- params: list of complex A unit vector representing a quantum state. Values are amplitudes. """ self._name = "dcsp" self._get_num_qubits(params) if label is None: self._label = "DCSP" super().__init__(self._name, self.num_qubits, params, label=label) def _define(self): self.definition = self._define_initialize() def _define_initialize(self): n_qubits = int(log2(len(self.params))) data = [Amplitude(i, a) for i, a in enumerate(self.params)] state_tree = state_decomposition(n_qubits, data) angle_tree = create_angles_tree(state_tree) circuit = QuantumCircuit() add_register(circuit, angle_tree, n_qubits - 1) bottom_up(angle_tree, circuit, n_qubits) return circuit def _get_num_qubits(self, params): if not log2(len(params)).is_integer(): Exception("The number of amplitudes is not a power of 2") self.num_qubits = len(params) - 1 @staticmethod def initialize(q_circuit, state, qubits=None): """ Appends a DcspInitialize gate into the q_circuit """ if qubits is None: q_circuit.append(DcspInitialize(state), q_circuit.qubits) else: q_circuit.append(DcspInitialize(state), qubits)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import QuantumCircuit from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits to represent the uncertainty num_uncertainty_qubits = 3 # parameters for considered random distribution S = 2.0 # initial spot price vol = 0.4 # volatility of 40% r = 0.05 # annual interest rate of 4% T = 40 / 365 # 40 days to maturity # resulting parameters for log-normal distribution mu = (r - 0.5 * vol**2) * T + np.log(S) sigma = vol * np.sqrt(T) mean = np.exp(mu + sigma**2 / 2) variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2) stddev = np.sqrt(variance) # lowest and highest value considered for the spot price; in between, an equidistant discretization is considered. low = np.maximum(0, mean - 3 * stddev) high = mean + 3 * stddev # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, high) ) # plot probability distribution x = uncertainty_model.values y = uncertainty_model.probabilities plt.bar(x, y, width=0.2) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.grid() plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15) plt.ylabel("Probability ($\%$)", size=15) plt.show() # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 1.896 # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [0, 1] offsets = [0, 0] f_min = 0 f_max = high - strike_price european_call_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=c_approx, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective num_qubits = european_call_objective.num_qubits european_call = QuantumCircuit(num_qubits) european_call.append(uncertainty_model, range(num_uncertainty_qubits)) european_call.append(european_call_objective, range(num_qubits)) # draw the circuit european_call.draw() # plot exact payoff function (evaluated on the grid of the uncertainty model) x = uncertainty_model.values y = np.maximum(0, x - strike_price) plt.plot(x, y, "ro-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Spot Price", size=15) plt.ylabel("Payoff", size=15) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.show() # evaluate exact expected value (normalized to the [0, 1] interval) exact_value = np.dot(uncertainty_model.probabilities, y) exact_delta = sum(uncertainty_model.probabilities[x >= strike_price]) print("exact expected value:\t%.4f" % exact_value) print("exact delta value: \t%.4f" % exact_delta) european_call.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_call, objective_qubits=[3], post_processing=european_call_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) from qiskit_finance.applications.estimation import EuropeanCallPricing european_call_pricing = EuropeanCallPricing( num_state_qubits=num_uncertainty_qubits, strike_price=strike_price, rescaling_factor=c_approx, bounds=(low, high), uncertainty_model=uncertainty_model, ) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_pricing.to_estimation_problem() # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (european_call_pricing.interpret(result))) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) from qiskit_finance.applications.estimation import EuropeanCallDelta european_call_delta = EuropeanCallDelta( num_state_qubits=num_uncertainty_qubits, strike_price=strike_price, bounds=(low, high), uncertainty_model=uncertainty_model, ) european_call_delta._objective.decompose().draw() european_call_delta_circ = QuantumCircuit(european_call_delta._objective.num_qubits) european_call_delta_circ.append(uncertainty_model, range(num_uncertainty_qubits)) european_call_delta_circ.append( european_call_delta._objective, range(european_call_delta._objective.num_qubits) ) european_call_delta_circ.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_delta.to_estimation_problem() # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) conf_int = np.array(result_delta.confidence_interval_processed) print("Exact delta: \t%.4f" % exact_delta) print("Esimated value: \t%.4f" % european_call_delta.interpret(result_delta)) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# Create circuit to test transpiler on from qiskit import QuantumCircuit from qiskit.circuit.library import GroverOperator, Diagonal oracle = Diagonal([1]*7 + [-1]) qc = QuantumCircuit(3) qc.h([0,1,2]) qc = qc.compose(GroverOperator(oracle)) # Use Statevector object to calculate the ideal output from qiskit.quantum_info import Statevector ideal_distribution = Statevector.from_instruction(qc).probabilities_dict() from qiskit.visualization import plot_histogram plot_histogram(ideal_distribution) from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService() backend = service.backend('ibm_algiers') # Need to add measurements to the circuit qc.measure_all() from qiskit import transpile circuits = [] for optimization_level in [0, 3]: t_qc = transpile(qc, backend, optimization_level=optimization_level, seed_transpiler=0) print(f'CNOTs (optimization_level={optimization_level}): ', t_qc.count_ops()['cx']) circuits.append(t_qc) from qiskit.transpiler import PassManager, InstructionDurations from qiskit.transpiler.passes import ASAPSchedule, DynamicalDecoupling from qiskit.circuit.library import XGate # Get gate durations so the transpiler knows how long each operation takes durations = InstructionDurations.from_backend(backend) # This is the sequence we'll apply to idling qubits dd_sequence = [XGate(), XGate()] # Run scheduling and dynamic decoupling passes on circuit pm = PassManager([ASAPSchedule(durations), DynamicalDecoupling(durations, dd_sequence)] ) circ_dd = pm.run(circuits[1]) # Add this new circuit to our list circuits.append(circ_dd) from qiskit_ibm_runtime import Sampler, Session with Session(service=service, backend=backend): sampler = Sampler() job = sampler.run( circuits=circuits, # sample all three circuits skip_transpilation=True, shots=8000) result = job.result() from qiskit.visualization import plot_histogram binary_prob = [quasi_dist.binary_probabilities() for quasi_dist in result.quasi_dists] plot_histogram(binary_prob+[ideal_distribution], bar_labels=False, legend=['optimization_level=0', 'optimization_level=3', 'optimization_level=3 + dd', 'ideal distribution']) from qiskit.quantum_info import hellinger_fidelity for counts in result.quasi_dists: print( f"{hellinger_fidelity(counts.binary_probabilities(), ideal_distribution):.3f}" ) import qiskit_ibm_runtime qiskit_ibm_runtime.version.get_version_info() from qiskit.tools.jupyter import * %qiskit_version_table %qiskit_copyright
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the ResetAfterMeasureSimplification pass""" from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit.circuit.classicalregister import Clbit from qiskit.transpiler.passes.optimization import ResetAfterMeasureSimplification from qiskit.test import QiskitTestCase class TestResetAfterMeasureSimplificationt(QiskitTestCase): """Test ResetAfterMeasureSimplification transpiler pass.""" def test_simple(self): """Test simple""" qc = QuantumCircuit(1, 1) qc.measure(0, 0) qc.reset(0) new_qc = ResetAfterMeasureSimplification()(qc) ans_qc = QuantumCircuit(1, 1) ans_qc.measure(0, 0) ans_qc.x(0).c_if(ans_qc.clbits[0], 1) self.assertEqual(new_qc, ans_qc) def test_simple_null(self): """Test simple no change in circuit""" qc = QuantumCircuit(1, 1) qc.measure(0, 0) qc.x(0) qc.reset(0) new_qc = ResetAfterMeasureSimplification()(qc) self.assertEqual(new_qc, qc) def test_simple_multi_reg(self): """Test simple, multiple registers""" cr1 = ClassicalRegister(1, "c1") cr2 = ClassicalRegister(1, "c2") qr = QuantumRegister(1, "q") qc = QuantumCircuit(qr, cr1, cr2) qc.measure(0, 1) qc.reset(0) new_qc = ResetAfterMeasureSimplification()(qc) ans_qc = QuantumCircuit(qr, cr1, cr2) ans_qc.measure(0, 1) ans_qc.x(0).c_if(cr2[0], 1) self.assertEqual(new_qc, ans_qc) def test_simple_multi_reg_null(self): """Test simple, multiple registers, null change""" cr1 = ClassicalRegister(1, "c1") cr2 = ClassicalRegister(1, "c2") qr = QuantumRegister(2, "q") qc = QuantumCircuit(qr, cr1, cr2) qc.measure(0, 1) qc.reset(1) # reset not on same qubit as meas new_qc = ResetAfterMeasureSimplification()(qc) self.assertEqual(new_qc, qc) def test_simple_multi_resets(self): """Only first reset is collapsed""" qc = QuantumCircuit(1, 2) qc.measure(0, 0) qc.reset(0) qc.reset(0) new_qc = ResetAfterMeasureSimplification()(qc) ans_qc = QuantumCircuit(1, 2) ans_qc.measure(0, 0) ans_qc.x(0).c_if(ans_qc.clbits[0], 1) ans_qc.reset(0) self.assertEqual(new_qc, ans_qc) def test_simple_multi_resets_with_resets_before_measure(self): """Reset BEFORE measurement not collapsed""" qc = QuantumCircuit(2, 2) qc.measure(0, 0) qc.reset(0) qc.reset(1) qc.measure(1, 1) new_qc = ResetAfterMeasureSimplification()(qc) ans_qc = QuantumCircuit(2, 2) ans_qc.measure(0, 0) ans_qc.x(0).c_if(Clbit(ClassicalRegister(2, "c"), 0), 1) ans_qc.reset(1) ans_qc.measure(1, 1) self.assertEqual(new_qc, ans_qc) def test_barriers_work(self): """Test that barriers block consolidation""" qc = QuantumCircuit(1, 1) qc.measure(0, 0) qc.barrier(0) qc.reset(0) new_qc = ResetAfterMeasureSimplification()(qc) self.assertEqual(new_qc, qc) def test_bv_circuit(self): """Test Bernstein Vazirani circuit with midcircuit measurement.""" bitstring = "11111" qc = QuantumCircuit(2, len(bitstring)) qc.x(1) qc.h(1) for idx, bit in enumerate(bitstring[::-1]): qc.h(0) if int(bit): qc.cx(0, 1) qc.h(0) qc.measure(0, idx) if idx != len(bitstring) - 1: qc.reset(0) # reset control qc.reset(1) qc.x(1) qc.h(1) new_qc = ResetAfterMeasureSimplification()(qc) for op in new_qc.data: if op.operation.name == "reset": self.assertEqual(op.qubits[0], new_qc.qubits[1]) def test_simple_if_else(self): """Test that the pass recurses into an if-else.""" pass_ = ResetAfterMeasureSimplification() base_test = QuantumCircuit(1, 1) base_test.measure(0, 0) base_test.reset(0) base_expected = QuantumCircuit(1, 1) base_expected.measure(0, 0) base_expected.x(0).c_if(0, True) test = QuantumCircuit(1, 1) test.if_else( (test.clbits[0], True), base_test.copy(), base_test.copy(), test.qubits, test.clbits ) expected = QuantumCircuit(1, 1) expected.if_else( (expected.clbits[0], True), base_expected.copy(), base_expected.copy(), expected.qubits, expected.clbits, ) self.assertEqual(pass_(test), expected) def test_nested_control_flow(self): """Test that the pass recurses into nested control flow.""" pass_ = ResetAfterMeasureSimplification() base_test = QuantumCircuit(1, 1) base_test.measure(0, 0) base_test.reset(0) base_expected = QuantumCircuit(1, 1) base_expected.measure(0, 0) base_expected.x(0).c_if(0, True) body_test = QuantumCircuit(1, 1) body_test.for_loop((0,), None, base_expected.copy(), body_test.qubits, body_test.clbits) body_expected = QuantumCircuit(1, 1) body_expected.for_loop( (0,), None, base_expected.copy(), body_expected.qubits, body_expected.clbits ) test = QuantumCircuit(1, 1) test.while_loop((test.clbits[0], True), body_test, test.qubits, test.clbits) expected = QuantumCircuit(1, 1) expected.while_loop( (expected.clbits[0], True), body_expected, expected.qubits, expected.clbits ) self.assertEqual(pass_(test), expected)
https://github.com/daimurat/qiskit-implementation
daimurat
# データ取得に必要なpandas, pandas_datareaderのインストール !pip install pandas pandas_datareader import numpy as np import pandas as pd import pandas_datareader.data as web import datetime import matplotlib.pyplot as plt from qiskit import Aer from qiskit.circuit.library import QFT from qiskit.aqua import QuantumInstance, aqua_globals from qiskit.quantum_info import state_fidelity from qiskit.aqua.algorithms import HHL, NumPyLSsolver from qiskit.aqua.components.eigs import EigsQPE from qiskit.aqua.components.reciprocals import LookupRotation from qiskit.aqua.operators import MatrixOperator from qiskit.aqua.components.initial_states import Custom # 銘柄選択 codes = ["GOOG", 'AAPL', 'FB', 'AMZN'] # GAFA # 2017年の1年間のデータを使用 start = datetime.datetime(2017, 1, 1) end = datetime.datetime(2017, 12, 31) # Yahoo! Financeから日次の株価データを取得 data = web.DataReader(codes, 'yahoo', start, end) df = data['Adj Close'] ## 直近のデータの表示 display(df.tail()) ## 株価をプロットしてみる fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(15, 6)) df.loc[:,['AAPL', 'FB']].plot(ax=axes[0]) df.loc[:,['GOOG', 'AMZN']].plot(ax=axes[1]) daily_return = df.pct_change() display(daily_return.tail()) expected_return = daily_return.dropna(how='all').mean() * 252 # 年率換算のため年間の営業日数252を掛ける print(expected_return) cov = daily_return.dropna(how='all').cov() * 252 # 年率換算のため display(cov) R = expected_return.values Pi = np.ones(4) S = cov.values row1 = np.append(np.zeros(2), R).reshape(1,-1) row2 = np.append(np.zeros(2), Pi).reshape(1,-1) row3 = np.concatenate([R.reshape(-1,1), Pi.reshape(-1,1), S], axis=1) W = np.concatenate([row1, row2, row3]) np.set_printoptions(linewidth=200) print(W) mu = 0.1 # ポートフォリオのリターン xi = 1.0 mu_xi_0 = np.append(np.array([mu, xi]), np.zeros_like(R)) print(mu_xi_0) matrix, vector, truncate_powerdim, truncate_hermitian = HHL.matrix_resize(W, mu_xi_0) # 2**3=8次元の行列になっているか確認 print(matrix) def create_eigs(matrix, num_ancillae, num_time_slices, negative_evals): ne_qfts = [None, None] if negative_evals: num_ancillae += 1 # The QFT and IQFT circuits for handling negative eigenvalues ne_qfts = [QFT(num_ancillae - 1), QFT(num_ancillae - 1).inverse()] """ Specifically, this class is based on PhaseEstimationCircuit with no measurements and has additional handling of negative eigenvalues """ return EigsQPE(MatrixOperator(matrix=matrix), # The Hamiltonian Operator object QFT(num_ancillae).inverse(), num_time_slices=num_time_slices, num_ancillae=num_ancillae, expansion_mode='trotter', expansion_order=2, # The suzuki expansion order, has a minimum value of 1 evo_time=None, # This is t, can set to: np.pi*3/4 negative_evals=negative_evals, # Set True to indicate negative eigenvalues need to be handled ne_qfts=ne_qfts) # 扱う問題の次元 orig_size = len(vector) # 固有値探索の初期化 eigs = create_eigs(matrix, 7, 50, True) num_q, num_a = eigs.get_register_sizes() # 制御回転の初期化 c = 0.5*(2 * np.pi * (1. / 2**(num_a) )) reci = LookupRotation(scale=c, negative_evals=eigs._negative_evals, evo_time=eigs._evo_time) # 初期状態の設定 init_state = Custom(num_q, state_vector=vector) algo = HHL( matrix, vector, truncate_powerdim, truncate_hermitian, eigs, # The eigenvalue estimation instance init_state, # The initial quantum state preparation reci, # The eigenvalue reciprocal and controlled rotation instance num_q, # Number of qubits required for the matrix Operator instance num_a, # Number of ancillary qubits for Eigenvalues instance orig_size # The original dimension of the problem (if truncate_powerdim) ) ## 結果 x_HHL = algo.run(QuantumInstance(Aer.get_backend('statevector_simulator'))) ## 厳密解 # x_exact = np.linalg.lstsq(matrix, vector, rcond=0)[0] x_exact = NumPyLSsolver(matrix, vector).run() # 解の信頼度を求める def fidelity(hhl, ref): solution_hhl_normed = hhl / np.linalg.norm(hhl) solution_ref_normed = ref / np.linalg.norm(ref) fidelity = state_fidelity(solution_hhl_normed, solution_ref_normed) print("Fidelity:\t\t %f" % fidelity) fidelity(x_HHL.solution, x_exact.solution) # the number of qubits required print("circuit_width:\t", x_HHL['circuit_info']['width']) # the maximum number of gates print("circuit_depth:\t", x_HHL['circuit_info']['depth']) # To verify whether running the circuit on current real hardware is feasible print("CNOT gates:\t", x_HHL['circuit_info']['operations']['cx']) w_opt_HHL = x_HHL.solution[2:6] w_opt_exact = x_exact.solution[2:6] w_opt = pd.DataFrame(np.vstack([w_opt_exact, w_opt_HHL]).T, index=df.columns, columns=['exact', 'HHL']) w_opt w_opt.plot.bar() # 2018年の1年間のデータを使用 start = datetime.datetime(2017, 12, 30) end = datetime.datetime(2018, 12, 31) # Yahoo! Financeから日次の株価データを取得 data = web.DataReader(codes, 'yahoo', start, end) df2018 = data['Adj Close'] display(df2018.tail()) ## 株価をプロットしてみる fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(15, 6)) df2018.loc[:,['AAPL', 'FB']].plot(ax=axes[0]) df2018.loc[:,['GOOG', 'AMZN']].plot(ax=axes[1]) # ポートフォリオの資産価値の推移 pf_value = df2018.dot(w_opt) pf_value.head() # exact と HHLで初期金額が異なることがありうるので、期初の値で規格化したリターンをみる。 pf_value.exact = pf_value.exact / pf_value.exact[0] pf_value.HHL = pf_value.HHL / pf_value.HHL[0] print(pf_value.tail()) pf_value.plot(figsize=(9, 6)) pf_value.pct_change().std() * np.sqrt(252) ## 年率換算
https://github.com/Axect/QuantumAlgorithms
Axect
from qiskit import QuantumCircuit,Aer, execute from qiskit.visualization import plot_histogram import numpy as np import matplotlib.pyplot as plt def check_computational_basis(basis): n = int(np.log2(len(basis))) qc = QuantumCircuit(n,n) initial_state = np.array(basis) / np.linalg.norm(basis) qc.initialize(initial_state, reversed(range(n))) # Input : LSB -> MSB qc.measure(range(n), reversed(range(n))) # Readout: LSB -> MSB backend = Aer.get_backend('qasm_simulator') counts = execute(qc,backend).result().get_counts().keys() return counts def gen_bases(n): return np.eye(2**n) bases = gen_bases(3) for i in range(bases.shape[0]): basis = bases[i].tolist() print(f"basis: {basis} -> {check_computational_basis(basis)}") def convert_zbasis_to_cbasis(zbasis): """ Converts a basis state in the Z basis to the computational basis Example: Input: [0,0] -> Output: [1,0,0,0] Input: [0,1] -> Output: [0,1,0,0] Input: [1,0] -> Output: [0,0,1,0] Input: [1,1] -> Output: [0,0,0,1] """ n = 2**len(zbasis) # z basis to binary number bin_str = "".join([str(x) for x in zbasis]) num = int(bin_str,2) # binary number to computational basis cbasis = np.zeros(n) cbasis[num] = 1 return cbasis def cswap_test(x): qc = QuantumCircuit(len(x)+1, 1) input_state = convert_zbasis_to_cbasis(x) qc.initialize(input_state, reversed(range(1,len(x)+1))) qc.barrier() qc.h(0) qc.cswap(0,1,2) qc.h(0) qc.measure(0,0) backend = Aer.get_backend('qasm_simulator') return qc, execute(qc,backend).result().get_counts() qc, counts = cswap_test([0,1]) qc.draw(output='mpl', style='iqx') plot_histogram(counts) states = [ [0,0], [0,1], [1,0], [1,1] ] fig, ax = plt.subplots(1,4, figsize=(16,4)) for i, state in enumerate(states): _, counts = cswap_test(state) plot_histogram(counts, ax=ax[i]) ax[i].set_title(f"Input: {state}") plt.tight_layout() plt.show()
https://github.com/henrik-dreyer/MPS-in-Qiskit
henrik-dreyer
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Oct 5 17:51:05 2019 @author: henrikdreyer Indexing convention for all tensors 2-A-3 | 1 1 | 2-A-3 """ from ncon import ncon import numpy as np from qiskit import QuantumCircuit, QuantumRegister from qiskit.quantum_info.operators import Operator def normalize(x): """ INPUT: x(vector):input state OUPUT y(vector): x normalized """ y=x/np.linalg.norm(x) return y def extract_phase(x): """ INPUT: x(vector): input state OUPUT y(vector): same state but the first coefficient is real positive """ y=x*np.exp(-1j*np.angle(x[0])) return y def complement(V): """ INPUT: V(array): rectangular a x b matrix with a > b OUTPUT W(array): columns = orthonormal basis for complement of V """ W=embed_isometry(V) W=W[:,V.shape[1]:] return W def find_orth(O): """ Given a non-complete orthonormal basis of a vector space O, find another vector that is orthogonal to all others """ rand_vec=np.random.rand(O.shape[0],1) A=np.hstack((O,rand_vec)) b=np.zeros(O.shape[1]+1) b[-1]=1 x=np.linalg.lstsq(A.T,b,rcond=None)[0] return x/np.linalg.norm(x) def embed_isometry(V,defect=0): """ V (array): rectangular a x b matrix with a > b with orthogonal columns defect (int): if V should not be filled up to a square matrix, set defect s.t. the output matrix is a x (a-defect) Complete an isometry V with dimension a x b to a unitary with dimension a x a, i.e. add a-b normalized columns to V that are orthogonal to the first a columns """ a=V.shape[0] b=V.shape[1] for i in range(a-b-defect): x=np.expand_dims(find_orth(V),axis=1) V=np.hstack((V,x.conj())) return V def test_isometry(V): """ check if ---V------ ---- | | | | | = | | | | --V.conj-- ---- is true """ VdaggerV=ncon([V,V.conj()],([1,2,-1],[1,2,-2])) return np.allclose(VdaggerV,np.eye(V.shape[2])) def create_random_tensors(N,chi,d=2): """ N (int): number of sites d (int): physical dimension. Default = qubits chi (int): bond dimension Creates a list of N random complex tensors with bond dimension chi and physical dimension d each """ A=[] for _ in range(N): A.append(np.random.rand(d,chi,chi)+1j*np.random.rand(d,chi,chi)) return A def convert_to_isometry(A,phi_initial,phi_final): """ Input: A (list): list of tensors of shape (d, chi, chi) phi_initial (vector): (chi,1) phi_final (vector): (chi,1) Takes as input an MPS of the form PSI = phi_final - A_N - A_{N-1} - ... - A_1 - phi_initial | | | and creates a list of isometries V_1, ... V_N and new vectors phi_initial_out and phi_final_out,s.t. PSI = phi_final' - V_N - V_{N-1} - ... - V_1 - phi_final_out | | | the Vs are isometries in the sense that ---V------ ---- | | | | | = | | | | --V.conj-- ---- Return: isometries (list): list of isometric tensors that generates the same state phi_initial (vector): bew right boundary phi_final (vector): bew left boundary Ms (list): list of intermediary Schmidt matrices """ N=len(A) chi=A[0].shape[1] d=A[0].shape[0] #Construct isometries from N to 1 A=A[::-1] """ SVD: phi_final - A_N - 2 = U_N - M_N - 2 | | 1 1 then append phi_final to disentangle 2-U_N-3 = 2-phi_final U_N - 3 | | 1 1 """ left_hand_side=ncon([phi_final,A[0]],([1],[-1,1,-2])) U,S,VH=np.linalg.svd(left_hand_side,full_matrices=True) S=np.append(S,np.zeros(max(0,chi-S.shape[0]))) M=np.dot(np.diag(S),VH) Ms=[M] U=ncon([U,phi_final],([-1,-3],[-2])) U=U.reshape(chi*d,d) U=embed_isometry(U,defect=chi*(d-1)) #First unitary can have dimension d<chi, so add orthogonal vectors isometries=[U] """ from N to 1, SVD successively: 2 - M_k - V_{k-1} - 3 = 2- U_{k-1} - M_{k-1} - 3 | | 1 1 """ for k in range(1,N): left_hand_side=ncon([M,A[k]],([-2,1],[-1,1,-3])) left_hand_side=left_hand_side.reshape(chi*d,chi) U,S,VH=np.linalg.svd(left_hand_side,full_matrices=False) M=np.dot(np.diag(S),VH) Ms.append(M) isometries.append(U) phi_initial_out=np.dot(M,phi_initial) phi_final_out=phi_final isometries=isometries[::-1] Ms=Ms[::-1] return isometries, phi_initial_out, phi_final_out, Ms def create_statevector(A,phi_initial,phi_final,qiskit_ordering=False): """ INPUT: A (list): list of N MPS tensors of size (d,chi,chi) phi_initial (vector): right boundary condition of size (chi,1) phi_final (vector): left boundary condition of size (chi,1) RETURNS: Psi(vector): the vector phi_final - A_N - A_{N-1} - ... - A_1 - phi_initial | | | N N-1 1 [N.B.: Reversed Qiskit Ordering] B L O C K E D schmidt_matrix (array, optional): the matrix 2 - A_N - A_{N-1} - ... - A_1 - phi_initial | | | 1 This is useful to check, for the unitary MPS, if after the application of A_N, the state is a product state between ancilla and physical space (the schmidt_matrix has rank 1 in this case). This must be the case, in order to implement successfully on the quantum computer. """ N=len(A) chi=A[0].shape[1] d=A[0].shape[0] Psi=ncon([phi_initial, A[0]], ([1],[-1,-2,1])) for i in range(1,N): Psi=ncon([Psi,A[i]],([-1,1],[-2,-3,1])) Psi=Psi.reshape((d**(i+1),chi)) if qiskit_ordering: Psi=Psi.reshape(np.append(d*np.ones(N,dtype=int),chi)) Psi=ncon([Psi],-np.append(list(range(N,0,-1)),N+1)) Psi=Psi.reshape(d**N,chi) schmidt_matrix=Psi Psi=np.dot(Psi,phi_final) return Psi, schmidt_matrix def isunitary(U): """ INPUT: U (array) OUPUT: flag (bool) """ if np.allclose(np.eye(len(U)), U.dot(U.T.conj())): return True else: return False def isometry_to_unitary(V): """ INPUT: V(tensor): tensor with indices 2-V-3 | 1 that is isometric in the sense that ---V------ ---- | | | | | = | | | | --V.conj-- ---- OUTPUT: U(matrix): unitary matrix that fulfills |0> | -U- = -V- | | with leg ordering 3 | 2-U-4 | 1 """ chi=V.shape[1] d=V.shape[0] Vp=V.reshape(chi*d,chi) W=complement(Vp) U=np.zeros((chi*d,d,chi),dtype=np.complex128) U[:,0,:]=Vp U[:,1,:]=W U=U.reshape(chi*d,chi*d) return U def MPS_to_circuit(A, phi_initial, phi_final): """ INPUT: A (list): list of N MPS tensors of size (d,chi,chi) phi_initial (vector): right boundary condition of size (chi,1) phi_final (vector): left boundary condition of size (chi,1) keep_ancilla (bool, optional): the MPS is generated via an ancilla that disentangles at the end of the procedure. By default, the ancilla is measured out and thrown away at the end. Set to True to keep the ancilla (in the first ceil(log(chi)) qubits) OUTPUT: qc(QuantumCircuit): the circuit that produces the MPS q0...qn phi_final - A_{N-1} - A_{N-2} - ... - A_0 - phi_initial | | | q_{n+N} q_{n+N-1} q_{n+1} where n = ceil(log2(chi)) is the number of ancilla qubits reg(QuantumRegister): the register in which the MPS wavefunction sits (to distinguish from the ancilla) N.B. By construction, after applying qc the system will be in a product state between the first ceil(log2(chi)) qubits and the rest. Those first qubits form the ancilla register and the remaining qubits are in the QuantumRegister 'reg'. The ancilla is guaranteed to be in phi_final. """ N=len(A) chi=A[0].shape[1] d=A[0].shape[0] #Normalize boundary conditions phi_final=phi_final/np.linalg.norm(phi_final) phi_initial=phi_initial/np.linalg.norm(phi_initial) #Convert MPS to isometric form Vs,phi_initial_U,phi_final_U,Ms=convert_to_isometry(A,phi_initial,phi_final) #Construct circuit n_ancilla_qubits=int(np.log2(chi)) ancilla = QuantumRegister(n_ancilla_qubits) reg = QuantumRegister(N) qc=QuantumCircuit(ancilla,reg) phi_initial_U=phi_initial_U/np.linalg.norm(phi_initial_U) qc.initialize(phi_initial_U,range(n_ancilla_qubits)) for i in range(N): qubits=list(range(n_ancilla_qubits)) qubits.append(i+n_ancilla_qubits) qc.unitary(Operator(isometry_to_unitary(Vs[i].reshape(d,chi,chi))), qubits) return qc, reg
https://github.com/sebasmos/QuantumVE
sebasmos
import numpy as np import qiskit.pulse as pulse from qiskit.circuit import Parameter from qiskit_experiments.calibration_management.backend_calibrations import BackendCalibrations from qiskit import IBMQ, schedule API_KEY = "5bd4ecfdc74e6680da7c79998259781431661e5326ae2f88eea95dee8f74b87530ba63fbca8105404de4ffd36e4b484631907acff73c805580928218a5ccf0b3" import qiskit as q from qiskit import IBMQ,schedule import numpy as np import qiskit.pulse as pulse from qiskit.circuit import Parameter from qiskit_experiments.calibration_management.backend_calibrations import BackendCalibrations %matplotlib inline import sys sys.path.insert(0, '..') # Add qiskit_runtime directory to the path IBMQ.save_account(API_KEY) # Details in: https://qiskit.org/documentation/install.html IBMQ.save_account(API_KEY, overwrite=True) IBMQ.load_account() provider = IBMQ.get_provider("ibm-q") for backend in provider.backends(): try: qubit_count = len(backend.properties().quibits) except: qubit_count = "simulated" print(f"{backend.name()} has {backend.status().pending_jobs} queued and { qubit_count} qubits") qubit = 0 # The qubit we will work with def setup_cals(backend) -> BackendCalibrations: """A function to instantiate calibrations and add a couple of template schedules.""" cals = BackendCalibrations(backend) dur = Parameter("dur") amp = Parameter("amp") sigma = Parameter("σ") beta = Parameter("β") drive = pulse.DriveChannel(Parameter("ch0")) # Define and add template schedules. with pulse.build(name="xp") as xp: pulse.play(pulse.Drag(dur, amp, sigma, beta), drive) with pulse.build(name="xm") as xm: pulse.play(pulse.Drag(dur, -amp, sigma, beta), drive) with pulse.build(name="x90p") as x90p: pulse.play(pulse.Drag(dur, Parameter("amp"), sigma, Parameter("β")), drive) cals.add_schedule(xp) cals.add_schedule(xm) cals.add_schedule(x90p) return cals def add_parameter_guesses(cals: BackendCalibrations): """Add guesses for the parameter values to the calibrations.""" for sched in ["xp", "x90p"]: cals.add_parameter_value(80, "σ", schedule=sched) cals.add_parameter_value(0.5, "β", schedule=sched) cals.add_parameter_value(320, "dur", schedule=sched) cals.add_parameter_value(0.5, "amp", schedule=sched) cals = setup_cals(backend) add_parameter_guesses(cals) from qiskit_experiments.calibration_management.basis_gate_library import FixedFrequencyTransmon library = FixedFrequencyTransmon(default_values={"duration": 320}) cals = BackendCalibrations(backend, library) from qiskit_experiments.library.characterization.qubit_spectroscopy import QubitSpectroscopy import pandas as pd pd.DataFrame(cals.parameters_table(qubit_list=[qubit, ()])) freq01_estimate = backend.defaults().qubit_freq_est[qubit] frequencies = np.linspace(freq01_estimate -15e6, freq01_estimate + 15e6, 51) spec = QubitSpectroscopy(qubit, frequencies) spec.set_experiment_options(amp=0.1) circuit = spec.circuits(backend)[0] circuit.draw(output="mpl") schedule(circuit, backend).draw() spec_data = spec.run(backend) spec_data.block_for_results() spec_data.figure(0) print(spec_data.analysis_results("f01")) from qiskit_experiments.calibration_management.update_library import Frequency Frequency.update(cals, spec_data) pd.DataFrame(cals.parameters_table(qubit_list=[qubit])) from qiskit_experiments.library.calibration import Rabi from qiskit_experiments.calibration_management.update_library import Amplitude rabi = Rabi(qubit) rabi.set_experiment_options( amplitudes=np.linspace(-0.95, 0.95, 51), schedule=cals.get_schedule("x", (qubit,), assign_params={"amp": Parameter("amp")}), ) rabi_data = rabi.run(backend) rabi_data.block_for_results() rabi_data.figure(0) print(rabi_data.analysis_results("rabi_rate")) Amplitude.update(cals, rabi_data, angles_schedules=[(np.pi, "amp", "x"), (np.pi/2, "amp", "sx")]) pd.DataFrame(cals.parameters_table(qubit_list=[qubit, ()], parameters="amp")) cals.get_schedule("sx", qubit) cals.get_schedule("x", qubit) cals.get_schedule("y", qubit) cals.save(file_type="csv", overwrite=True, file_prefix="Armonk") cals = BackendCalibrations(backend, library) cals.load_parameter_values(file_name="Armonkparameter_values.csv") pd.DataFrame(cals.parameters_table(qubit_list=[qubit, ()], parameters="amp")) from qiskit_experiments.library.calibration.drag import DragCal from qiskit_experiments.calibration_management.update_library import Drag cal_drag = DragCal(qubit) cal_drag.set_experiment_options( rp=cals.get_schedule("x", qubit, assign_params={"β": Parameter("β")}), betas=np.linspace(-20, 20, 25), reps=[3, 5, 7] ) cal_drag.circuits(backend)[1].draw(output='mpl') drag_data = cal_drag.run(backend) drag_data.block_for_results() drag_data.figure(0) print(drag_data.analysis_results("beta")) Drag.update(cals, drag_data, parameter="β", schedule="x") pd.DataFrame(cals.parameters_table(qubit_list=[qubit, ()], parameters="β")) from qiskit_experiments.library.calibration.fine_amplitude import FineXAmplitude from qiskit_experiments.calibration_management.update_library import Amplitude amp_x_cal = FineXAmplitude(qubit) amp_x_cal.set_experiment_options(schedule=cals.get_schedule("x", qubit)) amp_x_cal.circuits(backend)[5].draw(output="mpl") data_fine = amp_x_cal.run(backend) data_fine.block_for_results() data_fine.figure(0) print(data_fine.analysis_results("d_theta")) dtheta = data_fine.analysis_results("d_theta").value.value target_angle = np.pi scale = target_angle / (target_angle + dtheta) pulse_amp = cals.get_parameter_value("amp", qubit, "x") print(f"The ideal angle is {target_angle:.2f} rad. We measured a deviation of {dtheta:.3f} rad.") print(f"Thus, scale the {pulse_amp:.4f} pulse amplitude by {scale:.3f} to obtain {pulse_amp*scale:.5f}.") Amplitude.update(cals, data_fine, angles_schedules=[(target_angle, "amp", "x")]) pd.DataFrame(cals.parameters_table(qubit_list=[qubit, ()], parameters="amp")) amp_x_cal.set_experiment_options(schedule=cals.get_schedule("x", qubit)) data_fine2 = amp_x_cal.run(backend) data_fine2.block_for_results() data_fine2.figure(0) print(data_fine2.analysis_results("d_theta")) from qiskit_experiments.library.calibration.fine_amplitude import FineSXAmplitude amp_sx_cal = FineSXAmplitude(qubit) amp_sx_cal.set_experiment_options(schedule=cals.get_schedule("sx", qubit)) amp_sx_cal.circuits(backend)[5].draw(output="mpl") data_fine_sx = amp_sx_cal.run(backend) data_fine_sx.block_for_results() data_fine_sx.figure(0) print(data_fine_sx.analysis_results("d_theta")) Amplitude.update(cals, data_fine_sx, angles_schedules=[(np.pi/2, "amp", "sx")]) pd.DataFrame(cals.parameters_table(qubit_list=[qubit, ()], parameters="amp")) cals.get_schedule("sx", qubit) cals.get_schedule("x", qubit) cals.get_schedule("y", qubit) import qiskit.tools.jupyter %qiskit_copyright
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# -*- 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/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ QasmSimulator reset error NoiseModel integration tests """ from test.terra.utils.utils import list2dict from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors.standard_errors import reset_error # Backwards compatibility for Terra <= 0.13 if not hasattr(QuantumCircuit, 'i'): QuantumCircuit.i = QuantumCircuit.iden # ========================================================================== # Reset Gate Errors # ========================================================================== def reset_gate_error_circuits(): """Reset gate error noise model circuits""" circuits = [] # 50% reset to 0 state on qubit 0 qr = QuantumRegister(2, 'qr') cr = ClassicalRegister(2, 'cr') circuit = QuantumCircuit(qr, cr) circuit.x(qr) circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # 25% reset to 0 state on qubit 1 qr = QuantumRegister(2, 'qr') cr = ClassicalRegister(2, 'cr') circuit = QuantumCircuit(qr, cr) circuit.x(qr) circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # 100% reset error to 0 on all qubits qr = QuantumRegister(1, 'qr') cr = ClassicalRegister(1, 'cr') circuit = QuantumCircuit(qr, cr) circuit.x(qr) circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # 100% reset error to 1 on all qubits qr = QuantumRegister(1, 'qr') cr = ClassicalRegister(1, 'cr') circuit = QuantumCircuit(qr, cr) circuit.i(qr) circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # 25% reset error to 0 and 1 on all qubits qr = QuantumRegister(2, 'qr') cr = ClassicalRegister(2, 'cr') circuit = QuantumCircuit(qr, cr) circuit.i(qr[0]) circuit.x(qr[1]) circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def reset_gate_error_noise_models(): """Reset gate error noise models""" noise_models = [] # 50% reset to 0 state on qubit 0 error = reset_error(0.5) noise_model = NoiseModel() noise_model.add_quantum_error(error, 'x', [0]) noise_models.append(noise_model) # 25% reset to 0 state on qubit 1 error = reset_error(0.25) noise_model = NoiseModel() noise_model.add_quantum_error(error, 'x', [1]) noise_models.append(noise_model) # 100% reset error to 0 on all qubits error = reset_error(1) noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(error, ['id', 'x']) noise_models.append(noise_model) # 100% reset error to 1 on all qubits error = reset_error(0, 1) noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(error, ['id', 'x']) noise_models.append(noise_model) # 25% reset error to 0 and 1 on all qubits error = reset_error(0.25, 0.25) noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(error, ['id', 'x']) noise_models.append(noise_model) return noise_models def reset_gate_error_counts(shots, hex_counts=True): """Reset gate error circuits reference counts""" counts_lists = [] # 50% reset to 0 state on qubit 0 counts = [0, 0, shots / 2, shots / 2] counts_lists.append(counts) # 25% reset to 0 state on qubit 1 counts = [0, shots / 4, 0, 3 * shots / 4] counts_lists.append(counts) # 100% reset error to 0 on all qubits counts = [shots, 0, 0, 0] counts_lists.append(counts) # 100% reset error to 1 on all qubits counts = [0, shots, 0, 0] counts_lists.append(counts) # 25% reset error to 0 and 1 on all qubits counts = [3 * shots / 16, shots / 16, 9 * shots / 16, 3 * shots / 16] counts_lists.append(counts) # Convert to counts dict return [list2dict(i, hex_counts) for i in counts_lists]
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(2) #Defining qubits c = ClassicalRegister(2) #Defining bits qc = QuantumCircuit(q, c) #Making a Circuit #Entanglement qc.h(q[0]) #Hadamard Gate qc.cx(q[0], q[1]) #CNOT Gate (Control on 1st qubit and target on 2nd qubit) qc.measure(q, c) #Measure qubits to bits qc.draw('mpl') qc.draw('text') qc.draw('latex')
https://github.com/adarsh1chand/Qiskit-Mentorship-Program-2021
adarsh1chand
import numpy as np #Operator Imports from qiskit import QuantumRegister, QuantumCircuit from qiskit.opflow import X, Y, Z, I, Zero, StateFn, CircuitStateFn, SummedOp, ListOp, PauliExpectation, PauliSumOp from qiskit.opflow.gradients import Gradient, Hessian from qiskit.circuit import Parameter from qiskit.utils import QuantumInstance from qiskit_machine_learning.neural_networks import OpflowQNN from qiskit.aqua.components.optimizers import ADAM, AQGD, COBYLA # imports to plot stuff import matplotlib.pyplot as plt from IPython.display import display plt.style.use('dark_background') class QuantumODESolver(object): """ Main Class for the ODE solver using Hybrid Classical-Quantum neural network. Instantiate this class to use the solver. Implementation of the following paper: arXiv:2011.10395v2 in Qiskit. >> Developed as part of Qiskit Mentorship Program 2021 (Project #32: Solving Navier-Stokes equations using Qiskit for Water Management.) << Init Parameters --------------- num_qubits : Number of qubits in the quantum register of the quantum model circuit. variational_layers : Number of variational layers in the model circuit. encoder_layers : Number of encoder layers in the model circuit. """ def __init__(self, num_qubits = 1, variational_layers = 1, encoder_layers = 1): self.num_qubits = num_qubits self.encoder_layers = encoder_layers self.variational_layers = variational_layers self.encoder_symbols = [] self.unitary_symbols = [] self.model_circuit = QuantumCircuit(self.num_qubits) self.model = None self.measure_op = None self.gradient_op = None # Construct encoder block of the model self.construct_encoder() # Construct variational block of the model #self.construct_variational_ansatz() # Get measurement observable self.get_measurement_observable() # Forming combined model self.compile_model() print("Model compiled...........................") # Initialize unitary parameters self.unitary_params = np.random.random(size = (len(self.unitary_symbols), )) # Initialize gradient op of the model circuit self.gradient_op = Gradient(grad_method = 'fin_diff').convert(operator = self.model, params = (self.encoder_symbols)) def construct_encoder(self): """ Apply Quantum Feature map (Chebyshev sparse encoding) to the final model circuit. Feel free to change the code below to implement other quantum feature maps. Parameters ---------- None Returns ------- None """ self.encoder_block = QuantumCircuit(self.num_qubits, name = 'Encoder Block') x = Parameter('x') self.encoder_symbols.append(x) for i in range(self.num_qubits): self.encoder_block.ry(2 * (i+1) * np.arccos(x), i) #print("Encoder Block------------------------------------") #display(self.encoder_block.draw(output = 'mpl')) return def construct_variational_ansatz(self, layer): """ Apply Hardware-efficient ansatz as the variational block in the final model circuit. Feel free to change the code below to implement different architectures for the variational part of the model circuit. Parameters ---------- layer : Layer number of the variational block to be created. To differentiate between the subsequent layers of the same variational block, if the same block is repeated. If layer is same for two blocks, then the two blocks will have the same values for the unitary parameters. Returns ------- None """ self.variational_block = QuantumCircuit(self.num_qubits, name = 'Variational Block ' + str(layer + 1)) # First, we apply Wall of unitaries for i in range(self.num_qubits): theta_z0 = Parameter('theta_z0' + str(i) + str(layer)) self.unitary_symbols.append(theta_z0) theta_x = Parameter('theta_x' + str(i) + str(layer)) self.unitary_symbols.append(theta_x) theta_z1 = Parameter('theta_z1'+ str(i) + str(layer)) self.unitary_symbols.append(theta_z1) self.variational_block.rz(theta_z0, i) self.variational_block.rx(theta_x, i) self.variational_block.rz(theta_z1, i) # Next, we apply Entanglement wall (in a cyclic fashion, joining immediate neighbours) for i in range(1, self.num_qubits): self.variational_block.cx(i - 1, i) #if num_qubits > 1: # self.variational_block.cx(self.num_qubits-1, 0) #print("Variational block--------------------------------") #display(self.variational_block.draw(output = 'mpl')) return def get_measurement_observable(self): """ Construct operator for measurement of expectation value of the final model circuit. Note, can be any quantum circuit, but for now considering only the total magnetic spin of the quantum register. Feel free to change this functin as per design choice. Parameters ---------- None Returns ------- None """ self.measure_op = None for i in range(self.num_qubits): block = None for j in range(self.num_qubits): if j == i: if block is None: block = Z else: block = Z ^ block else: if block is None: block = I else: block = I ^ block if self.measure_op is None: self.measure_op = block else: self.measure_op = self.measure_op + block #print("Measurement op \n, ", self.measure_op) return def compile_model(self): """ Compile (concatenate) the variational blocks and encoder blocks to get the final model circuit expectation operator. Feel free to change the code of this function to change the overall architecture of the quantum model circuit (i.e, whether or not to repeat variational or encoder blocks ("Data re-uploading") etc.) Parameters ---------- None Returns ------- None """ measure = self.convert_to_statefn(self.measure_op, is_measurement = True) for i in range(self.encoder_layers): if i == 0: self.construct_variational_ansatz(layer = i) self.model_circuit.append(self.variational_block, range(self.num_qubits)) self.model_circuit.append(self.encoder_block, range(self.num_qubits)) self.construct_variational_ansatz(layer = self.encoder_layers) self.model_circuit.append(self.variational_block, range(self.num_qubits)) self.model = PauliExpectation().convert(measure @ CircuitStateFn(self.model_circuit)) return def convert_to_statefn(self, obj, is_measurement = False): """ Convert obj to StateFn, throws exception if cannot convert. """ try: if is_measurement: return ~StateFn(obj) else: return StateFn(obj) except Exception as err: print("Cannot convert object of type {} to StateFn ".format(type(obj))) print("Complete error log is as follows-------------") print(">> {} <<".format(err)) return def resolve_parameters(self, data, param_values): """ Resolves the parameter values for free parameters in the final model circuit. Parameters ---------- data : Classical data that goes into the encoder block. param_values : Parameter values for the free parameter in the unitary block. Returns ------- A dictionary that maps each free parameter in the final model circuit (encoder blocks + unitary blocks) to corresponding value. The output of this function can directly be used to bind parameter values in the model circuit operator (if successful). """ param_dict = {} data = np.array(data) if len(param_values.shape) == 1: param_values = list(param_values) else: param_values = list(param_values.flatten()) data_size = data.shape[0] model_param_values = [] model_param_vars = [] if data.shape[-1] != len(self.encoder_symbols) and len(data.shape) != len(self.encoder_symbols): print("Dimensionality of data does not match the number of free parameters for encoding data in the model circuit") return if len(param_values) != len(self.unitary_symbols): print(len(self.unitary_symbols)) print(len(param_values)) print("Number of param values supplied not equal to number of free parameters in the unitary blocks of the model circuit") return for var in self.encoder_symbols: model_param_vars.append(var) if len(data.shape) == 1: model_param_values.append(list(data)) else: for p in data: model_param_values.append(list(p)) #print("After resolving encoder params : ", model_param_values) for param in param_values: model_param_values.append([param] * data_size) #print("After resolving unitary params : ", model_param_values) for var in self.unitary_symbols: model_param_vars.append(var) param_dict = dict(zip(model_param_vars, model_param_values)) if len(param_dict.keys()) != len(self.encoder_symbols) + len(self.unitary_symbols): print("Resolving of parameters failed, check the number of parameter values passes for resolving !!") print("Number of free parameters : {}".format(len(self.encoder_symbols) + len(self.unitary_symbols))) print("Number of resolved params : {}".format(len(param_dict.keys()))) print(param_dict) return return param_dict def predict(self, data, param_values = None, is_training = False, verbose = False): """ Get expectation value and gradient at each data point from the model circuit. Parameters ---------- data: Classical Grid points which is to be encoded as input in the quantum model. param_values : (Optional) Parameter values for the unitary block parameters at which the model output should be evaluated. If not provided by user, it fills this variable with already stored parameter values in the object of QuantumODESolver class. is_training : Boolean flag to denote whether the call to this function is being made at the time of training. If True, then the function outputs both solution of the differential equation at grid points x and the corresponding gradients of the solution function at those points. If False, it just outputs the evaulated solution at grid points. verbose : (Optional) To print every predict function call output in each iteration of optimizer. Useful to check how many calls the optimizer makes to the predict function. Returns ------- Either two lists of solution values at grid points x and corresponding gradients at those points, or simply a list of solution values at grid points x. """ batch_size = 1 exp_values = [] grad_values = [] if param_values is None: param_values = self.unitary_params param_values = np.array(param_values).flatten() if len(param_values) == len(self.unitary_params): param_values = param_values[np.newaxis, :] else: if len(param_values.flatten()) % len(self.unitary_params) != 0: print("Cannot reshape the parameter values provided into shape = ({}, )".format(len(self.unitary_params))) sys.exit() batch_size = int(len(param_values.flatten()) / len(self.unitary_params)) param_values = np.reshape(param_values, newshape = (batch_size, len(self.unitary_params))) # Predicting for each batch of parameters supplied for batch in range(batch_size): batch_exp_value = None batch_grad_value = None if verbose: print("Predicting for batch {} / {}".format((batch + 1), batch_size), end = '\r') batch_param_values = param_values[batch] param_dict = self.resolve_parameters(data, batch_param_values) if param_dict is None: print("Prediction failed for batch {} / {}...".format((batch + 1), batch_size)) sys.exit() batch_exp_value = self.model.bind_parameters(param_dict) batch_exp_value = np.real(batch_exp_value.eval()).flatten() / self.num_qubits exp_values.append(list(batch_exp_value)) if is_training: batch_grad_value = np.real(self.gradient_op.bind_parameters(param_dict).eval()).flatten() grad_values.append(list(batch_grad_value)) if is_training: return exp_values, grad_values else: return exp_values def solution(self, x, param_values = None, is_training = False, verbose = False): """ Internally calls the predict function and outputs the value of solution for given array points in the arguments. Also takes care of the floating boundary condition. Parameters ---------- x : Numpy array of data grid points at which the solution (function that solves the required differential equation) needs to be evaluated. param_values : (Optional) Parameter values for the unitary block parameters at which the model output should be evaluated. If not provided by user, it fills this variable with already stored parameter values in the object of QuantumODESolver class. is_training : Boolean flag to denote whether the call to this function is being made at the time of training. If True, then the function outputs both solution of the differential equation at grid points x and the corresponding gradients of the solution function at those points. If False, it just outputs the evaulated solution at grid points. verbose : (Optional) To print every predict function call output in each iteration of optimizer. Useful to check how many calls the optimizer makes to the predict function. Returns ------- Either two lists of solution values at grid points x and corresponding gradients at those points, or simply a list of solution values at grid points x. """ u, du_dx = self.predict(x, param_values, is_training = True, verbose = verbose) # Floating boundary condition bc = self.predict(np.array([0.0]), param_values, verbose = verbose) # Reshaping arrays u = np.array(u) bc = np.array(bc) du_dx = np.array(du_dx) u = np.reshape(u, newshape = (u.shape[1], u.shape[0])) bc = np.reshape(bc, newshape = (bc.shape[1], bc.shape[0])) du_dx = np.reshape(du_dx, newshape = (du_dx.shape[1], du_dx.shape[0])) # With floating boundary condition, the value of function itself is defined in such a way # that the boundary condition is always satisfied irrespective of the model (quantum circuit's) output. u = np.array([1] * u.shape[1]) - bc + u if is_training: return u, du_dx else: return u def fit(self, x, y = None, epochs = 20, batch_size = 5, lr = 0.05, optimizer_maxiter = 5, verbose = False): """ Fit function for the quantum model used to train the model. Feel free to change the loss function method inside as per the differential equation required to solve. Parameters ---------- x : Numpy array of data grid points at which the model is fitted. y : (Optional) values which can be further used to define boundary conditions or initial conditions. Default to None. epochs : Number of epochs for which the model should be trained. batch_size : Number of data grid points to be taken in a single batch of training. Note, that the update to the parameter happens for each batch rather than at the end of epoch. lr : learning rate used for the ADAM optimizer. Not required if some other optimizer is chosen. optimizer_maxiter : Max iterations for which a single batch of training data should be used to update the parameter values. This parameter is passed to the optimizer (currently implemented for ADAM). verbose : (Optional) To print every loss function call output in each iteration of optimizer. Useful to check how many calls the optimizer makes to the loss function. Returns ------- List of parameter values after the model is trained. """ def loss_function(param_values): # get function value (f(x)) and gradients at points specified (array 'x' above) u, du_dx = self.solution(curr_batch, param_values, is_training = True, verbose = verbose) # Change the line below as per the differential equation required to solve # Following differential equation is taken from arXiv:2011.10395v2 loss = np.mean(np.log((du_dx + 20 * u *(0.1 + np.tan(20 * u))) ** 2), axis = 0) return loss epoch = 0 batch_start_idx = 0 curr_batch = x epoch_end = False print("Initial Loss : {}".format(loss_function(param_values = None))) print("Initial unitary params : {}".format(self.unitary_params)) print("Initial learning rate : {}".format(lr)) print("Training Begins...........................................................................................") while(epoch < epochs): epoch_loss = 0.0 batch_start_idx = 0 curr_batch = None epoch_end = False while(not epoch_end): print("Training for Batch {} / {}".format(int(batch_start_idx / batch_size) + 1, int(np.ceil(len(x) / batch_size))), end = '\r') curr_batch = x[batch_start_idx : min(batch_start_idx + batch_size, len(x))] self.unitary_params, epoch_loss , _ = ADAM(maxiter = optimizer_maxiter, lr = lr).optimize(len(self.unitary_symbols), loss_function, initial_point = self.unitary_params) if min(batch_start_idx + batch_size, len(x)) == len(x): epoch_end = True else: batch_start_idx += batch_size curr_batch = x print("Epoch : {}, Current Loss : {}".format((epoch + 1), loss_function(param_values = None))) print("Updated param values: ", self.unitary_params) print("Current learning rate : {}".format(lr)) print("-------------------------------------------------------------------------------------------------------") epoch += 1 #lr = (epoch + 1) * (1e-02 - 1e-04)/(epochs) return self.unitary_params def __call__(self): print("This model is constructed for-----") print("Number of qubits : {}".format(self.num_qubits)) print("Number of layers (depth) : For encoder block - {}, For variational block - {}".format(self.encoder_layers, self.variational_layers)) print("Structure of encoder block-----") display(self.encoder_block.draw(output = 'mpl')) print("Structure of variational block-----") display(self.variational_block.draw(output = 'mpl')) print("Complete model circuit looks like : ") display(self.model_circuit.draw(output = 'mpl')) print("Number of variational parameters : {}".format(len(self.unitary_symbols))) print("Number of encoder parameters : {}".format(len(self.encoder_symbols))) # Defining the solver architecture num_qubits = 6 enc_layers = 5 var_layers = 1 # Creating data grid points X = np.linspace(0, 0.9, 20) # Instantiating the solver solver = QuantumODESolver(num_qubits, var_layers, enc_layers) # Summary of model architecture solver() # Training the solver solver.fit(X, verbose = False) # Testing the solver X_test = np.linspace(0, 0.9, 30) predicted = solver.solution(X_test) plt.plot(X_test, np.exp(-20 * 0.1 * X_test) * np.cos(20 * X_test), c = 'yellow') plt.plot(X_test, predicted, c = 'blue') plt.show()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from __future__ import annotations import numpy as np import networkx as nx num_nodes = 4 w = np.array([[0., 1., 1., 0.], [1., 0., 1., 1.], [1., 1., 0., 1.], [0., 1., 1., 0.]]) G = nx.from_numpy_array(w) layout = nx.random_layout(G, seed=10) colors = ['r', 'g', 'b', 'y'] nx.draw(G, layout, node_color=colors) labels = nx.get_edge_attributes(G, 'weight') nx.draw_networkx_edge_labels(G, pos=layout, edge_labels=labels); def objective_value(x: np.ndarray, w: np.ndarray) -> float: """Compute the value of a cut. Args: x: Binary string as numpy array. w: Adjacency matrix. Returns: Value of the cut. """ X = np.outer(x, (1 - x)) w_01 = np.where(w != 0, 1, 0) return np.sum(w_01 * X) def bitfield(n: int, L: int) -> list[int]: result = np.binary_repr(n, L) return [int(digit) for digit in result] # [2:] to chop off the "0b" part # use the brute-force way to generate the oracle L = num_nodes max = 2**L sol = np.inf for i in range(max): cur = bitfield(i, L) how_many_nonzero = np.count_nonzero(cur) if how_many_nonzero * 2 != L: # not balanced continue cur_v = objective_value(np.array(cur), w) if cur_v < sol: sol = cur_v print(f'Objective value computed by the brute-force method is {sol}') from qiskit.quantum_info import Pauli, SparsePauliOp def get_operator(weight_matrix: np.ndarray) -> tuple[SparsePauliOp, float]: r"""Generate Hamiltonian for the graph partitioning Notes: Goals: 1 Separate the vertices into two set of the same size. 2 Make sure the number of edges between the two set is minimized. Hamiltonian: H = H_A + H_B H_A = sum\_{(i,j)\in E}{(1-ZiZj)/2} H_B = (sum_{i}{Zi})^2 = sum_{i}{Zi^2}+sum_{i!=j}{ZiZj} H_A is for achieving goal 2 and H_B is for achieving goal 1. Args: weight_matrix: Adjacency matrix. Returns: Operator for the Hamiltonian A constant shift for the obj function. """ num_nodes = len(weight_matrix) pauli_list = [] coeffs = [] shift = 0 for i in range(num_nodes): for j in range(i): if weight_matrix[i, j] != 0: x_p = np.zeros(num_nodes, dtype=bool) z_p = np.zeros(num_nodes, dtype=bool) z_p[i] = True z_p[j] = True pauli_list.append(Pauli((z_p, x_p))) coeffs.append(-0.5) shift += 0.5 for i in range(num_nodes): for j in range(num_nodes): if i != j: x_p = np.zeros(num_nodes, dtype=bool) z_p = np.zeros(num_nodes, dtype=bool) z_p[i] = True z_p[j] = True pauli_list.append(Pauli((z_p, x_p))) coeffs.append(1.0) else: shift += 1 return SparsePauliOp(pauli_list, coeffs=coeffs), shift qubit_op, offset = get_operator(w) from qiskit.algorithms.minimum_eigensolvers import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit.primitives import Sampler from qiskit.quantum_info import Pauli, Statevector from qiskit.result import QuasiDistribution from qiskit.utils import algorithm_globals sampler = Sampler() def sample_most_likely(state_vector: QuasiDistribution | Statevector) -> np.ndarray: """Compute the most likely binary string from state vector. Args: state_vector: State vector or quasi-distribution. Returns: Binary string as an array of ints. """ if isinstance(state_vector, QuasiDistribution): values = list(state_vector.values()) else: values = state_vector n = int(np.log2(len(values))) k = np.argmax(np.abs(values)) x = bitfield(k, n) x.reverse() return np.asarray(x) algorithm_globals.random_seed = 10598 optimizer = COBYLA() qaoa = QAOA(sampler, optimizer, reps=2) result = qaoa.compute_minimum_eigenvalue(qubit_op) x = sample_most_likely(result.eigenstate) print(x) print(f'Objective value computed by QAOA is {objective_value(x, w)}') from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit.quantum_info import Operator npme = NumPyMinimumEigensolver() result = npme.compute_minimum_eigenvalue(Operator(qubit_op)) x = sample_most_likely(result.eigenstate) print(x) print(f'Objective value computed by the NumPyMinimumEigensolver is {objective_value(x, w)}') from qiskit.algorithms.minimum_eigensolvers import SamplingVQE from qiskit.circuit.library import TwoLocal from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 10598 optimizer = COBYLA() ansatz = TwoLocal(qubit_op.num_qubits, "ry", "cz", reps=2, entanglement="linear") sampling_vqe = SamplingVQE(sampler, ansatz, optimizer) result = sampling_vqe.compute_minimum_eigenvalue(qubit_op) x = sample_most_likely(result.eigenstate) print(x) print(f"Objective value computed by VQE is {objective_value(x, w)}") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# You can make the bars more transparent to better see the ones that are behind # if they overlap. import numpy as np from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_city from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0,1) qc.ry(np.pi/3, 0) qc.rx(np.pi/5, 1) state = Statevector(qc) plot_state_city(state, alpha=0.6)
https://github.com/MonitSharma/qiskit-projects
MonitSharma
#imports import qiskit import numpy as np from qiskit.visualization import plot_histogram # model class Model: simulator = qiskit.Aer.get_backend('qasm_simulator') def draw_current_circuit(self): print(self.add_circuit.draw()) # initialize 2 qubits def __init__(self): # TODO initialize with more friendly state vectors? self.circuit = qiskit.QuantumCircuit(2, 2) self.state1 = self.circuit.initialize(qiskit.quantum_info.random_statevector(2).data, 0) self.state2 = self.circuit.initialize(qiskit.quantum_info.random_statevector(2).data, 1) self.add_circuit = qiskit.QuantumCircuit(2) # Measure qubits and return state with max probability: ex. [0,1] def measureState(self): self.circuit.measure([0, 1], [1, 0]) job = qiskit.execute(self.circuit, self.simulator, shots=1) # 1 shot to keep it luck dependent? result = job.result() count = result.get_counts() # max_value = max(result.values()) # return [k for k,v in count.items() if v==1][0] return [int(list(count)[0][0]), int(list(count)[0][1])] # Return a probability coefficient of specific state # state is an array of size 2 which contains 0 or 1 # such as [0,1], [0,0], [1,0], [1,1] def getProbabilityOf(self, state): # to get state vector of qubit backend = qiskit.Aer.get_backend('statevector_simulator') result = qiskit.execute(self.circuit, backend).result() out_state = result.get_statevector() if state == [0, 0]: return out_state[0] elif state == [0, 1]: return out_state[1] elif state == [1, 0]: return out_state[2] else: return out_state[3] # Add a gate to the end of the circuit (at specified qubit) def add_unitary(self, name, qubit_no): if name == "H" or name == "h": self.add_circuit.h(qubit_no) elif name == "X" or name == "x": self.add_circuit.x(qubit_no) elif name == "Y" or name == "y": self.add_circuit.y(qubit_no) elif name == "Z" or name == "z": self.add_circuit.z(qubit_no) self.circuit += self.add_circuit def add_r_gate(self, parameter, qubit_no): self.add_circuit.rz(parameter, qubit_no) self.circuit += self.add_circuit def add_cnot(self, control_qubit_no, target_qubit_no): self.add_circuit.cx(control_qubit_no, target_qubit_no) self.circuit += self.add_circuit
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 library of integer comparison circuits.""" import unittest import numpy as np from ddt import ddt, data, unpack from qiskit.test.base import QiskitTestCase from qiskit import BasicAer, execute from qiskit.circuit import QuantumCircuit from qiskit.circuit.library import IntegerComparator @ddt class TestIntegerComparator(QiskitTestCase): """Test the integer comparator circuit.""" def assertComparisonIsCorrect(self, comp, num_state_qubits, value, geq): """Assert that the comparator output is correct.""" qc = QuantumCircuit(comp.num_qubits) # initialize circuit qc.h(list(range(num_state_qubits))) # set equal superposition state qc.append(comp, list(range(comp.num_qubits))) # add comparator # run simulation backend = BasicAer.get_backend("statevector_simulator") statevector = execute(qc, backend).result().get_statevector() for i, amplitude in enumerate(statevector): prob = np.abs(amplitude) ** 2 if prob > 1e-6: # equal superposition self.assertEqual(True, np.isclose(1.0, prob * 2.0**num_state_qubits)) b_value = f"{i:b}".rjust(qc.width(), "0") x = int(b_value[(-num_state_qubits):], 2) comp_result = int(b_value[-num_state_qubits - 1], 2) if geq: self.assertEqual(x >= value, comp_result == 1) else: self.assertEqual(x < value, comp_result == 1) @data( [1, 0, True], [1, 1, True], [2, -1, True], [3, 5, True], [3, 2, True], [3, 2, False], [4, 6, False], ) @unpack def test_fixed_value_comparator(self, num_state_qubits, value, geq): """Test the fixed value comparator circuit.""" # build the circuit with the comparator comp = IntegerComparator(num_state_qubits, value, geq=geq) self.assertComparisonIsCorrect(comp, num_state_qubits, value, geq) def test_mutability(self): """Test changing the arguments of the comparator.""" comp = IntegerComparator() with self.subTest(msg="missing num state qubits and value"): with self.assertRaises(AttributeError): print(comp.draw()) comp.num_state_qubits = 2 with self.subTest(msg="missing value"): with self.assertRaises(AttributeError): print(comp.draw()) comp.value = 0 comp.geq = True with self.subTest(msg="updating num state qubits"): comp.num_state_qubits = 1 self.assertComparisonIsCorrect(comp, 1, 0, True) with self.subTest(msg="updating the value"): comp.num_state_qubits = 3 comp.value = 2 self.assertComparisonIsCorrect(comp, 3, 2, True) with self.subTest(msg="updating geq"): comp.geq = False self.assertComparisonIsCorrect(comp, 3, 2, False) if __name__ == "__main__": unittest.main()
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
from qiskit import QuantumCircuit, QuantumRegister from qiskit.quantum_info import SparsePauliOp def heisenberg_hamiltonian( length: int, jx: float = 1.0, jy: float = 0.0, jz: float = 0.0 ) -> SparsePauliOp: terms = [] for i in range(length - 1): if jx: terms.append(("XX", [i, i + 1], jx)) if jy: terms.append(("YY", [i, i + 1], jy)) if jz: terms.append(("ZZ", [i, i + 1], jz)) return SparsePauliOp.from_sparse_list(terms, num_qubits=length) def state_prep_circuit(num_qubits: int, layers: int = 1) -> QuantumCircuit: qubits = QuantumRegister(num_qubits, name="q") circuit = QuantumCircuit(qubits) circuit.h(qubits) for _ in range(layers): for i in range(0, num_qubits - 1, 2): circuit.cx(qubits[i], qubits[i + 1]) circuit.ry(0.1, qubits) for i in range(1, num_qubits - 1, 2): circuit.cx(qubits[i], qubits[i + 1]) circuit.ry(0.1, qubits) return circuit length = 5 hamiltonian = heisenberg_hamiltonian(length, 1.0, 1.0) circuit = state_prep_circuit(length, layers=2) print(hamiltonian) circuit.draw("mpl") from qiskit_aer.primitives import Estimator estimator = Estimator(approximation=True) job = estimator.run(circuit, hamiltonian, shots=None) result = job.result() exact_value = result.values[0] print(f"Exact energy: {exact_value}") from qiskit_ibm_runtime import QiskitRuntimeService hub = "ibm-q-internal" group = "deployed" project = "default" service = QiskitRuntimeService(instance=f"{hub}/{group}/{project}") from qiskit_ibm_runtime import Estimator, Options, Session from qiskit.transpiler import CouplingMap backend = service.get_backend("simulator_statevector") # set simulation options simulator = { "basis_gates": ["id", "rz", "sx", "cx", "reset"], "coupling_map": list(CouplingMap.from_line(length + 1)), } shots = 10000 import math options = Options( simulator=simulator, resilience_level=0, ) with Session(service=service, backend=backend): estimator = Estimator(options=options) job = estimator.run(circuit, hamiltonian, shots=shots) result = job.result() experiment_value = result.values[0] error = abs(experiment_value - exact_value) variance = result.metadata[0]["variance"] std = math.sqrt(variance / shots) print(f"Estimated energy: {experiment_value}") print(f"Energy error: {error}") print(f"Variance: {variance}") print(f"Standard error: {std}") from qiskit_aer.noise import NoiseModel, ReadoutError noise_model = NoiseModel() ##### your code here ##### # add modest readout error on all qubits p0given1 = 0.05 p1given0 = 0.02 readout_error = ReadoutError( [ [1 - p1given0, p1given0], [p0given1, 1 - p0given1], ] ) noise_model.add_all_qubit_readout_error(readout_error) # add really bad readout error on qubit 0 p0given1 = 0.5 p1given0 = 0.2 readout_error = ReadoutError( [ [1 - p1given0, p1given0], [p0given1, 1 - p0given1], ] ) noise_model.add_readout_error(readout_error, [0]) print(noise_model) # Submit your answer from qc_grader.challenges.qgss_2023 import grade_lab5_ex1 grade_lab5_ex1(noise_model) options = Options( simulator=dict(noise_model=noise_model, **simulator), resilience_level=0, transpilation=dict(initial_layout=list(range(length))), ) with Session(service=service, backend=backend): estimator = Estimator(options=options) job = estimator.run(circuit, hamiltonian, shots=shots) result = job.result() experiment_value = result.values[0] error = abs(experiment_value - exact_value) variance = result.metadata[0]["variance"] std = math.sqrt(variance / shots) print(f"Estimated energy: {experiment_value}") print(f"Energy error: {error}") print(f"Variance: {variance}") print(f"Standard error: {std}") options = Options( simulator=dict(noise_model=noise_model, **simulator), resilience_level=0, transpilation=dict(initial_layout=list(range(1, length + 1))), ) with Session(service=service, backend=backend): estimator = Estimator(options=options) job = estimator.run(circuit, hamiltonian, shots=shots) result = job.result() experiment_value = result.values[0] error = abs(experiment_value - exact_value) variance = result.metadata[0]["variance"] std = math.sqrt(variance / shots) print(f"Estimated energy: {experiment_value}") print(f"Energy error: {error}") print(f"Variance: {variance}") print(f"Standard error: {std}") options = Options( simulator=dict(noise_model=noise_model, **simulator), resilience_level=1, transpilation=dict(initial_layout=list(range(1, length + 1))), ) with Session(service=service, backend=backend): estimator = Estimator(options=options) job = estimator.run(circuit, hamiltonian, shots=shots) result = job.result() experiment_value = result.values[0] error = abs(experiment_value - exact_value) variance = result.metadata[0]["variance"] std = math.sqrt(variance / shots) print(f"Estimated energy: {experiment_value}") print(f"Energy error: {error}") print(f"Variance: {variance}") print(f"Standard error: {std}") new_shots: int ##### your code here ##### new_shots = 20000 # Submit your answer from qc_grader.challenges.qgss_2023 import grade_lab5_ex2 grade_lab5_ex2(new_shots) from qiskit_aer.noise import depolarizing_error noise_model = NoiseModel() ##### your code here ##### noise_model.add_all_qubit_quantum_error(depolarizing_error(0.01, 2), ["cx"]) print(noise_model) # Submit your answer from qc_grader.challenges.qgss_2023 import grade_lab5_ex3 grade_lab5_ex3(noise_model) options = Options( simulator=dict(noise_model=noise_model, **simulator), resilience_level=1, ) with Session(service=service, backend=backend): estimator = Estimator(options=options) job = estimator.run(circuit, hamiltonian, shots=shots) result = job.result() experiment_value = result.values[0] error = abs(experiment_value - exact_value) variance = result.metadata[0]["variance"] std = math.sqrt(variance / shots) print(f"Estimated energy: {experiment_value}") print(f"Energy error: {error}") print(f"Variance: {variance}") print(f"Standard error: {std}") options = Options( simulator=dict(noise_model=noise_model, **simulator), resilience_level=2, ) with Session(service=service, backend=backend): estimator = Estimator(options=options) job = estimator.run(circuit, hamiltonian, shots=shots) result = job.result() experiment_value = result.values[0] error = abs(experiment_value - exact_value) variances = result.metadata[0]["zne"]["noise_amplification"]["variance"] print(f"Estimated energy: {experiment_value}") print(f"Energy error: {error}") print(f"Variances: {variances}") from qiskit_aer.noise import depolarizing_error, amplitude_damping_error noise_model = NoiseModel() ##### your code here ##### noise_model.add_all_qubit_quantum_error(amplitude_damping_error(0.01).tensor(amplitude_damping_error(0.05)), ["cx"]) print(noise_model) options = Options( simulator=dict(noise_model=noise_model, **simulator), resilience_level=1, ) with Session(service=service, backend=backend): estimator = Estimator(options=options) job = estimator.run(circuit, hamiltonian, shots=shots) result = job.result() experiment_value = result.values[0] error = abs(experiment_value - exact_value) variance = result.metadata[0]["variance"] std = math.sqrt(variance / shots) print(f"Estimated energy: {experiment_value}") print(f"Energy error: {error}") print(f"Variance: {variance}") print(f"Standard error: {std}") options = Options( simulator=dict(noise_model=noise_model, **simulator), resilience_level=2, ) with Session(service=service, backend=backend): estimator = Estimator(options=options) job = estimator.run(circuit, hamiltonian, shots=shots) result = job.result() experiment_value = result.values[0] error = abs(experiment_value - exact_value) variances = result.metadata[0]["zne"]["noise_amplification"]["variance"] print(f"Estimated energy: {experiment_value}") print(f"Energy error: {error}") print(f"Variances: {variances}")
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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/Chibikuri/qwopt
Chibikuri
import sys sys.path.append('../../') import unittest import numpy as np from qwopt.compiler.op_creater import OperationCreator from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit import Aer, execute, transpile STATE_VECTOR = Aer.get_backend('statevector_simulator') QASM = Aer.get_backend('qasm_simulator') class OpcreatorTest(unittest.TestCase): def test_Kop(self): graph = np.array([[0, 1, 0, 1], [0, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]) pb = prob_transition(graph, gtype='google') # print(pb) op_creator = OperationCreator(graph, pb) nq = op_creator.q_size shots = 100000 bins = [format(i, '0%sb' % str(nq//2)) for i in range(2**(nq//2))] cont = QuantumRegister(nq//2, 'cont') targ = QuantumRegister(nq//2, 'targ') anc = QuantumRegister(nq//2, 'ancillae') c = ClassicalRegister(nq//2) qc = QuantumCircuit(cont, targ, anc, c) qc.h(cont) Kop = op_creator.K_operation() qc.append(Kop, qargs=[*cont, *targ, *anc]) qc.measure(targ, c) nqc = transpile(qc, basis_gates=['cx', 'u3', 'h', 'x']) # print(nqc) job = execute(qc, backend=QASM, shots=shots) counts = job.result().get_counts(qc) # print(counts) prob = [counts.get(i, 0)/shots for i in bins] # print(prob)s def test_Top(self): ''' Experiment 1 for two dim ''' graph = np.array([[0, 1, 0, 1], [0, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]) pb = prob_transition(graph, gtype='google') op_creator = OperationCreator(graph, pb) Tops = op_creator.T_operation() nq = op_creator.q_size qr = QuantumRegister(nq) c = ClassicalRegister(nq//2) anc = QuantumRegister(nq//2) qc = QuantumCircuit(qr, anc, c) # first element is input value and second one is ideal output target = [[0, 1/np.sqrt(2), 0, 1/np.sqrt(2)], [1/np.sqrt(2), 0, 1/np.sqrt(2), 0]] qc.x(qr[0]) qc.initialize(target[0], [qr[2], qr[3]]) for ts in Tops: qc.append(ts, qargs=[*qr, *anc]) qc.measure(qr[2:5], c) shots = 100000 job = execute(qc, backend=QASM, shots=shots) count = job.result().get_counts(qc) bins = [format(i, "02b") for i in range(4)] prob = [count.get(i, 0)/shots for i in bins] # FIXME is rtol value proper? isCorrect = np.isclose([i**2 for i in target[1]], prob, rtol=1e-2) self.assertEqual(all(isCorrect), True) def test_Dop(self): graph = np.array([[0, 1, 0, 1], [0, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]) pb = prob_transition(graph, gtype='google') op_creater = OperationCreator(graph, pb) nq = op_creater.q_size shots = 1000 targ = QuantumRegister(nq//2, 'target') qc = QuantumCircuit(targ) Dop = op_creater.D_operation() qc.append(Dop, qargs=targ) job = execute(qc, backend=STATE_VECTOR) vec = job.result().get_statevector(qc) nqc = transpile(qc, basis_gates=['cx', 'h', 'x']) ideal = [-1.0+0.0j, -0.0+0.0j, -0.0+0.0j, -0.0+0.0j,] isCorrect = np.isclose(ideal, vec) self.assertEqual(all(isCorrect), True) def prob_transition(graph, gtype='normal', alpha=0.85): if gtype == 'google': return google_matrix(alpha, graph) else: pmatrix = np.zeros(graph.shape) indegrees = np.sum(graph, axis=0) for ix, indeg in enumerate(indegrees): if indeg == 0: pmatrix[:, ix] = graph[:, ix] else: pmatrix[:, ix] = graph[:, ix]/indeg return pmatrix def google_matrix(alpha, C): E = connect_to_E(C) N = len(C) G = alpha*E + (1-alpha)/N * np.ones((N, N), dtype=float) return G def connect_to_E(C): ''' C is conectivity matrix C: np.array output E: np.array ''' N = len(C) C = np.array(C) E = np.zeros(C.shape) rowsum = np.sum(C, axis=0) for ind, val in enumerate(rowsum): if val == 0: for j in range(N): E[j][ind] = 1/N else: for j in range(N): E[j][ind] = C[j][ind]/val assert(np.sum(np.sum(E, axis=0))==N) return E if __name__ == '__main__': unittest.main()
https://github.com/cjsproject/qiskit_learning
cjsproject
%matplotlib inline # Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * # Loading your IBM Q account(s) provider = IBMQ.load_account() provider.backends() from qiskit.providers.ibmq import least_busy large_enough_devices = provider.backends(filters=lambda x: x.configuration().n_qubits > 3 and not x.configuration().simulator) backend = least_busy(large_enough_devices) print("The best backend is " + backend.name()) # quasm_sim not necessary #simulator = Aer.get_backend('qasm_simulator') from qiskit.tools.monitor import job_monitor # circuit on q reg with 1 qubit circuit = QuantumCircuit(2, 2) # hadamard on A circuit.h(0) # CNOT on B controlled by A circuit.cx(0 , 1) circuit.measure([0, 1], [0, 1]) job = execute(circuit, backend, shots=1000) job_monitor(job) results = job.result() counts = results.get_counts(circuit) print(f"total count for 0 and 1 are: {counts}") circuit.draw() plot_histogram(counts)
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """ Example use of the initialize gate to prepare arbitrary pure states. """ import math from qiskit import QuantumCircuit, execute, BasicAer ############################################################### # Make a quantum circuit for state initialization. ############################################################### circuit = QuantumCircuit(4, 4, name="initializer_circ") desired_vector = [ 1 / math.sqrt(4) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(8) * complex(0, 1), 0, 0, 0, 0, 1 / math.sqrt(4) * complex(1, 0), 1 / math.sqrt(8) * complex(1, 0), ] circuit.initialize(desired_vector, [0, 1, 2, 3]) circuit.measure([0, 1, 2, 3], [0, 1, 2, 3]) print(circuit) ############################################################### # Execute on a simulator backend. ############################################################### shots = 10000 # Desired vector print("Desired probabilities: ") print([format(abs(x * x), ".3f") for x in desired_vector]) # Initialize on local simulator sim_backend = BasicAer.get_backend("qasm_simulator") job = execute(circuit, sim_backend, shots=shots) result = job.result() counts = result.get_counts(circuit) qubit_strings = [format(i, "04b") for i in range(2**4)] print("Probabilities from simulator: ") print([format(counts.get(s, 0) / shots, ".3f") for s in qubit_strings])
https://github.com/qiskit-community/qiskit-bip-mapper
qiskit-community
# 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. """Test the BIPMapping pass.""" import unittest from qiskit import QuantumCircuit from qiskit.circuit.library.standard_gates import SwapGate from qiskit.compiler.transpiler import transpile from qiskit.transpiler.coupling import CouplingMap from qiskit.transpiler.preset_passmanagers.plugin import list_stage_plugins class TestBIPMapping(unittest.TestCase): """Tests the BIPMapping plugin.""" def test_plugin_in_list(self): """Test bip plugin is installed.""" self.assertIn("bip", list_stage_plugins("routing")) def test_trivial_case(self): """No need to have any swap, the CX are distance 1 to each other. q0:--(+)-[H]-(+)- | | q1:---.-------|-- | q2:-----------.-- CouplingMap map: [1]--[0]--[2] """ coupling = CouplingMap([[0, 1], [0, 2]]) circuit = QuantumCircuit(3) circuit.cx(1, 0) circuit.h(0) circuit.cx(2, 0) actual = transpile( circuit, coupling_map=coupling, routing_method="bip", optimization_level=0 ) self.assertEqual(11, len(actual)) for inst, _, _ in actual.data: # there are no swaps self.assertFalse(isinstance(inst, SwapGate))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.circuit.library import RealAmplitudes from qiskit.algorithms.optimizers import COBYLA from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, SamplingVQE from qiskit.primitives import Sampler from qiskit_optimization.converters import LinearEqualityToPenalty from qiskit_optimization.algorithms import MinimumEigenOptimizer from qiskit_optimization.translators import from_docplex_mp from qiskit.utils import algorithm_globals import numpy as np import matplotlib.pyplot as plt from docplex.mp.model import Model algorithm_globals.random_seed = 123456 # prepare problem instance n = 6 # number of assets q = 0.5 # risk factor budget = n // 2 # budget penalty = 2 * n # scaling of penalty term # instance from [1] mu = np.array([0.7313, 0.9893, 0.2725, 0.8750, 0.7667, 0.3622]) sigma = np.array( [ [0.7312, -0.6233, 0.4689, -0.5452, -0.0082, -0.3809], [-0.6233, 2.4732, -0.7538, 2.4659, -0.0733, 0.8945], [0.4689, -0.7538, 1.1543, -1.4095, 0.0007, -0.4301], [-0.5452, 2.4659, -1.4095, 3.5067, 0.2012, 1.0922], [-0.0082, -0.0733, 0.0007, 0.2012, 0.6231, 0.1509], [-0.3809, 0.8945, -0.4301, 1.0922, 0.1509, 0.8992], ] ) # or create random instance # mu, sigma = portfolio.random_model(n, seed=123) # expected returns and covariance matrix # create docplex model mdl = Model("portfolio_optimization") x = mdl.binary_var_list(range(n), name="x") objective = mdl.sum([mu[i] * x[i] for i in range(n)]) objective -= q * mdl.sum([sigma[i, j] * x[i] * x[j] for i in range(n) for j in range(n)]) mdl.maximize(objective) mdl.add_constraint(mdl.sum(x[i] for i in range(n)) == budget) # case to qp = from_docplex_mp(mdl) # solve classically as reference opt_result = MinimumEigenOptimizer(NumPyMinimumEigensolver()).solve(qp) print(opt_result.prettyprint()) # we convert the problem to an unconstrained problem for further analysis, # otherwise this would not be necessary as the MinimumEigenSolver would do this # translation automatically linear2penalty = LinearEqualityToPenalty(penalty=penalty) qp = linear2penalty.convert(qp) _, offset = qp.to_ising() # set classical optimizer maxiter = 100 optimizer = COBYLA(maxiter=maxiter) # set variational ansatz ansatz = RealAmplitudes(n, reps=1) m = ansatz.num_parameters # set sampler sampler = Sampler() # run variational optimization for different values of alpha alphas = [1.0, 0.50, 0.25] # confidence levels to be evaluated # dictionaries to store optimization progress and results objectives = {alpha: [] for alpha in alphas} # set of tested objective functions w.r.t. alpha results = {} # results of minimum eigensolver w.r.t alpha # callback to store intermediate results def callback(i, params, obj, stddev, alpha): # we translate the objective from the internal Ising representation # to the original optimization problem objectives[alpha].append(np.real_if_close(-(obj + offset))) # loop over all given alpha values for alpha in alphas: # initialize SamplingVQE using CVaR vqe = SamplingVQE( sampler=sampler, ansatz=ansatz, optimizer=optimizer, aggregation=alpha, callback=lambda i, params, obj, stddev: callback(i, params, obj, stddev, alpha), ) # initialize optimization algorithm based on CVaR-SamplingVQE opt_alg = MinimumEigenOptimizer(vqe) # solve problem results[alpha] = opt_alg.solve(qp) # print results print("alpha = {}:".format(alpha)) print(results[alpha].prettyprint()) print() # plot resulting history of objective values plt.figure(figsize=(10, 5)) plt.plot([0, maxiter], [opt_result.fval, opt_result.fval], "r--", linewidth=2, label="optimum") for alpha in alphas: plt.plot(objectives[alpha], label="alpha = %.2f" % alpha, linewidth=2) plt.legend(loc="lower right", fontsize=14) plt.xlim(0, maxiter) plt.xticks(fontsize=14) plt.xlabel("iterations", fontsize=14) plt.yticks(fontsize=14) plt.ylabel("objective value", fontsize=14) plt.show() # evaluate and sort all objective values objective_values = np.zeros(2**n) for i in range(2**n): x_bin = ("{0:0%sb}" % n).format(i) x = [0 if x_ == "0" else 1 for x_ in reversed(x_bin)] objective_values[i] = qp.objective.evaluate(x) ind = np.argsort(objective_values) # evaluate final optimal probability for each alpha for alpha in alphas: probabilities = np.fromiter( results[alpha].min_eigen_solver_result.eigenstate.binary_probabilities().values(), dtype=float, ) print("optimal probability (alpha = %.2f): %.4f" % (alpha, probabilities[ind][-1:])) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience
PacktPublishing
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created Nov 2020 @author: hassi """ # Import the required math import numpy as np import random #To create random state vector import cmath #To juggle complex exponentials from math import sqrt, pi, sin, cos from IPython.core.display import display # Import the required Qiskit classes from qiskit import QuantumCircuit, execute, Aer # Import Blochsphere visualization from qiskit.visualization import plot_bloch_multivector, plot_state_qsphere # Categorize our gates rot_gates=["rx","ry","rz"] unitary_gates=["u1","u2","u3"] single_gates=["id","x","y","z","t","tdg","s","sdg","h"]+rot_gates oneq_gates=single_gates+unitary_gates control_gates=["cx","cy","cz","ch"] twoq_gates=control_gates+["swap"] all_gates=oneq_gates+twoq_gates+rot_gates+unitary_gates # List our start states start_states=["1","+","-","R","L","r","d"] valid_start=["0"]+start_states # Function that returns the state vector (Psi) for the circuit def get_psi(circuit): global psi backend = Aer.get_backend('statevector_simulator') result = execute(circuit, backend).result() psi = result.get_statevector(circuit) return(psi) # Function that returns the unitary of the circuit def get_unitary(circuit): simulator = Aer.get_backend('unitary_simulator') result = execute(circuit, simulator).result() unitary = result.get_unitary(circuit) return(unitary) # Function that creates a quantum circuit def create_circuit(n_qubits,start): # Create the initial state vector if start=="1": initial_vector = [0,complex(1,0)] elif start=="+": # Create |+> state initial_vector = [1/sqrt(2) * complex(1, 0), 1/sqrt(2) * complex(1, 0)] elif start=="-": # Create |-> state initial_vector = [1/sqrt(2) * complex(1, 0), -1/sqrt(2) * complex(1, 0)] elif start=="R": # Create |R> state initial_vector = [1/sqrt(2) * complex(1, 0), 1*1.j/sqrt(2) * complex(1, 0)] elif start=="L": # Create |L> state initial_vector = [1/sqrt(2) * complex(1, 0), -1*1.j/sqrt(2) * complex(1, 0)] elif start=="r": # Create random initial vector theta=random.random()*pi phi=random.random()*2*pi a = cos(theta/2) b = cmath.exp(phi*1j)*sin(theta/2) initial_vector = [a * complex(1, 0), b * complex(1, 0)] elif start=="d": a = cos(start_theta/2) b = cmath.exp(start_phi*1j)*sin(start_theta/2) initial_vector = [a * complex(1, 0), b * complex(1, 0)] else: initial_vector = [complex(1,0),0] if start!="n": print("\nInitial vector for |"+start+"\u232A:") print(np.around(initial_vector, decimals = 3)) # Create the circuit circuit = QuantumCircuit(n_qubits) # If the start state is not |0> initialize the qubit if start in start_states: circuit.initialize(initial_vector,n_qubits-1) return(circuit) # Function that creates the required outputs for the circuit def qgate_out(circuit,start): # Print the circuit psi=get_psi(circuit) if start!="n": print("\nCircuit:") print("--------") print(circuit) print("\nState vector:") print("-------------") print(np.around(psi, decimals = 3)) display(plot_bloch_multivector(psi)) if circuit.num_qubits>1 and gate in control_gates: display(plot_state_qsphere(psi)) return(psi) # Function that adds a gate to a circuit def qgate(gate,start): # If the gates require angles, add those to the QASM code qasm_angle_gates={"rx":"rx("+str(theta)+") q[0];", "ry":"ry("+str(theta)+") q[0];", "rz":"rz("+str(phi)+") q[0];", "u1":"u1("+str(phi)+") q[0];", "u2":"u2("+str(phi)+","+str(lam)+") q[0];", "u3":"u3("+str(theta)+","+str(phi)+","+str(lam)+") q[0];"} # Create the circuits and then add the gate using QASM import if gate in oneq_gates: circuit=create_circuit(1,start) qasm_string='OPENQASM 2.0; include "qelib1.inc"; qreg q[1];' else: circuit=create_circuit(2,start) qasm_string='OPENQASM 2.0; include "qelib1.inc"; qreg q[2];' qgate_out(circuit,start) if gate in oneq_gates: if gate in rot_gates+unitary_gates: circuit+=QuantumCircuit.from_qasm_str(qasm_string+qasm_angle_gates[gate]) else: circuit+=QuantumCircuit.from_qasm_str(qasm_string+gate+" q[0];") else: circuit+=QuantumCircuit.from_qasm_str(qasm_string+gate+" q[1],q[0];") return(circuit) # Main navigation def main(): print("Ch 6: Visualizing the quantum gates") print("-----------------------------------") # Set the global parameters global phi, theta, lam, start_theta, start_phi phi=0.0 theta=0.0 lam=0.0 global gate gate="" while gate !="exit": # Set up the start conditions start=input("Start state:\n0. |0\u27E9 \n1. |1\u27E9 \n+. |+\u27E9\n-. |-\u27E9\nR. |R\u27E9\nL. |L\u27E9\nr. Random (a|0\u27E9 + b|1\u27E9)\nd. Define (\u03B8 and \u03D5)\n") if start =="d": # Specify initial vector start_theta=float(input("Enter start \u03B8:\n")) start_phi=float(input("Enter start \u03D5:\n")) # Select a gate print("Enter a gate:\nAvailable gates:\n",all_gates) gate=input() if gate in ["rx", "ry","u3"]: theta=input("Enter rotation (\u03B8):\n") if gate in ["u1","u2","u3","rz",]: phi=input("Enter rotation (\u03D5):\n") if gate in ["u2","u3"]: lam=input("Enter rotation (\u03BB):\n") if gate in all_gates and start in valid_start: # Display the gate unitary for a blank circuit blank_qc=qgate(gate,"n") print("\nUnitary for the " + gate + " gate:\n") print(np.around(get_unitary(blank_qc), decimals = 3)) # Build the quantum circuit for the gate input("Press Enter to see the start setup...") qc=qgate(gate, start) # Visualize the circuit and the qubit(s) input("Press Enter to see the result after the "+gate+" gate...") qgate_out(qc,start) input("Press Enter to test another gate...") else: if start not in valid_start: print("Not a valid start state.") if gate not in all_gates: print("Not a valid gate.") print("Try again...") if __name__ == '__main__': main()
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
"""A quantum tic tac toe running in command line""" from qiskit import Aer from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import CompositeGate from qiskit import execute import numpy as np from composite_gates import cry,cnx,any_x,bus_or,x_bus class Move(): def __init__(self,indices,player,q1=None,q2=None): """A data structure for game moves""" self.indices = indices self.player=player self.q1=q1 self.q2=q2 def __str__(self): return str([self.indices,self.player,self.q1,self.q2]) class Board(): def __init__(self,x,y,print_info=False): #quantum register, classical register, quantum circuit. self.print_info=print_info self.q = QuantumRegister(1) self.c = ClassicalRegister(1) self.qc = QuantumCircuit(self.q, self.c) self.qc.cry = cry self.qc.x_bus = x_bus self.qc.cnx = cnx self.qc.any_x = any_x self.qc.bus_or = bus_or #the dimensions of the bord self.x=x self.y=y #To keep track of what is in each cell, no entanglement etc. #Provides a graphic of the game state. self.cells = np.empty((x,y),dtype=object) self.cells[:]='' #Initially game is empty. self.game_full = False self.moves = [] def __str__(self): return str(self.cells) def add_move(self,indices,player): """Adds a move if it is non-clashing, otherwise passes it on""" for index in indices: if index[0] >= self.x: return 'Index out of range' if index[1] >= self.y: return 'Index out of range' status = self._add_move(indices,player) if status=='ok': if player==0: char = 'X' elif player==1: char = 'O' char+=str(len(self.moves)) for index in indices: s = self.cells[index[0],index[1]] if s: #If the cell has some text #Add char with a comma self.cells[index[0],index[1]]+=' '+char else: #cell is empty so just add char self.cells[index[0],index[1]]+=char print(self.cells) return status def _add_move(self,indices,player): """Actually adds the move if not clashing, otherwise passes it to _add_clashing_move""" if len(indices)==2: if indices[0]==indices[1]: indices = [indices[0]] num=len(indices) caught_clashes = False #turns true if all moves are safe clashes for existing_move in self.moves: for index in indices: if index in existing_move.indices: if len(existing_move.indices)==1: return 'overfull' #This move will ALWAYS be there, if it can. #hence, overfull. else: #captures any clash caught_clashes = True if caught_clashes: return self._add_clashing_move(indices,player) else: #Reach this section if there are no clashes at all if num==1: self.moves.append(Move(indices,player)) #No control needed return 'ok' else: self.q.size+=2 #indicator qubit, and move qubit q1 = self.q[self.q.size-2] #To make this readable... q2 = self.q[self.q.size-1] self.qc.h(q1) #the last qubit in register. self.qc.x(q2) self.qc.cx(q1,q2) self.moves.append(Move(indices,player,q1,q2)) return 'ok' def _add_clashing_move(self,indices,player): """Adds a clashing move""" if len(indices)==1: #100% of qubit is on one clashing spot. #This spot COULD be occupied. self.q.size+=1 #Only one bit needed, move happens or not. index = indices[0] bus = [] for existing_move in self.moves: if index in existing_move.indices: if index==existing_move.indices[0]: bus.append(existing_move.q1) elif index==existing_move.indices[1]: bus.append(existing_move.q2) #Now if any entry on the bus is true, our qubit is false. self.qc.x(self.q[self.q.size-1]) # make it 1 self.qc.any_x(self.qc,*bus,self.q[self.q.size-1]) #negate is any dependents are true. #So the new move can happen if none of the others happen. self.moves.append(Move(indices,player,self.q[self.q.size-1])) return 'ok' elif len(indices)==2: #Check first spot is not occupied, then second spot if first #is not occupied. self.q.size+=2 #Two bits needed (maybe) for each index. #This can be optimized, in effect only one qubit is needed, #and its result indicates the selected qubit. #However, then some control qubit is needed too. #Since there are moves that could possibly be erased completely! bus0 = [] bus1 = [] for existing_move in self.moves: if indices[0] in existing_move.indices: if indices[0]==existing_move.indices[0]: bus0.append(existing_move.q1) elif indices[0]==existing_move.indices[1]: bus0.append(existing_move.q2) if indices[1] in existing_move.indices: if indices[1]==existing_move.indices[0]: bus1.append(existing_move.q1) elif indices[1]==existing_move.indices[1]: bus1.append(existing_move.q2) #Now if any entry on the bus is true, our first qubit is false. q1 = self.q[self.q.size-2] #a bit easier to look at (: q2 = self.q[self.q.size-1] if bus0: self.qc.x(q1) self.qc.cnx(self.qc,*bus0,q1) else: self.qc.h(q1) #And now the second qubit is 1 only if none of its competitors #are 1, and likewise if the previous qubit is zero. self.qc.x(q2) self.qc.bus_or(self.qc,q2,bus1,[q1]) self.moves.append(Move(indices,player,q1,q2)) return 'ok' def run(self): """Game loop""" self.running=True if self.print_info: print("Welcome to Quantum tic tac toe!") print("At each turn choose if to make one or two moves.") print("Playing one move at a time is a classic tic tac toe game.") print("At each turn the game state is printed.") print("This constitutes a 3x3 grid (standard game!).") print("You will see empty cells if no move was made on that part of the board.") print("Moves made by X are marked with Xi, 'i' some number.") print("e.g. X3 is the third move, played by X. When a move is made in a super position,") print("You will see its label, say X3, appear in several places.") print("This means your move is in a superposition of two classical moves!") print("A superposition of classical moves does not guarantee that a spot is occupied,") print("so other players can attempt to occupy it too.") print("Then the new move will be anti-correlated with the move already in that spot.") print("And so the game branches out into many simultaneous states.") print("The outcome is then computed by simulation...") print("so don't make too many quantum moves or it will take long to compute!") print("Enter 'q' at any time to quit") print("Enter 'end' to end the game, and compute the winner(s).") print("Good luck!") while self.running: self.ask_player(0) self.ask_player(1) if self.game_full: self.compute_winner() def ask_player(self,player): """Ask a player for move details""" asking=False if self.running: asking = True while asking: if player==0: player_name = 'X' elif player==1: player_name = 'O' print("PLAYER "+player_name+" :") cells = self.question('Play in 1 or 2 cells?') if cells=='1': x = int(self.question('x index:')) y = int(self.question('y index:')) status = self.add_move([[y,x]],player) if status == 'ok': asking = False else: print(status) elif cells=='2': x1 = int(self.question('x1 index:')) y1 = int(self.question('y1 index:')) x2 = int(self.question('x2 index:')) y2 = int(self.question('y2 index:')) status = self.add_move([[y1,x1],[y2,x2]],player) if status == 'ok': asking = False else: print(status) if not self.running: asking=False def question(self,text): """ask user a question""" if self.running: answer = input(text) if answer=='q': self.running=False return None elif answer=='end': self.game_full = True self.running = False else: return answer else: return None def compute_winner(self): """Find overall game winner, by finding winners of each outcome""" self.c.size = self.q.size #Make them the same self.qc.measure(self.q, self.c) #Measure backend = Aer.get_backend('qasm_simulator') job_sim = execute(self.qc, backend=backend, shots=100) sim_result = job_sim.result() print("simulation: ", sim_result) print(sim_result.get_counts(self.qc)) self.counts = sim_result.get_counts(self.qc) for count in self.counts: #Takes key names c = list(count)[:-1] #splits key '1011' => ['1','0','1','1'] c = c[::-1] #invert it so it goes 0 up... #Ignore the last bit since I dont know how to get rid of it #It is zero always. #The reason it is included is that I create a quantum register and #then start adding operations, quantum registers need at least one bit. counter = 0 weight = self.counts[count] empty = np.zeros((self.x,self.y),dtype=str) for m in self.moves: if m.player == 0: char = 'x' elif m.player==1: char = 'o' result = [] if m.q1: result.append(c[counter]) counter+=1 if m.q2: result.append(c[counter]) counter+=1 #print(result) if len(result) == len(m.indices): #print(m) if result[0]=='1': empty[m.indices[0][0],m.indices[0][1]] = char if len(result)>1: if result[1]=='1': if result[0]=='1': print('problem! a move appeard in two places.') print(m) empty[m.indices[1][0],m.indices[1][1]] = char elif not result: #Then it was a classcal move empty[m.indices[0][0],m.indices[0][1]] = char xscore,oscore=self.winners(empty) print('X wins: '+str(xscore)) print('O wins: '+str(oscore)) print('Shots: '+str(weight)) print(empty) def winners(self,empty): """Compute winners of a board""" oscore = 0 xscore = 0 for x in range(self.x): if empty[x,1]==empty[x,0] and empty[x,2]==empty[x,1]: if empty[x,0]=='o': oscore+=1 elif empty[x,0]=='x': xscore +=1 for y in range(self.y): if empty[1,y]==empty[0,y] and empty[2,y]==empty[0,y]: if empty[0,y]=='o': oscore+=1 elif empty[0,y]=='x': xscore +=1 if empty[0,0]==empty[1,1] and empty[1,1]==empty[2,2]: if empty[0,0]=='o': oscore+=1 elif empty[0,0]=='x': xscore += 1 if empty[2,0]==empty[1,1] and empty[1,1]==empty[0,2]: if empty[2,0]=='o': oscore+=1 elif empty[2,0]=='x': xscore += 1 return [xscore,oscore] def _populate_board(self): """Automatically populate as below, for testing purposes""" self.add_move([[2,2],[0,0]],1) self.add_move([[1,1],[1,2]],0) self.add_move([[1,2],[2,1]],1) self.add_move([[2,1]],0) self.add_move([[0,1]],1) self.add_move([[1,0]],0) self.add_move([[2,0]],1) self.add_move([[2,2]],0) self.add_move([[0,0]],1) self.add_move([[0,2]],0) self.add_move([[1,1]],1) self.add_move([[1,2]],0) if __name__=="__main__": B= Board(3,3) B.run() #B._populate_board() #a = B.compute_winner()
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
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()
https://github.com/abbarreto/qiskit4
abbarreto
https://github.com/LFL-Lab/metal-library
LFL-Lab
# Qiskit Metal imports import qiskit_metal as metal from ... import OpenToGround from ... import RouteMeander # Custom Components imports from metal_library.components.inductive_coupler import InductiveCoupler class QubitCavity(): def __init__(self, design, options: dict component_name: str, ) TransmonCross(design, "transmon", options=options) return design
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
%pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git --upgrade # qc-grader should be 0.18.12 (or higher) import qc_grader qc_grader.__version__ ### Install Qiskit and relevant packages, if needed ### IMPORTANT: Make sure you are on 3.10 > python < 3.12 %pip install qiskit[visualization]==1.0.2 %pip install qiskit-ibm-runtime %pip install qiskit-aer %pip install graphviz %pip install qiskit-serverless -U %pip install qiskit-transpiler-service -U %pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git -U import qisit ### INSTALL QISKIT: Locally on a Mac or Linux ### %pip install 'qiskit[visualization]'==1.0.2 ### Install the other required packages as well %pip install qiskit_aer %pip install qiskit_ibm_runtime %pip install matplotlib %pip install pylatexenc %pip install qiskit-transpiler-service %pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git ### CHECK OTHER DEPENDENCIES %pip show pylatexenc matplotlib qc_grader #qc-grader should be 0.18.8 (or higher) ### Install Qiskit, if needed %pip install qiskit[visualization]==1.0.2 %pip install qiskit_aer %pip install qiskit_ibm_runtime %pip install matplotlib %pip install pylatexenc %pip install qiskit-transpiler-service %pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git ### Install Qiskit and relevant packages, if needed %pip install qiskit[visualization]==1.0.2 %pip install qiskit_ibm_runtime %pip install qiskit_aer %pip install qiskit-transpiler-service %pip install graphviz %pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git %pip install qiskit-serverless -U %pip install qiskit-transpiler-service -U %pip install circuit-knitting-toolbox -U ### Install Qiskit and relevant packages, if needed ### IMPORTANT: Make sure you are using python 3.10 or 3.11 for compatibility of the required packages %pip install qiskit[visualization]==1.0.2 %pip install qiskit-ibm-runtime %pip install qiskit-aer %pip install graphviz %pip install qiskit-transpiler-service %pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git -U import qc_grader qc_grader.__version__ %pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git -U import qc_grader qc_grader.__version__ %pip install -r git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git -U %pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git -U
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from game_engines.quantum_slot import quantum_slot_machine quantum_slot_machine()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the BIPMapping pass""" import unittest from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit.circuit import Barrier from qiskit.circuit.library.standard_gates import SwapGate, CXGate from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeLima from qiskit.transpiler import CouplingMap, Layout, PassManager, Target from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.passes import BIPMapping from qiskit.transpiler.passes import CheckMap, Collect2qBlocks, ConsolidateBlocks, UnitarySynthesis from qiskit.utils import optionals @unittest.skipUnless(optionals.HAS_CPLEX, "cplex is required to run the BIPMapping tests") @unittest.skipUnless(optionals.HAS_DOCPLEX, "docplex is required to run the BIPMapping tests") class TestBIPMapping(QiskitTestCase): """Tests the BIPMapping pass.""" def test_empty(self): """Returns the original circuit if the circuit is empty.""" coupling = CouplingMap([[0, 1]]) circuit = QuantumCircuit(2) with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"): actual = BIPMapping(coupling)(circuit) self.assertEqual(circuit, actual) def test_no_two_qubit_gates(self): """Returns the original circuit if the circuit has no 2q-gates q0:--[H]-- q1:------- CouplingMap map: [0]--[1] """ coupling = CouplingMap([[0, 1]]) circuit = QuantumCircuit(2) circuit.h(0) with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"): actual = BIPMapping(coupling)(circuit) self.assertEqual(circuit, actual) def test_trivial_case(self): """No need to have any swap, the CX are distance 1 to each other q0:--(+)-[H]-(+)- | | q1:---.-------|-- | q2:-----------.-- CouplingMap map: [1]--[0]--[2] """ coupling = CouplingMap([[0, 1], [0, 2]]) circuit = QuantumCircuit(3) circuit.cx(1, 0) circuit.h(0) circuit.cx(2, 0) with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"): actual = BIPMapping(coupling)(circuit) self.assertEqual(3, len(actual)) for inst, _, _ in actual.data: # there are no swaps self.assertFalse(isinstance(inst, SwapGate)) def test_no_swap(self): """Adding no swap if not giving initial layout""" coupling = CouplingMap([[0, 1], [0, 2]]) circuit = QuantumCircuit(3) circuit.cx(1, 2) with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"): actual = BIPMapping(coupling)(circuit) q = QuantumRegister(3, name="q") expected = QuantumCircuit(q) expected.cx(q[0], q[1]) self.assertEqual(expected, actual) def test_ignore_initial_layout(self): """Ignoring initial layout even when it is supplied""" coupling = CouplingMap([[0, 1], [0, 2]]) circuit = QuantumCircuit(3) circuit.cx(1, 2) property_set = {"layout": Layout.generate_trivial_layout(*circuit.qubits)} with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"): actual = BIPMapping(coupling)(circuit, property_set) q = QuantumRegister(3, name="q") expected = QuantumCircuit(q) expected.cx(q[0], q[1]) self.assertEqual(expected, actual) def test_can_map_measurements_correctly(self): """Verify measurement nodes are updated to map correct cregs to re-mapped qregs.""" coupling = CouplingMap([[0, 1], [0, 2]]) qr = QuantumRegister(3, "qr") cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.cx(qr[1], qr[2]) circuit.measure(qr[1], cr[0]) circuit.measure(qr[2], cr[1]) with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"): actual = BIPMapping(coupling)(circuit) q = QuantumRegister(3, "q") expected = QuantumCircuit(q, cr) expected.cx(q[0], q[1]) expected.measure(q[0], cr[0]) # <- changed due to initial layout change expected.measure(q[1], cr[1]) # <- changed due to initial layout change self.assertEqual(expected, actual) def test_can_map_measurements_correctly_with_target(self): """Verify measurement nodes are updated to map correct cregs to re-mapped qregs.""" target = Target() target.add_instruction(CXGate(), {(0, 1): None, (0, 2): None}) qr = QuantumRegister(3, "qr") cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.cx(qr[1], qr[2]) circuit.measure(qr[1], cr[0]) circuit.measure(qr[2], cr[1]) with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"): actual = BIPMapping(target)(circuit) q = QuantumRegister(3, "q") expected = QuantumCircuit(q, cr) expected.cx(q[0], q[1]) expected.measure(q[0], cr[0]) # <- changed due to initial layout change expected.measure(q[1], cr[1]) # <- changed due to initial layout change self.assertEqual(expected, actual) def test_never_modify_mapped_circuit(self): """Test that the mapping is idempotent. It should not modify a circuit which is already compatible with the coupling map, and can be applied repeatedly without modifying the circuit. """ coupling = CouplingMap([[0, 1], [0, 2]]) circuit = QuantumCircuit(3, 2) circuit.cx(1, 2) circuit.measure(1, 0) circuit.measure(2, 1) dag = circuit_to_dag(circuit) with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"): mapped_dag = BIPMapping(coupling).run(dag) remapped_dag = BIPMapping(coupling).run(mapped_dag) self.assertEqual(mapped_dag, remapped_dag) def test_no_swap_multi_layer(self): """Can find the best layout for a circuit with multiple layers.""" coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) qr = QuantumRegister(4, name="qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) circuit.cx(qr[0], qr[3]) property_set = {} with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"): actual = BIPMapping(coupling, objective="depth")(circuit, property_set) self.assertEqual(2, actual.depth()) CheckMap(coupling)(actual, property_set) self.assertTrue(property_set["is_swap_mapped"]) def test_unmappable_cnots_in_a_layer(self): """Test mapping of a circuit with 2 cnots in a layer into T-shape coupling, which BIPMapping cannot map.""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(4, "c") circuit = QuantumCircuit(qr, cr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[2], qr[3]) circuit.measure(qr, cr) coupling = CouplingMap([[0, 1], [1, 2], [1, 3]]) # {0: [1], 1: [2, 3]} with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"): actual = BIPMapping(coupling)(circuit) # Fails to map and returns the original circuit self.assertEqual(circuit, actual) def test_multi_cregs(self): """Test for multiple ClassicalRegisters.""" # ┌───┐ ░ ┌─┐ # qr_0: ──■────────────┤ X ├─░─┤M├───────── # ┌─┴─┐ ┌───┐└─┬─┘ ░ └╥┘┌─┐ # qr_1: ┤ X ├──■──┤ H ├──■───░──╫─┤M├────── # └───┘┌─┴─┐└───┘ ░ ║ └╥┘┌─┐ # qr_2: ──■──┤ X ├───────────░──╫──╫─┤M├─── # ┌─┴─┐└───┘ ░ ║ ║ └╥┘┌─┐ # qr_3: ┤ X ├────────────────░──╫──╫──╫─┤M├ # └───┘ ░ ║ ║ ║ └╥┘ # c: 2/════════════════════════╩══╬══╩══╬═ # 0 ║ 1 ║ # ║ ║ # d: 2/═══════════════════════════╩═════╩═ # 0 1 qr = QuantumRegister(4, "qr") cr1 = ClassicalRegister(2, "c") cr2 = ClassicalRegister(2, "d") circuit = QuantumCircuit(qr, cr1, cr2) circuit.cx(qr[0], qr[1]) circuit.cx(qr[2], qr[3]) circuit.cx(qr[1], qr[2]) circuit.h(qr[1]) circuit.cx(qr[1], qr[0]) circuit.barrier(qr) circuit.measure(qr[0], cr1[0]) circuit.measure(qr[1], cr2[0]) circuit.measure(qr[2], cr1[1]) circuit.measure(qr[3], cr2[1]) coupling = CouplingMap([[0, 1], [0, 2], [2, 3]]) # linear [1, 0, 2, 3] property_set = {} with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"): actual = BIPMapping(coupling, objective="depth")(circuit, property_set) self.assertEqual(5, actual.depth()) CheckMap(coupling)(actual, property_set) self.assertTrue(property_set["is_swap_mapped"]) def test_swaps_in_dummy_steps(self): """Test the case when swaps are inserted in dummy steps.""" # ┌───┐ ░ ░ # q_0: ──■──┤ H ├─░───■────────░───■─────── # ┌─┴─┐├───┤ ░ │ ░ │ # q_1: ┤ X ├┤ H ├─░───┼────■───░───┼────■── # └───┘├───┤ ░ │ ┌─┴─┐ ░ ┌─┴─┐ │ # q_2: ──■──┤ H ├─░───┼──┤ X ├─░─┤ X ├──┼── # ┌─┴─┐├───┤ ░ ┌─┴─┐└───┘ ░ └───┘┌─┴─┐ # q_3: ┤ X ├┤ H ├─░─┤ X ├──────░──────┤ X ├ # └───┘└───┘ ░ └───┘ ░ └───┘ circuit = QuantumCircuit(4) circuit.cx(0, 1) circuit.cx(2, 3) circuit.h([0, 1, 2, 3]) circuit.barrier() circuit.cx(0, 3) circuit.cx(1, 2) circuit.barrier() circuit.cx(0, 2) circuit.cx(1, 3) coupling = CouplingMap.from_line(4) property_set = {} with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"): actual = BIPMapping(coupling, objective="depth")(circuit, property_set) self.assertEqual(7, actual.depth()) CheckMap(coupling)(actual, property_set) self.assertTrue(property_set["is_swap_mapped"]) # no swaps before the first barrier for inst, _, _ in actual.data: if isinstance(inst, Barrier): break self.assertFalse(isinstance(inst, SwapGate)) def test_different_number_of_virtual_and_physical_qubits(self): """Test the case when number of virtual and physical qubits are different.""" # q_0: ──■────■─────── # ┌─┴─┐ │ # q_1: ┤ X ├──┼────■── # └───┘ │ ┌─┴─┐ # q_2: ──■────┼──┤ X ├ # ┌─┴─┐┌─┴─┐└───┘ # q_3: ┤ X ├┤ X ├───── # └───┘└───┘ circuit = QuantumCircuit(4) circuit.cx(0, 1) circuit.cx(2, 3) circuit.cx(0, 3) circuit.cx(1, 2) coupling = CouplingMap.from_line(5) with self.assertRaises(TranspilerError): with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"): BIPMapping(coupling)(circuit) def test_qubit_subset(self): """Test if `qubit_subset` option works as expected.""" circuit = QuantumCircuit(3) circuit.cx(0, 1) circuit.cx(1, 2) circuit.cx(0, 2) coupling = CouplingMap([(0, 1), (1, 3), (3, 2)]) qubit_subset = [0, 1, 3] with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"): actual = BIPMapping(coupling, qubit_subset=qubit_subset)(circuit) # all used qubits are in qubit_subset bit_indices = {bit: index for index, bit in enumerate(actual.qubits)} for _, qargs, _ in actual.data: for q in qargs: self.assertTrue(bit_indices[q] in qubit_subset) # ancilla qubits are set in the resulting qubit idle = QuantumRegister(1, name="ancilla") self.assertEqual(idle[0], actual._layout.initial_layout[2]) def test_unconnected_qubit_subset(self): """Fails if qubits in `qubit_subset` are not connected.""" circuit = QuantumCircuit(3) circuit.cx(0, 1) coupling = CouplingMap([(0, 1), (1, 3), (3, 2)]) with self.assertRaises(TranspilerError): with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"): BIPMapping(coupling, qubit_subset=[0, 1, 2])(circuit) def test_objective_function(self): """Test if ``objective`` functions prioritize metrics correctly.""" # ┌──────┐┌──────┐ ┌──────┐ # q_0: ┤0 ├┤0 ├─────┤0 ├ # │ Dcx ││ │ │ Dcx │ # q_1: ┤1 ├┤ Dcx ├──■──┤1 ├ # └──────┘│ │ │ └──────┘ # q_2: ───■────┤1 ├──┼─────■──── # ┌─┴─┐ └──────┘┌─┴─┐ ┌─┴─┐ # q_3: ─┤ X ├──────────┤ X ├─┤ X ├── # └───┘ └───┘ └───┘ qc = QuantumCircuit(4) qc.dcx(0, 1) qc.cx(2, 3) qc.dcx(0, 2) qc.cx(1, 3) qc.dcx(0, 1) qc.cx(2, 3) coupling = CouplingMap(FakeLima().configuration().coupling_map) with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"): dep_opt = BIPMapping(coupling, objective="depth", qubit_subset=[0, 1, 3, 4])(qc) with self.assertWarnsRegex(DeprecationWarning, r"^The class.*is deprecated"): err_opt = BIPMapping( coupling, objective="gate_error", qubit_subset=[0, 1, 3, 4], backend_prop=FakeLima().properties(), )(qc) # depth = number of su4 layers (mirrored gates have to be consolidated as single su4 gates) pm_ = PassManager([Collect2qBlocks(), ConsolidateBlocks(basis_gates=["cx", "u"])]) dep_opt = pm_.run(dep_opt) err_opt = pm_.run(err_opt) self.assertLessEqual(dep_opt.depth(), err_opt.depth()) # count CNOTs after synthesized dep_opt = UnitarySynthesis(basis_gates=["cx", "u"])(dep_opt) err_opt = UnitarySynthesis(basis_gates=["cx", "u"])(err_opt) self.assertGreater(dep_opt.count_ops()["cx"], err_opt.count_ops()["cx"])
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit_aer import AerSimulator from qiskit.tools.visualization import plot_histogram import random circ = QuantumCircuit(40, 40) # Initialize with a Hadamard layer circ.h(range(40)) # Apply some random CNOT and T gates qubit_indices = [i for i in range(40)] for i in range(10): control, target, t = random.sample(qubit_indices, 3) circ.cx(control, target) circ.t(t) circ.measure(range(40), range(40)) # Create statevector method simulator statevector_simulator = AerSimulator(method='statevector') # Transpile circuit for backend tcirc = transpile(circ, statevector_simulator) # Try and run circuit statevector_result = statevector_simulator.run(tcirc, shots=1).result() print('This succeeded?: {}'.format(statevector_result.success)) print('Why not? {}'.format(statevector_result.status)) # Create extended stabilizer method simulator extended_stabilizer_simulator = AerSimulator(method='extended_stabilizer') # Transpile circuit for backend tcirc = transpile(circ, extended_stabilizer_simulator) extended_stabilizer_result = extended_stabilizer_simulator.run(tcirc, shots=1).result() print('This succeeded?: {}'.format(extended_stabilizer_result.success)) small_circ = QuantumCircuit(2, 2) small_circ.h(0) small_circ.cx(0, 1) small_circ.t(0) small_circ.measure([0, 1], [0, 1]) # This circuit should give 00 or 11 with equal probability... expected_results ={'00': 50, '11': 50} tsmall_circ = transpile(small_circ, extended_stabilizer_simulator) result = extended_stabilizer_simulator.run( tsmall_circ, shots=100).result() counts = result.get_counts(0) print('100 shots in {}s'.format(result.time_taken)) plot_histogram([expected_results, counts], legend=['Expected', 'Extended Stabilizer']) # Add runtime options for extended stabilizer simulator opts = {'extended_stabilizer_approximation_error': 0.03} reduced_error = extended_stabilizer_simulator.run( tsmall_circ, shots=100, **opts).result() reduced_error_counts = reduced_error.get_counts(0) print('100 shots in {}s'.format(reduced_error.time_taken)) plot_histogram([expected_results, reduced_error_counts], legend=['Expected', 'Extended Stabilizer']) print("The circuit above, with 100 shots at precision 0.03 " "and default mixing time, needed {}s".format(int(reduced_error.time_taken))) opts = { 'extended_stabilizer_approximation_error': 0.03, 'extended_stabilizer_mixing_time': 100 } optimized = extended_stabilizer_simulator.run( tsmall_circ, shots=100, **opts).result() print('Dialing down the mixing time, we completed in just {}s'.format(optimized.time_taken)) # We set these options here only to make the example run more quickly. opts = {'extended_stabilizer_mixing_time': 100} multishot = extended_stabilizer_simulator.run( tcirc, shots=100, **opts).result() print("100 shots took {} s".format(multishot.time_taken)) opts = { 'extended_stabilizer_measure_sampling': True, 'extended_stabilizer_mixing_time': 100 } measure_sampling = extended_stabilizer_simulator.run( circ, shots=100, **opts).result() print("With the optimization, 100 shots took {} s".format(result.time_taken)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/quantastica/qiskit-forest
quantastica
# 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 the QAOA algorithm.""" import unittest from functools import partial from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np import rustworkx as rx from ddt import ddt, idata, unpack from scipy.optimize import minimize as scipy_minimize from qiskit import QuantumCircuit from qiskit_algorithms.minimum_eigensolvers import QAOA from qiskit_algorithms.optimizers import COBYLA, NELDER_MEAD from qiskit.circuit import Parameter from qiskit.primitives import Sampler from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit.result import QuasiDistribution from qiskit.utils import algorithm_globals W1 = np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]) P1 = 1 M1 = SparsePauliOp.from_list( [ ("IIIX", 1), ("IIXI", 1), ("IXII", 1), ("XIII", 1), ] ) S1 = {"0101", "1010"} W2 = np.array( [ [0.0, 8.0, -9.0, 0.0], [8.0, 0.0, 7.0, 9.0], [-9.0, 7.0, 0.0, -8.0], [0.0, 9.0, -8.0, 0.0], ] ) P2 = 1 M2 = None S2 = {"1011", "0100"} CUSTOM_SUPERPOSITION = [1 / np.sqrt(15)] * 15 + [0] @ddt class TestQAOA(QiskitAlgorithmsTestCase): """Test QAOA with MaxCut.""" def setUp(self): super().setUp() self.seed = 10598 algorithm_globals.random_seed = self.seed self.sampler = Sampler() @idata( [ [W1, P1, M1, S1], [W2, P2, M2, S2], ] ) @unpack def test_qaoa(self, w, reps, mixer, solutions): """QAOA test""" self.log.debug("Testing %s-step QAOA with MaxCut on graph\n%s", reps, w) qubit_op, _ = self._get_operator(w) qaoa = QAOA(self.sampler, COBYLA(), reps=reps, mixer=mixer) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, solutions) @idata( [ [W1, P1, S1], [W2, P2, S2], ] ) @unpack def test_qaoa_qc_mixer(self, w, prob, solutions): """QAOA test with a mixer as a parameterized circuit""" self.log.debug( "Testing %s-step QAOA with MaxCut on graph with a mixer as a parameterized circuit\n%s", prob, w, ) optimizer = COBYLA() qubit_op, _ = self._get_operator(w) num_qubits = qubit_op.num_qubits mixer = QuantumCircuit(num_qubits) theta = Parameter("θ") mixer.rx(theta, range(num_qubits)) qaoa = QAOA(self.sampler, optimizer, reps=prob, mixer=mixer) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, solutions) def test_qaoa_qc_mixer_many_parameters(self): """QAOA test with a mixer as a parameterized circuit with the num of parameters > 1.""" optimizer = COBYLA() qubit_op, _ = self._get_operator(W1) num_qubits = qubit_op.num_qubits mixer = QuantumCircuit(num_qubits) for i in range(num_qubits): theta = Parameter("θ" + str(i)) mixer.rx(theta, range(num_qubits)) qaoa = QAOA(self.sampler, optimizer, reps=2, mixer=mixer) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) self.log.debug(x) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, S1) def test_qaoa_qc_mixer_no_parameters(self): """QAOA test with a mixer as a parameterized circuit with zero parameters.""" qubit_op, _ = self._get_operator(W1) num_qubits = qubit_op.num_qubits mixer = QuantumCircuit(num_qubits) # just arbitrary circuit mixer.rx(np.pi / 2, range(num_qubits)) qaoa = QAOA(self.sampler, COBYLA(), reps=1, mixer=mixer) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) # we just assert that we get a result, it is not meaningful. self.assertIsNotNone(result.eigenstate) def test_change_operator_size(self): """QAOA change operator size test""" qubit_op, _ = self._get_operator( np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]) ) qaoa = QAOA(self.sampler, COBYLA(), reps=1) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest(msg="QAOA 4x4"): self.assertIn(graph_solution, {"0101", "1010"}) qubit_op, _ = self._get_operator( np.array( [ [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0], ] ) ) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest(msg="QAOA 6x6"): self.assertIn(graph_solution, {"010101", "101010"}) @idata([[W2, S2, None], [W2, S2, [0.0, 0.0]], [W2, S2, [1.0, 0.8]]]) @unpack def test_qaoa_initial_point(self, w, solutions, init_pt): """Check first parameter value used is initial point as expected""" qubit_op, _ = self._get_operator(w) first_pt = [] def cb_callback(eval_count, parameters, mean, metadata): nonlocal first_pt if eval_count == 1: first_pt = list(parameters) qaoa = QAOA( self.sampler, COBYLA(), initial_point=init_pt, callback=cb_callback, ) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest("Initial Point"): # If None the preferred random initial point of QAOA variational form if init_pt is None: self.assertLess(result.eigenvalue, -0.97) else: self.assertListEqual(init_pt, first_pt) with self.subTest("Solution"): self.assertIn(graph_solution, solutions) def test_qaoa_random_initial_point(self): """QAOA random initial point""" w = rx.adjacency_matrix( rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed) ) qubit_op, _ = self._get_operator(w) qaoa = QAOA(self.sampler, NELDER_MEAD(disp=True), reps=2) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) self.assertLess(result.eigenvalue, -0.97) def test_optimizer_scipy_callable(self): """Test passing a SciPy optimizer directly as callable.""" w = rx.adjacency_matrix( rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed) ) qubit_op, _ = self._get_operator(w) qaoa = QAOA( self.sampler, partial(scipy_minimize, method="Nelder-Mead", options={"maxiter": 2}), ) result = qaoa.compute_minimum_eigenvalue(qubit_op) self.assertEqual(result.cost_function_evals, 5) def _get_operator(self, weight_matrix): """Generate Hamiltonian for the max-cut problem of a graph. Args: weight_matrix (numpy.ndarray) : adjacency matrix. Returns: PauliSumOp: operator for the Hamiltonian float: a constant shift for the obj function. """ num_nodes = weight_matrix.shape[0] pauli_list = [] shift = 0 for i in range(num_nodes): for j in range(i): if weight_matrix[i, j] != 0: x_p = np.zeros(num_nodes, dtype=bool) z_p = np.zeros(num_nodes, dtype=bool) z_p[i] = True z_p[j] = True pauli_list.append([0.5 * weight_matrix[i, j], Pauli((z_p, x_p))]) shift -= 0.5 * weight_matrix[i, j] lst = [(pauli[1].to_label(), pauli[0]) for pauli in pauli_list] return SparsePauliOp.from_list(lst), shift def _get_graph_solution(self, x: np.ndarray) -> str: """Get graph solution from binary string. Args: x : binary string as numpy array. Returns: a graph solution as string. """ return "".join([str(int(i)) for i in 1 - x]) def _sample_most_likely(self, state_vector: QuasiDistribution) -> np.ndarray: """Compute the most likely binary string from state vector. Args: state_vector: Quasi-distribution. Returns: Binary string as numpy.ndarray of ints. """ values = list(state_vector.values()) n = int(np.log2(len(values))) k = np.argmax(np.abs(values)) x = np.zeros(n) for i in range(n): x[i] = k % 2 k >>= 1 return x if __name__ == "__main__": unittest.main()
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. """Test of generated fake backends.""" import math import unittest from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, schedule, transpile, assemble from qiskit.pulse import Schedule from qiskit.qobj import PulseQobj from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider.utils.configurable_backend import ConfigurableFakeBackend from qiskit.providers.fake_provider import FakeAthens, FakePerth from qiskit.utils import optionals def get_test_circuit(): """Generates simple circuit for tests.""" desired_vector = [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)] qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.initialize(desired_vector, [qr[0], qr[1]]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) return qc class GeneratedFakeBackendsTest(QiskitTestCase): """Generated fake backends test.""" def setUp(self) -> None: self.backend = ConfigurableFakeBackend("Tashkent", n_qubits=4) @unittest.skip("Skipped until qiskit-aer#741 is fixed and released") @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test") def test_transpile_schedule_and_assemble(self): """Test transpile, schedule and assemble on generated backend.""" qc = get_test_circuit() circuit = transpile(qc, backend=self.backend) self.assertTrue(isinstance(circuit, QuantumCircuit)) self.assertEqual(circuit.num_qubits, 4) experiments = schedule(circuits=circuit, backend=self.backend) self.assertTrue(isinstance(experiments, Schedule)) self.assertGreater(experiments.duration, 0) qobj = assemble(experiments, backend=self.backend) self.assertTrue(isinstance(qobj, PulseQobj)) self.assertEqual(qobj.header.backend_name, "Tashkent") self.assertEqual(len(qobj.experiments), 1) job = self.backend.run(qobj) result = job.result() self.assertTrue(result.success) self.assertEqual(len(result.results), 1) class FakeBackendsTest(QiskitTestCase): """fake backends test.""" @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test") def test_fake_backends_get_kwargs(self): """Fake backends honor kwargs passed.""" backend = FakeAthens() qc = QuantumCircuit(2) qc.x(range(0, 2)) qc.measure_all() trans_qc = transpile(qc, backend) raw_counts = backend.run(trans_qc, shots=1000).result().get_counts() self.assertEqual(sum(raw_counts.values()), 1000) @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test") def test_fake_backend_v2_noise_model_always_present(self): """Test that FakeBackendV2 instances always run with noise.""" backend = FakePerth() qc = QuantumCircuit(1) qc.x(0) qc.measure_all() res = backend.run(qc, shots=1000).result().get_counts() # Assert noise was present and result wasn't ideal self.assertNotEqual(res, {"1": 1000})
https://github.com/qiskit-community/qiskit-pocket-guide
qiskit-community
from qiskit.quantum_info import Statevector from qiskit.quantum_info import Statevector, \ Operator, state_fidelity sv_a = Statevector.from_label('+') sv_b = sv_a.evolve(Operator.from_label('T')) print(state_fidelity(sv_a, sv_b))
https://github.com/alpine-quantum-technologies/qiskit-aqt-provider-rc
alpine-quantum-technologies
# This code is part of Qiskit. # # (C) Copyright IBM 2019, Alpine Quantum Technologies GmbH 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. from typing import List from numpy import pi from qiskit import QuantumCircuit from qiskit_aqt_provider import api_models def _qiskit_to_aqt_circuit(circuit: QuantumCircuit) -> api_models.Circuit: """Convert a Qiskit `QuantumCircuit` into a payload for AQT's quantum_circuit job type. Args: circuit: Qiskit circuit to convert. Returns: AQT API circuit payload. """ count = 0 qubit_map = {} for bit in circuit.qubits: qubit_map[bit] = count count += 1 ops: List[api_models.OperationModel] = [] num_measurements = 0 for instruction in circuit.data: inst = instruction[0] qubits = [qubit_map[bit] for bit in instruction[1]] if inst.name != "measure" and num_measurements > 0: raise ValueError( "Measurement operations can only be located at the end of the circuit." ) if inst.name == "rz": ops.append( api_models.Operation.rz( phi=float(inst.params[0]) / pi, qubit=qubits[0], ) ) elif inst.name == "r": ops.append( api_models.Operation.r( phi=float(inst.params[1]) / pi, theta=float(inst.params[0]) / pi, qubit=qubits[0], ) ) elif inst.name == "rxx": ops.append( api_models.Operation.rxx( theta=float(inst.params[0]) / pi, qubits=qubits[:2], ) ) elif inst.name == "measure": num_measurements += 1 elif inst.name == "barrier": continue else: raise ValueError(f"Operation '{inst.name}' not in basis gate set: {{rz, r, rxx}}") if not num_measurements: raise ValueError("Circuit must have at least one measurement operation.") ops.append(api_models.Operation.measure()) return api_models.Circuit(__root__=ops) def circuits_to_aqt_job(circuits: List[QuantumCircuit], shots: int) -> api_models.JobSubmission: """Convert a list of circuits to the corresponding AQT API job request payload. Args: circuits: circuits to execute shots: number of repetitions per circuit. Returns: JobSubmission: AQT API payload for submitting the quantum circuits job. """ return api_models.JobSubmission( job_type="quantum_circuit", label="qiskit", payload=api_models.QuantumCircuits( circuits=[ api_models.QuantumCircuit( repetitions=shots, quantum_circuit=_qiskit_to_aqt_circuit(circuit), number_of_qubits=circuit.num_qubits, ) for circuit in circuits ] ), )
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """HamiltonianGate tests""" import numpy as np from numpy.testing import assert_allclose import qiskit from qiskit.extensions.hamiltonian_gate import HamiltonianGate, UnitaryGate from qiskit.extensions.exceptions import ExtensionError from qiskit.test import QiskitTestCase from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Parameter from qiskit.quantum_info import Operator from qiskit.converters import circuit_to_dag, dag_to_circuit class TestHamiltonianGate(QiskitTestCase): """Tests for the HamiltonianGate class.""" def test_set_matrix(self): """Test instantiation""" hamiltonian = HamiltonianGate([[0, 1], [1, 0]], 1) self.assertEqual(hamiltonian.num_qubits, 1) def test_set_matrix_raises(self): """test non-unitary""" with self.assertRaises(ExtensionError): HamiltonianGate([[1, 0], [1, 1]], 1) def test_complex_time_raises(self): """test non-unitary""" with self.assertRaises(ExtensionError): HamiltonianGate([[1, 0], [1, 1]], 1j) def test_conjugate(self): """test conjugate""" ham = HamiltonianGate([[0, 1j], [-1j, 2]], np.pi / 4) np.testing.assert_array_almost_equal(ham.conjugate().to_matrix(), np.conj(ham.to_matrix())) def test_transpose(self): """test transpose""" ham = HamiltonianGate([[15, 1j], [-1j, -2]], np.pi / 7) np.testing.assert_array_almost_equal( ham.transpose().to_matrix(), np.transpose(ham.to_matrix()) ) def test_adjoint(self): """test adjoint operation""" ham = HamiltonianGate([[3, 4j], [-4j, -0.2]], np.pi * 0.143) np.testing.assert_array_almost_equal( ham.adjoint().to_matrix(), np.transpose(np.conj(ham.to_matrix())) ) class TestHamiltonianCircuit(QiskitTestCase): """Hamiltonian gate circuit tests.""" def test_1q_hamiltonian(self): """test 1 qubit hamiltonian""" qr = QuantumRegister(1, "q0") cr = ClassicalRegister(1, "c0") qc = QuantumCircuit(qr, cr) matrix = np.zeros((2, 2)) qc.x(qr[0]) theta = Parameter("theta") qc.append(HamiltonianGate(matrix, theta), [qr[0]]) qc = qc.bind_parameters({theta: 1}) # test of text drawer self.log.info(qc) dag = circuit_to_dag(qc) dag_nodes = dag.named_nodes("hamiltonian") self.assertTrue(len(dag_nodes) == 1) dnode = dag_nodes[0] self.assertIsInstance(dnode.op, HamiltonianGate) self.assertEqual(dnode.qargs, tuple(qc.qubits)) assert_allclose(dnode.op.to_matrix(), np.eye(2)) def test_error_and_deprecation_warning_on_qasm(self): """test that an error is thrown if the method `qasm` is called.""" matrix = np.zeros((2, 2)) hamiltonian_gate = HamiltonianGate(data=matrix, time=1) with self.assertRaises(ExtensionError): with self.assertWarns(DeprecationWarning): hamiltonian_gate.qasm() def test_2q_hamiltonian(self): """test 2 qubit hamiltonian""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) matrix = Operator.from_label("XY") qc.x(qr[0]) theta = Parameter("theta") uni2q = HamiltonianGate(matrix, theta) qc.append(uni2q, [qr[0], qr[1]]) qc2 = qc.bind_parameters({theta: -np.pi / 2}) dag = circuit_to_dag(qc2) nodes = dag.two_qubit_ops() self.assertEqual(len(nodes), 1) dnode = nodes[0] self.assertIsInstance(dnode.op, HamiltonianGate) self.assertEqual(dnode.qargs, (qr[0], qr[1])) # Equality based on Pauli exponential identity np.testing.assert_array_almost_equal(dnode.op.to_matrix(), 1j * matrix.data) qc3 = dag_to_circuit(dag) self.assertEqual(qc2, qc3) def test_3q_hamiltonian(self): """test 3 qubit hamiltonian on non-consecutive bits""" qr = QuantumRegister(4) qc = QuantumCircuit(qr) qc.x(qr[0]) matrix = Operator.from_label("XZY") theta = Parameter("theta") uni3q = HamiltonianGate(matrix, theta) qc.append(uni3q, [qr[0], qr[1], qr[3]]) qc.cx(qr[3], qr[2]) # test of text drawer self.log.info(qc) qc = qc.bind_parameters({theta: -np.pi / 2}) dag = circuit_to_dag(qc) nodes = dag.multi_qubit_ops() self.assertEqual(len(nodes), 1) dnode = nodes[0] self.assertIsInstance(dnode.op, HamiltonianGate) self.assertEqual(dnode.qargs, (qr[0], qr[1], qr[3])) np.testing.assert_almost_equal(dnode.op.to_matrix(), 1j * matrix.data) def test_qobj_with_hamiltonian(self): """test qobj output with hamiltonian""" qr = QuantumRegister(4) qc = QuantumCircuit(qr) qc.rx(np.pi / 4, qr[0]) matrix = Operator.from_label("XIZ") theta = Parameter("theta") uni = HamiltonianGate(matrix, theta, label="XIZ") qc.append(uni, [qr[0], qr[1], qr[3]]) qc.cx(qr[3], qr[2]) qc = qc.bind_parameters({theta: np.pi / 2}) qobj = qiskit.compiler.assemble(qc) instr = qobj.experiments[0].instructions[1] self.assertEqual(instr.name, "hamiltonian") # Also test label self.assertEqual(instr.label, "XIZ") np.testing.assert_array_almost_equal( np.array(instr.params[0]).astype(np.complex64), matrix.data ) def test_decomposes_into_correct_unitary(self): """test 2 qubit hamiltonian""" qc = QuantumCircuit(2) matrix = Operator.from_label("XY") theta = Parameter("theta") uni2q = HamiltonianGate(matrix, theta) qc.append(uni2q, [0, 1]) qc = qc.bind_parameters({theta: -np.pi / 2}).decompose() decomposed_ham = qc.data[0].operation self.assertEqual(decomposed_ham, UnitaryGate(Operator.from_label("XY")))
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() # our backend is the Pulse Simulator from resources import helper from qiskit.providers.aer import PulseSimulator backend_sim = PulseSimulator() # sample duration for pulse instructions dt = 1e-9 # create the model duffing_model = helper.get_transmon(dt) # get qubit frequency from Duffing model qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift() import numpy as np # visualization tools import matplotlib.pyplot as plt plt.style.use('dark_background') # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz kHz = 1.0e3 # kilohertz us = 1.0e-6 # microseconds ns = 1.0e-9 # nanoseconds from qiskit import pulse from qiskit.pulse import Play, Acquire from qiskit.pulse.pulse_lib import GaussianSquare # qubit to be used throughout the notebook qubit = 0 ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) # Construct a measurement schedule and add it to an InstructionScheduleMap meas_samples = 1200 meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150) measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit)) inst_map = pulse.InstructionScheduleMap() inst_map.add('measure', [qubit], measure_sched) # save the measurement/acquire pulse for later measure = inst_map.get('measure', qubits=[qubit]) from qiskit.pulse import pulse_lib def build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma): ### create a Rabi schedule (already done) ### create a Gaussian Rabi pulse using pulse_lib ### play Rabi pulse on the Rabi schedule and return rabi_schedule = pulse.Schedule(name='rabi_experiment') ### WRITE YOUR CODE BETWEEN THESE LINES - START rabi_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp, sigma=drive_sigma) rabi_schedule = pulse.Schedule() rabi_schedule += Play(rabi_pulse, drive_chan) ### WRITE YOUR CODE BETWEEN THESE LINES - END # add measurement to rabi_schedule # << indicates time shift the beginning to the start of the schedule rabi_schedule += measure << rabi_schedule.duration return rabi_schedule # Gaussian pulse parameters, with varying amplitude drive_duration = 128 num_rabi_points = 41 drive_amps = np.linspace(0, 0.9, num_rabi_points) drive_sigma = 16 # now vary the amplitude for each drive amp rabi_schedules = [] for drive_amp in drive_amps: rabi_schedules.append(build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma)) rabi_schedules[-1].draw() # assemble the schedules into a Qobj from qiskit import assemble rabi_qobj = assemble(**helper.get_params('rabi', globals())) answer1a = rabi_qobj # run the simulation rabi_result = backend_sim.run(rabi_qobj, duffing_model).result() # retrieve the data from the experiment rabi_values = helper.get_values_from_result(rabi_result, qubit) fit_params, y_fit = helper.fit_sinusoid(drive_amps, rabi_values, [1, 0, 0.5, 0]) plt.scatter(drive_amps, rabi_values, color='white') plt.plot(drive_amps, y_fit, color='red') drive_period = fit_params[2] # get period of rabi oscillation plt.axvline(0, color='red', linestyle='--') plt.axvline(drive_period/2, color='red', linestyle='--') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() print("Pi pulse amplitude is %f"%float(drive_period/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_duration, amp=drive_period/4, sigma=drive_sigma, name='x90_pulse') # Ramsey experiment parameters time_max_us = 0.4 time_step_us = 0.0035 times_us = np.arange(0.1, time_max_us, time_step_us) # Convert to units of dt delay_times_dt = times_us * us / dt def build_ramsey_pulse_schedule(delay): ### create a Ramsey pulse schedule (already done) ### play an x90 pulse on the drive channel ### play another x90 pulse after delay ### add measurement pulse to schedule ramsey_schedule = pulse.Schedule(name='ramsey_experiment') ### HINT: include delay by adding it to the duration of the schedule ### round delay to nearest integer with int(delay) ### WRITE YOUR CODE BETWEEN THESE LINES - START ramsey_schedule = pulse.Schedule() ramsey_schedule += Play(x90_pulse, drive_chan) ramsey_schedule += Play(x90_pulse, drive_chan) << ramsey_schedule.duration + int(delay) ramsey_schedule += measure << ramsey_schedule.duration ### WRITE YOUR CODE BETWEEN THESE LINES - END return ramsey_schedule # create schedules for Ramsey experiment ramsey_schedules = [] for delay in delay_times_dt: ramsey_schedules.append(build_ramsey_pulse_schedule(delay)) ramsey_schedules[-1].draw() # assemble the schedules into a Qobj # the helper will drive the pulses off-resonantly by an unknown value ramsey_qobj = assemble(**helper.get_params('ramsey', globals())) answer1b = ramsey_qobj # run the simulation ramsey_result = backend_sim.run(ramsey_qobj, duffing_model).result() # retrieve the data from the experiment ramsey_values = helper.get_values_from_result(ramsey_result, qubit) # off-resonance component fit_params, y_fit = helper.fit_sinusoid(times_us, ramsey_values, [1, 0.7, 0.1, 0.25]) _, _, ramsey_period_us, _, = fit_params del_f_MHz = 1/ramsey_period_us # freq is MHz since times in us plt.scatter(times_us, np.real(ramsey_values), color='white') plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.6f} MHz") plt.xlim(np.min(times_us), 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(loc=3) plt.show() print("Drive is off-resonant by %f MHz"%float(del_f_MHz)) name = 'Saasha Joshi' email = 'saashajoshi08@gmail.com' from grading_tools import grade grade(answer1a, name, email, 'lab6', 'ex1a') grade(answer1b, name, email, 'lab6', 'ex1b') from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();')); from grading_tools import send_code;send_code('ex1.ipynb')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np # Import Qiskit from qiskit import QuantumCircuit, transpile from qiskit_aer import AerSimulator # Construct quantum circuit circ = QuantumCircuit(2, 2) circ.h(0) circ.cx(0, 1) circ.measure([0,1], [0,1]) # Select the AerSimulator from the Aer provider simulator = AerSimulator(method='matrix_product_state') # Run and get counts, using the matrix_product_state method tcirc = transpile(circ, simulator) result = simulator.run(tcirc).result() counts = result.get_counts(0) counts circ = QuantumCircuit(2, 2) circ.h(0) circ.cx(0, 1) # Define a snapshot that shows the current state vector circ.save_statevector(label='my_sv') circ.save_matrix_product_state(label='my_mps') circ.measure([0,1], [0,1]) # Execute and get saved data tcirc = transpile(circ, simulator) result = simulator.run(tcirc).result() data = result.data(0) #print the result data data num_qubits = 50 circ = QuantumCircuit(num_qubits, num_qubits) # Create EPR state circ.h(0) for i in range (0, num_qubits-1): circ.cx(i, i+1) # Measure circ.measure(range(num_qubits), range(num_qubits)) tcirc = transpile(circ, simulator) result = simulator.run(tcirc).result() print("Time taken: {} sec".format(result.time_taken)) result.get_counts() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.pulse_v2 import draw, IQXSimple from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() qc = transpile(qc, FakeBoeblingen(), layout_method='trivial') sched = schedule(qc, FakeBoeblingen()) draw(sched, style=IQXSimple(), backend=FakeBoeblingen())
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
# -*- 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. """ This module contains the definition of a base class for inverse quantum fourier transforms. """ from abc import abstractmethod from qiskit import QuantumRegister, QuantumCircuit from qiskit.aqua import Pluggable, AquaError class IQFT(Pluggable): """Base class for Inverse QFT. This method should initialize the module and its configuration, and use an exception if a component of the module is available. Args: configuration (dict): configuration dictionary """ @abstractmethod def __init__(self, *args, **kwargs): super().__init__() @classmethod def init_params(cls, params): iqft_params = params.get(Pluggable.SECTION_KEY_IQFT) kwargs = {k: v for k, v in iqft_params.items() if k != 'name'} return cls(**kwargs) @abstractmethod def _build_matrix(self): raise NotImplementedError @abstractmethod def _build_circuit(self, qubits=None, circuit=None, do_swaps=True): raise NotImplementedError def construct_circuit(self, mode='circuit', qubits=None, circuit=None, do_swaps=True): """Construct the circuit. Args: mode (str): 'matrix' or 'circuit' qubits (QuantumRegister or qubits): register or qubits to build the circuit on. circuit (QuantumCircuit): circuit for construction. do_swaps (bool): include the swaps. Returns: The matrix or circuit depending on the specified mode. """ if mode == 'circuit': return self._build_circuit(qubits=qubits, circuit=circuit, do_swaps=do_swaps) elif mode == 'matrix': return self._build_matrix() else: raise AquaError('Unrecognized mode: {}.'.format(mode))
https://github.com/Qubico-Hack/tutorials
Qubico-Hack
!pip install qiskit torch torchvision matplotlib !pip install qiskit-machine-learning !pip install torchviz !pip install qiskit[all] !pip install qiskit == 0.45.2 !pip install qiskit_algorithms == 0.7.1 !pip install qiskit-ibm-runtime == 0.17.0 !pip install qiskit-aer == 0.13.2 #Quentum net draw !pip install pylatexenc # PyTorch import torch from torch.utils.data import DataLoader, Subset from torchvision import datasets, transforms import torch.optim as optim from torch.nn import Module, Conv2d, Linear, Dropout2d, CrossEntropyLoss import torch.nn.functional as F from torchviz import make_dot from torch import Tensor from torch import cat # Qiskit from qiskit import Aer from qiskit_machine_learning.connectors import TorchConnector from qiskit_machine_learning.neural_networks.estimator_qnn import EstimatorQNN from qiskit_machine_learning.circuit.library import QNNCircuit # Visualization import matplotlib.pyplot as plt import numpy as np # Folder direction train_data = datasets.ImageFolder('/content/drive/MyDrive/QCNN/Data-set/Train', transform=transforms.Compose([transforms.ToTensor()])) test_data = datasets.ImageFolder('/content/drive/MyDrive/QCNN/Data-set/Test', transform=transforms.Compose([transforms.ToTensor()])) #e train and test Tensor size print(f"Data tensor Dimension:",train_data[0][0].shape) #Convert to DataLoader train_loader = DataLoader(train_data, shuffle=True, batch_size=1) test_loader = DataLoader(test_data, shuffle=True, batch_size=1) #Show the labels print((train_loader.dataset.class_to_idx)) n_samples_show = 5 data_iter = iter(train_loader) fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 10)) while n_samples_show > 0: images, targets = data_iter.__next__() axes[n_samples_show - 1].imshow(images[0, 0].numpy().squeeze(), cmap=plt.cm.rainbow) axes[n_samples_show - 1].set_xticks([]) axes[n_samples_show - 1].set_yticks([]) axes[n_samples_show - 1].set_title(f"Labeled: {targets[0].item()}") n_samples_show -= 1 # batch size batch_size = 10 # Quantum Neural Networ model def create_qnn(): qnn_circuit = QNNCircuit(2) qnn = EstimatorQNN(circuit=qnn_circuit) return qnn qnn = create_qnn() print(qnn.circuit) # Calcular dinámicamente el tamaño de entrada para fc1 def get_conv_output_size(model, shape): batch_size = 1 input = torch.autograd.Variable(torch.rand(batch_size, *shape)) output_feat = model._forward_features(input) n_size = output_feat.data.view(batch_size, -1).size(1) return n_size #Definimos red neuronal en PyTorch class Net(Module): def __init__(self, qnn): super(Net, self).__init__() self.conv1 = Conv2d(3, 24, kernel_size=5) self.conv2 = Conv2d(24, 48, kernel_size=5) self.dropout = Dropout2d() # Calcular dinámicamente el tamaño de entrada para fc1 #self.conv_output_size = self._get_conv_output_size((3, 432, 432)) self.fc1 = Linear(529200, 512) # Reducir el número de neuronas en fc1 self.fc2 = Linear(512, 2) # Salida 2 para dos clases self.qnn = TorchConnector(qnn) self.fc3 = Linear(1, 1) # Salida 2 para dos clases def _get_conv_output_size(self, shape): batch_size = 1 input = torch.autograd.Variable(torch.rand(batch_size, *shape)) output_feat = self._forward_features(input) n_size = output_feat.data.view(batch_size, -1).size(1) print("Tamaño calculado:", n_size) return n_size def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) x = x.view(x.shape[0], -1) x = F.relu(self.fc1(x)) x = self.fc2(x) x = self.qnn(x) # Aplicamos la red cuántica nuevamente en la sección forward x = self.fc3(x) return cat((x, 1 - x), -1) # Crea una instancia del modelo model = Net(qnn) # Imprimir el modelo print(model) print(f"Device: {next(model.parameters()).device}") #dummy_tensor = next(iter(train_loader))[0].to('cuda') dummy_tensor = next(iter(train_loader))[0] output = model(dummy_tensor) params = dict(list(model.named_parameters())) # Concatenamos los tensores utilizando torch.cat en lugar de cat concatenated_output = torch.cat((output, 1 - output), -1) make_dot(concatenated_output, params=params).render("rnn_torchviz", format="png") # Definimos optimizador y función de pérdida optimizer = optim.Adam(model.parameters(), lr=0.0001) loss_func = CrossEntropyLoss() # Empezamos entrenamiento epochs = 3 # Número de épocas loss_list = [] model.train() # Modelo en modo entrenamiento for epoch in range(epochs): correct = 0 total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad(set_to_none=True) # Se inicializa gradiente output = model(data) loss = loss_func(output, target) loss.backward() # Backward pass optimizer.step() # Optimizamos pesos total_loss.append(loss.item()) # Cálculo de la función de pérdida train_pred = output.argmax(dim=1, keepdim=True) correct += train_pred.eq(target.view_as(train_pred)).sum().item() loss_list.append(sum(total_loss) / len(total_loss)) accuracy = 100 * correct / len(train_loader) #Cálculo de precisión print(f"Training [{100.0 * (epoch + 1) / epochs:.0f}%]\tLoss: {loss_list[-1]:.4f}\tAccuracy: {accuracy:.2f}%") # Evaluar el modelo en el conjunto de prueba model.eval() correct = 0 with torch.no_grad(): for data, target in test_loader: output = model(data) test_pred = output.argmax(dim=1, keepdim=True) correct += test_pred.eq(target.view_as(test_pred)).sum().item() accuracy = 100 * correct / len(test_loader.dataset) print(f"Accuracy on test set: {accuracy:.2f}%") # Graficar la pérdida durante el entrenamiento plt.plot(loss_list) plt.xlabel('Época') plt.ylabel('Pérdida') plt.title('Pérdida durante el entrenamiento') plt.show() # Guardar los pesos del modelo torch.save(model.state_dict(), '/content/drive/MyDrive/QCNN/Weigth/Epoca_3_modelo_pesos.pth') from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, classification_report, roc_curve, auc # Evaluar el modelo en el conjunto de prueba model.eval() all_preds = [] all_targets = [] with torch.no_grad(): for data, target in test_loader: output = model(data) test_pred = output.argmax(dim=1, keepdim=True) all_preds.append(test_pred.item()) all_targets.append(target.item()) # Calcular y mostrar métricas adicionales accuracy = accuracy_score(all_targets, all_preds) precision = precision_score(all_targets, all_preds) recall = recall_score(all_targets, all_preds) f1 = f1_score(all_targets, all_preds) print(f"Accuracy: {accuracy:.2f}") print(f"Precision: {precision:.2f}") print(f"Recall: {recall:.2f}") print(f"F1 Score: {f1:.2f}") # Mostrar el informe de clasificación print("\nClassification Report:") print(classification_report(all_targets, all_preds)) # Evaluar el modelo en el conjunto de prueba model.eval() all_probs = [] with torch.no_grad(): for data, target in test_loader: output = model(data) probs = output[:, 1].numpy() # Probabilidades de pertenecer a la clase 1 all_probs.append(probs) # Concatenar las probabilidades de todas las muestras all_probs = np.concatenate(all_probs) # Calcular la curva ROC y el AUC fpr, tpr, thresholds = roc_curve(all_targets, all_probs) roc_auc = auc(fpr, tpr) # Mostrar la curva ROC y el AUC plt.figure() plt.plot(fpr, tpr, color='darkorange', lw=2, label=f'AUC = {roc_auc:.2f}') plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('Tasa de Falsos Positivos (FPR)') plt.ylabel('Tasa de Verdaderos Positivos (TPR)') plt.title('Curva ROC') plt.legend(loc="lower right") plt.show()
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
# -*- 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 Truth Table-based Quantum Oracle. """ import logging import operator import math import numpy as np from functools import reduce from dlx import DLX from qiskit import QuantumRegister, QuantumCircuit from qiskit.aqua import AquaError from qiskit.aqua.circuits import ESOP from qiskit.aqua.components.oracles import Oracle from qiskit.aqua.utils.arithmetic import is_power_of_2 from ._pyeda_check import _check_pluggable_valid as check_pyeda_valid logger = logging.getLogger(__name__) def get_prime_implicants(ones=None, dcs=None): """ Compute all prime implicants for a truth table using the Quine-McCluskey Algorithm Args: ones (list of int): The list of integers corresponding to '1' outputs dcs (list of int): The list of integers corresponding to don't-cares Return: list of lists of int, representing all prime implicants """ def combine_terms(terms, num1s_dict=None): if num1s_dict is None: num1s_dict = {} for num in terms: num1s = bin(num).count('1') if num1s not in num1s_dict: num1s_dict[num1s] = [num] else: num1s_dict[num1s].append(num) new_implicants = {} new_num1s_dict = {} prime_dict = {mt: True for mt in sorted(terms)} cur_num1s, max_num1s = min(num1s_dict.keys()), max(num1s_dict.keys()) while cur_num1s < max_num1s: if cur_num1s in num1s_dict and (cur_num1s + 1) in num1s_dict: for cur_term in sorted(num1s_dict[cur_num1s]): for next_term in sorted(num1s_dict[cur_num1s + 1]): if isinstance(cur_term, int): diff_mask = dc_mask = cur_term ^ next_term implicant_mask = cur_term & next_term elif isinstance(cur_term, tuple): if terms[cur_term][1] == terms[next_term][1]: diff_mask = terms[cur_term][0] ^ terms[next_term][0] dc_mask = diff_mask | terms[cur_term][1] implicant_mask = terms[cur_term][0] & terms[next_term][0] else: continue else: raise AquaError('Unexpected type: {}.'.format(type(cur_term))) if bin(diff_mask).count('1') == 1: prime_dict[cur_term] = False prime_dict[next_term] = False if isinstance(cur_term, int): cur_implicant = (cur_term, next_term) elif isinstance(cur_term, tuple): cur_implicant = tuple(sorted((*cur_term, *next_term))) else: raise AquaError('Unexpected type: {}.'.format(type(cur_term))) new_implicants[cur_implicant] = ( implicant_mask, dc_mask ) num1s = bin(implicant_mask).count('1') if num1s not in new_num1s_dict: new_num1s_dict[num1s] = [cur_implicant] else: if cur_implicant not in new_num1s_dict[num1s]: new_num1s_dict[num1s].append(cur_implicant) cur_num1s += 1 return new_implicants, new_num1s_dict, prime_dict terms = ones + dcs cur_num1s_dict = None prime_implicants = [] while True: next_implicants, next_num1s_dict, cur_prime_dict = combine_terms(terms, num1s_dict=cur_num1s_dict) for implicant in cur_prime_dict: if cur_prime_dict[implicant]: if isinstance(implicant, int): if implicant not in dcs: prime_implicants.append((implicant,)) else: if not set.issubset(set(implicant), dcs): prime_implicants.append(implicant) if next_implicants: terms = next_implicants cur_num1s_dict = next_num1s_dict else: break return prime_implicants def get_exact_covers(cols, rows, num_cols=None): """ Use Algorithm X to get all solutions to the exact cover problem https://en.wikipedia.org/wiki/Knuth%27s_Algorithm_X Args: cols (list of int): A list of integers representing the columns to be covered rows (list of list of int): A list of lists of integers representing the rows num_cols (int): The total number of columns Returns: All exact covers """ if num_cols is None: num_cols = max(cols) + 1 ec = DLX([(c, 0 if c in cols else 1) for c in range(num_cols)]) ec.appendRows([[c] for c in cols]) ec.appendRows(rows) exact_covers = [] for s in ec.solve(): cover = [] for i in s: cover.append(ec.getRowList(i)) exact_covers.append(cover) return exact_covers class TruthTableOracle(Oracle): CONFIGURATION = { 'name': 'TruthTableOracle', 'description': 'Truth Table Oracle', 'input_schema': { '$schema': 'http://json-schema.org/schema#', 'id': 'truth_table_oracle_schema', 'type': 'object', 'properties': { 'bitmaps': { "type": "array", "default": [], "items": { "type": "string" } }, "optimization": { "type": "string", "default": "off", 'oneOf': [ { 'enum': [ 'off', 'qm-dlx' ] } ] }, 'mct_mode': { 'type': 'string', 'default': 'basic', 'oneOf': [ { 'enum': [ 'basic', 'basic-dirty-ancilla', 'advanced', 'noancilla', ] } ] }, }, 'additionalProperties': False } } def __init__(self, bitmaps, optimization='off', mct_mode='basic'): """ Constructor for Truth Table-based Oracle Args: bitmaps (str or [str]): A single binary string or a list of binary strings representing the desired single- and multi-value truth table. optimization (str): Optimization mode to use for minimizing the circuit. Currently, besides no optimization ('off'), Aqua also supports a 'qm-dlx' mode, which uses the Quine-McCluskey algorithm to compute the prime implicants of the truth table, and then compute an exact cover to try to reduce the circuit. mct_mode (str): The mode to use when constructing multiple-control Toffoli. """ if isinstance(bitmaps, str): bitmaps = [bitmaps] self.validate(locals()) super().__init__() self._mct_mode = mct_mode self._optimization = optimization self._bitmaps = bitmaps # check that the input bitmaps length is a power of 2 if not is_power_of_2(len(bitmaps[0])): raise AquaError('Length of any bitmap must be a power of 2.') for bitmap in bitmaps[1:]: if not len(bitmap) == len(bitmaps[0]): raise AquaError('Length of all bitmaps must be the same.') self._nbits = int(math.log(len(bitmaps[0]), 2)) self._num_outputs = len(bitmaps) esop_exprs = [] for bitmap in bitmaps: esop_expr = self._get_esop_ast(bitmap) esop_exprs.append(esop_expr) self._esops = [ ESOP(esop_expr, num_vars=self._nbits) for esop_expr in esop_exprs ] if esop_exprs else None self.construct_circuit() @staticmethod def check_pluggable_valid(): check_pyeda_valid(TruthTableOracle.CONFIGURATION['name']) def _get_esop_ast(self, bitmap): from pyeda.inter import exprvars, And, Xor v = exprvars('v', self._nbits) def binstr_to_vars(binstr): return [ (~v[x[1] - 1] if x[0] == '0' else v[x[1] - 1]) for x in zip(binstr, reversed(range(1, self._nbits + 1))) ][::-1] if self._optimization == 'off': expression = Xor(*[ And(*binstr_to_vars(term)) for term in [np.binary_repr(idx, self._nbits) for idx, v in enumerate(bitmap) if v == '1']]) else: # self._optimization == 'qm-dlx': ones = [i for i, v in enumerate(bitmap) if v == '1'] if not ones: return ('const', 0,) dcs = [i for i, v in enumerate(bitmap) if v == '*' or v == '-' or v.lower() == 'x'] pis = get_prime_implicants(ones=ones, dcs=dcs) cover = get_exact_covers(ones, pis)[-1] clauses = [] for c in cover: if len(c) == 1: term = np.binary_repr(c[0], self._nbits) clause = And(*[ v for i, v in enumerate(binstr_to_vars(term)) ]) elif len(c) > 1: c_or = reduce(operator.or_, c) c_and = reduce(operator.and_, c) _ = np.binary_repr(c_and ^ c_or, self._nbits)[::-1] clause = And(*[ v for i, v in enumerate(binstr_to_vars(np.binary_repr(c_and, self._nbits))) if _[i] == '0' ]) else: raise AquaError('Unexpected cover term size {}.'.format(len(c))) if clause: clauses.append(clause) expression = Xor(*clauses) raw_ast = expression.to_ast() idx_mapping = { u: v + 1 for u, v in zip(sorted(expression.usupport), [v.indices[0] for v in sorted(expression.support)]) } if raw_ast[0] == 'and' or raw_ast[0] == 'or' or raw_ast[0] == 'xor': clauses = [] for c in raw_ast[1:]: if c[0] == 'lit': clauses.append(('lit', (idx_mapping[c[1]]) if c[1] > 0 else (-idx_mapping[-c[1]]))) elif (c[0] == 'or' or c[0] == 'and') and (raw_ast[0] != c[0]): clause = [] for l in c[1:]: clause.append(('lit', (idx_mapping[l[1]]) if l[1] > 0 else (-idx_mapping[-l[1]]))) clauses.append((c[0], *clause)) else: raise AquaError('Unrecognized logic expression: {}'.format(raw_ast)) elif raw_ast[0] == 'const' or raw_ast[0] == 'lit': return raw_ast else: raise AquaError('Unrecognized root expression type: {}.'.format(raw_ast[0])) ast = (raw_ast[0], *clauses) return ast @property def variable_register(self): return self._variable_register @property def ancillary_register(self): return self._ancillary_register @property def output_register(self): return self._output_register def construct_circuit(self): if self._circuit is not None: return self._circuit self._circuit = QuantumCircuit() self._output_register = QuantumRegister(self._num_outputs, name='o') if self._esops: for i, e in enumerate(self._esops): if e is not None: ci = e.construct_circuit(output_register=self._output_register, output_idx=i) self._circuit += ci self._variable_register = self._ancillary_register = None for qreg in self._circuit.qregs: if qreg.name == 'v': self._variable_register = qreg elif qreg.name == 'a': self._ancillary_register = qreg else: self._variable_register = QuantumRegister(self._nbits, name='v') self._ancillary_register = None self._circuit.add_register(self._variable_register, self._output_register) return self._circuit def evaluate_classically(self, measurement): assignment = [(var + 1) * (int(tf) * 2 - 1) for tf, var in zip(measurement[::-1], range(len(measurement)))] ret = [bitmap[int(measurement, 2)] == '1' for bitmap in self._bitmaps] if self._num_outputs == 1: return ret[0], assignment else: return ret, assignment
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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. """Test QASM3 exporter.""" # We can't really help how long the lines output by the exporter are in some cases. # pylint: disable=line-too-long from io import StringIO from math import pi import re import unittest from ddt import ddt, data from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile from qiskit.circuit import Parameter, Qubit, Clbit, Instruction, Gate, Delay, Barrier from qiskit.circuit.classical import expr from qiskit.circuit.controlflow import CASE_DEFAULT from qiskit.test import QiskitTestCase from qiskit.qasm3 import Exporter, dumps, dump, QASM3ExporterError, ExperimentalFeatures from qiskit.qasm3.exporter import QASM3Builder from qiskit.qasm3.printer import BasicPrinter # Tests marked with this decorator should be restored after gate definition with parameters is fixed # properly, and the dummy tests after them should be deleted. See gh-7335. requires_fixed_parameterisation = unittest.expectedFailure class TestQASM3Functions(QiskitTestCase): """QASM3 module - high level functions""" def setUp(self): self.circuit = QuantumCircuit(2) self.circuit.u(2 * pi, 3 * pi, -5 * pi, 0) self.expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "qubit[2] q;", "U(2*pi, 3*pi, -5*pi) q[0];", "", ] ) super().setUp() def test_dumps(self): """Test dumps.""" result = dumps(self.circuit) self.assertEqual(result, self.expected_qasm) def test_dump(self): """Test dump into an IO stream.""" io = StringIO() dump(self.circuit, io) result = io.getvalue() self.assertEqual(result, self.expected_qasm) @ddt class TestCircuitQASM3(QiskitTestCase): """QASM3 exporter.""" maxDiff = 1_000_000 @classmethod def setUpClass(cls): # These regexes are not perfect by any means, but sufficient for simple tests on controlled # input circuits. They can allow false negatives (in which case, update the regex), but to # be useful for the tests must _never_ have false positive matches. We use an explicit # space (`\s`) or semicolon rather than the end-of-word `\b` because we want to ensure that # the exporter isn't putting out invalid characters as part of the identifiers. cls.register_regex = re.compile( r"^\s*(let|(qu)?bit(\[\d+\])?)\s+(?P<name>\w+)[\s;]", re.U | re.M ) scalar_type_names = { "angle", "duration", "float", "int", "stretch", "uint", } cls.scalar_parameter_regex = re.compile( r"^\s*((input|output|const)\s+)?" # Modifier rf"({'|'.join(scalar_type_names)})\s*(\[[^\]]+\])?\s+" # Type name and designator r"(?P<name>\w+)[\s;]", # Parameter name re.U | re.M, ) super().setUpClass() def test_regs_conds_qasm(self): """Test with registers and conditionals.""" qr1 = QuantumRegister(1, "qr1") qr2 = QuantumRegister(2, "qr2") cr = ClassicalRegister(3, "cr") qc = QuantumCircuit(qr1, qr2, cr) qc.measure(qr1[0], cr[0]) qc.measure(qr2[0], cr[1]) qc.measure(qr2[1], cr[2]) qc.x(qr2[1]).c_if(cr, 0) qc.y(qr1[0]).c_if(cr, 1) qc.z(qr1[0]).c_if(cr, 2) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[3] cr;", "qubit[1] qr1;", "qubit[2] qr2;", "cr[0] = measure qr1[0];", "cr[1] = measure qr2[0];", "cr[2] = measure qr2[1];", "if (cr == 0) {", " x qr2[1];", "}", "if (cr == 1) {", " y qr1[0];", "}", "if (cr == 2) {", " z qr1[0];", "}", "", ] ) self.assertEqual(Exporter().dumps(qc), expected_qasm) def test_registers_as_aliases(self): """Test that different types of alias creation and concatenation work.""" qubits = [Qubit() for _ in [None] * 10] first_four = QuantumRegister(name="first_four", bits=qubits[:4]) last_five = QuantumRegister(name="last_five", bits=qubits[5:]) alternate = QuantumRegister(name="alternate", bits=qubits[::2]) sporadic = QuantumRegister(name="sporadic", bits=[qubits[4], qubits[2], qubits[9]]) qc = QuantumCircuit(qubits, first_four, last_five, alternate, sporadic) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "qubit _qubit0;", "qubit _qubit1;", "qubit _qubit2;", "qubit _qubit3;", "qubit _qubit4;", "qubit _qubit5;", "qubit _qubit6;", "qubit _qubit7;", "qubit _qubit8;", "qubit _qubit9;", "let first_four = {_qubit0, _qubit1, _qubit2, _qubit3};", "let last_five = {_qubit5, _qubit6, _qubit7, _qubit8, _qubit9};", "let alternate = {first_four[0], first_four[2], _qubit4, last_five[1], last_five[3]};", "let sporadic = {alternate[2], alternate[1], last_five[4]};", "", ] ) self.assertEqual(Exporter(allow_aliasing=True).dumps(qc), expected_qasm) def test_composite_circuit(self): """Test with a composite circuit instruction and barriers""" composite_circ_qreg = QuantumRegister(2) composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ") composite_circ.h(0) composite_circ.x(1) composite_circ.cx(0, 1) composite_circ_instr = composite_circ.to_gate() qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0, 1) qc.barrier() qc.append(composite_circ_instr, [0, 1]) qc.measure([0, 1], [0, 1]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate composite_circ _gate_q_0, _gate_q_1 {", " h _gate_q_0;", " x _gate_q_1;", " cx _gate_q_0, _gate_q_1;", "}", "bit[2] cr;", "qubit[2] qr;", "h qr[0];", "cx qr[0], qr[1];", "barrier qr[0], qr[1];", "composite_circ qr[0], qr[1];", "cr[0] = measure qr[0];", "cr[1] = measure qr[1];", "", ] ) self.assertEqual(Exporter().dumps(qc), expected_qasm) def test_custom_gate(self): """Test custom gates (via to_gate).""" composite_circ_qreg = QuantumRegister(2) composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ") composite_circ.h(0) composite_circ.x(1) composite_circ.cx(0, 1) composite_circ_instr = composite_circ.to_gate() qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0, 1) qc.barrier() qc.append(composite_circ_instr, [0, 1]) qc.measure([0, 1], [0, 1]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate composite_circ _gate_q_0, _gate_q_1 {", " h _gate_q_0;", " x _gate_q_1;", " cx _gate_q_0, _gate_q_1;", "}", "bit[2] cr;", "qubit[2] qr;", "h qr[0];", "cx qr[0], qr[1];", "barrier qr[0], qr[1];", "composite_circ qr[0], qr[1];", "cr[0] = measure qr[0];", "cr[1] = measure qr[1];", "", ] ) self.assertEqual(Exporter().dumps(qc), expected_qasm) def test_same_composite_circuits(self): """Test when a composite circuit is added to the circuit multiple times.""" composite_circ_qreg = QuantumRegister(2) composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ") composite_circ.h(0) composite_circ.x(1) composite_circ.cx(0, 1) composite_circ_instr = composite_circ.to_gate() qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0, 1) qc.barrier() qc.append(composite_circ_instr, [0, 1]) qc.append(composite_circ_instr, [0, 1]) qc.measure([0, 1], [0, 1]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate composite_circ _gate_q_0, _gate_q_1 {", " h _gate_q_0;", " x _gate_q_1;", " cx _gate_q_0, _gate_q_1;", "}", "bit[2] cr;", "qubit[2] qr;", "h qr[0];", "cx qr[0], qr[1];", "barrier qr[0], qr[1];", "composite_circ qr[0], qr[1];", "composite_circ qr[0], qr[1];", "cr[0] = measure qr[0];", "cr[1] = measure qr[1];", "", ] ) self.assertEqual(Exporter().dumps(qc), expected_qasm) def test_composite_circuits_with_same_name(self): """Test when multiple composite circuit instructions same name and different implementation.""" my_gate = QuantumCircuit(1, name="my_gate") my_gate.h(0) my_gate_inst1 = my_gate.to_gate() my_gate = QuantumCircuit(1, name="my_gate") my_gate.x(0) my_gate_inst2 = my_gate.to_gate() my_gate = QuantumCircuit(1, name="my_gate") my_gate.x(0) my_gate_inst3 = my_gate.to_gate() qr = QuantumRegister(1, name="qr") circuit = QuantumCircuit(qr, name="circuit") circuit.append(my_gate_inst1, [qr[0]]) circuit.append(my_gate_inst2, [qr[0]]) my_gate_inst2_id = id(circuit.data[-1].operation) circuit.append(my_gate_inst3, [qr[0]]) my_gate_inst3_id = id(circuit.data[-1].operation) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate my_gate _gate_q_0 {", " h _gate_q_0;", "}", f"gate my_gate_{my_gate_inst2_id} _gate_q_0 {{", " x _gate_q_0;", "}", f"gate my_gate_{my_gate_inst3_id} _gate_q_0 {{", " x _gate_q_0;", "}", "qubit[1] qr;", "my_gate qr[0];", f"my_gate_{my_gate_inst2_id} qr[0];", f"my_gate_{my_gate_inst3_id} qr[0];", "", ] ) self.assertEqual(Exporter().dumps(circuit), expected_qasm) def test_pi_disable_constants_false(self): """Test pi constant (disable_constants=False)""" circuit = QuantumCircuit(2) circuit.u(2 * pi, 3 * pi, -5 * pi, 0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "qubit[2] q;", "U(2*pi, 3*pi, -5*pi) q[0];", "", ] ) self.assertEqual(Exporter(disable_constants=False).dumps(circuit), expected_qasm) def test_pi_disable_constants_true(self): """Test pi constant (disable_constants=True)""" circuit = QuantumCircuit(2) circuit.u(2 * pi, 3 * pi, -5 * pi, 0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "qubit[2] q;", "U(6.283185307179586, 9.42477796076938, -15.707963267948966) q[0];", "", ] ) self.assertEqual(Exporter(disable_constants=True).dumps(circuit), expected_qasm) def test_custom_gate_with_unbound_parameter(self): """Test custom gate with unbound parameter.""" parameter_a = Parameter("a") custom = QuantumCircuit(1, name="custom") custom.rx(parameter_a, 0) circuit = QuantumCircuit(1) circuit.append(custom.to_gate(), [0]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "input float[64] a;", "gate custom(a) _gate_q_0 {", " rx(a) _gate_q_0;", "}", "qubit[1] q;", "custom(a) q[0];", "", ] ) self.assertEqual(Exporter().dumps(circuit), expected_qasm) def test_custom_gate_with_bound_parameter(self): """Test custom gate with bound parameter.""" parameter_a = Parameter("a") custom = QuantumCircuit(1) custom.rx(parameter_a, 0) custom_gate = custom.bind_parameters({parameter_a: 0.5}).to_gate() custom_gate.name = "custom" circuit = QuantumCircuit(1) circuit.append(custom_gate, [0]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate custom _gate_q_0 {", " rx(0.5) _gate_q_0;", "}", "qubit[1] q;", "custom q[0];", "", ] ) self.assertEqual(Exporter().dumps(circuit), expected_qasm) @requires_fixed_parameterisation def test_custom_gate_with_params_bound_main_call(self): """Custom gate with unbound parameters that are bound in the main circuit""" parameter0 = Parameter("p0") parameter1 = Parameter("p1") custom = QuantumCircuit(2, name="custom") custom.rz(parameter0, 0) custom.rz(parameter1 / 2, 1) qr_all_qubits = QuantumRegister(3, "q") qr_r = QuantumRegister(3, "r") circuit = QuantumCircuit(qr_all_qubits, qr_r) circuit.append(custom.to_gate(), [qr_all_qubits[0], qr_r[0]]) circuit.assign_parameters({parameter0: pi, parameter1: pi / 2}, inplace=True) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate custom(_gate_p_0, _gate_p_0) _gate_q_0, _gate_q_1 {", " rz(pi) _gate_q_0;", " rz(pi/4) _gate_q_1;", "}", "qubit[3] q;", "qubit[3] r;", "custom(pi, pi/2) q[0], r[0];", "", ] ) self.assertEqual(Exporter().dumps(circuit), expected_qasm) def test_reused_custom_parameter(self): """Test reused custom gate with parameter.""" parameter_a = Parameter("a") custom = QuantumCircuit(1) custom.rx(parameter_a, 0) circuit = QuantumCircuit(1) circuit.append(custom.bind_parameters({parameter_a: 0.5}).to_gate(), [0]) circuit.append(custom.bind_parameters({parameter_a: 1}).to_gate(), [0]) circuit_name_0 = circuit.data[0].operation.definition.name circuit_name_1 = circuit.data[1].operation.definition.name expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', f"gate {circuit_name_0} _gate_q_0 {{", " rx(0.5) _gate_q_0;", "}", f"gate {circuit_name_1} _gate_q_0 {{", " rx(1.0) _gate_q_0;", "}", "qubit[1] q;", f"{circuit_name_0} q[0];", f"{circuit_name_1} q[0];", "", ] ) self.assertEqual(Exporter().dumps(circuit), expected_qasm) def test_unbound_circuit(self): """Test with unbound parameters (turning them into inputs).""" qc = QuantumCircuit(1) theta = Parameter("θ") qc.rz(theta, 0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "input float[64] θ;", "qubit[1] q;", "rz(θ) q[0];", "", ] ) self.assertEqual(Exporter().dumps(qc), expected_qasm) def test_unknown_parameterized_gate_called_multiple_times(self): """Test that a parameterised gate is called correctly if the first instance of it is generic.""" x, y = Parameter("x"), Parameter("y") qc = QuantumCircuit(2) qc.rzx(x, 0, 1) qc.rzx(y, 0, 1) qc.rzx(0.5, 0, 1) expected_qasm = "\n".join( [ "OPENQASM 3;", "input float[64] x;", "input float[64] y;", "gate rzx(x) _gate_q_0, _gate_q_1 {", " h _gate_q_1;", " cx _gate_q_0, _gate_q_1;", " rz(x) _gate_q_1;", " cx _gate_q_0, _gate_q_1;", " h _gate_q_1;", "}", "qubit[2] q;", "rzx(x) q[0], q[1];", "rzx(y) q[0], q[1];", "rzx(0.5) q[0], q[1];", "", ] ) # Set the includes and basis gates to ensure that this gate is unknown. exporter = Exporter(includes=[], basis_gates=("rz", "h", "cx")) self.assertEqual(exporter.dumps(qc), expected_qasm) def test_gate_qasm_with_ctrl_state(self): """Test with open controlled gate that has ctrl_state""" qc = QuantumCircuit(2) qc.ch(0, 1, ctrl_state=0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate ch_o0 _gate_q_0, _gate_q_1 {", " x _gate_q_0;", " ch _gate_q_0, _gate_q_1;", " x _gate_q_0;", "}", "qubit[2] q;", "ch_o0 q[0], q[1];", "", ] ) self.assertEqual(Exporter().dumps(qc), expected_qasm) def test_custom_gate_collision_with_stdlib(self): """Test a custom gate with name collision with the standard library.""" custom = QuantumCircuit(2, name="cx") custom.cx(0, 1) custom_gate = custom.to_gate() qc = QuantumCircuit(2) qc.append(custom_gate, [0, 1]) custom_gate_id = id(qc.data[-1].operation) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', f"gate cx_{custom_gate_id} _gate_q_0, _gate_q_1 {{", " cx _gate_q_0, _gate_q_1;", "}", "qubit[2] q;", f"cx_{custom_gate_id} q[0], q[1];", "", ] ) self.assertEqual(Exporter().dumps(qc), expected_qasm) @requires_fixed_parameterisation def test_no_include(self): """Test explicit gate declaration (no include)""" q = QuantumRegister(2, "q") circuit = QuantumCircuit(q) circuit.rz(pi / 2, 0) circuit.sx(0) circuit.cx(0, 1) expected_qasm = "\n".join( [ "OPENQASM 3;", "gate u3(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {", " U(0, 0, pi/2) _gate_q_0;", "}", "gate u1(_gate_p_0) _gate_q_0 {", " u3(0, 0, pi/2) _gate_q_0;", "}", "gate rz(_gate_p_0) _gate_q_0 {", " u1(pi/2) _gate_q_0;", "}", "gate sdg _gate_q_0 {", " u1(-pi/2) _gate_q_0;", "}", "gate u2(_gate_p_0, _gate_p_1) _gate_q_0 {", " u3(pi/2, 0, pi) _gate_q_0;", "}", "gate h _gate_q_0 {", " u2(0, pi) _gate_q_0;", "}", "gate sx _gate_q_0 {", " sdg _gate_q_0;", " h _gate_q_0;", " sdg _gate_q_0;", "}", "gate cx c, t {", " ctrl @ U(pi, 0, pi) c, t;", "}", "qubit[2] q;", "rz(pi/2) q[0];", "sx q[0];", "cx q[0], q[1];", "", ] ) self.assertEqual(Exporter(includes=[]).dumps(circuit), expected_qasm) @requires_fixed_parameterisation def test_teleportation(self): """Teleportation with physical qubits""" qc = QuantumCircuit(3, 2) qc.h(1) qc.cx(1, 2) qc.barrier() qc.cx(0, 1) qc.h(0) qc.barrier() qc.measure([0, 1], [0, 1]) qc.barrier() qc.x(2).c_if(qc.clbits[1], 1) qc.z(2).c_if(qc.clbits[0], 1) transpiled = transpile(qc, initial_layout=[0, 1, 2]) expected_qasm = "\n".join( [ "OPENQASM 3;", "gate u3(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {", " U(pi/2, 0, pi) _gate_q_0;", "}", "gate u2(_gate_p_0, _gate_p_1) _gate_q_0 {", " u3(pi/2, 0, pi) _gate_q_0;", "}", "gate h _gate_q_0 {", " u2(0, pi) _gate_q_0;", "}", "gate cx c, t {", " ctrl @ U(pi, 0, pi) c, t;", "}", "gate x _gate_q_0 {", " u3(pi, 0, pi) _gate_q_0;", "}", "gate u1(_gate_p_0) _gate_q_0 {", " u3(0, 0, pi) _gate_q_0;", "}", "gate z _gate_q_0 {", " u1(pi) _gate_q_0;", "}", "bit[2] c;", "h $1;", "cx $1, $2;", "barrier $0, $1, $2;", "cx $0, $1;", "h $0;", "barrier $0, $1, $2;", "c[0] = measure $0;", "c[1] = measure $1;", "barrier $0, $1, $2;", "if (c[1]) {", " x $2;", "}", "if (c[0]) {", " z $2;", "}", "", ] ) self.assertEqual(Exporter(includes=[]).dumps(transpiled), expected_qasm) @requires_fixed_parameterisation def test_basis_gates(self): """Teleportation with physical qubits""" qc = QuantumCircuit(3, 2) qc.h(1) qc.cx(1, 2) qc.barrier() qc.cx(0, 1) qc.h(0) qc.barrier() qc.measure([0, 1], [0, 1]) qc.barrier() qc.x(2).c_if(qc.clbits[1], 1) qc.z(2).c_if(qc.clbits[0], 1) transpiled = transpile(qc, initial_layout=[0, 1, 2]) expected_qasm = "\n".join( [ "OPENQASM 3;", "gate u3(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {", " U(pi/2, 0, pi) _gate_q_0;", "}", "gate u2(_gate_p_0, _gate_p_1) _gate_q_0 {", " u3(pi/2, 0, pi) _gate_q_0;", "}", "gate h _gate_q_0 {", " u2(0, pi) _gate_q_0;", "}", "gate x _gate_q_0 {", " u3(pi, 0, pi) _gate_q_0;", "}", "bit[2] c;", "h $1;", "cx $1, $2;", "barrier $0, $1, $2;", "cx $0, $1;", "h $0;", "barrier $0, $1, $2;", "c[0] = measure $0;", "c[1] = measure $1;", "barrier $0, $1, $2;", "if (c[1]) {", " x $2;", "}", "if (c[0]) {", " z $2;", "}", "", ] ) self.assertEqual( Exporter(includes=[], basis_gates=["cx", "z", "U"]).dumps(transpiled), expected_qasm, ) def test_opaque_instruction_in_basis_gates(self): """Test that an instruction that is set in the basis gates is output verbatim with no definition.""" qc = QuantumCircuit(1) qc.x(0) qc.append(Gate("my_gate", 1, []), [0], []) basis_gates = ["my_gate", "x"] transpiled = transpile(qc, initial_layout=[0]) expected_qasm = "\n".join( [ "OPENQASM 3;", "x $0;", "my_gate $0;", "", ] ) self.assertEqual( Exporter(includes=[], basis_gates=basis_gates).dumps(transpiled), expected_qasm ) def test_reset_statement(self): """Test that a reset statement gets output into valid QASM 3. This includes tests of reset operations on single qubits and in nested scopes.""" qreg = QuantumRegister(2, "qr") qc = QuantumCircuit(qreg) qc.reset(0) qc.reset([0, 1]) expected_qasm = "\n".join( [ "OPENQASM 3;", "qubit[2] qr;", "reset qr[0];", "reset qr[0];", "reset qr[1];", "", ] ) self.assertEqual(Exporter(includes=[]).dumps(qc), expected_qasm) def test_delay_statement(self): """Test that delay operations get output into valid QASM 3.""" qreg = QuantumRegister(2, "qr") qc = QuantumCircuit(qreg) qc.delay(100, qreg[0], unit="ms") qc.delay(2, qreg[1], unit="ps") # "ps" is not a valid unit in OQ3, so we need to convert. expected_qasm = "\n".join( [ "OPENQASM 3;", "qubit[2] qr;", "delay[100ms] qr[0];", "delay[2000ns] qr[1];", "", ] ) self.assertEqual(Exporter(includes=[]).dumps(qc), expected_qasm) def test_loose_qubits(self): """Test that qubits that are not in any register can be used without issue.""" bits = [Qubit(), Qubit()] qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(bits, qr, cr) qc.h(0) qc.h(1) qc.h(2) qc.h(3) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit _qubit0;", "qubit _qubit1;", "qubit[2] qr;", "h _qubit0;", "h _qubit1;", "h qr[0];", "h qr[1];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_loose_clbits(self): """Test that clbits that are not in any register can be used without issue.""" qreg = QuantumRegister(1, name="qr") bits = [Clbit() for _ in [None] * 7] cr1 = ClassicalRegister(name="cr1", bits=bits[1:3]) cr2 = ClassicalRegister(name="cr2", bits=bits[4:6]) qc = QuantumCircuit(bits, qreg, cr1, cr2) qc.measure(0, 0) qc.measure(0, 1) qc.measure(0, 2) qc.measure(0, 3) qc.measure(0, 4) qc.measure(0, 5) qc.measure(0, 6) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit _bit0;", "bit _bit3;", "bit _bit6;", "bit[2] cr1;", "bit[2] cr2;", "qubit[1] qr;", "_bit0 = measure qr[0];", "cr1[0] = measure qr[0];", "cr1[1] = measure qr[0];", "_bit3 = measure qr[0];", "cr2[0] = measure qr[0];", "cr2[1] = measure qr[0];", "_bit6 = measure qr[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_classical_register_aliasing(self): """Test that clbits that are not in any register can be used without issue.""" qreg = QuantumRegister(1, name="qr") bits = [Clbit() for _ in [None] * 7] cr1 = ClassicalRegister(name="cr1", bits=bits[1:3]) cr2 = ClassicalRegister(name="cr2", bits=bits[4:6]) # cr3 overlaps cr2, but this should be allowed in this alias form. cr3 = ClassicalRegister(name="cr3", bits=bits[5:]) qc = QuantumCircuit(bits, qreg, cr1, cr2, cr3) qc.measure(0, 0) qc.measure(0, 1) qc.measure(0, 2) qc.measure(0, 3) qc.measure(0, 4) qc.measure(0, 5) qc.measure(0, 6) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit _bit0;", "bit _bit1;", "bit _bit2;", "bit _bit3;", "bit _bit4;", "bit _bit5;", "bit _bit6;", "let cr1 = {_bit1, _bit2};", "let cr2 = {_bit4, _bit5};", "let cr3 = {cr2[1], _bit6};", "qubit[1] qr;", "_bit0 = measure qr[0];", "cr1[0] = measure qr[0];", "cr1[1] = measure qr[0];", "_bit3 = measure qr[0];", "cr2[0] = measure qr[0];", "cr3[0] = measure qr[0];", "cr3[1] = measure qr[0];", "", ] ) self.assertEqual(dumps(qc, allow_aliasing=True), expected_qasm) def test_old_alias_classical_registers_option(self): """Test that the ``alias_classical_registers`` option still functions during its changeover period.""" qreg = QuantumRegister(1, name="qr") bits = [Clbit() for _ in [None] * 7] cr1 = ClassicalRegister(name="cr1", bits=bits[1:3]) cr2 = ClassicalRegister(name="cr2", bits=bits[4:6]) # cr3 overlaps cr2, but this should be allowed in this alias form. cr3 = ClassicalRegister(name="cr3", bits=bits[5:]) qc = QuantumCircuit(bits, qreg, cr1, cr2, cr3) qc.measure(0, 0) qc.measure(0, 1) qc.measure(0, 2) qc.measure(0, 3) qc.measure(0, 4) qc.measure(0, 5) qc.measure(0, 6) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit _bit0;", "bit _bit1;", "bit _bit2;", "bit _bit3;", "bit _bit4;", "bit _bit5;", "bit _bit6;", "let cr1 = {_bit1, _bit2};", "let cr2 = {_bit4, _bit5};", "let cr3 = {cr2[1], _bit6};", "qubit[1] qr;", "_bit0 = measure qr[0];", "cr1[0] = measure qr[0];", "cr1[1] = measure qr[0];", "_bit3 = measure qr[0];", "cr2[0] = measure qr[0];", "cr3[0] = measure qr[0];", "cr3[1] = measure qr[0];", "", ] ) self.assertEqual(dumps(qc, alias_classical_registers=True), expected_qasm) def test_simple_for_loop(self): """Test that a simple for loop outputs the expected result.""" parameter = Parameter("x") loop_body = QuantumCircuit(1) loop_body.rx(parameter, 0) loop_body.break_loop() loop_body.continue_loop() qc = QuantumCircuit(2) qc.for_loop([0, 3, 4], parameter, loop_body, [1], []) qc.x(0) qr_name = qc.qregs[0].name expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', f"qubit[2] {qr_name};", f"for {parameter.name} in {{0, 3, 4}} {{", f" rx({parameter.name}) {qr_name}[1];", " break;", " continue;", "}", f"x {qr_name}[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_nested_for_loop(self): """Test that a for loop nested inside another outputs the expected result.""" inner_parameter = Parameter("x") outer_parameter = Parameter("y") inner_body = QuantumCircuit(2) inner_body.rz(inner_parameter, 0) inner_body.rz(outer_parameter, 1) inner_body.break_loop() outer_body = QuantumCircuit(2) outer_body.h(0) outer_body.rz(outer_parameter, 1) # Note we reverse the order of the bits here to test that this is traced. outer_body.for_loop(range(1, 5, 2), inner_parameter, inner_body, [1, 0], []) outer_body.continue_loop() qc = QuantumCircuit(2) qc.for_loop(range(4), outer_parameter, outer_body, [0, 1], []) qc.x(0) qr_name = qc.qregs[0].name expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', f"qubit[2] {qr_name};", f"for {outer_parameter.name} in [0:3] {{", f" h {qr_name}[0];", f" rz({outer_parameter.name}) {qr_name}[1];", f" for {inner_parameter.name} in [1:2:4] {{", # Note the reversed bit order. f" rz({inner_parameter.name}) {qr_name}[1];", f" rz({outer_parameter.name}) {qr_name}[0];", " break;", " }", " continue;", "}", f"x {qr_name}[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_regular_parameter_in_nested_for_loop(self): """Test that a for loop nested inside another outputs the expected result, including defining parameters that are used in nested loop scopes.""" inner_parameter = Parameter("x") outer_parameter = Parameter("y") regular_parameter = Parameter("t") inner_body = QuantumCircuit(2) inner_body.h(0) inner_body.rx(regular_parameter, 1) inner_body.break_loop() outer_body = QuantumCircuit(2) outer_body.h(0) outer_body.h(1) # Note we reverse the order of the bits here to test that this is traced. outer_body.for_loop(range(1, 5, 2), inner_parameter, inner_body, [1, 0], []) outer_body.continue_loop() qc = QuantumCircuit(2) qc.for_loop(range(4), outer_parameter, outer_body, [0, 1], []) qc.x(0) qr_name = qc.qregs[0].name expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', # This next line will be missing until gh-7280 is fixed. f"input float[64] {regular_parameter.name};", f"qubit[2] {qr_name};", f"for {outer_parameter.name} in [0:3] {{", f" h {qr_name}[0];", f" h {qr_name}[1];", f" for {inner_parameter.name} in [1:2:4] {{", # Note the reversed bit order. f" h {qr_name}[1];", f" rx({regular_parameter.name}) {qr_name}[0];", " break;", " }", " continue;", "}", f"x {qr_name}[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_for_loop_with_no_parameter(self): """Test that a for loop with the parameter set to ``None`` outputs the expected result.""" loop_body = QuantumCircuit(1) loop_body.h(0) qc = QuantumCircuit(2) qc.for_loop([0, 3, 4], None, loop_body, [1], []) qr_name = qc.qregs[0].name expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', f"qubit[2] {qr_name};", "for _ in {0, 3, 4} {", f" h {qr_name}[1];", "}", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_simple_while_loop(self): """Test that a simple while loop works correctly.""" loop_body = QuantumCircuit(1) loop_body.h(0) loop_body.break_loop() loop_body.continue_loop() qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(qr, cr) qc.while_loop((cr, 0), loop_body, [1], []) qc.x(0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit[2] qr;", "while (cr == 0) {", " h qr[1];", " break;", " continue;", "}", "x qr[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_nested_while_loop(self): """Test that a while loop nested inside another outputs the expected result.""" inner_body = QuantumCircuit(2, 2) inner_body.measure(0, 0) inner_body.measure(1, 1) inner_body.break_loop() outer_body = QuantumCircuit(2, 2) outer_body.measure(0, 0) outer_body.measure(1, 1) # We reverse the order of the bits here to test this works, and test a single-bit condition. outer_body.while_loop((outer_body.clbits[0], 0), inner_body, [1, 0], [1, 0]) outer_body.continue_loop() qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(qr, cr) qc.while_loop((cr, 0), outer_body, [0, 1], [0, 1]) qc.x(0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit[2] qr;", "while (cr == 0) {", " cr[0] = measure qr[0];", " cr[1] = measure qr[1];", # Note the reversed bits in the body. " while (!cr[0]) {", " cr[1] = measure qr[1];", " cr[0] = measure qr[0];", " break;", " }", " continue;", "}", "x qr[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_simple_if_statement(self): """Test that a simple if statement with no else works correctly.""" true_body = QuantumCircuit(1) true_body.h(0) qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(qr, cr) qc.if_test((cr, 0), true_body, [1], []) qc.x(0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit[2] qr;", "if (cr == 0) {", " h qr[1];", "}", "x qr[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_simple_if_else_statement(self): """Test that a simple if statement with an else branch works correctly.""" true_body = QuantumCircuit(1) true_body.h(0) false_body = QuantumCircuit(1) false_body.z(0) qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(qr, cr) qc.if_else((cr, 0), true_body, false_body, [1], []) qc.x(0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit[2] qr;", "if (cr == 0) {", " h qr[1];", "} else {", " z qr[1];", "}", "x qr[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_nested_if_else_statement(self): """Test that a nested if/else statement works correctly.""" inner_true_body = QuantumCircuit(2, 2) inner_true_body.measure(0, 0) inner_false_body = QuantumCircuit(2, 2) inner_false_body.measure(1, 1) outer_true_body = QuantumCircuit(2, 2) outer_true_body.if_else( (outer_true_body.clbits[0], 0), inner_true_body, inner_false_body, [0, 1], [0, 1] ) outer_false_body = QuantumCircuit(2, 2) # Note the flipped bits here. outer_false_body.if_else( (outer_false_body.clbits[0], 1), inner_true_body, inner_false_body, [1, 0], [1, 0] ) qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(qr, cr) qc.if_else((cr, 0), outer_true_body, outer_false_body, [0, 1], [0, 1]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit[2] qr;", "if (cr == 0) {", " if (!cr[0]) {", " cr[0] = measure qr[0];", " } else {", " cr[1] = measure qr[1];", " }", "} else {", " if (cr[0]) {", " cr[1] = measure qr[1];", " } else {", " cr[0] = measure qr[0];", " }", "}", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_chain_else_if(self): """Test the basic 'else/if' chaining logic for flattening the else scope if its content is a single if/else statement.""" inner_true_body = QuantumCircuit(2, 2) inner_true_body.measure(0, 0) inner_false_body = QuantumCircuit(2, 2) inner_false_body.measure(1, 1) outer_true_body = QuantumCircuit(2, 2) outer_true_body.if_else( (outer_true_body.clbits[0], 0), inner_true_body, inner_false_body, [0, 1], [0, 1] ) outer_false_body = QuantumCircuit(2, 2) # Note the flipped bits here. outer_false_body.if_else( (outer_false_body.clbits[0], 1), inner_true_body, inner_false_body, [1, 0], [1, 0] ) qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(qr, cr) qc.if_else((cr, 0), outer_true_body, outer_false_body, [0, 1], [0, 1]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit[2] qr;", "if (cr == 0) {", " if (!cr[0]) {", " cr[0] = measure qr[0];", " } else {", " cr[1] = measure qr[1];", " }", "} else if (cr[0]) {", " cr[1] = measure qr[1];", "} else {", " cr[0] = measure qr[0];", "}", "", ] ) # This is not the default behaviour, and it's pretty buried how you'd access it. builder = QASM3Builder( qc, includeslist=("stdgates.inc",), basis_gates=("U",), disable_constants=False, allow_aliasing=False, ) stream = StringIO() BasicPrinter(stream, indent=" ", chain_else_if=True).visit(builder.build_program()) self.assertEqual(stream.getvalue(), expected_qasm) def test_chain_else_if_does_not_chain_if_extra_instructions(self): """Test the basic 'else/if' chaining logic for flattening the else scope if its content is a single if/else statement does not cause a flattening if the 'else' block is not a single if/else.""" inner_true_body = QuantumCircuit(2, 2) inner_true_body.measure(0, 0) inner_false_body = QuantumCircuit(2, 2) inner_false_body.measure(1, 1) outer_true_body = QuantumCircuit(2, 2) outer_true_body.if_else( (outer_true_body.clbits[0], 0), inner_true_body, inner_false_body, [0, 1], [0, 1] ) outer_false_body = QuantumCircuit(2, 2) # Note the flipped bits here. outer_false_body.if_else( (outer_false_body.clbits[0], 1), inner_true_body, inner_false_body, [1, 0], [1, 0] ) outer_false_body.h(0) qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(qr, cr) qc.if_else((cr, 0), outer_true_body, outer_false_body, [0, 1], [0, 1]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit[2] qr;", "if (cr == 0) {", " if (!cr[0]) {", " cr[0] = measure qr[0];", " } else {", " cr[1] = measure qr[1];", " }", "} else {", " if (cr[0]) {", " cr[1] = measure qr[1];", " } else {", " cr[0] = measure qr[0];", " }", " h qr[0];", "}", "", ] ) # This is not the default behaviour, and it's pretty buried how you'd access it. builder = QASM3Builder( qc, includeslist=("stdgates.inc",), basis_gates=("U",), disable_constants=False, allow_aliasing=False, ) stream = StringIO() BasicPrinter(stream, indent=" ", chain_else_if=True).visit(builder.build_program()) self.assertEqual(stream.getvalue(), expected_qasm) def test_custom_gate_used_in_loop_scope(self): """Test that a custom gate only used within a loop scope still gets a definition at the top level.""" parameter_a = Parameter("a") parameter_b = Parameter("b") custom = QuantumCircuit(1) custom.rx(parameter_a, 0) custom_gate = custom.bind_parameters({parameter_a: 0.5}).to_gate() custom_gate.name = "custom" loop_body = QuantumCircuit(1) loop_body.append(custom_gate, [0]) qc = QuantumCircuit(1) qc.for_loop(range(2), parameter_b, loop_body, [0], []) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate custom _gate_q_0 {", " rx(0.5) _gate_q_0;", "}", "qubit[1] q;", "for b in [0:1] {", " custom q[0];", "}", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_registers_have_escaped_names(self): """Test that both types of register are emitted with safely escaped names if they begin with invalid names. Regression test of gh-9658.""" qc = QuantumCircuit( QuantumRegister(2, name="q_{reg}"), ClassicalRegister(2, name="c_{reg}") ) qc.measure([0, 1], [0, 1]) out_qasm = dumps(qc) matches = {match_["name"] for match_ in self.register_regex.finditer(out_qasm)} self.assertEqual(len(matches), 2, msg=f"Observed OQ3 output:\n{out_qasm}") def test_parameters_have_escaped_names(self): """Test that parameters are emitted with safely escaped names if they begin with invalid names. Regression test of gh-9658.""" qc = QuantumCircuit(1) qc.u(Parameter("p_{0}"), 2 * Parameter("p_?0!"), 0, 0) out_qasm = dumps(qc) matches = {match_["name"] for match_ in self.scalar_parameter_regex.finditer(out_qasm)} self.assertEqual(len(matches), 2, msg=f"Observed OQ3 output:\n{out_qasm}") def test_parameter_expression_after_naming_escape(self): """Test that :class:`.Parameter` instances are correctly renamed when they are used with :class:`.ParameterExpression` blocks, even if they have names that needed to be escaped.""" param = Parameter("measure") # an invalid name qc = QuantumCircuit(1) qc.u(2 * param, 0, 0, 0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "input float[64] _measure;", "qubit[1] q;", "U(2*_measure, 0, 0) q[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_parameters_and_registers_cannot_have_naming_clashes(self): """Test that parameters and registers are considered part of the same symbol table for the purposes of avoiding clashes.""" qreg = QuantumRegister(1, "clash") param = Parameter("clash") qc = QuantumCircuit(qreg) qc.u(param, 0, 0, 0) out_qasm = dumps(qc) register_name = self.register_regex.search(out_qasm) parameter_name = self.scalar_parameter_regex.search(out_qasm) self.assertTrue(register_name) self.assertTrue(parameter_name) self.assertIn("clash", register_name["name"]) self.assertIn("clash", parameter_name["name"]) self.assertNotEqual(register_name["name"], parameter_name["name"]) # Not necessarily all the reserved keywords, just a sensibly-sized subset. @data("bit", "const", "def", "defcal", "float", "gate", "include", "int", "let", "measure") def test_reserved_keywords_as_names_are_escaped(self, keyword): """Test that reserved keywords used to name registers and parameters are escaped into another form when output, and the escaping cannot introduce new conflicts.""" with self.subTest("register"): qreg = QuantumRegister(1, keyword) qc = QuantumCircuit(qreg) out_qasm = dumps(qc) register_name = self.register_regex.search(out_qasm) self.assertTrue(register_name, msg=f"Observed OQ3:\n{out_qasm}") self.assertNotEqual(keyword, register_name["name"]) with self.subTest("parameter"): qc = QuantumCircuit(1) param = Parameter(keyword) qc.u(param, 0, 0, 0) out_qasm = dumps(qc) parameter_name = self.scalar_parameter_regex.search(out_qasm) self.assertTrue(parameter_name, msg=f"Observed OQ3:\n{out_qasm}") self.assertNotEqual(keyword, parameter_name["name"]) def test_expr_condition(self): """Simple test that the conditions of `if`s and `while`s can be `Expr` nodes.""" bits = [Qubit(), Clbit()] cr = ClassicalRegister(2, "cr") if_body = QuantumCircuit(1) if_body.x(0) while_body = QuantumCircuit(1) while_body.x(0) qc = QuantumCircuit(bits, cr) qc.if_test(expr.logic_not(qc.clbits[0]), if_body, [0], []) qc.while_loop(expr.equal(cr, 3), while_body, [0], []) expected = """\ OPENQASM 3; include "stdgates.inc"; bit _bit0; bit[2] cr; qubit _qubit0; if (!_bit0) { x _qubit0; } while (cr == 3) { x _qubit0; } """ self.assertEqual(dumps(qc), expected) def test_expr_nested_condition(self): """Simple test that the conditions of `if`s and `while`s can be `Expr` nodes when nested, and the mapping of inner bits to outer bits is correct.""" bits = [Qubit(), Clbit(), Clbit()] cr = ClassicalRegister(2, "cr") inner_if_body = QuantumCircuit(1) inner_if_body.x(0) outer_if_body = QuantumCircuit(1, 1) outer_if_body.if_test(expr.lift(outer_if_body.clbits[0]), inner_if_body, [0], []) inner_while_body = QuantumCircuit(1) inner_while_body.x(0) outer_while_body = QuantumCircuit([Qubit()], cr) outer_while_body.while_loop(expr.equal(expr.bit_and(cr, 3), 3), inner_while_body, [0], []) qc = QuantumCircuit(bits, cr) qc.if_test(expr.logic_not(qc.clbits[0]), outer_if_body, [0], [1]) qc.while_loop(expr.equal(cr, 3), outer_while_body, [0], cr) expected = """\ OPENQASM 3; include "stdgates.inc"; bit _bit0; bit _bit1; bit[2] cr; qubit _qubit0; if (!_bit0) { if (_bit1) { x _qubit0; } } while (cr == 3) { while ((cr & 3) == 3) { x _qubit0; } } """ self.assertEqual(dumps(qc), expected) def test_expr_associativity_left(self): """Test that operations that are in the expression tree in a left-associative form are output to OQ3 correctly.""" body = QuantumCircuit() cr1 = ClassicalRegister(3, "cr1") cr2 = ClassicalRegister(3, "cr2") cr3 = ClassicalRegister(3, "cr3") qc = QuantumCircuit(cr1, cr2, cr3) qc.if_test(expr.equal(expr.bit_and(expr.bit_and(cr1, cr2), cr3), 7), body.copy(), [], []) qc.if_test(expr.equal(expr.bit_or(expr.bit_or(cr1, cr2), cr3), 7), body.copy(), [], []) qc.if_test(expr.equal(expr.bit_xor(expr.bit_xor(cr1, cr2), cr3), 7), body.copy(), [], []) qc.if_test(expr.logic_and(expr.logic_and(cr1[0], cr1[1]), cr1[2]), body.copy(), [], []) qc.if_test(expr.logic_or(expr.logic_or(cr1[0], cr1[1]), cr1[2]), body.copy(), [], []) # Note that bitwise operations have lower priority than `==` so there's extra parentheses. # All these operators are left-associative in OQ3. expected = """\ OPENQASM 3; include "stdgates.inc"; bit[3] cr1; bit[3] cr2; bit[3] cr3; if ((cr1 & cr2 & cr3) == 7) { } if ((cr1 | cr2 | cr3) == 7) { } if ((cr1 ^ cr2 ^ cr3) == 7) { } if (cr1[0] && cr1[1] && cr1[2]) { } if (cr1[0] || cr1[1] || cr1[2]) { } """ self.assertEqual(dumps(qc), expected) def test_expr_associativity_right(self): """Test that operations that are in the expression tree in a right-associative form are output to OQ3 correctly.""" body = QuantumCircuit() cr1 = ClassicalRegister(3, "cr1") cr2 = ClassicalRegister(3, "cr2") cr3 = ClassicalRegister(3, "cr3") qc = QuantumCircuit(cr1, cr2, cr3) qc.if_test(expr.equal(expr.bit_and(cr1, expr.bit_and(cr2, cr3)), 7), body.copy(), [], []) qc.if_test(expr.equal(expr.bit_or(cr1, expr.bit_or(cr2, cr3)), 7), body.copy(), [], []) qc.if_test(expr.equal(expr.bit_xor(cr1, expr.bit_xor(cr2, cr3)), 7), body.copy(), [], []) qc.if_test(expr.logic_and(cr1[0], expr.logic_and(cr1[1], cr1[2])), body.copy(), [], []) qc.if_test(expr.logic_or(cr1[0], expr.logic_or(cr1[1], cr1[2])), body.copy(), [], []) # Note that bitwise operations have lower priority than `==` so there's extra parentheses. # All these operators are left-associative in OQ3, so we need parentheses for them to be # parsed correctly. Mathematically, they're all actually associative in general, so the # order doesn't _technically_ matter. expected = """\ OPENQASM 3; include "stdgates.inc"; bit[3] cr1; bit[3] cr2; bit[3] cr3; if ((cr1 & (cr2 & cr3)) == 7) { } if ((cr1 | (cr2 | cr3)) == 7) { } if ((cr1 ^ (cr2 ^ cr3)) == 7) { } if (cr1[0] && (cr1[1] && cr1[2])) { } if (cr1[0] || (cr1[1] || cr1[2])) { } """ self.assertEqual(dumps(qc), expected) def test_expr_binding_unary(self): """Test that nested unary operators don't insert unnecessary brackets.""" body = QuantumCircuit() cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(cr) qc.if_test(expr.equal(expr.bit_not(expr.bit_not(cr)), 3), body.copy(), [], []) qc.if_test(expr.logic_not(expr.logic_not(cr[0])), body.copy(), [], []) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[2] cr; if (~~cr == 3) { } if (!!cr[0]) { } """ self.assertEqual(dumps(qc), expected) def test_expr_precedence(self): """Test that the precedence properties of operators are correctly output.""" body = QuantumCircuit() cr = ClassicalRegister(2, "cr") # This tree is _completely_ inside out, so there's brackets needed round every operand. inside_out = expr.logic_not( expr.less( expr.bit_and( expr.bit_xor(expr.bit_or(cr, cr), expr.bit_or(cr, cr)), expr.bit_xor(expr.bit_or(cr, cr), expr.bit_or(cr, cr)), ), expr.bit_and( expr.bit_xor(expr.bit_or(cr, cr), expr.bit_or(cr, cr)), expr.bit_xor(expr.bit_or(cr, cr), expr.bit_or(cr, cr)), ), ) ) # This one is the other way round - the tightest-binding operations are on the inside, so no # brackets should be needed at all except to put in a comparison to a bitwise binary # operation, since those bind less tightly than anything that can cast them to a bool. outside_in = expr.logic_or( expr.logic_and( expr.equal(expr.bit_or(cr, cr), expr.bit_and(cr, cr)), expr.equal(expr.bit_and(cr, cr), expr.bit_or(cr, cr)), ), expr.logic_and( expr.greater(expr.bit_or(cr, cr), expr.bit_xor(cr, cr)), expr.less_equal(expr.bit_xor(cr, cr), expr.bit_or(cr, cr)), ), ) # And an extra test of the logical operator order. logics = expr.logic_or( expr.logic_and( expr.logic_or(expr.logic_not(cr[0]), expr.logic_not(cr[0])), expr.logic_not(expr.logic_and(cr[0], cr[0])), ), expr.logic_and( expr.logic_not(expr.logic_and(cr[0], cr[0])), expr.logic_or(expr.logic_not(cr[0]), expr.logic_not(cr[0])), ), ) qc = QuantumCircuit(cr) qc.if_test(inside_out, body.copy(), [], []) qc.if_test(outside_in, body.copy(), [], []) qc.if_test(logics, body.copy(), [], []) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[2] cr; if (!((((cr | cr) ^ (cr | cr)) & ((cr | cr) ^ (cr | cr)))\ < (((cr | cr) ^ (cr | cr)) & ((cr | cr) ^ (cr | cr))))) { } if ((cr | cr) == (cr & cr) && (cr & cr) == (cr | cr)\ || (cr | cr) > (cr ^ cr) && (cr ^ cr) <= (cr | cr)) { } if ((!cr[0] || !cr[0]) && !(cr[0] && cr[0]) || !(cr[0] && cr[0]) && (!cr[0] || !cr[0])) { } """ self.assertEqual(dumps(qc), expected) def test_no_unnecessary_cast(self): """This is a bit of a cross `Expr`-constructor / OQ3-exporter test. It doesn't really matter whether or not the `Expr` constructor functions insert cast nodes into their output for the literals (at the time of writing [commit 2616602], they don't because they do some type inference) but the OQ3 export definitely shouldn't have them.""" cr = ClassicalRegister(8, "cr") qc = QuantumCircuit(cr) # Note that the integer '1' has a minimum bit-width of 1, whereas the register has a width # of 8. We're testing to make sure that there's no spurious cast up from `bit[1]` to # `bit[8]`, or anything like that, _whether or not_ the `Expr` node includes one. qc.if_test(expr.equal(cr, 1), QuantumCircuit(), [], []) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[8] cr; if (cr == 1) { } """ self.assertEqual(dumps(qc), expected) class TestCircuitQASM3ExporterTemporaryCasesWithBadParameterisation(QiskitTestCase): """Test functionality that is not what we _want_, but is what we need to do while the definition of custom gates with parameterisation does not work correctly. These tests are modified versions of those marked with the `requires_fixed_parameterisation` decorator, and this whole class can be deleted once those are fixed. See gh-7335. """ maxDiff = 1_000_000 def test_basis_gates(self): """Teleportation with physical qubits""" qc = QuantumCircuit(3, 2) first_h = qc.h(1)[0].operation qc.cx(1, 2) qc.barrier() qc.cx(0, 1) qc.h(0) qc.barrier() qc.measure([0, 1], [0, 1]) qc.barrier() first_x = qc.x(2).c_if(qc.clbits[1], 1)[0].operation qc.z(2).c_if(qc.clbits[0], 1) u2 = first_h.definition.data[0].operation u3_1 = u2.definition.data[0].operation u3_2 = first_x.definition.data[0].operation expected_qasm = "\n".join( [ "OPENQASM 3;", f"gate u3_{id(u3_1)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(pi/2, 0, pi) _gate_q_0;", "}", f"gate u2_{id(u2)}(_gate_p_0, _gate_p_1) _gate_q_0 {{", f" u3_{id(u3_1)}(pi/2, 0, pi) _gate_q_0;", "}", "gate h _gate_q_0 {", f" u2_{id(u2)}(0, pi) _gate_q_0;", "}", f"gate u3_{id(u3_2)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(pi, 0, pi) _gate_q_0;", "}", "gate x _gate_q_0 {", f" u3_{id(u3_2)}(pi, 0, pi) _gate_q_0;", "}", "bit[2] c;", "qubit[3] q;", "h q[1];", "cx q[1], q[2];", "barrier q[0], q[1], q[2];", "cx q[0], q[1];", "h q[0];", "barrier q[0], q[1], q[2];", "c[0] = measure q[0];", "c[1] = measure q[1];", "barrier q[0], q[1], q[2];", "if (c[1]) {", " x q[2];", "}", "if (c[0]) {", " z q[2];", "}", "", ] ) self.assertEqual( Exporter(includes=[], basis_gates=["cx", "z", "U"]).dumps(qc), expected_qasm, ) def test_teleportation(self): """Teleportation with physical qubits""" qc = QuantumCircuit(3, 2) qc.h(1) qc.cx(1, 2) qc.barrier() qc.cx(0, 1) qc.h(0) qc.barrier() qc.measure([0, 1], [0, 1]) qc.barrier() qc.x(2).c_if(qc.clbits[1], 1) qc.z(2).c_if(qc.clbits[0], 1) transpiled = transpile(qc, initial_layout=[0, 1, 2]) first_h = transpiled.data[0].operation u2 = first_h.definition.data[0].operation u3_1 = u2.definition.data[0].operation first_x = transpiled.data[-2].operation u3_2 = first_x.definition.data[0].operation first_z = transpiled.data[-1].operation u1 = first_z.definition.data[0].operation u3_3 = u1.definition.data[0].operation expected_qasm = "\n".join( [ "OPENQASM 3;", f"gate u3_{id(u3_1)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(pi/2, 0, pi) _gate_q_0;", "}", f"gate u2_{id(u2)}(_gate_p_0, _gate_p_1) _gate_q_0 {{", f" u3_{id(u3_1)}(pi/2, 0, pi) _gate_q_0;", "}", "gate h _gate_q_0 {", f" u2_{id(u2)}(0, pi) _gate_q_0;", "}", "gate cx c, t {", " ctrl @ U(pi, 0, pi) c, t;", "}", f"gate u3_{id(u3_2)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(pi, 0, pi) _gate_q_0;", "}", "gate x _gate_q_0 {", f" u3_{id(u3_2)}(pi, 0, pi) _gate_q_0;", "}", f"gate u3_{id(u3_3)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(0, 0, pi) _gate_q_0;", "}", f"gate u1_{id(u1)}(_gate_p_0) _gate_q_0 {{", f" u3_{id(u3_3)}(0, 0, pi) _gate_q_0;", "}", "gate z _gate_q_0 {", f" u1_{id(u1)}(pi) _gate_q_0;", "}", "bit[2] c;", "h $1;", "cx $1, $2;", "barrier $0, $1, $2;", "cx $0, $1;", "h $0;", "barrier $0, $1, $2;", "c[0] = measure $0;", "c[1] = measure $1;", "barrier $0, $1, $2;", "if (c[1]) {", " x $2;", "}", "if (c[0]) {", " z $2;", "}", "", ] ) self.assertEqual(Exporter(includes=[]).dumps(transpiled), expected_qasm) def test_custom_gate_with_params_bound_main_call(self): """Custom gate with unbound parameters that are bound in the main circuit""" parameter0 = Parameter("p0") parameter1 = Parameter("p1") custom = QuantumCircuit(2, name="custom") custom.rz(parameter0, 0) custom.rz(parameter1 / 2, 1) qr_all_qubits = QuantumRegister(3, "q") qr_r = QuantumRegister(3, "r") circuit = QuantumCircuit(qr_all_qubits, qr_r) circuit.append(custom.to_gate(), [qr_all_qubits[0], qr_r[0]]) circuit.assign_parameters({parameter0: pi, parameter1: pi / 2}, inplace=True) custom_id = id(circuit.data[0].operation) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', f"gate custom_{custom_id}(_gate_p_0, _gate_p_1) _gate_q_0, _gate_q_1 {{", " rz(pi) _gate_q_0;", " rz(pi/4) _gate_q_1;", "}", "qubit[3] q;", "qubit[3] r;", f"custom_{custom_id}(pi, pi/2) q[0], r[0];", "", ] ) self.assertEqual(Exporter().dumps(circuit), expected_qasm) def test_no_include(self): """Test explicit gate declaration (no include)""" q = QuantumRegister(2, "q") circuit = QuantumCircuit(q) circuit.rz(pi / 2, 0) circuit.sx(0) circuit.cx(0, 1) rz = circuit.data[0].operation u1_1 = rz.definition.data[0].operation u3_1 = u1_1.definition.data[0].operation sx = circuit.data[1].operation sdg = sx.definition.data[0].operation u1_2 = sdg.definition.data[0].operation u3_2 = u1_2.definition.data[0].operation h_ = sx.definition.data[1].operation u2_1 = h_.definition.data[0].operation u3_3 = u2_1.definition.data[0].operation expected_qasm = "\n".join( [ "OPENQASM 3;", f"gate u3_{id(u3_1)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(0, 0, pi/2) _gate_q_0;", "}", f"gate u1_{id(u1_1)}(_gate_p_0) _gate_q_0 {{", f" u3_{id(u3_1)}(0, 0, pi/2) _gate_q_0;", "}", f"gate rz_{id(rz)}(_gate_p_0) _gate_q_0 {{", f" u1_{id(u1_1)}(pi/2) _gate_q_0;", "}", f"gate u3_{id(u3_2)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(0, 0, -pi/2) _gate_q_0;", "}", f"gate u1_{id(u1_2)}(_gate_p_0) _gate_q_0 {{", f" u3_{id(u3_2)}(0, 0, -pi/2) _gate_q_0;", "}", "gate sdg _gate_q_0 {", f" u1_{id(u1_2)}(-pi/2) _gate_q_0;", "}", f"gate u3_{id(u3_3)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(pi/2, 0, pi) _gate_q_0;", "}", f"gate u2_{id(u2_1)}(_gate_p_0, _gate_p_1) _gate_q_0 {{", f" u3_{id(u3_3)}(pi/2, 0, pi) _gate_q_0;", "}", "gate h _gate_q_0 {", f" u2_{id(u2_1)}(0, pi) _gate_q_0;", "}", "gate sx _gate_q_0 {", " sdg _gate_q_0;", " h _gate_q_0;", " sdg _gate_q_0;", "}", "gate cx c, t {", " ctrl @ U(pi, 0, pi) c, t;", "}", "qubit[2] q;", f"rz_{id(rz)}(pi/2) q[0];", "sx q[0];", "cx q[0], q[1];", "", ] ) self.assertEqual(Exporter(includes=[]).dumps(circuit), expected_qasm) def test_unusual_conditions(self): """Test that special QASM constructs such as ``measure`` are correctly handled when the Terra instructions have old-style conditions.""" qc = QuantumCircuit(3, 2) qc.h(0) qc.measure(0, 0) qc.measure(1, 1).c_if(0, True) qc.reset([0, 1]).c_if(0, True) with qc.while_loop((qc.clbits[0], True)): qc.break_loop().c_if(0, True) qc.continue_loop().c_if(0, True) # Terra forbids delay and barrier from being conditioned through `c_if`, but in theory they # should work fine in a dynamic-circuits sense (although what a conditional barrier _means_ # is a whole other kettle of fish). delay = Delay(16, "dt") delay.condition = (qc.clbits[0], True) qc.append(delay, [0], []) barrier = Barrier(2) barrier.condition = (qc.clbits[0], True) qc.append(barrier, [0, 1], []) expected = """ OPENQASM 3; include "stdgates.inc"; bit[2] c; qubit[3] q; h q[0]; c[0] = measure q[0]; if (c[0]) { c[1] = measure q[1]; } if (c[0]) { reset q[0]; } if (c[0]) { reset q[1]; } while (c[0]) { if (c[0]) { break; } if (c[0]) { continue; } } if (c[0]) { delay[16dt] q[0]; } if (c[0]) { barrier q[0], q[1]; }""" self.assertEqual(dumps(qc).strip(), expected.strip()) class TestExperimentalFeatures(QiskitTestCase): """Tests of features that are hidden behind experimental flags.""" maxDiff = None def test_switch_forbidden_without_flag(self): """Omitting the feature flag should raise an error.""" case = QuantumCircuit(1) circuit = QuantumCircuit(1, 1) circuit.switch(circuit.clbits[0], [((True, False), case)], [0], []) with self.assertRaisesRegex(QASM3ExporterError, "'switch' statements are not stabilized"): dumps(circuit) def test_switch_clbit(self): """Test that a switch statement can be constructed with a bit as a condition.""" qubit = Qubit() clbit = Clbit() case1 = QuantumCircuit([qubit, clbit]) case1.x(0) case2 = QuantumCircuit([qubit, clbit]) case2.z(0) circuit = QuantumCircuit([qubit, clbit]) circuit.switch(clbit, [(True, case1), (False, case2)], [0], [0]) test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1) expected = """\ OPENQASM 3; include "stdgates.inc"; bit _bit0; int switch_dummy; qubit _qubit0; switch_dummy = _bit0; switch (switch_dummy) { case 1: { x _qubit0; } break; case 0: { z _qubit0; } break; } """ self.assertEqual(test, expected) def test_switch_register(self): """Test that a switch statement can be constructed with a register as a condition.""" qubit = Qubit() creg = ClassicalRegister(2, "c") case1 = QuantumCircuit([qubit], creg) case1.x(0) case2 = QuantumCircuit([qubit], creg) case2.y(0) case3 = QuantumCircuit([qubit], creg) case3.z(0) circuit = QuantumCircuit([qubit], creg) circuit.switch(creg, [(0, case1), (1, case2), (2, case3)], [0], circuit.clbits) test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[2] c; int switch_dummy; qubit _qubit0; switch_dummy = c; switch (switch_dummy) { case 0: { x _qubit0; } break; case 1: { y _qubit0; } break; case 2: { z _qubit0; } break; } """ self.assertEqual(test, expected) def test_switch_with_default(self): """Test that a switch statement can be constructed with a default case at the end.""" qubit = Qubit() creg = ClassicalRegister(2, "c") case1 = QuantumCircuit([qubit], creg) case1.x(0) case2 = QuantumCircuit([qubit], creg) case2.y(0) case3 = QuantumCircuit([qubit], creg) case3.z(0) circuit = QuantumCircuit([qubit], creg) circuit.switch(creg, [(0, case1), (1, case2), (CASE_DEFAULT, case3)], [0], circuit.clbits) test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[2] c; int switch_dummy; qubit _qubit0; switch_dummy = c; switch (switch_dummy) { case 0: { x _qubit0; } break; case 1: { y _qubit0; } break; default: { z _qubit0; } break; } """ self.assertEqual(test, expected) def test_switch_multiple_cases_to_same_block(self): """Test that it is possible to add multiple cases that apply to the same block, if they are given as a compound value. This is an allowed special case of block fall-through.""" qubit = Qubit() creg = ClassicalRegister(2, "c") case1 = QuantumCircuit([qubit], creg) case1.x(0) case2 = QuantumCircuit([qubit], creg) case2.y(0) circuit = QuantumCircuit([qubit], creg) circuit.switch(creg, [(0, case1), ((1, 2), case2)], [0], circuit.clbits) test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[2] c; int switch_dummy; qubit _qubit0; switch_dummy = c; switch (switch_dummy) { case 0: { x _qubit0; } break; case 1: case 2: { y _qubit0; } break; } """ self.assertEqual(test, expected) def test_multiple_switches_dont_clash_on_dummy(self): """Test that having more than one switch statement in the circuit doesn't cause naming clashes in the dummy integer value used.""" qubit = Qubit() creg = ClassicalRegister(2, "switch_dummy") case1 = QuantumCircuit([qubit], creg) case1.x(0) case2 = QuantumCircuit([qubit], creg) case2.y(0) circuit = QuantumCircuit([qubit], creg) circuit.switch(creg, [(0, case1), ((1, 2), case2)], [0], circuit.clbits) circuit.switch(creg, [(0, case1), ((1, 2), case2)], [0], circuit.clbits) test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[2] switch_dummy; int switch_dummy__generated0; int switch_dummy__generated1; qubit _qubit0; switch_dummy__generated0 = switch_dummy; switch (switch_dummy__generated0) { case 0: { x _qubit0; } break; case 1: case 2: { y _qubit0; } break; } switch_dummy__generated1 = switch_dummy; switch (switch_dummy__generated1) { case 0: { x _qubit0; } break; case 1: case 2: { y _qubit0; } break; } """ self.assertEqual(test, expected) def test_switch_nested_in_if(self): """Test that the switch statement works when in a nested scope, including the dummy classical variable being declared globally. This isn't necessary in the OQ3 language, but it is universally valid and the IBM QSS stack prefers that. They're our primary consumers of OQ3 strings, so it's best to play nicely with them.""" qubit = Qubit() creg = ClassicalRegister(2, "c") case1 = QuantumCircuit([qubit], creg) case1.x(0) case2 = QuantumCircuit([qubit], creg) case2.y(0) body = QuantumCircuit([qubit], creg) body.switch(creg, [(0, case1), ((1, 2), case2)], [0], body.clbits) circuit = QuantumCircuit([qubit], creg) circuit.if_else((creg, 1), body.copy(), body, [0], body.clbits) test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[2] c; int switch_dummy; int switch_dummy__generated0; qubit _qubit0; if (c == 1) { switch_dummy = c; switch (switch_dummy) { case 0: { x _qubit0; } break; case 1: case 2: { y _qubit0; } break; } } else { switch_dummy__generated0 = c; switch (switch_dummy__generated0) { case 0: { x _qubit0; } break; case 1: case 2: { y _qubit0; } break; } } """ self.assertEqual(test, expected) def test_expr_target(self): """Simple test that the target of `switch` can be `Expr` nodes.""" bits = [Qubit(), Clbit()] cr = ClassicalRegister(2, "cr") case0 = QuantumCircuit(1) case0.x(0) case1 = QuantumCircuit(1) case1.x(0) qc = QuantumCircuit(bits, cr) qc.switch(expr.logic_not(bits[1]), [(False, case0)], [0], []) qc.switch(expr.bit_and(cr, 3), [(3, case1)], [0], []) expected = """\ OPENQASM 3; include "stdgates.inc"; bit _bit0; bit[2] cr; int switch_dummy; int switch_dummy__generated0; qubit _qubit0; switch_dummy = !_bit0; switch (switch_dummy) { case 0: { x _qubit0; } break; } switch_dummy__generated0 = cr & 3; switch (switch_dummy__generated0) { case 3: { x _qubit0; } break; } """ test = dumps(qc, experimental=ExperimentalFeatures.SWITCH_CASE_V1) self.assertEqual(test, expected) @ddt class TestQASM3ExporterFailurePaths(QiskitTestCase): """Tests of the failure paths for the exporter.""" def test_disallow_overlapping_classical_registers_if_no_aliasing(self): """Test that the exporter rejects circuits with a classical bit in more than one register if the ``alias_classical_registers`` option is set false.""" qubits = [Qubit() for _ in [None] * 3] clbits = [Clbit() for _ in [None] * 5] registers = [ClassicalRegister(bits=clbits[:4]), ClassicalRegister(bits=clbits[1:])] qc = QuantumCircuit(qubits, *registers) exporter = Exporter(alias_classical_registers=False) with self.assertRaisesRegex(QASM3ExporterError, r"classical registers .* overlap"): exporter.dumps(qc) @data([1, 2, 1.1], [1j, 2]) def test_disallow_for_loops_with_non_integers(self, indices): """Test that the exporter rejects ``for`` loops that include non-integer values in their index sets.""" loop_body = QuantumCircuit() qc = QuantumCircuit(2, 2) qc.for_loop(indices, None, loop_body, [], []) exporter = Exporter() with self.assertRaisesRegex( QASM3ExporterError, r"The values in QASM 3 'for' loops must all be integers.*" ): exporter.dumps(qc) def test_disallow_custom_subroutine_with_parameters(self): """Test that the exporter throws an error instead of trying to export a subroutine with parameters, while this is not supported.""" subroutine = QuantumCircuit(1) subroutine.rx(Parameter("x"), 0) qc = QuantumCircuit(1) qc.append(subroutine.to_instruction(), [0], []) exporter = Exporter() with self.assertRaisesRegex( QASM3ExporterError, "Exporting non-unitary instructions is not yet supported" ): exporter.dumps(qc) def test_disallow_opaque_instruction(self): """Test that the exporter throws an error instead of trying to export something into a ``defcal`` block, while this is not supported.""" qc = QuantumCircuit(1) qc.append(Instruction("opaque", 1, 0, []), [0], []) exporter = Exporter() with self.assertRaisesRegex( QASM3ExporterError, "Exporting opaque instructions .* is not yet supported" ): exporter.dumps(qc)
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
# -*- 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/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
# Importing standard Qiskit libraries from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import Aer, assemble from qiskit.visualization import plot_histogram, plot_bloch_multivector, plot_state_qsphere, plot_state_city, plot_state_paulivec, plot_state_hinton # Ignore warnings import warnings warnings.filterwarnings('ignore') # Define backend sim = Aer.get_backend('aer_simulator') def createBellStates(inp1, inp2): qc = QuantumCircuit(2) qc.reset(range(2)) if inp1=='1': qc.x(0) if inp2=='1': qc.x(1) qc.barrier() qc.h(0) qc.cx(0,1) qc.save_statevector() qobj = assemble(qc) result = sim.run(qobj).result() state = result.get_statevector() return qc, state, result print('Note: Since these qubits are in entangled state, their state cannot be written as two separate qubit states. This also means that we lose information when we try to plot our state on separate Bloch spheres as seen below.\n') inp1 = 0 inp2 = 1 qc, state, result = createBellStates(inp1, inp2) display(plot_bloch_multivector(state)) # Uncomment below code in order to explore other states #for inp2 in ['0', '1']: #for inp1 in ['0', '1']: #qc, state, result = createBellStates(inp1, inp2) #print('For inputs',inp2,inp1,'Representation of Entangled States are:') # Uncomment any of the below functions to visualize the resulting quantum states # Draw the quantum circuit #display(qc.draw()) # Plot states on QSphere #display(plot_state_qsphere(state)) # Plot states on Bloch Multivector #display(plot_bloch_multivector(state)) # Plot histogram #display(plot_histogram(result.get_counts())) # Plot state matrix like a city #display(plot_state_city(state)) # Represent state matix using Pauli operators as the basis #display(plot_state_paulivec(state)) # Plot state matrix as Hinton representation #display(plot_state_hinton(state)) #print('\n')''' from qiskit import IBMQ, execute from qiskit.providers.ibmq import least_busy from qiskit.tools import job_monitor # Loading your IBM Quantum account(s) provider = IBMQ.load_account() backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational==True)) def createBSRealDevice(inp1, inp2): qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.reset(range(2)) if inp1 == 1: qc.x(0) if inp2 == 1: qc.x(1) qc.barrier() qc.h(0) qc.cx(0,1) qc.measure(qr, cr) job = execute(qc, backend=backend, shots=100) job_monitor(job) result = job.result() return qc, result inp1 = 0 inp2 = 0 print('For inputs',inp2,inp1,'Representation of Entangled States are,') #first results qc, first_result = createBSRealDevice(inp1, inp2) first_counts = first_result.get_counts() # Draw the quantum circuit display(qc.draw()) #second results qc, second_result = createBSRealDevice(inp1, inp2) second_counts = second_result.get_counts() # Plot results on histogram with legend legend = ['First execution', 'Second execution'] plot_histogram([first_counts, second_counts], legend=legend) def ghzCircuit(inp1, inp2, inp3): qc = QuantumCircuit(3) qc.reset(range(3)) if inp1 == 1: qc.x(0) if inp2 == 1: qc.x(1) if inp3 == 1: qc.x(2) qc.barrier() qc.h(0) qc.cx(0,1) qc.cx(0,2) qc.save_statevector() qobj = assemble(qc) result = sim.run(qobj).result() state = result.get_statevector() return qc, state, result print('Note: Since these qubits are in entangled state, their state cannot be written as two separate qubit states. This also means that we lose information when we try to plot our state on separate Bloch spheres as seen below.\n') inp1 = 0 inp2 = 1 inp3 = 1 qc, state, result = ghzCircuit(inp1, inp2, inp3) display(plot_bloch_multivector(state)) # Uncomment below code in order to explore other states #for inp3 in ['0','1']: #for inp2 in ['0','1']: #for inp1 in ['0','1']: #qc, state, result = ghzCircuit(inp1, inp2, inp3) #print('For inputs',inp3,inp2,inp1,'Representation of GHZ States are:') # Uncomment any of the below functions to visualize the resulting quantum states # Draw the quantum circuit #display(qc.draw()) # Plot states on QSphere #display(plot_state_qsphere(state)) # Plot states on Bloch Multivector #display(plot_bloch_multivector(state)) # Plot histogram #display(plot_histogram(result.get_counts())) # Plot state matrix like a city #display(plot_state_city(state)) # Represent state matix using Pauli operators as the basis #display(plot_state_paulivec(state)) # Plot state matrix as Hinton representation #display(plot_state_hinton(state)) #print('\n') def ghz5QCircuit(inp1, inp2, inp3, inp4, inp5): qc = QuantumCircuit(5) #qc.reset(range(5)) if inp1 == 1: qc.x(0) if inp2 == 1: qc.x(1) if inp3 == 1: qc.x(2) if inp4 == 1: qc.x(3) if inp5 == 1: qc.x(4) qc.barrier() qc.h(0) qc.cx(0,1) qc.cx(0,2) qc.cx(0,3) qc.cx(0,4) qc.save_statevector() qobj = assemble(qc) result = sim.run(qobj).result() state = result.get_statevector() return qc, state, result # Explore GHZ States for input 00010. Note: the input has been stated in little-endian format. inp1 = 0 inp2 = 1 inp3 = 0 inp4 = 0 inp5 = 0 qc, state, result = ghz5QCircuit(inp1, inp2, inp3, inp4, inp5) print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ States are:') display(plot_state_qsphere(state)) print('\n') # Explore GHZ States for input 11001. Note: the input has been stated in little-endian format. inp1 = 1 inp2 = 0 inp3 = 0 inp4 = 1 inp5 = 1 qc, state, result = ghz5QCircuit(inp1, inp2, inp3, inp4, inp5) print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ States are:') display(plot_state_qsphere(state)) print('\n') # Explore GHZ States for input 01010. Note: the input has been stated in little-endian format. inp1 = 0 inp2 = 1 inp3 = 0 inp4 = 1 inp5 = 0 qc, state, result = ghz5QCircuit(inp1, inp2, inp3, inp4, inp5) print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ States are:') display(plot_state_qsphere(state)) print('\n') # Uncomment below code in order to explore other states #for inp5 in ['0','1']: #for inp4 in ['0','1']: #for inp3 in ['0','1']: #for inp2 in ['0','1']: #for inp1 in ['0','1']: #qc, state, result = ghz5QCircuit(inp1, inp2, inp3, inp4, inp5) #print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ States are:') # Uncomment any of the below functions to visualize the resulting quantum states # Draw the quantum circuit #display(qc.draw()) # Plot states on QSphere #display(plot_state_qsphere(state)) # Plot states on Bloch Multivector #display(plot_bloch_multivector(state)) # Plot histogram #display(plot_histogram(result.get_counts())) # Plot state matrix like a city #display(plot_state_city(state)) # Represent state matix using Pauli operators as the basis #display(plot_state_paulivec(state)) # Plot state matrix as Hinton representation #display(plot_state_hinton(state)) #print('\n') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 5 and not x.configuration().simulator and x.status().operational==True)) def create5QGHZRealDevice(inp1, inp2, inp3, inp4, inp5): qr = QuantumRegister(5) cr = ClassicalRegister(5) qc = QuantumCircuit(qr, cr) qc.reset(range(5)) if inp1=='1': qc.x(0) if inp2=='1': qc.x(1) if inp3=='1': qc.x(1) if inp4=='1': qc.x(1) if inp5=='1': qc.x(1) qc.barrier() qc.h(0) qc.cx(0,1) qc.cx(0,2) qc.cx(0,3) qc.cx(0,4) qc.measure(qr, cr) job = execute(qc, backend=backend, shots=1000) job_monitor(job) result = job.result() return qc, result inp1 = 0 inp2 = 0 inp3 = 0 inp4 = 0 inp5 = 0 #first results qc, first_result = create5QGHZRealDevice(inp1, inp2, inp3, inp4, inp5) first_counts = first_result.get_counts() # Draw the quantum circuit display(qc.draw()) #second results qc, second_result = create5QGHZRealDevice(inp1, inp2, inp3, inp4, inp5) second_counts = second_result.get_counts() print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ circuit states are,') # Plot results on histogram with legend legend = ['First execution', 'Second execution'] plot_histogram([first_counts, second_counts], legend=legend) import qiskit qiskit.__qiskit_version__
https://github.com/liudingshan/QiskitGrovers
liudingshan
import qiskit as qis from qiskit.tools.visualization import plot_bloch_multivector import matplotlib.pyplot as plt from qiskit.tools.visualization import plot_histogram import math as math # Define Registers qr = qis.QuantumRegister(3) cr = qis.ClassicalRegister(3) # Make Circuit circuit = qis.QuantumCircuit(qr, cr) # Make Gates and Circuit Additions circuit.h(qr[0]) circuit.h(qr[1]) circuit.x(qr[2]) circuit.h(qr[2]) circuit.ccx(qr[0], qr[1], qr[2]) circuit.h(qr[0]) circuit.x(qr[0]) circuit.h(qr[1]) circuit.x(qr[1]) circuit.h(qr[1]) circuit.cx(qr[0], qr[1]) circuit.h(qr[1]) circuit.x(qr[0]) circuit.x(qr[1]) circuit.h(qr[0]) circuit.h(qr[1]) circuit.h(qr[2]) # Choose Unitary Simulator simulator = qis.Aer.get_backend('unitary_simulator') # Get Unitary Results (Multiplication of all Gates/Additions) result = qis.execute(circuit, backend=simulator).result() unitary = result.get_unitary() # Plot Unitary Results print(unitary) # Choose Statevector Simulator simulator = qis.Aer.get_backend('statevector_simulator') # Get Statevector Results result = qis.execute(circuit, backend=simulator).result() statevector = result.get_statevector() # Plot Statevector Results plot_bloch_multivector(statevector) # Measure Qubits to Classical circuit.measure(qr[0], cr[0]) circuit.measure(qr[1], cr[1]) # Print Circuit (Along w/ Measurements) #print(circuit) circuit.draw(output='mpl') # Choose Qasm Simulator simulator = qis.Aer.get_backend('qasm_simulator') # Get Qasm Results result = qis.execute(circuit, backend=simulator).result() # Plot Qasm Measurements plot_histogram(result.get_counts(circuit)) plt.show() print()
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
#!/usr/bin/env python3 # Author: Daniel Escanez-Exposito, Andrea Hernández Martín from qiskit import QuantumCircuit from crypto.six_state.sender import Sender from crypto.six_state.receiver import Receiver import binascii SIX_STATE_SIMULATOR = 'SIX-STATE SIMULATOR' ## An implementation of the Six-State protocol ## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html class SixStateAlgorithm: ## Generate a key for Alice and Bob def __generate_key(self, backend, original_bits_size, verbose): # Encoder Alice alice = Sender('Alice', original_bits_size) alice.set_values() alice.set_axes() message = alice.encode_quantum_message() # Interceptor Eve eve = Receiver('Eve', original_bits_size) eve.set_axes() message = eve.decode_quantum_message(message, self.measure_density, backend) # Decoder Bob bob = Receiver('Bob', original_bits_size) bob.set_axes() message = bob.decode_quantum_message(message, 1, backend) # Alice - Bob Remove Garbage alice_axes = alice.axes # Alice share her axes bob_axes = bob.axes # Bob share his axes # Delete the difference alice.remove_garbage(bob_axes) bob.remove_garbage(alice_axes) # Bob share some values of the key to check SHARED_SIZE = round(0.5 * len(bob.key)) shared_key = bob.key[:SHARED_SIZE] if verbose: alice.show_values() alice.show_axes() eve.show_values() eve.show_axes() bob.show_values() bob.show_axes() alice.show_key() bob.show_key() print('\nShared Bob Key:') print(shared_key) # Alice check the shared key if alice.check_key(shared_key): shared_size = len(shared_key) alice.confirm_key(shared_size) bob.confirm_key(shared_size) if verbose: print('\nFinal Keys') alice.show_key() bob.show_key() print('\nSecure Communication!') elif verbose: print('\nUnsecure Communication! Eve has been detected intercepting messages\n') return alice, bob ## Run the implementation of Six-State protocol def run(self, message, backend, original_bits_size, measure_density, n_bits, verbose): ## The original size of the message self.original_bits_size = original_bits_size ## The probability of an interception occurring self.measure_density = measure_density alice, bob = self.__generate_key(backend, original_bits_size, verbose) if not (alice.is_safe_key and bob.is_safe_key): if verbose: print('❌ Message not send') return False alice.generate_otp(n_bits) bob.generate_otp(n_bits) encoded_message = alice.xor_otp_message(message) decoded_message = bob.xor_otp_message(encoded_message) if verbose: alice.show_otp() bob.show_otp() print('\nInitial Message:') print(message) print('Encoded Message:') print(encoded_message) print('💡 Decoded Message:') print(decoded_message) if message == decoded_message: print('\n✅ The initial message and the decoded message are identical') else: print('\n❌ The initial message and the decoded message are different') return True
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. """Test the legacy Scheduling passes""" import unittest from ddt import ddt, data, unpack from qiskit import QuantumCircuit from qiskit.circuit import Delay, Parameter from qiskit.circuit.library.standard_gates import XGate, YGate, CXGate from qiskit.test import QiskitTestCase from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.instruction_durations import InstructionDurations from qiskit.transpiler.passes import ASAPSchedule, ALAPSchedule, DynamicalDecoupling from qiskit.transpiler.passmanager import PassManager from qiskit.transpiler.target import Target, InstructionProperties @ddt class TestSchedulingPass(QiskitTestCase): """Tests the Scheduling passes""" def test_alap_agree_with_reverse_asap_reverse(self): """Test if ALAP schedule agrees with doubly-reversed ASAP schedule.""" qc = QuantumCircuit(2) qc.h(0) qc.delay(500, 1) qc.cx(0, 1) qc.measure_all() durations = InstructionDurations( [("h", 0, 200), ("cx", [0, 1], 700), ("measure", None, 1000)] ) pm = PassManager(ALAPSchedule(durations)) alap_qc = pm.run(qc) pm = PassManager(ASAPSchedule(durations)) new_qc = pm.run(qc.reverse_ops()) new_qc = new_qc.reverse_ops() new_qc.name = new_qc.name self.assertEqual(alap_qc, new_qc) @data(ALAPSchedule, ASAPSchedule) def test_classically_controlled_gate_after_measure(self, schedule_pass): """Test if ALAP/ASAP schedules circuits with c_if after measure with a common clbit. See: https://github.com/Qiskit/qiskit-terra/issues/7654 (input) ┌─┐ q_0: ┤M├─────────── └╥┘ ┌───┐ q_1: ─╫────┤ X ├─── ║ └─╥─┘ ║ ┌────╨────┐ c: 1/═╩═╡ c_0 = T ╞ 0 └─────────┘ (scheduled) ┌─┐┌────────────────┐ q_0: ───────────────────┤M├┤ Delay(200[dt]) ├ ┌─────────────────┐└╥┘└─────┬───┬──────┘ q_1: ┤ Delay(1000[dt]) ├─╫───────┤ X ├─────── └─────────────────┘ ║ └─╥─┘ ║ ┌────╨────┐ c: 1/════════════════════╩════╡ c_0=0x1 ╞════ 0 └─────────┘ """ qc = QuantumCircuit(2, 1) qc.measure(0, 0) qc.x(1).c_if(0, True) durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)]) pm = PassManager(schedule_pass(durations)) scheduled = pm.run(qc) expected = QuantumCircuit(2, 1) expected.measure(0, 0) expected.delay(1000, 1) # x.c_if starts after measure expected.x(1).c_if(0, True) expected.delay(200, 0) self.assertEqual(expected, scheduled) @data(ALAPSchedule, ASAPSchedule) def test_measure_after_measure(self, schedule_pass): """Test if ALAP/ASAP schedules circuits with measure after measure with a common clbit. See: https://github.com/Qiskit/qiskit-terra/issues/7654 (input) ┌───┐┌─┐ q_0: ┤ X ├┤M├─── └───┘└╥┘┌─┐ q_1: ──────╫─┤M├ ║ └╥┘ c: 1/══════╩══╩═ 0 0 (scheduled) ┌───┐ ┌─┐┌─────────────────┐ q_0: ───────┤ X ├───────┤M├┤ Delay(1000[dt]) ├ ┌──────┴───┴──────┐└╥┘└───────┬─┬───────┘ q_1: ┤ Delay(1200[dt]) ├─╫─────────┤M├──────── └─────────────────┘ ║ └╥┘ c: 1/════════════════════╩══════════╩═════════ 0 0 """ qc = QuantumCircuit(2, 1) qc.x(0) qc.measure(0, 0) qc.measure(1, 0) durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)]) pm = PassManager(schedule_pass(durations)) scheduled = pm.run(qc) expected = QuantumCircuit(2, 1) expected.x(0) expected.measure(0, 0) expected.delay(1200, 1) expected.measure(1, 0) expected.delay(1000, 0) self.assertEqual(expected, scheduled) @data(ALAPSchedule, ASAPSchedule) def test_c_if_on_different_qubits(self, schedule_pass): """Test if ALAP/ASAP schedules circuits with `c_if`s on different qubits. (input) ┌─┐ q_0: ┤M├────────────────────── └╥┘ ┌───┐ q_1: ─╫────┤ X ├────────────── ║ └─╥─┘ ┌───┐ q_2: ─╫──────╫────────┤ X ├─── ║ ║ └─╥─┘ ║ ┌────╨────┐┌────╨────┐ c: 1/═╩═╡ c_0 = T ╞╡ c_0 = T ╞ 0 └─────────┘└─────────┘ (scheduled) ┌─┐┌────────────────┐ q_0: ───────────────────┤M├┤ Delay(200[dt]) ├─────────── ┌─────────────────┐└╥┘└─────┬───┬──────┘ q_1: ┤ Delay(1000[dt]) ├─╫───────┤ X ├────────────────── ├─────────────────┤ ║ └─╥─┘ ┌───┐ q_2: ┤ Delay(1000[dt]) ├─╫─────────╫────────────┤ X ├─── └─────────────────┘ ║ ║ └─╥─┘ ║ ┌────╨────┐ ┌────╨────┐ c: 1/════════════════════╩════╡ c_0=0x1 ╞════╡ c_0=0x1 ╞ 0 └─────────┘ └─────────┘ """ qc = QuantumCircuit(3, 1) qc.measure(0, 0) qc.x(1).c_if(0, True) qc.x(2).c_if(0, True) durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)]) pm = PassManager(schedule_pass(durations)) scheduled = pm.run(qc) expected = QuantumCircuit(3, 1) expected.measure(0, 0) expected.delay(1000, 1) expected.delay(1000, 2) expected.x(1).c_if(0, True) expected.x(2).c_if(0, True) expected.delay(200, 0) self.assertEqual(expected, scheduled) @data(ALAPSchedule, ASAPSchedule) def test_shorter_measure_after_measure(self, schedule_pass): """Test if ALAP/ASAP schedules circuits with shorter measure after measure with a common clbit. (input) ┌─┐ q_0: ┤M├─── └╥┘┌─┐ q_1: ─╫─┤M├ ║ └╥┘ c: 1/═╩══╩═ 0 0 (scheduled) ┌─┐┌────────────────┐ q_0: ───────────────────┤M├┤ Delay(700[dt]) ├ ┌─────────────────┐└╥┘└──────┬─┬───────┘ q_1: ┤ Delay(1000[dt]) ├─╫────────┤M├──────── └─────────────────┘ ║ └╥┘ c: 1/════════════════════╩═════════╩═════════ 0 0 """ qc = QuantumCircuit(2, 1) qc.measure(0, 0) qc.measure(1, 0) durations = InstructionDurations([("measure", [0], 1000), ("measure", [1], 700)]) pm = PassManager(schedule_pass(durations)) scheduled = pm.run(qc) expected = QuantumCircuit(2, 1) expected.measure(0, 0) expected.delay(1000, 1) expected.measure(1, 0) expected.delay(700, 0) self.assertEqual(expected, scheduled) @data(ALAPSchedule, ASAPSchedule) def test_measure_after_c_if(self, schedule_pass): """Test if ALAP/ASAP schedules circuits with c_if after measure with a common clbit. (input) ┌─┐ q_0: ┤M├────────────── └╥┘ ┌───┐ q_1: ─╫────┤ X ├────── ║ └─╥─┘ ┌─┐ q_2: ─╫──────╫─────┤M├ ║ ┌────╨────┐└╥┘ c: 1/═╩═╡ c_0 = T ╞═╩═ 0 └─────────┘ 0 (scheduled) ┌─┐┌─────────────────┐ q_0: ───────────────────┤M├┤ Delay(1000[dt]) ├────────────────── ┌─────────────────┐└╥┘└──────┬───┬──────┘┌────────────────┐ q_1: ┤ Delay(1000[dt]) ├─╫────────┤ X ├───────┤ Delay(800[dt]) ├ ├─────────────────┤ ║ └─╥─┘ └──────┬─┬───────┘ q_2: ┤ Delay(1000[dt]) ├─╫──────────╫────────────────┤M├──────── └─────────────────┘ ║ ┌────╨────┐ └╥┘ c: 1/════════════════════╩═════╡ c_0=0x1 ╞════════════╩═════════ 0 └─────────┘ 0 """ qc = QuantumCircuit(3, 1) qc.measure(0, 0) qc.x(1).c_if(0, 1) qc.measure(2, 0) durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)]) pm = PassManager(schedule_pass(durations)) scheduled = pm.run(qc) expected = QuantumCircuit(3, 1) expected.delay(1000, 1) expected.delay(1000, 2) expected.measure(0, 0) expected.x(1).c_if(0, 1) expected.measure(2, 0) expected.delay(1000, 0) expected.delay(800, 1) self.assertEqual(expected, scheduled) def test_parallel_gate_different_length(self): """Test circuit having two parallel instruction with different length. (input) ┌───┐┌─┐ q_0: ┤ X ├┤M├─── ├───┤└╥┘┌─┐ q_1: ┤ X ├─╫─┤M├ └───┘ ║ └╥┘ c: 2/══════╩══╩═ 0 1 (expected, ALAP) ┌────────────────┐┌───┐┌─┐ q_0: ┤ Delay(200[dt]) ├┤ X ├┤M├ └─────┬───┬──────┘└┬─┬┘└╥┘ q_1: ──────┤ X ├────────┤M├──╫─ └───┘ └╥┘ ║ c: 2/════════════════════╩═══╩═ 1 0 (expected, ASAP) ┌───┐┌─┐┌────────────────┐ q_0: ┤ X ├┤M├┤ Delay(200[dt]) ├ ├───┤└╥┘└──────┬─┬───────┘ q_1: ┤ X ├─╫────────┤M├──────── └───┘ ║ └╥┘ c: 2/══════╩═════════╩═════════ 0 1 """ qc = QuantumCircuit(2, 2) qc.x(0) qc.x(1) qc.measure(0, 0) qc.measure(1, 1) durations = InstructionDurations( [("x", [0], 200), ("x", [1], 400), ("measure", None, 1000)] ) pm = PassManager(ALAPSchedule(durations)) qc_alap = pm.run(qc) alap_expected = QuantumCircuit(2, 2) alap_expected.delay(200, 0) alap_expected.x(0) alap_expected.x(1) alap_expected.measure(0, 0) alap_expected.measure(1, 1) self.assertEqual(qc_alap, alap_expected) pm = PassManager(ASAPSchedule(durations)) qc_asap = pm.run(qc) asap_expected = QuantumCircuit(2, 2) asap_expected.x(0) asap_expected.x(1) asap_expected.measure(0, 0) # immediately start after X gate asap_expected.measure(1, 1) asap_expected.delay(200, 0) self.assertEqual(qc_asap, asap_expected) def test_parallel_gate_different_length_with_barrier(self): """Test circuit having two parallel instruction with different length with barrier. (input) ┌───┐┌─┐ q_0: ┤ X ├┤M├─── ├───┤└╥┘┌─┐ q_1: ┤ X ├─╫─┤M├ └───┘ ║ └╥┘ c: 2/══════╩══╩═ 0 1 (expected, ALAP) ┌────────────────┐┌───┐ ░ ┌─┐ q_0: ┤ Delay(200[dt]) ├┤ X ├─░─┤M├─── └─────┬───┬──────┘└───┘ ░ └╥┘┌─┐ q_1: ──────┤ X ├─────────────░──╫─┤M├ └───┘ ░ ║ └╥┘ c: 2/═══════════════════════════╩══╩═ 0 1 (expected, ASAP) ┌───┐┌────────────────┐ ░ ┌─┐ q_0: ┤ X ├┤ Delay(200[dt]) ├─░─┤M├─── ├───┤└────────────────┘ ░ └╥┘┌─┐ q_1: ┤ X ├───────────────────░──╫─┤M├ └───┘ ░ ║ └╥┘ c: 2/═══════════════════════════╩══╩═ 0 1 """ qc = QuantumCircuit(2, 2) qc.x(0) qc.x(1) qc.barrier() qc.measure(0, 0) qc.measure(1, 1) durations = InstructionDurations( [("x", [0], 200), ("x", [1], 400), ("measure", None, 1000)] ) pm = PassManager(ALAPSchedule(durations)) qc_alap = pm.run(qc) alap_expected = QuantumCircuit(2, 2) alap_expected.delay(200, 0) alap_expected.x(0) alap_expected.x(1) alap_expected.barrier() alap_expected.measure(0, 0) alap_expected.measure(1, 1) self.assertEqual(qc_alap, alap_expected) pm = PassManager(ASAPSchedule(durations)) qc_asap = pm.run(qc) asap_expected = QuantumCircuit(2, 2) asap_expected.x(0) asap_expected.delay(200, 0) asap_expected.x(1) asap_expected.barrier() asap_expected.measure(0, 0) asap_expected.measure(1, 1) self.assertEqual(qc_asap, asap_expected) def test_measure_after_c_if_on_edge_locking(self): """Test if ALAP/ASAP schedules circuits with c_if after measure with a common clbit. The scheduler is configured to reproduce behavior of the 0.20.0, in which clbit lock is applied to the end-edge of measure instruction. See https://github.com/Qiskit/qiskit-terra/pull/7655 (input) ┌─┐ q_0: ┤M├────────────── └╥┘ ┌───┐ q_1: ─╫────┤ X ├────── ║ └─╥─┘ ┌─┐ q_2: ─╫──────╫─────┤M├ ║ ┌────╨────┐└╥┘ c: 1/═╩═╡ c_0 = T ╞═╩═ 0 └─────────┘ 0 (ASAP scheduled) ┌─┐┌────────────────┐ q_0: ───────────────────┤M├┤ Delay(200[dt]) ├───────────────────── ┌─────────────────┐└╥┘└─────┬───┬──────┘ q_1: ┤ Delay(1000[dt]) ├─╫───────┤ X ├──────────────────────────── └─────────────────┘ ║ └─╥─┘ ┌─┐┌────────────────┐ q_2: ────────────────────╫─────────╫─────────┤M├┤ Delay(200[dt]) ├ ║ ┌────╨────┐ └╥┘└────────────────┘ c: 1/════════════════════╩════╡ c_0=0x1 ╞═════╩═══════════════════ 0 └─────────┘ 0 (ALAP scheduled) ┌─┐┌────────────────┐ q_0: ───────────────────┤M├┤ Delay(200[dt]) ├─── ┌─────────────────┐└╥┘└─────┬───┬──────┘ q_1: ┤ Delay(1000[dt]) ├─╫───────┤ X ├────────── └┬────────────────┤ ║ └─╥─┘ ┌─┐ q_2: ─┤ Delay(200[dt]) ├─╫─────────╫─────────┤M├ └────────────────┘ ║ ┌────╨────┐ └╥┘ c: 1/════════════════════╩════╡ c_0=0x1 ╞═════╩═ 0 └─────────┘ 0 """ qc = QuantumCircuit(3, 1) qc.measure(0, 0) qc.x(1).c_if(0, 1) qc.measure(2, 0) durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)]) # lock at the end edge actual_asap = PassManager(ASAPSchedule(durations, clbit_write_latency=1000)).run(qc) actual_alap = PassManager(ALAPSchedule(durations, clbit_write_latency=1000)).run(qc) # start times of 2nd measure depends on ASAP/ALAP expected_asap = QuantumCircuit(3, 1) expected_asap.measure(0, 0) expected_asap.delay(1000, 1) expected_asap.x(1).c_if(0, 1) expected_asap.measure(2, 0) expected_asap.delay(200, 0) expected_asap.delay(200, 2) self.assertEqual(expected_asap, actual_asap) expected_alap = QuantumCircuit(3, 1) expected_alap.measure(0, 0) expected_alap.delay(1000, 1) expected_alap.x(1).c_if(0, 1) expected_alap.delay(200, 2) expected_alap.measure(2, 0) expected_alap.delay(200, 0) self.assertEqual(expected_alap, actual_alap) @data([100, 200], [500, 0], [1000, 200]) @unpack def test_active_reset_circuit(self, write_lat, cond_lat): """Test practical example of reset circuit. Because of the stimulus pulse overlap with the previous XGate on the q register, measure instruction is always triggered after XGate regardless of write latency. Thus only conditional latency matters in the scheduling. (input) ┌─┐ ┌───┐ ┌─┐ ┌───┐ ┌─┐ ┌───┐ q: ┤M├───┤ X ├───┤M├───┤ X ├───┤M├───┤ X ├─── └╥┘ └─╥─┘ └╥┘ └─╥─┘ └╥┘ └─╥─┘ ║ ┌────╨────┐ ║ ┌────╨────┐ ║ ┌────╨────┐ c: 1/═╩═╡ c_0=0x1 ╞═╩═╡ c_0=0x1 ╞═╩═╡ c_0=0x1 ╞ 0 └─────────┘ 0 └─────────┘ 0 └─────────┘ """ qc = QuantumCircuit(1, 1) qc.measure(0, 0) qc.x(0).c_if(0, 1) qc.measure(0, 0) qc.x(0).c_if(0, 1) qc.measure(0, 0) qc.x(0).c_if(0, 1) durations = InstructionDurations([("x", None, 100), ("measure", None, 1000)]) actual_asap = PassManager( ASAPSchedule(durations, clbit_write_latency=write_lat, conditional_latency=cond_lat) ).run(qc) actual_alap = PassManager( ALAPSchedule(durations, clbit_write_latency=write_lat, conditional_latency=cond_lat) ).run(qc) expected = QuantumCircuit(1, 1) expected.measure(0, 0) if cond_lat > 0: expected.delay(cond_lat, 0) expected.x(0).c_if(0, 1) expected.measure(0, 0) if cond_lat > 0: expected.delay(cond_lat, 0) expected.x(0).c_if(0, 1) expected.measure(0, 0) if cond_lat > 0: expected.delay(cond_lat, 0) expected.x(0).c_if(0, 1) self.assertEqual(expected, actual_asap) self.assertEqual(expected, actual_alap) def test_random_complicated_circuit(self): """Test scheduling complicated circuit with control flow. (input) ┌────────────────┐ ┌───┐ ░ ┌───┐ » q_0: ┤ Delay(100[dt]) ├───┤ X ├────░──────────────────┤ X ├───» └────────────────┘ └─╥─┘ ░ ┌───┐ └─╥─┘ » q_1: ───────────────────────╫──────░───────┤ X ├────────╫─────» ║ ░ ┌─┐ └─╥─┘ ║ » q_2: ───────────────────────╫──────░─┤M├─────╫──────────╫─────» ┌────╨────┐ ░ └╥┘┌────╨────┐┌────╨────┐» c: 1/══════════════════╡ c_0=0x1 ╞════╩═╡ c_0=0x0 ╞╡ c_0=0x0 ╞» └─────────┘ 0 └─────────┘└─────────┘» « ┌────────────────┐┌───┐ «q_0: ┤ Delay(300[dt]) ├┤ X ├─────■───── « └────────────────┘└───┘ ┌─┴─┐ «q_1: ────────■─────────────────┤ X ├─── « ┌─┴─┐ ┌─┐ └─╥─┘ «q_2: ──────┤ X ├────────┤M├──────╫───── « └───┘ └╥┘ ┌────╨────┐ «c: 1/════════════════════╩══╡ c_0=0x0 ╞ « 0 └─────────┘ (ASAP scheduled) duration = 2800 dt ┌────────────────┐┌────────────────┐ ┌───┐ ░ ┌─────────────────┐» q_0: ┤ Delay(100[dt]) ├┤ Delay(100[dt]) ├───┤ X ├────░─┤ Delay(1400[dt]) ├» ├────────────────┤└────────────────┘ └─╥─┘ ░ ├─────────────────┤» q_1: ┤ Delay(300[dt]) ├───────────────────────╫──────░─┤ Delay(1200[dt]) ├» ├────────────────┤ ║ ░ └───────┬─┬───────┘» q_2: ┤ Delay(300[dt]) ├───────────────────────╫──────░─────────┤M├────────» └────────────────┘ ┌────╨────┐ ░ └╥┘ » c: 1/════════════════════════════════════╡ c_0=0x1 ╞════════════╩═════════» └─────────┘ 0 » « ┌───┐ ┌────────────────┐» «q_0: ────────────────────────────────┤ X ├───┤ Delay(300[dt]) ├» « ┌───┐ └─╥─┘ └────────────────┘» «q_1: ───┤ X ├──────────────────────────╫─────────────■─────────» « └─╥─┘ ┌────────────────┐ ║ ┌─┴─┐ » «q_2: ─────╫─────┤ Delay(300[dt]) ├─────╫───────────┤ X ├───────» « ┌────╨────┐└────────────────┘┌────╨────┐ └───┘ » «c: 1/╡ c_0=0x0 ╞══════════════════╡ c_0=0x0 ╞══════════════════» « └─────────┘ └─────────┘ » « ┌───┐ ┌────────────────┐ «q_0: ──────┤ X ├────────────■─────┤ Delay(700[dt]) ├ « ┌─────┴───┴──────┐ ┌─┴─┐ ├────────────────┤ «q_1: ┤ Delay(400[dt]) ├───┤ X ├───┤ Delay(700[dt]) ├ « ├────────────────┤ └─╥─┘ └──────┬─┬───────┘ «q_2: ┤ Delay(300[dt]) ├─────╫────────────┤M├──────── « └────────────────┘┌────╨────┐ └╥┘ «c: 1/══════════════════╡ c_0=0x0 ╞════════╩═════════ « └─────────┘ 0 (ALAP scheduled) duration = 3100 ┌────────────────┐┌────────────────┐ ┌───┐ ░ ┌─────────────────┐» q_0: ┤ Delay(100[dt]) ├┤ Delay(100[dt]) ├───┤ X ├────░─┤ Delay(1400[dt]) ├» ├────────────────┤└────────────────┘ └─╥─┘ ░ ├─────────────────┤» q_1: ┤ Delay(300[dt]) ├───────────────────────╫──────░─┤ Delay(1200[dt]) ├» ├────────────────┤ ║ ░ └───────┬─┬───────┘» q_2: ┤ Delay(300[dt]) ├───────────────────────╫──────░─────────┤M├────────» └────────────────┘ ┌────╨────┐ ░ └╥┘ » c: 1/════════════════════════════════════╡ c_0=0x1 ╞════════════╩═════════» └─────────┘ 0 » « ┌───┐ ┌────────────────┐» «q_0: ────────────────────────────────┤ X ├───┤ Delay(300[dt]) ├» « ┌───┐ ┌────────────────┐ └─╥─┘ └────────────────┘» «q_1: ───┤ X ├───┤ Delay(300[dt]) ├─────╫─────────────■─────────» « └─╥─┘ ├────────────────┤ ║ ┌─┴─┐ » «q_2: ─────╫─────┤ Delay(600[dt]) ├─────╫───────────┤ X ├───────» « ┌────╨────┐└────────────────┘┌────╨────┐ └───┘ » «c: 1/╡ c_0=0x0 ╞══════════════════╡ c_0=0x0 ╞══════════════════» « └─────────┘ └─────────┘ » « ┌───┐ ┌────────────────┐ «q_0: ──────┤ X ├────────────■─────┤ Delay(700[dt]) ├ « ┌─────┴───┴──────┐ ┌─┴─┐ ├────────────────┤ «q_1: ┤ Delay(100[dt]) ├───┤ X ├───┤ Delay(700[dt]) ├ « └──────┬─┬───────┘ └─╥─┘ └────────────────┘ «q_2: ───────┤M├─────────────╫─────────────────────── « └╥┘ ┌────╨────┐ «c: 1/════════╩═════════╡ c_0=0x0 ╞══════════════════ « 0 └─────────┘ """ qc = QuantumCircuit(3, 1) qc.delay(100, 0) qc.x(0).c_if(0, 1) qc.barrier() qc.measure(2, 0) qc.x(1).c_if(0, 0) qc.x(0).c_if(0, 0) qc.delay(300, 0) qc.cx(1, 2) qc.x(0) qc.cx(0, 1).c_if(0, 0) qc.measure(2, 0) durations = InstructionDurations( [("x", None, 100), ("measure", None, 1000), ("cx", None, 200)] ) actual_asap = PassManager( ASAPSchedule(durations, clbit_write_latency=100, conditional_latency=200) ).run(qc) actual_alap = PassManager( ALAPSchedule(durations, clbit_write_latency=100, conditional_latency=200) ).run(qc) expected_asap = QuantumCircuit(3, 1) expected_asap.delay(100, 0) expected_asap.delay(100, 0) # due to conditional latency of 200dt expected_asap.delay(300, 1) expected_asap.delay(300, 2) expected_asap.x(0).c_if(0, 1) expected_asap.barrier() expected_asap.delay(1400, 0) expected_asap.delay(1200, 1) expected_asap.measure(2, 0) expected_asap.x(1).c_if(0, 0) expected_asap.x(0).c_if(0, 0) expected_asap.delay(300, 0) expected_asap.x(0) expected_asap.delay(300, 2) expected_asap.cx(1, 2) expected_asap.delay(400, 1) expected_asap.cx(0, 1).c_if(0, 0) expected_asap.delay(700, 0) # creg is released at t0 of cx(0,1).c_if(0,0) expected_asap.delay( 700, 1 ) # no creg write until 100dt. thus measure can move left by 300dt. expected_asap.delay(300, 2) expected_asap.measure(2, 0) self.assertEqual(expected_asap, actual_asap) self.assertEqual(actual_asap.duration, 3100) expected_alap = QuantumCircuit(3, 1) expected_alap.delay(100, 0) expected_alap.delay(100, 0) # due to conditional latency of 200dt expected_alap.delay(300, 1) expected_alap.delay(300, 2) expected_alap.x(0).c_if(0, 1) expected_alap.barrier() expected_alap.delay(1400, 0) expected_alap.delay(1200, 1) expected_alap.measure(2, 0) expected_alap.x(1).c_if(0, 0) expected_alap.x(0).c_if(0, 0) expected_alap.delay(300, 0) expected_alap.x(0) expected_alap.delay(300, 1) expected_alap.delay(600, 2) expected_alap.cx(1, 2) expected_alap.delay(100, 1) expected_alap.cx(0, 1).c_if(0, 0) expected_alap.measure(2, 0) expected_alap.delay(700, 0) expected_alap.delay(700, 1) self.assertEqual(expected_alap, actual_alap) self.assertEqual(actual_alap.duration, 3100) def test_dag_introduces_extra_dependency_between_conditionals(self): """Test dependency between conditional operations in the scheduling. In the below example circuit, the conditional x on q1 could start at time 0, however it must be scheduled after the conditional x on q0 in ASAP scheduling. That is because circuit model used in the transpiler passes (DAGCircuit) interprets instructions acting on common clbits must be run in the order given by the original circuit (QuantumCircuit). (input) ┌────────────────┐ ┌───┐ q_0: ┤ Delay(100[dt]) ├───┤ X ├─── └─────┬───┬──────┘ └─╥─┘ q_1: ──────┤ X ├────────────╫───── └─╥─┘ ║ ┌────╨────┐ ┌────╨────┐ c: 1/═══╡ c_0=0x1 ╞════╡ c_0=0x1 ╞ └─────────┘ └─────────┘ (ASAP scheduled) ┌────────────────┐ ┌───┐ q_0: ┤ Delay(100[dt]) ├───┤ X ├────────────── ├────────────────┤ └─╥─┘ ┌───┐ q_1: ┤ Delay(100[dt]) ├─────╫────────┤ X ├─── └────────────────┘ ║ └─╥─┘ ┌────╨────┐┌────╨────┐ c: 1/══════════════════╡ c_0=0x1 ╞╡ c_0=0x1 ╞ └─────────┘└─────────┘ """ qc = QuantumCircuit(2, 1) qc.delay(100, 0) qc.x(0).c_if(0, True) qc.x(1).c_if(0, True) durations = InstructionDurations([("x", None, 160)]) pm = PassManager(ASAPSchedule(durations)) scheduled = pm.run(qc) expected = QuantumCircuit(2, 1) expected.delay(100, 0) expected.delay(100, 1) # due to extra dependency on clbits expected.x(0).c_if(0, True) expected.x(1).c_if(0, True) self.assertEqual(expected, scheduled) @data(ALAPSchedule, ASAPSchedule) def test_respect_target_instruction_constraints(self, schedule_pass): """Test if ALAP/ASAP does not pad delays for qubits that do not support delay instructions. See: https://github.com/Qiskit/qiskit-terra/issues/9993 """ target = Target(dt=1) target.add_instruction(XGate(), {(1,): InstructionProperties(duration=200)}) # delays are not supported qc = QuantumCircuit(2) qc.x(1) pm = PassManager(schedule_pass(target=target)) scheduled = pm.run(qc) expected = QuantumCircuit(2) expected.x(1) # no delay on qubit 0 self.assertEqual(expected, scheduled) def test_dd_respect_target_instruction_constraints(self): """Test if DD pass does not pad delays for qubits that do not support delay instructions and does not insert DD gates for qubits that do not support necessary gates. See: https://github.com/Qiskit/qiskit-terra/issues/9993 """ qc = QuantumCircuit(3) qc.cx(0, 1) qc.cx(1, 2) target = Target(dt=1) # Y is partially supported (not supported on qubit 2) target.add_instruction( XGate(), {(q,): InstructionProperties(duration=100) for q in range(2)} ) target.add_instruction( CXGate(), { (0, 1): InstructionProperties(duration=1000), (1, 2): InstructionProperties(duration=1000), }, ) # delays are not supported # No DD instructions nor delays are padded due to no delay support in the target pm_xx = PassManager( [ ALAPSchedule(target=target), DynamicalDecoupling(durations=None, dd_sequence=[XGate(), XGate()], target=target), ] ) scheduled = pm_xx.run(qc) self.assertEqual(qc, scheduled) # Fails since Y is not supported in the target with self.assertRaises(TranspilerError): PassManager( [ ALAPSchedule(target=target), DynamicalDecoupling( durations=None, dd_sequence=[XGate(), YGate(), XGate(), YGate()], target=target, ), ] ) # Add delay support to the target target.add_instruction(Delay(Parameter("t")), {(q,): None for q in range(3)}) # No error but no DD on qubit 2 (just delay is padded) since X is not supported on it scheduled = pm_xx.run(qc) expected = QuantumCircuit(3) expected.delay(1000, [2]) expected.cx(0, 1) expected.cx(1, 2) expected.delay(200, [0]) expected.x([0]) expected.delay(400, [0]) expected.x([0]) expected.delay(200, [0]) self.assertEqual(expected, scheduled) if __name__ == "__main__": unittest.main()
https://github.com/QuTech-Delft/quantuminspire
QuTech-Delft
import numpy as np import os from qiskit import transpile, QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit_aer import Aer from qiskit.providers.basic_provider import BasicProvider from qiskit.visualization import circuit_drawer, plot_histogram from IPython.display import display, Math, Latex from quantuminspire.credentials import get_authentication from quantuminspire.api import QuantumInspireAPI from quantuminspire.qiskit import QI QI_URL = os.getenv('API_URL', 'https://api.quantum-inspire.com/') def format_vector(state_vector, decimal_precision=7): """ Format the state vector into a LaTeX formatted string. Args: state_vector (list or array): The state vector with complex values e.g. [-1, 2j+1]. Returns: str: The LaTeX format. """ result = [] epsilon = 1/pow(10, decimal_precision) state_vector = np.asarray(state_vector) bit_length = (len(state_vector) - 1).bit_length() for index, complex_value in enumerate(state_vector): has_imag_part = np.round(complex_value.imag, decimal_precision) != 0.0 value = complex_value if has_imag_part else complex_value.real value_round = np.round(value, decimal_precision) if np.abs(value_round) < epsilon: continue binary_state = '{0:0{1}b}'.format(index, bit_length) result.append(r'{0:+2g}\left\lvert {1}\right\rangle '.format(value_round, binary_state)) return ''.join(result) def run_circuit(q_circuit, q_register, number_of_qubits=None, backend_name='statevector_simulator'): """ Run a circuit on all base state vectors and show the output. Args: q_circuit (QuantumCircuit): q_register (QuantumRegister) number_of_qubits (int or None): The number of qubits. backend (str): ... """ if not isinstance(number_of_qubits, int): number_of_qubits = q_register.size if q_register.size != number_of_qubits: warnings.warn('incorrect register size?') latex_text = r'\mathrm{running\ circuit\ on\ set\ of\ basis\ states:}' display(Math(latex_text)) base_states = 2 ** number_of_qubits backend = Aer.get_backend(backend_name) for base_state in range(base_states): pre_circuit = QuantumCircuit(q_register) state = base_state for kk in range(number_of_qubits): if state % 2 == 1: pre_circuit.x(q[kk]) state = state // 2 input_state = r'\left\lvert{0:0{1}b}\right\rangle'.format(base_state, number_of_qubits) circuit_total = pre_circuit.compose(q_circuit) circuit_total = transpile(circuit_total, backend) job = backend.run(circuit_total, shots=10) output_state = job.result().get_statevector(circuit_total) latex_text = input_state + r'\mathrm{transforms\ to}: ' + format_vector(output_state) display(Math(latex_text)) n=3 N=2**n q = QuantumRegister(n) qc = QuantumCircuit(q) if n==1: def black_box(qc, q): qc.z(q) elif n==2: def black_box(qc, q): for i in range(n): qc.s(q[i]) qc.h(q[1]) qc.cx(q[0], q[1]) qc.h(q[1]) for i in range(n): qc.s(q[i]) else: def black_box(qc, q): qc.h(q[2]) qc.ccx(q[0], q[1], q[2]) qc.h(q[2]) black_box(qc,q) cplot=qc.draw(output='mpl') display(cplot) print('black box circuit:') run_circuit(qc, q) def n_controlled_Z(circuit, controls, target): """Implement a Z gate with multiple controls""" if (len(controls) > 2): raise ValueError('The controlled Z with more than 2 ' + 'controls is not implemented') elif (len(controls) == 1): circuit.h(target) circuit.cx(controls[0], target) circuit.h(target) elif (len(controls) == 2): circuit.h(target) circuit.ccx(controls[0], controls[1], target) circuit.h(target) def inversion_about_average(circuit, f_in, n): """Apply inversion about the average step of Grover's algorithm.""" # Hadamards everywhere if n==1: circuit.x(f_in[0]) return for j in range(n): circuit.h(f_in[j]) # D matrix: flips the sign of the state |000> only for j in range(n): circuit.x(f_in[j]) n_controlled_Z(circuit, [f_in[j] for j in range(n-1)], f_in[n-1]) for j in range(n): circuit.x(f_in[j]) # Hadamards everywhere again for j in range(n): circuit.h(f_in[j]) qInvAvg = QuantumCircuit(q) inversion_about_average(qInvAvg, q, n) qInvAvg.draw(output='mpl') print('inversion average circuit:') qc = QuantumCircuit(q) inversion_about_average(qc, q, n) run_circuit(qc, q, n) theta = 2*np.arcsin(1/np.sqrt(N)) r=np.pi*np.sqrt(N)/4 display(Math(r'\textrm{Rotation of the winner: } \theta = %.2f \mathrm{\ [deg]}' % (np.rad2deg(theta))) ) print('Optimal number of Grover iterations for n=%d: %.1f' % (n,r) ) T=int(r) for i in range(int(r+2)): p=np.sin((i+1/2)*theta)**2 print('%d iterations: p %.2f' % (i, p)) """Grover search implemented in Qiskit. This module contains the code necessary to run Grover search on 3 qubits, both with a simulator and with a real quantum computing device. This code is the companion for the paper "An introduction to quantum computing, without the physics", Giacomo Nannicini, https://arxiv.org/abs/1708.03684. """ def input_state(circuit, f_in, n): """(n+1)-qubit input state for Grover search.""" for j in range(n): circuit.h(f_in[j]) q = QuantumRegister(n) ans = ClassicalRegister(n) qc = QuantumCircuit(q, ans) input_state(qc, q, n) backend = Aer.get_backend('statevector_simulator') qc = transpile(qc, backend) job = backend.run(qc, shots=10) result = job.result() state_vector = result.get_statevector(qc) m=display( Math(r'\mathrm{state\ after\ initialization:\ }' + format_vector(state_vector))) # apply T rounds of oracle and inversion about the average print('number of iterations T=%d'% T) for t in range(T): for i in range(n): qc.barrier(q[i]) # for better visualization qc.id(q[0]) # Apply T full iterations black_box(qc, q) for i in range(n): qc.barrier(q[i]) qc.id(q[0]) inversion_about_average(qc, q, n) # Measure the output register in the computational basis for j in range(n): qc.measure(q[j], ans[j]) # Execute circuit backend = BasicProvider().get_backend(name="basic_simulator") qc = transpile(qc, backend=backend) job = backend.run(qc, shots=10) result = job.result() # Get counts and plot histogram counts = result.get_counts() plot_histogram(counts) qc.draw(output='mpl') authentication = get_authentication() QI.set_authentication(authentication, QI_URL) QI.backends() qi_backend = QI.get_backend('QX single-node simulator') qc=transpile(qc, backend=qi_backend) j=qi_backend.run(qc, shots=512) result = j.result() print('Generated histogram:') print(result.get_counts()) plot_histogram(result.get_counts(qc))
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
mathelatics
from qiskit import QuantumCircuit, QuantumRegister from qiskit.quantum_info import SparsePauliOp def heisenberg_hamiltonian( length: int, jx: float = 1.0, jy: float = 0.0, jz: float = 0.0 ) -> SparsePauliOp: terms = [] for i in range(length - 1): if jx: terms.append(("XX", [i, i + 1], jx)) if jy: terms.append(("YY", [i, i + 1], jy)) if jz: terms.append(("ZZ", [i, i + 1], jz)) return SparsePauliOp.from_sparse_list(terms, num_qubits=length) def state_prep_circuit(num_qubits: int, layers: int = 1) -> QuantumCircuit: qubits = QuantumRegister(num_qubits, name="q") circuit = QuantumCircuit(qubits) circuit.h(qubits) for _ in range(layers): for i in range(0, num_qubits - 1, 2): circuit.cx(qubits[i], qubits[i + 1]) circuit.ry(0.1, qubits) for i in range(1, num_qubits - 1, 2): circuit.cx(qubits[i], qubits[i + 1]) circuit.ry(0.1, qubits) return circuit length = 5 hamiltonian = heisenberg_hamiltonian(length, 1.0, 1.0) circuit = state_prep_circuit(length, layers=2) print(hamiltonian) circuit.draw("mpl") from qiskit_aer.primitives import Estimator estimator = Estimator(approximation=True) job = estimator.run(circuit, hamiltonian, shots=None) result = job.result() exact_value = result.values[0] print(f"Exact energy: {exact_value}") from qiskit_ibm_runtime import QiskitRuntimeService hub = "ibm-q-internal" group = "deployed" project = "default" service = QiskitRuntimeService(instance=f"{hub}/{group}/{project}") from qiskit_ibm_runtime import Estimator, Options, Session from qiskit.transpiler import CouplingMap backend = service.get_backend("simulator_statevector") # set simulation options simulator = { "basis_gates": ["id", "rz", "sx", "cx", "reset"], "coupling_map": list(CouplingMap.from_line(length + 1)), } shots = 10000 import math options = Options( simulator=simulator, resilience_level=0, ) with Session(service=service, backend=backend): estimator = Estimator(options=options) job = estimator.run(circuit, hamiltonian, shots=shots) result = job.result() experiment_value = result.values[0] error = abs(experiment_value - exact_value) variance = result.metadata[0]["variance"] std = math.sqrt(variance / shots) print(f"Estimated energy: {experiment_value}") print(f"Energy error: {error}") print(f"Variance: {variance}") print(f"Standard error: {std}") from qiskit_aer.noise import NoiseModel, ReadoutError noise_model = NoiseModel() ##### your code here ##### # P(A|B) = [P(A|0), P(A|1)] = [ 1 - q0_01, q0_01 ] = [ 0.8, 0.2 ] q0_10 = 0.5 q0_01 = 0.2 qn_10 = 0.05 qn_01 = 0.02 re_l = [ReadoutError( [ [1 - q0_01, q0_01], [q0_10, 1 - q0_10], ] )] n_qubits = 6 for _ in range(n_qubits - 1): re_l.append(ReadoutError( [ [1 - qn_01, qn_01], [qn_10, 1 - qn_10], ] )) for q in range(n_qubits): noise_model.add_readout_error(re_l[q], (q, )) print(noise_model.to_dict()) # Submit your answer from qc_grader.challenges.qgss_2023 import grade_lab5_ex1 grade_lab5_ex1(noise_model) options = Options( simulator=dict(noise_model=noise_model, **simulator), resilience_level=0, transpilation=dict(initial_layout=list(range(length))), ) with Session(service=service, backend=backend): estimator = Estimator(options=options) job = estimator.run(circuit, hamiltonian, shots=shots) result = job.result() experiment_value = result.values[0] error = abs(experiment_value - exact_value) variance = result.metadata[0]["variance"] std = math.sqrt(variance / shots) print(f"Estimated energy: {experiment_value}") print(f"Energy error: {error}") print(f"Variance: {variance}") print(f"Standard error: {std}") options = Options( simulator=dict(noise_model=noise_model, **simulator), resilience_level=0, transpilation=dict(initial_layout=list(range(1, length + 1))), ) with Session(service=service, backend=backend): estimator = Estimator(options=options) job = estimator.run(circuit, hamiltonian, shots=shots) result = job.result() experiment_value = result.values[0] error = abs(experiment_value - exact_value) variance = result.metadata[0]["variance"] std = math.sqrt(variance / shots) print(f"Estimated energy: {experiment_value}") print(f"Energy error: {error}") print(f"Variance: {variance}") print(f"Standard error: {std}") options = Options( simulator=dict(noise_model=noise_model, **simulator), resilience_level=1, transpilation=dict(initial_layout=list(range(1, length + 1))), ) with Session(service=service, backend=backend): estimator = Estimator(options=options) job = estimator.run(circuit, hamiltonian, shots=shots) result = job.result() experiment_value = result.values[0] error = abs(experiment_value - exact_value) variance = result.metadata[0]["variance"] std = math.sqrt(variance / shots) print(f"Estimated energy: {experiment_value}") print(f"Energy error: {error}") print(f"Variance: {variance}") print(f"Standard error: {std}") new_shots: int ##### your code here ##### new_shots = 20000 # Submit your answer from qc_grader.challenges.qgss_2023 import grade_lab5_ex2 grade_lab5_ex2(new_shots) from qiskit_aer.noise import depolarizing_error noise_model = NoiseModel() ##### your code here ##### error = depolarizing_error(0.01, 2) noise_model.add_all_qubit_quantum_error(error, ['cx']) print(noise_model) # Submit your answer from qc_grader.challenges.qgss_2023 import grade_lab5_ex3 grade_lab5_ex3(noise_model) options = Options( simulator=dict(noise_model=noise_model, **simulator), resilience_level=1, ) with Session(service=service, backend=backend): estimator = Estimator(options=options) job = estimator.run(circuit, hamiltonian, shots=shots) result = job.result() experiment_value = result.values[0] error = abs(experiment_value - exact_value) variance = result.metadata[0]["variance"] std = math.sqrt(variance / shots) print(f"Estimated energy: {experiment_value}") print(f"Energy error: {error}") print(f"Variance: {variance}") print(f"Standard error: {std}") options = Options( simulator=dict(noise_model=noise_model, **simulator), resilience_level=2, ) with Session(service=service, backend=backend): estimator = Estimator(options=options) job = estimator.run(circuit, hamiltonian, shots=shots) result = job.result() experiment_value = result.values[0] error = abs(experiment_value - exact_value) variances = result.metadata[0]["zne"]["noise_amplification"]["variance"] print(f"Estimated energy: {experiment_value}") print(f"Energy error: {error}") print(f"Variances: {variances}")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# Useful additional packages import matplotlib.pyplot as plt import numpy as np from math import pi from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, transpile from qiskit.tools.visualization import circuit_drawer from qiskit.quantum_info import state_fidelity from qiskit import BasicAer backend = BasicAer.get_backend('unitary_simulator') q = QuantumRegister(1) qc = QuantumCircuit(q) qc.u(pi/2,pi/4,pi/8,q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.p(pi/2,q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.id(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.x(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.y(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.z(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.h(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.s(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.sdg(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.t(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.tdg(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.rx(pi/2,q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.ry(pi/2,q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.rz(pi/2,q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) q = QuantumRegister(2) qc = QuantumCircuit(q) qc.cx(q[0],q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cy(q[0],q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cz(q[0],q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.ch(q[0],q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.crz(pi/2,q[0],q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cp(pi/2,q[0], q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cu(pi/2, pi/2, pi/2, 0, q[0], q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.swap(q[0], q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) q = QuantumRegister(3) qc = QuantumCircuit(q) qc.ccx(q[0], q[1], q[2]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cswap(q[0], q[1], q[2]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.measure(q, c) qc.draw() backend = BasicAer.get_backend('qasm_simulator') job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.reset(q[0]) qc.measure(q, c) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.h(q) qc.reset(q[0]) qc.measure(q, c) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.x(q[0]).c_if(c, 0) qc.measure(q,c) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q,c) qc.x(q[0]).c_if(c, 0) qc.measure(q,c) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) # Initializing a three-qubit quantum state import math desired_vector = [ 1 / math.sqrt(16) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(16) * complex(1, 1), 0, 0, 1 / math.sqrt(8) * complex(1, 2), 1 / math.sqrt(16) * complex(1, 0), 0] q = QuantumRegister(3) qc = QuantumCircuit(q) qc.initialize(desired_vector, [q[0],q[1],q[2]]) qc.draw() backend = BasicAer.get_backend('statevector_simulator') job = backend.run(transpile(qc, backend)) qc_state = job.result().get_statevector(qc) qc_state state_fidelity(desired_vector,qc_state) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
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/1chooo/Quantum-Oracle
1chooo
# %% [markdown] # # 第3章原始程式碼 # %% #Program 3.1a Apply X-gate to qubit from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.x(1) qc.draw('mpl') # %% #Program 3.1b Show Bloch sphere of qubit w/wo X-gate from qiskit.quantum_info import Statevector state = Statevector.from_instruction(qc) state.draw('bloch') # %% #Program 3.2a Measure state of qubit w/o X-gate from qiskit import QuantumCircuit,execute from qiskit.providers.aer import AerSimulator from qiskit.visualization import plot_histogram import math qc = QuantumCircuit(1,1) qc.initialize([math.sqrt(1/3), math.sqrt(2/3)],0) qc.measure([0],[0]) print(qc) sim=AerSimulator() job=execute(qc, backend=sim, shots=1000) result=job.result() counts=result.get_counts(qc) print("Counts:",counts) plot_histogram(counts) # %% #Program 3.2b Measure state of qubit w/ X-gate from qiskit import QuantumCircuit,execute from qiskit.providers.aer import AerSimulator from qiskit.visualization import plot_histogram import math qc = QuantumCircuit(1,1) qc.initialize([math.sqrt(1/3), math.sqrt(2/3)],0) qc.x(0) qc.measure([0],[0]) print(qc) sim=AerSimulator() job=execute(qc, backend=sim, shots=1000) result=job.result() counts=result.get_counts(qc) print("Counts:",counts) plot_histogram(counts) # %% #Program 3.3a Apply X-gate and H-gate to qubit from qiskit import QuantumCircuit import math qc = QuantumCircuit(4) qc.initialize([1/math.sqrt(2), 1/math.sqrt(2)],0) qc.initialize([1/math.sqrt(2), -1/math.sqrt(2)],1) qc.h(2) qc.x(3) qc.h(3) qc.draw('mpl') # %% #Program 3.3b Show Bloch sphere of qubit w/ X-gate and H-gate from qiskit.quantum_info import Statevector state = Statevector.from_instruction(qc) state.draw('bloch') # %% #Program 3.4 Measure state of qubit w/ H-gate from qiskit import QuantumCircuit,execute from qiskit.providers.aer import AerSimulator from qiskit.visualization import plot_histogram qc = QuantumCircuit(1,1) qc.h(0) qc.measure([0],[0]) print("This is |+>:") print(qc) sim=AerSimulator() job=execute(qc, backend=sim, shots=1000) result=job.result() counts=result.get_counts(qc) print("Counts:",counts) plot_histogram(counts) # %% #Program 3.5 Measure state of qubit w/ X-gate and H-gate from qiskit import QuantumCircuit,execute from qiskit.providers.aer import AerSimulator from qiskit.visualization import plot_histogram qc = QuantumCircuit(1,1) qc.x(0) qc.h(0) qc.measure([0],[0]) print("This is |->:") print(qc) sim=AerSimulator() job=execute(qc, backend=sim, shots=1000) result=job.result() counts=result.get_counts(qc) print("Counts:",counts) plot_histogram(counts) # %% #Program 3.6 Measure state of qubit w/ H-gate from qiskit import QuantumCircuit,execute from qiskit.providers.aer import AerSimulator from qiskit.visualization import plot_histogram qc = QuantumCircuit(2,2) qc.h(0) qc.h(1) qc.measure([0,1],[0,1]) print("This is |++>:") print(qc) sim=AerSimulator() job=execute(qc, backend=sim, shots=1000) result=job.result() counts=result.get_counts(qc) print("Counts:",counts) plot_histogram(counts) # %% #Program 3.7a Apply X-, Y-, and Z-gate to qubit from qiskit import QuantumCircuit qc = QuantumCircuit(3) qc.x(0) qc.y(1) qc.z(2) qc.draw('mpl') # %% #Program 3.7b Show Bloch sphere of qubit w/ X-, Y-, and Z-gate from qiskit.quantum_info import Statevector state = Statevector.from_instruction(qc) state.draw('bloch') # %% #Program 3.8a Apply RX-, RY-, and RZ-gate to qubit from qiskit import QuantumCircuit import math qc = QuantumCircuit(3) qc.rx(math.pi/2, 0) qc.ry(math.pi/2, 1) qc.rz(math.pi/2, 2) qc.draw('mpl') # %% #Program 3.8b Show Bloch sphere of qubit w/ RX-, RY-, and RZ-gate from qiskit.quantum_info import Statevector state = Statevector.from_instruction(qc) state.draw('bloch') # %% #Program 3.9a Apply RX-, P-, S-, T-gate to qubit from qiskit import QuantumCircuit import math qc = QuantumCircuit(4) qc.rx(math.pi/2, [0,1,2,3]) qc.p(math.pi/8, 1) qc.s(2) qc.t(3) qc.draw('mpl') # %% #Program 3.9b Show Bloch sphere of qubit w/ RX-, P-, S-, and T-gate from qiskit.quantum_info import Statevector state = Statevector.from_instruction(qc) state.draw('bloch') # %% #Program 3.10a Apply RX-, I-, and U-gate to qubit from qiskit import QuantumCircuit import math qc = QuantumCircuit(4) qc.rx(math.pi/2, [0,1,2,3]) qc.i(1) qc.u(math.pi/2, 0, math.pi, 2) qc.u(0,0, math.pi/4, 3) qc.draw('mpl') # %% #Program 3.10b Show Bloch sphere of qubit w/ RX-, I-, and U-gate from qiskit.quantum_info import Statevector state = Statevector.from_instruction(qc) state.draw('bloch')
https://github.com/kerenavnery/qmail
kerenavnery
from qiskit import * from channel_class import Channel n_master = 2 # two qubits, the one on alice side n_slave = 1 # two quantum channels and one qubit on bobs side master_offset = 0 slave_offset = n_master circ = QuantumCircuit(n_master + n_slave) channel = Channel(slave_offset, 5000, remote_port = 5001) ## Master, Oracle circ.rx(0.234,0 + channel._offset) circ.rz(0.54,0 + channel._offset) circ.ry(0.94,0 + channel._offset) circ.rx(0.1,0 + channel._offset) ##Creating Entaglement circ.h(1+channel._offset) circ.cx(1+channel._offset,2+channel._offset) ## Master, teleportation protocol circ.cx(0 + channel._offset, 1 + channel._offset) circ.h(0 + channel._offset) # this should be done with classical communication ... #circ.cx(0 + channel._offset, 2 + channel._offset) #circ.cx(1 + channel._offset, 3 + channel._offset) channel.send(circ,[1]) ## TODO: remove circ.draw(output='mpl',filename='teleport_alice.png')
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=missing-docstring,invalid-name,no-member # pylint: disable=attribute-defined-outside-init import copy from qiskit.quantum_info.synthesis import OneQubitEulerDecomposer from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister try: from qiskit.compiler import transpile TRANSPILER_SEED_KEYWORD = "seed_transpiler" except ImportError: from qiskit.transpiler import transpile TRANSPILER_SEED_KEYWORD = "seed_mapper" try: from qiskit.quantum_info.random import random_unitary HAS_RANDOM_UNITARY = True except ImportError: from qiskit.tools.qi.qi import random_unitary_matrix HAS_RANDOM_UNITARY = False # Make a random circuit on a ring def make_circuit_ring(nq, depth, seed): assert int(nq / 2) == nq / 2 # for now size of ring must be even # Create a Quantum Register q = QuantumRegister(nq) # Create a Classical Register c = ClassicalRegister(nq) # Create a Quantum Circuit qc = QuantumCircuit(q, c) offset = 1 decomposer = OneQubitEulerDecomposer() # initial round of random single-qubit unitaries for i in range(nq): qc.h(q[i]) for j in range(depth): for i in range(int(nq / 2)): # round of CNOTS k = i * 2 + offset + j % 2 # j%2 makes alternating rounds overlap qc.cx(q[k % nq], q[(k + 1) % nq]) for i in range(nq): # round of single-qubit unitaries if HAS_RANDOM_UNITARY: u = random_unitary(2, seed).data else: u = random_unitary_matrix(2) # pylint: disable=used-before-assignment # noqa angles = decomposer.angles(u) qc.u3(angles[0], angles[1], angles[2], q[i]) # insert the final measurements qcm = copy.deepcopy(qc) for i in range(nq): qcm.measure(q[i], c[i]) return [qc, qcm, nq] class BenchRandomCircuitHex: params = [2 * i for i in range(2, 8)] param_names = ["n_qubits"] version = 3 def setup(self, n): depth = 2 * n self.seed = 0 self.circuit = make_circuit_ring(n, depth, self.seed)[0] def time_ibmq_backend_transpile(self, _): # Run with ibmq_16_melbourne configuration coupling_map = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] transpile( self.circuit, basis_gates=["u1", "u2", "u3", "cx", "id"], coupling_map=coupling_map, **{TRANSPILER_SEED_KEYWORD: self.seed}, ) def track_depth_ibmq_backend_transpile(self, _): # Run with ibmq_16_melbourne configuration coupling_map = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] return transpile( self.circuit, basis_gates=["u1", "u2", "u3", "cx", "id"], coupling_map=coupling_map, **{TRANSPILER_SEED_KEYWORD: self.seed}, ).depth()
https://github.com/hephaex/Quantum-Computing-Awesome-List
hephaex
import numpy as np import cirq def main(): circuit = make_bell_test_circuit() print("Circuit:") print(circuit) #Run Simulation sim = cirq.Simulator() repetitions = 1000 print("Simulating {} repetitions".format(repetitions)) result = sim.run(program=circuit, repetitions=repetitions) ## Collect Results a = np.array(result.measurements['a'] [:, 0]) b = np.array(result.measurements['b'] [:, 0]) x = np.array(result.measurements['x'] [:, 0]) y = np.array(result.measurements['y'] [:, 0]) outcomes = a ^ b == x & y win_percent = len([e for e in outcomes if e]) * 100/repetitions print() print('Results') print('a:', bitstring(a)) print('b:', bitstring(b)) print('x:', bitstring(x)) print('y:', bitstring(y)) print('(a XOR b) == (x AND y): \n', bitstring(outcomes)) print('Win rate: {}%' .format(win_percent)) def make_bell_test_circuit(): alice = cirq.GridQubit(0, 0) bob = cirq.GridQubit(1, 0) alice_referee = cirq.GridQubit(0, 1) bob_referee = cirq.GridQubit(1,1) circuit = cirq.Circuit() ## Prepare shared entanglement circuit.append([cirq.H(alice), cirq.CNOT(alice, bob), cirq.X(alice)**-0.25,]) ## Referee flip coins circuit.append([cirq.H(alice_referee), cirq.H(bob_referee), ]) ## Players do oa sqrt based on their referee coin circuit.append([cirq.CNOT(alice_referee, alice)**0.5, cirq.CNOT(bob_referee, bob)**0.5, ]) circuit.append([ cirq.measure(alice, key = 'a'), cirq.measure(bob, key = 'b'), cirq.measure(alice_referee, key = 'x'), cirq.measure(bob_referee, key = 'y'), ]) return circuit def bitstring(bits): return ''.join('1' if e else '_' for e in bits) if __name__ == '__main__': main()
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test cases for the circuit qasm_file and qasm_string method.""" import os from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit import Gate, Parameter from qiskit.exceptions import QiskitError from qiskit.test import QiskitTestCase from qiskit.transpiler.passes import Unroller from qiskit.converters.circuit_to_dag import circuit_to_dag class LoadFromQasmTest(QiskitTestCase): """Test circuit.from_qasm_* set of methods.""" def setUp(self): super().setUp() self.qasm_file_name = "entangled_registers.qasm" self.qasm_dir = os.path.join( os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm" ) self.qasm_file_path = os.path.join(self.qasm_dir, self.qasm_file_name) def test_qasm_file(self): """ Test qasm_file and get_circuit. If all is correct we should get the qasm file loaded in _qasm_file_path """ q_circuit = QuantumCircuit.from_qasm_file(self.qasm_file_path) qr_a = QuantumRegister(4, "a") qr_b = QuantumRegister(4, "b") cr_c = ClassicalRegister(4, "c") cr_d = ClassicalRegister(4, "d") q_circuit_2 = QuantumCircuit(qr_a, qr_b, cr_c, cr_d) q_circuit_2.h(qr_a) q_circuit_2.cx(qr_a, qr_b) q_circuit_2.barrier(qr_a) q_circuit_2.barrier(qr_b) q_circuit_2.measure(qr_a, cr_c) q_circuit_2.measure(qr_b, cr_d) self.assertEqual(q_circuit, q_circuit_2) def test_loading_all_qelib1_gates(self): """Test setting up a circuit with all gates defined in qiskit/qasm/libs/qelib1.inc.""" from qiskit.circuit.library import U1Gate, U2Gate, U3Gate, CU1Gate, CU3Gate, UGate all_gates_qasm = os.path.join(self.qasm_dir, "all_gates.qasm") qasm_circuit = QuantumCircuit.from_qasm_file(all_gates_qasm) ref_circuit = QuantumCircuit(3, 3) # abstract gates (legacy) ref_circuit.append(UGate(0.2, 0.1, 0.6), [0]) ref_circuit.cx(0, 1) # the hardware primitives ref_circuit.append(U3Gate(0.2, 0.1, 0.6), [0]) ref_circuit.append(U2Gate(0.1, 0.6), [0]) ref_circuit.append(U1Gate(0.6), [0]) ref_circuit.id(0) ref_circuit.cx(0, 1) # the standard single qubit gates ref_circuit.u(0.2, 0.1, 0.6, 0) ref_circuit.p(0.6, 0) ref_circuit.x(0) ref_circuit.y(0) ref_circuit.z(0) ref_circuit.h(0) ref_circuit.s(0) ref_circuit.t(0) ref_circuit.sdg(0) ref_circuit.tdg(0) ref_circuit.sx(0) ref_circuit.sxdg(0) # the standard rotations ref_circuit.rx(0.1, 0) ref_circuit.ry(0.1, 0) ref_circuit.rz(0.1, 0) # the barrier ref_circuit.barrier() # the standard user-defined gates ref_circuit.swap(0, 1) ref_circuit.cswap(0, 1, 2) ref_circuit.cy(0, 1) ref_circuit.cz(0, 1) ref_circuit.ch(0, 1) ref_circuit.csx(0, 1) ref_circuit.append(CU1Gate(0.6), [0, 1]) ref_circuit.append(CU3Gate(0.2, 0.1, 0.6), [0, 1]) ref_circuit.cp(0.6, 0, 1) ref_circuit.cu(0.2, 0.1, 0.6, 0, 0, 1) ref_circuit.ccx(0, 1, 2) ref_circuit.crx(0.6, 0, 1) ref_circuit.cry(0.6, 0, 1) ref_circuit.crz(0.6, 0, 1) ref_circuit.rxx(0.2, 0, 1) ref_circuit.rzz(0.2, 0, 1) ref_circuit.measure([0, 1, 2], [0, 1, 2]) self.assertEqual(qasm_circuit, ref_circuit) def test_fail_qasm_file(self): """ Test fail_qasm_file. If all is correct we should get a QiskitError """ self.assertRaises(QiskitError, QuantumCircuit.from_qasm_file, "") def test_qasm_text(self): """ Test qasm_text and get_circuit. If all is correct we should get the qasm file loaded from the string """ qasm_string = "// A simple 8 qubit example\nOPENQASM 2.0;\n" qasm_string += 'include "qelib1.inc";\nqreg a[4];\n' qasm_string += "qreg b[4];\ncreg c[4];\ncreg d[4];\nh a;\ncx a, b;\n" qasm_string += "barrier a;\nbarrier b;\nmeasure a[0]->c[0];\n" qasm_string += "measure a[1]->c[1];\nmeasure a[2]->c[2];\n" qasm_string += "measure a[3]->c[3];\nmeasure b[0]->d[0];\n" qasm_string += "measure b[1]->d[1];\nmeasure b[2]->d[2];\n" qasm_string += "measure b[3]->d[3];" q_circuit = QuantumCircuit.from_qasm_str(qasm_string) qr_a = QuantumRegister(4, "a") qr_b = QuantumRegister(4, "b") cr_c = ClassicalRegister(4, "c") cr_d = ClassicalRegister(4, "d") ref = QuantumCircuit(qr_a, qr_b, cr_c, cr_d) ref.h(qr_a[3]) ref.cx(qr_a[3], qr_b[3]) ref.h(qr_a[2]) ref.cx(qr_a[2], qr_b[2]) ref.h(qr_a[1]) ref.cx(qr_a[1], qr_b[1]) ref.h(qr_a[0]) ref.cx(qr_a[0], qr_b[0]) ref.barrier(qr_b) ref.measure(qr_b, cr_d) ref.barrier(qr_a) ref.measure(qr_a, cr_c) self.assertEqual(len(q_circuit.cregs), 2) self.assertEqual(len(q_circuit.qregs), 2) self.assertEqual(q_circuit, ref) def test_qasm_text_conditional(self): """ Test qasm_text and get_circuit when conditionals are present. """ qasm_string = ( "\n".join( [ "OPENQASM 2.0;", 'include "qelib1.inc";', "qreg q[1];", "creg c0[4];", "creg c1[4];", "x q[0];", "if(c1==4) x q[0];", ] ) + "\n" ) q_circuit = QuantumCircuit.from_qasm_str(qasm_string) qr = QuantumRegister(1, "q") cr0 = ClassicalRegister(4, "c0") cr1 = ClassicalRegister(4, "c1") ref = QuantumCircuit(qr, cr0, cr1) ref.x(qr[0]) ref.x(qr[0]).c_if(cr1, 4) self.assertEqual(len(q_circuit.cregs), 2) self.assertEqual(len(q_circuit.qregs), 1) self.assertEqual(q_circuit, ref) def test_opaque_gate(self): """ Test parse an opaque gate See https://github.com/Qiskit/qiskit-terra/issues/1566. """ qasm_string = ( "\n".join( [ "OPENQASM 2.0;", 'include "qelib1.inc";', "opaque my_gate(theta,phi,lambda) a,b;", "qreg q[3];", "my_gate(1,2,3) q[1],q[2];", ] ) + "\n" ) circuit = QuantumCircuit.from_qasm_str(qasm_string) qr = QuantumRegister(3, "q") expected = QuantumCircuit(qr) expected.append(Gate(name="my_gate", num_qubits=2, params=[1, 2, 3]), [qr[1], qr[2]]) self.assertEqual(circuit, expected) def test_qasm_example_file(self): """Loads qasm/example.qasm.""" qasm_filename = os.path.join(self.qasm_dir, "example.qasm") expected_circuit = QuantumCircuit.from_qasm_str( "\n".join( [ "OPENQASM 2.0;", 'include "qelib1.inc";', "qreg q[3];", "qreg r[3];", "creg c[3];", "creg d[3];", "h q[2];", "cx q[2],r[2];", "measure r[2] -> d[2];", "h q[1];", "cx q[1],r[1];", "measure r[1] -> d[1];", "h q[0];", "cx q[0],r[0];", "measure r[0] -> d[0];", "barrier q[0],q[1],q[2];", "measure q[2] -> c[2];", "measure q[1] -> c[1];", "measure q[0] -> c[0];", ] ) + "\n" ) q_circuit = QuantumCircuit.from_qasm_file(qasm_filename) self.assertEqual(q_circuit, expected_circuit) self.assertEqual(len(q_circuit.cregs), 2) self.assertEqual(len(q_circuit.qregs), 2) def test_qasm_qas_string_order(self): """Test that gates are returned in qasm in ascending order.""" expected_qasm = ( "\n".join( [ "OPENQASM 2.0;", 'include "qelib1.inc";', "qreg q[3];", "h q[0];", "h q[1];", "h q[2];", ] ) + "\n" ) qasm_string = """OPENQASM 2.0; include "qelib1.inc"; qreg q[3]; h q;""" q_circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual(q_circuit.qasm(), expected_qasm) def test_from_qasm_str_custom_gate1(self): """Test load custom gates (simple case)""" qasm_string = """OPENQASM 2.0; include "qelib1.inc"; gate rinv q {sdg q; h q; sdg q; h q; } qreg qr[1]; rinv qr[0];""" circuit = QuantumCircuit.from_qasm_str(qasm_string) rinv_q = QuantumRegister(1, name="q") rinv_gate = QuantumCircuit(rinv_q, name="rinv") rinv_gate.sdg(rinv_q) rinv_gate.h(rinv_q) rinv_gate.sdg(rinv_q) rinv_gate.h(rinv_q) rinv = rinv_gate.to_instruction() qr = QuantumRegister(1, name="qr") expected = QuantumCircuit(qr, name="circuit") expected.append(rinv, [qr[0]]) self.assertEqualUnroll(["sdg", "h"], circuit, expected) def test_from_qasm_str_custom_gate2(self): """Test load custom gates (no so simple case, different bit order) See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-551307250 """ qasm_string = """OPENQASM 2.0; include "qelib1.inc"; gate swap2 a,b { cx a,b; cx b,a; // different bit order cx a,b; } qreg qr[3]; swap2 qr[0], qr[1]; swap2 qr[1], qr[2];""" circuit = QuantumCircuit.from_qasm_str(qasm_string) ab_args = QuantumRegister(2, name="ab") swap_gate = QuantumCircuit(ab_args, name="swap2") swap_gate.cx(ab_args[0], ab_args[1]) swap_gate.cx(ab_args[1], ab_args[0]) swap_gate.cx(ab_args[0], ab_args[1]) swap = swap_gate.to_instruction() qr = QuantumRegister(3, name="qr") expected = QuantumCircuit(qr, name="circuit") expected.append(swap, [qr[0], qr[1]]) expected.append(swap, [qr[1], qr[2]]) self.assertEqualUnroll(["cx"], expected, circuit) def test_from_qasm_str_custom_gate3(self): """Test load custom gates (no so simple case, different bit count) See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-551307250 """ qasm_string = """OPENQASM 2.0; include "qelib1.inc"; gate cswap2 a,b,c { cx c,b; // different bit count ccx a,b,c; //previously defined gate cx c,b; } qreg qr[3]; cswap2 qr[1], qr[0], qr[2];""" circuit = QuantumCircuit.from_qasm_str(qasm_string) abc_args = QuantumRegister(3, name="abc") cswap_gate = QuantumCircuit(abc_args, name="cswap2") cswap_gate.cx(abc_args[2], abc_args[1]) cswap_gate.ccx(abc_args[0], abc_args[1], abc_args[2]) cswap_gate.cx(abc_args[2], abc_args[1]) cswap = cswap_gate.to_instruction() qr = QuantumRegister(3, name="qr") expected = QuantumCircuit(qr, name="circuit") expected.append(cswap, [qr[1], qr[0], qr[2]]) self.assertEqualUnroll(["cx", "h", "tdg", "t"], circuit, expected) def test_from_qasm_str_custom_gate4(self): """Test load custom gates (parameterized) See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-551307250 """ qasm_string = """OPENQASM 2.0; include "qelib1.inc"; gate my_gate(phi,lambda) q {u(1.5707963267948966,phi,lambda) q;} qreg qr[1]; my_gate(pi, pi) qr[0];""" circuit = QuantumCircuit.from_qasm_str(qasm_string) my_gate_circuit = QuantumCircuit(1, name="my_gate") phi = Parameter("phi") lam = Parameter("lambda") my_gate_circuit.u(1.5707963267948966, phi, lam, 0) my_gate = my_gate_circuit.to_gate() qr = QuantumRegister(1, name="qr") expected = QuantumCircuit(qr, name="circuit") expected.append(my_gate, [qr[0]]) expected = expected.bind_parameters({phi: 3.141592653589793, lam: 3.141592653589793}) self.assertEqualUnroll("u", circuit, expected) def test_from_qasm_str_custom_gate5(self): """Test load custom gates (parameterized, with biop and constant) See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-551307250 """ qasm_string = """OPENQASM 2.0; include "qelib1.inc"; gate my_gate(phi,lambda) q {u(pi/2,phi,lambda) q;} // biop with pi qreg qr[1]; my_gate(pi, pi) qr[0];""" circuit = QuantumCircuit.from_qasm_str(qasm_string) my_gate_circuit = QuantumCircuit(1, name="my_gate") phi = Parameter("phi") lam = Parameter("lambda") my_gate_circuit.u(1.5707963267948966, phi, lam, 0) my_gate = my_gate_circuit.to_gate() qr = QuantumRegister(1, name="qr") expected = QuantumCircuit(qr, name="circuit") expected.append(my_gate, [qr[0]]) expected = expected.bind_parameters({phi: 3.141592653589793, lam: 3.141592653589793}) self.assertEqualUnroll("u", circuit, expected) def test_from_qasm_str_custom_gate6(self): """Test load custom gates (parameters used in expressions) See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-591668924 """ qasm_string = """OPENQASM 2.0; include "qelib1.inc"; gate my_gate(phi,lambda) q {rx(phi+pi) q; ry(lambda/2) q;} // parameters used in expressions qreg qr[1]; my_gate(pi, pi) qr[0];""" circuit = QuantumCircuit.from_qasm_str(qasm_string) my_gate_circuit = QuantumCircuit(1, name="my_gate") phi = Parameter("phi") lam = Parameter("lambda") my_gate_circuit.rx(phi + 3.141592653589793, 0) my_gate_circuit.ry(lam / 2, 0) my_gate = my_gate_circuit.to_gate() qr = QuantumRegister(1, name="qr") expected = QuantumCircuit(qr, name="circuit") expected.append(my_gate, [qr[0]]) expected = expected.bind_parameters({phi: 3.141592653589793, lam: 3.141592653589793}) self.assertEqualUnroll(["rx", "ry"], circuit, expected) def test_from_qasm_str_custom_gate7(self): """Test load custom gates (build in functions) See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-592208951 """ qasm_string = """OPENQASM 2.0; include "qelib1.inc"; gate my_gate(phi,lambda) q {u(asin(cos(phi)/2), phi+pi, lambda/2) q;} // build func qreg qr[1]; my_gate(pi, pi) qr[0];""" circuit = QuantumCircuit.from_qasm_str(qasm_string) qr = QuantumRegister(1, name="qr") expected = QuantumCircuit(qr, name="circuit") expected.u(-0.5235987755982988, 6.283185307179586, 1.5707963267948966, qr[0]) self.assertEqualUnroll("u", circuit, expected) def test_from_qasm_str_nested_custom_gate(self): """Test chain of custom gates See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-592261942 """ qasm_string = """OPENQASM 2.0; include "qelib1.inc"; gate my_other_gate(phi,lambda) q {u(asin(cos(phi)/2), phi+pi, lambda/2) q;} gate my_gate(phi) r {my_other_gate(phi, phi+pi) r;} qreg qr[1]; my_gate(pi) qr[0];""" circuit = QuantumCircuit.from_qasm_str(qasm_string) qr = QuantumRegister(1, name="qr") expected = QuantumCircuit(qr, name="circuit") expected.u(-0.5235987755982988, 6.283185307179586, 3.141592653589793, qr[0]) self.assertEqualUnroll("u", circuit, expected) def test_from_qasm_str_delay(self): """Test delay instruction/opaque-gate See: https://github.com/Qiskit/qiskit-terra/issues/6510 """ qasm_string = """OPENQASM 2.0; include "qelib1.inc"; opaque delay(time) q; qreg q[1]; delay(172) q[0];""" circuit = QuantumCircuit.from_qasm_str(qasm_string) qr = QuantumRegister(1, name="q") expected = QuantumCircuit(qr, name="circuit") expected.delay(172, qr[0]) self.assertEqualUnroll("u", circuit, expected) def test_definition_with_u_cx(self): """Test that gate-definition bodies can use U and CX.""" qasm_string = """ OPENQASM 2.0; gate bell q0, q1 { U(pi/2, 0, pi) q0; CX q0, q1; } qreg q[2]; bell q[0], q[1]; """ circuit = QuantumCircuit.from_qasm_str(qasm_string) qr = QuantumRegister(2, "q") expected = QuantumCircuit(qr) expected.h(0) expected.cx(0, 1) self.assertEqualUnroll(["u", "cx"], circuit, expected) def assertEqualUnroll(self, basis, circuit, expected): """Compares the dags after unrolling to basis""" circuit_dag = circuit_to_dag(circuit) expected_dag = circuit_to_dag(expected) circuit_result = Unroller(basis).run(circuit_dag) expected_result = Unroller(basis).run(expected_dag) self.assertEqual(circuit_result, expected_result)
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# External imports from pylab import cm from sklearn import metrics import numpy as np import matplotlib.pyplot as plt # Qiskit imports from qiskit import QuantumCircuit from qiskit.circuit import ParameterVector from qiskit.visualization import circuit_drawer from qiskit.algorithms.optimizers import SPSA from qiskit.circuit.library import ZZFeatureMap from qiskit_machine_learning.kernels import TrainableFidelityQuantumKernel from qiskit_machine_learning.kernels.algorithms import QuantumKernelTrainer from qiskit_machine_learning.algorithms import QSVC from qiskit_machine_learning.datasets import ad_hoc_data class QKTCallback: """Callback wrapper class.""" def __init__(self) -> None: self._data = [[] for i in range(5)] def callback(self, x0, x1=None, x2=None, x3=None, x4=None): """ Args: x0: number of function evaluations x1: the parameters x2: the function value x3: the stepsize x4: whether the step was accepted """ self._data[0].append(x0) self._data[1].append(x1) self._data[2].append(x2) self._data[3].append(x3) self._data[4].append(x4) def get_callback_data(self): return self._data def clear_callback_data(self): self._data = [[] for i in range(5)] adhoc_dimension = 2 X_train, y_train, X_test, y_test, adhoc_total = ad_hoc_data( training_size=20, test_size=5, n=adhoc_dimension, gap=0.3, plot_data=False, one_hot=False, include_sample_total=True, ) plt.figure(figsize=(5, 5)) plt.ylim(0, 2 * np.pi) plt.xlim(0, 2 * np.pi) plt.imshow( np.asmatrix(adhoc_total).T, interpolation="nearest", origin="lower", cmap="RdBu", extent=[0, 2 * np.pi, 0, 2 * np.pi], ) plt.scatter( X_train[np.where(y_train[:] == 0), 0], X_train[np.where(y_train[:] == 0), 1], marker="s", facecolors="w", edgecolors="b", label="A train", ) plt.scatter( X_train[np.where(y_train[:] == 1), 0], X_train[np.where(y_train[:] == 1), 1], marker="o", facecolors="w", edgecolors="r", label="B train", ) plt.scatter( X_test[np.where(y_test[:] == 0), 0], X_test[np.where(y_test[:] == 0), 1], marker="s", facecolors="b", edgecolors="w", label="A test", ) plt.scatter( X_test[np.where(y_test[:] == 1), 0], X_test[np.where(y_test[:] == 1), 1], marker="o", facecolors="r", edgecolors="w", label="B test", ) plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0) plt.title("Ad hoc dataset for classification") plt.show() # Create a rotational layer to train. We will rotate each qubit the same amount. training_params = ParameterVector("θ", 1) fm0 = QuantumCircuit(2) fm0.ry(training_params[0], 0) fm0.ry(training_params[0], 1) # Use ZZFeatureMap to represent input data fm1 = ZZFeatureMap(2) # Create the feature map, composed of our two circuits fm = fm0.compose(fm1) print(circuit_drawer(fm)) print(f"Trainable parameters: {training_params}") # Instantiate quantum kernel quant_kernel = TrainableFidelityQuantumKernel(feature_map=fm, training_parameters=training_params) # Set up the optimizer cb_qkt = QKTCallback() spsa_opt = SPSA(maxiter=10, callback=cb_qkt.callback, learning_rate=0.05, perturbation=0.05) # Instantiate a quantum kernel trainer. qkt = QuantumKernelTrainer( quantum_kernel=quant_kernel, loss="svc_loss", optimizer=spsa_opt, initial_point=[np.pi / 2] ) # Train the kernel using QKT directly qka_results = qkt.fit(X_train, y_train) optimized_kernel = qka_results.quantum_kernel print(qka_results) # Use QSVC for classification qsvc = QSVC(quantum_kernel=optimized_kernel) # Fit the QSVC qsvc.fit(X_train, y_train) # Predict the labels labels_test = qsvc.predict(X_test) # Evalaute the test accuracy accuracy_test = metrics.balanced_accuracy_score(y_true=y_test, y_pred=labels_test) print(f"accuracy test: {accuracy_test}") plot_data = cb_qkt.get_callback_data() # callback data K = optimized_kernel.evaluate(X_train) # kernel matrix evaluated on the training samples plt.rcParams["font.size"] = 20 fig, ax = plt.subplots(1, 2, figsize=(14, 5)) ax[0].plot([i + 1 for i in range(len(plot_data[0]))], np.array(plot_data[2]), c="k", marker="o") ax[0].set_xlabel("Iterations") ax[0].set_ylabel("Loss") ax[1].imshow(K, cmap=cm.get_cmap("bwr", 20)) fig.tight_layout() plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/JohnBurke4/qaoa_testing_framework
JohnBurke4
from Image_Reader import ImageReader from DCT_Classic import DCT import Quantum_Subroutines import os import Image_Compression import cv2 import matplotlib.pyplot as plt import numpy as np from qiskit import QuantumCircuit, Aer, transpile from qiskit_aer.backends.aerbackend import AerBackend from qiskit.providers.fake_provider import FakeSydneyV2 from qiskit_aer import AerSimulator from qiskit.quantum_info import random_statevector import csv from CustomStatePrep import StatePreparation qc = QuantumCircuit(4) state = np.random.randint(-100, 100, size=16) state = state / np.linalg.norm(state) state = [ -0.28672064, 0.09159132, -0.33052518, 0.29866733, -0.39025865, -0.21504048, -0.09557355, 0.07566239, 0.03982231, 0.23495164, 0.10353801, -0.37432972, 0.37432972, -0.02787562, -0.28273841, -0.26282725, ] # state = [1] * 16 # state[0] = -1 # state[1] = 0 # # state[4] = 1 # # state[5] = 1 # # state[9] = 0 # # state[14] = -1 # state[14] = -1 # state[15] = -1 print(np.array(state).reshape(4, 4)) basis = ["cx", "ry", "x", "rz"] statePrepCircuit = StatePreparation(state, normalize=True) qc.append(statePrepCircuit, range(0, 4)) print(qc.decompose(reps=3)) sim = Aer.get_backend("aer_simulator") circ = transpile(qc, sim, basis_gates=basis) depth = circ.depth() gates = sum(dict(circ.count_ops()).values()) circ.save_statevector() result = sim.run(circ).result() out_vector = result.get_statevector().data print(out_vector)
https://github.com/abbarreto/qiskit3
abbarreto
0.4*7.6
https://github.com/epelaaez/QuantumLibrary
epelaaez
def dswap_test_circuit(qc1: QuantumCircuit, qc2: QuantumCircuit) -> QuantumCircuit: """ Construct the destructive SWAP test circuit given two circuits. Args: qc1(qiskit.QuantumCircuit): Quantum circuit for the first state. qc2(qiskit.QuantumCircuit): Quantum circuit for the second state. Output: (qiskit.QuantumCircuit): swap test circuit. """ # Helper variables n_total = qc1.num_qubits + qc2.num_qubits range_qc1 = [i for i in range(qc1.num_qubits)] range_qc2 = [i + qc1.num_qubits for i in range(qc2.num_qubits)] # Constructing the SWAP test circuit qc_swap = QuantumCircuit(n_total , n_total) qc_swap.append(qc1, range_qc1) qc_swap.append(qc2, range_qc2) for index, qubit in enumerate(range_qc1): qc_swap.cx(qubit, range_qc2[index]) qc_swap.h(qubit) for index, qubit in enumerate(range_qc1): qc_swap.measure(qubit, 2*index) for index, qubit in enumerate(range_qc2): qc_swap.measure(range_qc2[index] , 2*index + 1) return qc_swap import textwrap import qiskit from qiskit import QuantumCircuit, execute from typing import Union from qiskit.aqua import QuantumInstance from qiskit.providers import BaseBackend def measure_dswap_test(qc1: QuantumCircuit, qc2: QuantumCircuit, backend: Union[BaseBackend,QuantumInstance], num_shots: int=10000) -> float: """Returns the fidelity from a destructive SWAP test. Args: qc1 (QuantumCircuit): Quantum Circuit for the first state. qc2 (QuantumCircuit): Quantum Circuit for the second state. backend (Union[BaseBackend,QuantumInstance]): Backend. num_shots (int, optional): Number of shots. Defaults to 10000. Returns: float: result of the overlap betweeen the first and second state. """ n = qc1.num_qubits swap_circuit = dswap_test_circuit(qc1, qc2) # Check if the backend is a quantum instance. if qiskit.aqua.quantum_instance.QuantumInstance == type(backend): count = backend.execute(swap_circuit).get_counts() else: count = execute(swap_circuit, backend=backend, shots=num_shots).result().get_counts() result = 0 for meas, counts in count.items(): split_meas = textwrap.wrap(meas, 2) for m in split_meas: if m == '11': result -= counts else: result += counts total = sum(count.values()) return result/(n*total) from qiskit import QuantumCircuit, execute qc1 = QuantumCircuit(n) qc2 = QuantumCircuit(n) backend = BasicAer.get_backend('qasm_simulator') measure_dswap_test(qc1, qc2, backend) from qiskit import BasicAer backend = BasicAer.get_backend('qasm_simulator') num_shots = 10000 count = execute(swap_circuit, backend=backend, shots=num_shots).result().get_counts() import textwrap result = 0 for meas, counts in count.items(): split_meas = textwrap.wrap(meas, 2) for m in split_meas: if m == '11': result -= counts else: result += counts total = sum(count.values()) result/(n*total)
https://github.com/abbarreto/qiskit4
abbarreto
hub=qc-spring-22-2, group=group-5 and project=recPrYILNAOsYMWIV
https://github.com/arnavdas88/QuGlassyIsing
arnavdas88
!pip install qiskit J = 4.0 B_x = 2.0 B_z = 0.0 import numpy as np from qiskit.providers.aer import AerSimulator, QasmSimulator from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit.aqua.operators import * from qiskit.aqua import set_qiskit_aqua_logging, QuantumInstance from qiskit.aqua.algorithms import NumPyMinimumEigensolver, VQE, NumPyEigensolver from qiskit.circuit import QuantumCircuit, ParameterVector from qiskit.visualization import plot_histogram Hamiltonian = J * (Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z) - B_z * (( Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ) ) - B_x * ( ( X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X )) ansatz = TwoLocal(num_qubits=36, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True) print(ansatz) backend = AerSimulator(method='matrix_product_state') quantum_instance = QuantumInstance(backend, shots = 8192, initial_layout = None, optimization_level = 3) optimizer = COBYLA(maxiter=10000, tol=0.000000001) vqe = VQE(Hamiltonian, ansatz, optimizer, include_custom = False) print('We are using:', quantum_instance.backend) vqe_result = vqe.run(quantum_instance) print(vqe['result']) plot_histogram(vqe_result['eigenstate']) import pickle filename = "2D_Ising_Model_CountsDIS1.pkl" a = {'vqe_result': vqe_result} #This saves the data with open(filename, 'wb') as handle: pickle.dump(a, handle, protocol=pickle.HIGHEST_PROTOCOL) # This loads the data with open(filename, 'rb') as handle: b = pickle.load(handle)
https://github.com/BoschSamuel/QizGloria
BoschSamuel
# -- coding: utf-8 -- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import torch from torch.autograd import Function import torch.optim as optim from qiskit import QuantumRegister,QuantumCircuit,ClassicalRegister,execute from qiskit.circuit import Parameter from qiskit import Aer import numpy as np from tqdm import tqdm from matplotlib import pyplot as plt %matplotlib inline np.random.seed = 42 def to_numbers(tensor_list): num_list = [] for tensor in tensor_list: num_list += [tensor.item()] return num_list class QiskitCircuit(): def __init__(self,shots): self.theta = Parameter('Theta') self.phi = Parameter('Phi') self.lam = Parameter('Lambda') self.theta2 = Parameter('Theta2') self.phi2 = Parameter('Phi2') self.lam2 = Parameter('Lambda2') self.shots = shots def create_circuit(): qr = QuantumRegister(2,'q') cr = ClassicalRegister(2,'c') ckt = QuantumCircuit(qr,cr) ckt.h(qr[0]) ckt.h(qr[1]) ckt.cx(0,1) ckt.barrier() ckt.u3(self.theta,self.phi,self.lam,qr[0]) ckt.u3(self.theta2,self.phi2,self.lam2,qr[1]) ckt.barrier() ckt.cx(1,0) ckt.measure(qr,cr) return ckt self.circuit = create_circuit() def N_qubit_expectation_Z(self,counts, shots, nr_qubits): expects = 0 for key in counts.keys(): perc = counts[key]/shots #check = np.array([(float(key[i])-1/2)*2*perc for i in range(nr_qubits)]) check = (float(key[0])-1/2)*2*(float(key[1])-1/2)*2*perc expects += check return [expects] def bind(self, parameters): #print(to_numbers(parameters)) [self.theta,self.phi,self.lam] = to_numbers(parameters)[0:3] [self.theta2,self.phi2,self.lam2] = to_numbers(parameters)[3:6] self.circuit.data[4][0]._params = to_numbers(parameters)[0:3] self.circuit.data[5][0]._params = to_numbers(parameters)[3:6] def run(self, i): self.bind(i) backend = Aer.get_backend('qasm_simulator') job_sim = execute(self.circuit,backend,shots=self.shots) result_sim = job_sim.result() counts = result_sim.get_counts(self.circuit) return self.N_qubit_expectation_Z(counts,self.shots,2) class TorchCircuit(Function): @staticmethod def forward(ctx, i): if not hasattr(ctx, 'QiskitCirc'): ctx.QiskitCirc = QiskitCircuit(shots=10000) exp_value = ctx.QiskitCirc.run(i[0]) result = torch.tensor([exp_value]) ctx.save_for_backward(result, i) #print(result) return result @staticmethod def backward(ctx, grad_output): eps = 0.01 forward_tensor, i = ctx.saved_tensors input_numbers = to_numbers(i[0]) gradient = [] for k in range(len(input_numbers)): input_eps = input_numbers input_eps[k] = input_numbers[k] + eps exp_value = ctx.QiskitCirc.run(torch.tensor(input_eps))[0] result_eps = torch.tensor([exp_value]) gradient_result = (exp_value - forward_tensor[0][0].item())/eps gradient.append(gradient_result) # print(gradient) result = torch.tensor([gradient]) # print(result) #print("test tens size", result.float(), grad_output.float()) return result.float() * grad_output.float() torch.manual_seed(42) # x = torch.tensor([np.pi/4, np.pi/4, np.pi/4], requires_grad=True) x = torch.tensor([[0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], requires_grad=True) qc = TorchCircuit.apply y1 = qc(x) print(y1) y1.backward() print(x.grad) qc = TorchCircuit.apply def cost(x): target = -1 expval = qc(x) return torch.abs(qc(x).sum() - target) ** 2, expval x = torch.tensor([[np.pi/4, np.pi/4, np.pi/4, np.pi/4, np.pi/4, np.pi/4]], requires_grad=True) opt = torch.optim.Adam([x], lr=0.1) num_epoch = 100 loss_list = [] expval_list = [] for i in tqdm(range(num_epoch)): # for i in range(num_epoch): opt.zero_grad() loss, expval = cost(x) loss.backward() opt.step() loss_list.append(loss.item()) expval_list.append(expval.item()) # print(loss.item()) plt.plot(loss_list) # print(circuit(phi, theta)) # print(cost(x)) import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np import torchvision from torchvision import datasets, transforms batch_size_train = 1 batch_size_test = 1 learning_rate = 0.01 momentum = 0.5 log_interval = 10 torch.backends.cudnn.enabled = False transform=torchvision.transforms.Compose([ torchvision.transforms.ToTensor()]) mnist_trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transform) labels = mnist_trainset.targets #get labels labels = labels.numpy() idx1 = np.where(labels == 0) #search all zeros idx2 = np.where(labels == 1) # search all ones idx = np.concatenate((idx1[0][0:10],idx2[0][0:10])) # concatenate their indices #idx = idx2 mnist_trainset.targets = labels[idx] mnist_trainset.data = mnist_trainset.data[idx] print(mnist_trainset) train_loader = torch.utils.data.DataLoader(mnist_trainset, batch_size=batch_size_train, shuffle=True) class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 10, kernel_size=5) self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.conv2_drop = nn.Dropout2d() self.fc1 = nn.Linear(320, 50) self.fc2 = nn.Linear(50, 6) def forward(self, x): x = F.relu(F.max_pool2d(self.conv1(x), 2)) x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2)) x = x.view(-1, 320) x = F.relu(self.fc1(x)) x = F.dropout(x, training=self.training) x = self.fc2(x) #x = np.pi*F.tanh(x) #print(x) x = qc(x) # print(x) x = (x+1)/4 x = torch.cat((x, 1-x), -1) return x # return F.softmax(x) network = Net() optimizer = optim.SGD(network.parameters(), lr=learning_rate, momentum=momentum) epochs = 100 for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): # print(batch_idx) optimizer.zero_grad() output = network(data) print(output[0].data, target) loss = F.nll_loss(output, target) # print(output) # print(output[0][1].item(), target.item()) #print(loss) loss.backward() optimizer.step() total_loss.append(loss.item()) print(sum(total_loss)/len(total_loss))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeAuckland backend = FakeAuckland() ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) depths = [] gate_counts = [] non_local_gate_counts = [] levels = [str(x) for x in range(4)] for level in range(4): circ = transpile(ghz, backend, optimization_level=level) depths.append(circ.depth()) gate_counts.append(sum(circ.count_ops().values())) non_local_gate_counts.append(circ.num_nonlocal_gates()) fig, (ax1, ax2) = plt.subplots(2, 1) ax1.bar(levels, depths, label='Depth') ax1.set_xlabel("Optimization Level") ax1.set_ylabel("Depth") ax1.set_title("Output Circuit Depth") ax2.bar(levels, gate_counts, label='Number of Circuit Operations') ax2.bar(levels, non_local_gate_counts, label='Number of non-local gates') ax2.set_xlabel("Optimization Level") ax2.set_ylabel("Number of gates") ax2.legend() ax2.set_title("Number of output circuit gates") fig.tight_layout() plt.show()
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
import unittest import cirq from cirq.ops import H, X, I import random import matplotlib.pyplot as plt import numpy as np from numpy.random import randint import hypothesis.strategies as st from hypothesis import given, settings def generate_binary(len): return randint(2, size=len) def encode_message(bits, bases, messageLen): message = [] for i in range(messageLen): qubits = cirq.LineQubit.range(1) qc = cirq.Circuit() if bases[i] == 0: # Prepare qubit in Z-basis if bits[i] == 0: qc.append(cirq.I(qubits[0])) else: qc.append(cirq.X(qubits[0])) else: # Prepare qubit in X-basis if bits[i] == 0: qc.append(cirq.H(qubits[0])) else: qc.append(cirq.X(qubits[0])) qc.append(cirq.H(qubits[0])) message.append(qc) return message def measure_message(message, bases, messageLen): measurements = [] for q in range(messageLen): if bases[q] == 0: # measuring in Z-basis if (not message[q].has_measurements()): for qubit in message[q].all_qubits(): message[q].append(cirq.measure(qubit)) if bases[q] == 1: # measuring in X-basis if (not message[q].has_measurements()): for qubit in message[q].all_qubits(): message[q].append(cirq.H(qubit)) message[q].append(cirq.measure(qubit)) simulator = cirq.Simulator() measured_bit = simulator.run(message[q]) measurements.append((measured_bit.data.iat[0,0])) return measurements def remove_garbage(a_bases, b_bases, bits, messageLen): good_bits = [] for q in range(messageLen): if a_bases[q] == b_bases[q]: # If both used the same basis, add # this to the list of 'good' bits good_bits.append(bits[q]) return good_bits def sample_bits(bits, selection): sample = [] for i in selection: # use np.mod to make sure the # bit we sample is always in # the list range i = np.mod(i, len(bits)) # pop(i) removes the element of the # list at index 'i' sample.append(bits.pop(i)) return sample np.random.seed(seed=0) messageLen = 100 ## Step 1 # Alice generates bits alice_bits = generate_binary(messageLen) ## Step 2 # Create an array to tell us which qubits # are encoded in which bases alice_bases = generate_binary(messageLen) message = encode_message(alice_bits, alice_bases, messageLen) ## Step 3 # Decide which basis to measure in: bob_bases = generate_binary(messageLen) bob_results = measure_message(message, bob_bases, messageLen) ## Step 4 alice_key = remove_garbage(alice_bases, bob_bases, alice_bits, messageLen) bob_key = remove_garbage(alice_bases, bob_bases, bob_results, messageLen) ## Step 5 sample_size = 15 bit_selection = generate_binary(sample_size) bob_sample = sample_bits(bob_key, bit_selection) print(" bob_sample = " + str(bob_sample)) alice_sample = sample_bits(alice_key, bit_selection) print("alice_sample = "+ str(alice_sample)) bob_sample == alice_sample n = 100 # Step 1 alice_bits = generate_binary(messageLen) alice_bases = generate_binary(messageLen) # Step 2 message = encode_message(alice_bits, alice_bases, messageLen) # Interception! eve_bases = generate_binary(messageLen) intercepted_message = measure_message(message, eve_bases, messageLen) # Step 3 bob_bases = generate_binary(messageLen) bob_results = measure_message(message, bob_bases, messageLen) # Step 4 bob_key = remove_garbage(alice_bases, bob_bases, bob_results, messageLen) alice_key = remove_garbage(alice_bases, bob_bases, alice_bits, messageLen) # Step 5 sample_size = 15 # Change this to something lower and see if # Eve can intercept the message without Alice # and Bob finding out bit_selection = generate_binary(sample_size) bob_sample = sample_bits(bob_key, bit_selection) alice_sample = sample_bits(alice_key, bit_selection) if bob_sample != alice_sample: print("Eve's interference was detected.") else: print("Eve went undetected!") ########################################################################### ## Define composite strategies to generate lists of ints in equal length ## ########################################################################### @st.composite def single_list(draw): arrayLengths = draw(st.integers(min_value=1, max_value=100)) fixed_length_list = st.lists(st.integers(min_value=0, max_value=1), min_size=arrayLengths, max_size=arrayLengths) return (draw(fixed_length_list)) @st.composite def pair_of_lists(draw): arrayLengths = draw(st.integers(min_value=1, max_value=100)) fixed_length_list = st.lists(st.integers(min_value=0, max_value=1), min_size=arrayLengths, max_size=arrayLengths) return (draw(fixed_length_list), draw(fixed_length_list)) @st.composite def trio_of_lists(draw): arrayLengths = draw(st.integers(min_value=1, max_value=100)) fixed_length_list = st.lists(st.integers(min_value=0, max_value=1), min_size=arrayLengths, max_size=arrayLengths) return (draw(fixed_length_list), draw(fixed_length_list), draw(fixed_length_list)) @st.composite def long_trio_of_lists(draw): arrayLengths = draw(st.integers(min_value=100, max_value=110)) fixed_length_list = st.lists(st.integers(min_value=0, max_value=1), min_size=arrayLengths, max_size=arrayLengths) return (draw(fixed_length_list), draw(fixed_length_list), draw(fixed_length_list)) ########################## ## test generate binary ## ########################## @given(testLength = st.integers(min_value=0, max_value=10000)) def test_created_message_is_binary(testLength): binArr = generate_binary(testLength) for i in binArr: assert (i == 1 or i == 0) @given(testLength = st.integers(min_value=1, max_value=10000)) def test_created_message_equal_length_to_int_passed_in(testLength): binArr = generate_binary(testLength) assert(len(binArr) == testLength) ############################ ## encoding message tests ## ############################ @given(pair_of_lists()) @settings(deadline=None) def test_encode_message_equal_length_to_base(lists): alice_bits, alice_bases = lists circuitArr = encode_message(alice_bits, alice_bases, len(alice_bits)) assert(len(circuitArr) == len(alice_bits)) @given(pair_of_lists()) @settings(deadline=None) def test_encode_message_are_circuits(lists): alice_bits, alice_bases = lists circuitArr = encode_message(alice_bits, alice_bases, len(alice_bits)) for i in circuitArr: assert(isinstance(i, cirq.Circuit)) @given(pair_of_lists()) @settings(deadline=None) def test_encode_message_circuits_are_not_longer_than_2(lists): alice_bits, alice_bases = lists circuitArr = encode_message(alice_bits, alice_bases, len(alice_bits)) for i in circuitArr: assert(not(sum(1 for _ in i.all_operations()) > 2)) @given(pair_of_lists()) @settings(deadline=None) def test_encode_message_circuits_use_only_H_X_I(lists): alice_bits, alice_bases = lists circuitArr = encode_message(alice_bits, alice_bases, len(alice_bits)) for i in circuitArr: for gate in i.all_operations(): assert(isinstance(gate.gate, cirq.ops.identity.IdentityGate) or isinstance(gate.gate, cirq.ops.pauli_gates._PauliX) or isinstance(gate.gate, cirq.ops.common_gates.HPowGate)) ############################ ## decoding message tests ## ############################ @given(lists = trio_of_lists()) @settings(deadline=None) def test_decode_message_length_equals_base_length(lists): alice_bits, alice_bases, bob_base = lists encoded_message = encode_message(alice_bits, alice_bases, len(bob_base)) msmtArr = measure_message(encoded_message, bob_base, len(bob_base)) assert len(msmtArr) == len(bob_base) @given(lists = trio_of_lists()) @settings(deadline=None) def test_decode_message_is_binary(lists): alice_bits, alice_bases, bob_base = lists encoded_message = encode_message(alice_bits, alice_bases, len(bob_base)) msmtArr = measure_message(encoded_message, bob_base, len(bob_base)) for i in msmtArr: assert (i == 1 or i == 0) @given(lists = pair_of_lists()) @settings(deadline=None) def test_decode_with_same_base_returns_original_bits(lists): alice_bits, alice_bases = lists encoded_message = encode_message(alice_bits, alice_bases, len(alice_bits)) decodeWithSameBases = measure_message(encoded_message, alice_bases, len(alice_bases)) assert(np.array_equal(np.array(alice_bits), np.array(decodeWithSameBases))) @given(lists = pair_of_lists()) @settings(deadline=None) def test_decode_with_same_bases_return_same_array(lists): alice_bits, alice_bases = lists encoded_message = encode_message(alice_bits, alice_bases, len(alice_bits)) encoded_message2 = encode_message(alice_bits, alice_bases, len(alice_bits)) decodeWithSameBases = measure_message(encoded_message, alice_bases, len(alice_bases)) decodeWithSameBases2 = measure_message(encoded_message2, alice_bases, len(alice_bases)) assert(np.array_equal(np.array(decodeWithSameBases), np.array(decodeWithSameBases2))) @given(lists = long_trio_of_lists()) @settings(deadline=None) def test_decoding_runs_likely_different(lists): alice_bits, alice_bases, bob_base = lists encoded_message = encode_message(alice_bits, alice_bases, len(bob_base)) msmtArr = measure_message(encoded_message, alice_bases, len(alice_bases)) msmtArrRun2 = measure_message(encoded_message, bob_bases, len(bob_base)) assert(not np.array_equal(np.array(msmtArr), np.array(msmtArrRun2))) ############################## ## remove garbage/key tests ## ############################## @given(lists = trio_of_lists()) @settings(deadline=None) def test_key_smaller_or_equal_len_to_original_bits(lists): alice_bits, alice_bases, bob_base = lists assert len(remove_garbage(alice_bits, alice_bases, bob_base, len(bob_base))) <= len(bob_base) @given(lists = trio_of_lists()) @settings(deadline=None) def test_check_keys_equal(lists): alice_bits, alice_bases, bob_bases = lists message = encode_message(alice_bits, alice_bases, len(bob_bases)) bob_results = measure_message(message, bob_bases, len(bob_bases)) alice_key = remove_garbage(alice_bases, bob_bases, alice_bits, len(bob_bases)) bob_key = remove_garbage(alice_bases, bob_bases, bob_results, len(bob_bases)) assert(np.array_equal(np.array(alice_key), np.array(bob_key))) @given(lists = trio_of_lists()) @settings(deadline=None) def test_key_is_binary(lists): alice_bits, alice_bases, bob_bases = lists alice_key = remove_garbage(alice_bases, bob_bases, alice_bits, len(bob_bases)) for i in alice_key: assert (i == 1 or i == 0) if __name__ == "__main__": #test_created_message_is_binary() #test_created_message_equal_length_to_int_passed_in() #test_encode_message_equal_length_to_base() #test_encode_message_are_circuits() #test_encode_message_circuits_are_not_longer_than_2() #test_encode_message_circuits_use_only_H_X_I() #test_decode_message_length_equals_base_length() #test_decode_message_is_binary() #test_decode_with_same_base_returns_original_bits() #test_decode_with_same_bases_return_same_array() #test_decoding_runs_likely_different() #test_key_smaller_or_equal_len_to_original_bits() #test_check_keys_equal() #test_key_is_binary()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import transpile from qiskit import QuantumCircuit from qiskit.providers.fake_provider import FakeVigoV2 backend = FakeVigoV2() qc = QuantumCircuit(2, 1) qc.h(0) qc.x(1) qc.cp(np.pi/4, 0, 1) qc.h(0) qc.measure([0], [0]) qc_basis = transpile(qc, backend) qc_basis.draw(output='mpl')
https://github.com/anpaschool/QC-School-Fall2020
anpaschool
References 1. https://qiskit.org/textbook/preface.html 2. https://www.youtube.com/watch?v=IT-O-KSWlaE 3. https://www.youtube.com/watch?v=m4zs_fqS0Zw
https://github.com/ionq-samples/qiskit-getting-started
ionq-samples
#import Aer here, before calling qiskit_ionq_provider from qiskit import Aer from qiskit_ionq import IonQProvider #Call provider and set token value ionq_provider = IonQProvider(token='your token') ionq_provider.backends() import numpy as np from qiskit import execute from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.utils import QuantumInstance from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import COBYLA, ADAM, L_BFGS_B, SLSQP, SPSA from qiskit import Aer from qiskit.circuit import Parameter from qiskit.circuit.parametervector import ParameterVectorElement from qiskit_nature.drivers import PySCFDriver, UnitsType, Molecule from qiskit_nature.circuit.library import HartreeFock from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem from qiskit_nature.mappers.second_quantization import JordanWignerMapper from qiskit_nature.converters.second_quantization import QubitConverter from qiskit.algorithms import NumPyMinimumEigensolver from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver from qiskit_nature.runtime import VQEProgram from matplotlib import pyplot as plt %matplotlib inline class UCCAnsatz(): def __init__(self, params, num_particles, num_spin_orbitals): # number of qubits self.num_of_qubits = num_spin_orbitals # number of parameters self.num_params = len(params) # parameters self.params = [] for index in range(self.num_params): p = Parameter("t"+str(index)) self.params.append(ParameterVectorElement(p, index)) def UCC1(self): qc = QuantumCircuit(4) # basis rotation qc.rx(np.pi / 2, 0) qc.h(1) qc.h(2) qc.h(3) # parameter theta_0 qc.cx(0, 1) qc.cx(1, 2) qc.cx(2, 3) qc.rz(self.params[0], 3) qc.cx(2, 3) qc.cx(1, 2) qc.cx(0, 1) # basis rotation qc.rx(-np.pi / 2, 0) qc.h(1) qc.h(2) qc.h(3) return qc ################## Hamiltonian Definition ####################################### def GetHamiltonians(mol): # construct the driver driver = PySCFDriver(molecule=mol, unit=UnitsType.ANGSTROM, basis='sto6g') # the electronic structure problem problem = ElectronicStructureProblem(driver) # get quantum molecule q_molecule = driver.run() # classical eigenstate np_solver = NumPyMinimumEigensolver() np_groundstate_solver = GroundStateEigensolver(QubitConverter(JordanWignerMapper()), np_solver) np_result = np_groundstate_solver.solve(problem) print(f"Classical results is {np_result.eigenenergies}") # generate the second-quantized operators second_q_ops = problem.second_q_ops() # construct a qubit converter qubit_converter = QubitConverter(JordanWignerMapper()) # qubit Operations qubit_op = qubit_converter.convert(second_q_ops[0]) # return the qubit operations return qubit_op def constructAnsatz(params): # initialize the HF state hf_state = HartreeFock(4, [1, 1], QubitConverter(JordanWignerMapper())) # VQE circuit ansatz = UCCAnsatz(params, 2, 4).UCC1() # add initial state ansatz.compose(hf_state, front=True, inplace=True) # return the circuit return ansatz def constructCircuit(params, mol, backend_id): # Hamiltonian qubit_op = GetHamiltonians(mol) # Optimizer optimizer = COBYLA() # ansatz ansatz = constructAnsatz(params) print(ansatz) # initial parameters init_params = {} for index in range(len(params)): p = Parameter("t"+str(index)) init_params[ParameterVectorElement(p, index)] = 0.0 # backend if (backend_id == "qasm_simulator"): backend = Aer.get_backend("qasm_simulator") elif (backend_id == "ionq_qpu"): backend = ionq_provider.get_backend("ionq_qpu") def job_callback(job_id, job_status, queue_position, job) -> None: ''' Printing logs for debugging. The function is the parameter job_callback of QuantumInstance :param job_id: :param job_status: :param queue_position: :param job: :return: ''' print(f"[API JOB-CALLBACK] Job Id: {job_id}") print(f"[API JOB-CALLBACK] Job status: {job_status}") print(f"[API JOB-CALLBACK] Queue position: {queue_position}") print(f"[API JOB-CALLBACK] Job: {job}") ionq_quantum_instance = QuantumInstance(backend=backend, job_callback=job_callback) counts = [] values = [] stds = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) stds.append(std) # VQE algorithm algorithm = VQE(ansatz, optimizer=optimizer, initial_point = np.array([0.0]), callback=store_intermediate_result, quantum_instance=ionq_quantum_instance) result = algorithm.compute_minimum_eigenvalue(qubit_op) print(result) print("Optimized VQE Energy ", result.eigenvalue.real) print(values) # Execute program with default parameters def run(backend_id="qasm_simulator"): molecule = Molecule(geometry=[['H', [0., 0., 0.]], ['H', [0., 0., 0.75]]], charge=0, multiplicity=1) opt_values = constructCircuit([0.0], molecule, backend_id) run() opt_process = [-1.8308337397334875, -1.6045286426151377, -1.3176850880519417, -1.642972785671419, -1.853378862063689, -1.806712185391583, -1.8281518913000796, -1.853965175510973, -1.8546227409607912, -1.8512623145326073, -1.8499200431393457, -1.8490846844773303, -1.8508890835046492, -1.8474757232657733, -1.8492536553877457, -1.8544537700503756, -1.8461599187778577, -1.8476358718744068, -1.849466737807071] plt.plot(opt_process, linestyle="", marker="o") plt.show() run("ionq_qpu") opt_process_exp = [-1.8112359199652812, -1.4416498480789817, -1.2335035452225904, -1.4989706208229303, -1.6937521890989031, -1.6557546667316045, -1.6898027909394815, -1.740016937435431, -1.7592133266130963, -1.755505060521276, -1.7199835843097526, -1.7476529655074913, -1.7142357090197362, -1.7366022956905651, -1.7307574124517149, -1.7437590702130892, -1.721561556686939] plt.plot(opt_process, linestyle="", marker="o", color="b", label="simulator") plt.plot(opt_process_exp, linestyle="", marker="o", color="r", label="ionq_qpu") plt.legend() plt.show() opt_process_exp = [-1.8112359199652812, -1.4416498480789817, -1.2335035452225904, -1.4989706208229303, -1.6937521890989031, -1.6557546667316045, -1.6898027909394815, -1.740016937435431, -1.7592133266130963, -1.755505060521276, -1.7199835843097526, -1.7476529655074913, -1.7142357090197362, -1.7366022956905651, -1.7307574124517149, -1.7437590702130892, -1.721561556686939] opt_process = [-1.8308337397334875, -1.6045286426151377, -1.3176850880519417, -1.642972785671419, -1.853378862063689, -1.806712185391583, -1.8281518913000796, -1.853965175510973, -1.8546227409607912, -1.8512623145326073, -1.8499200431393457, -1.8490846844773303, -1.8508890835046492, -1.8474757232657733, -1.8492536553877457, -1.8544537700503756, -1.8461599187778577, -1.8476358718744068, -1.849466737807071] plt.plot(opt_process, linestyle="", marker="o", color="b", label="simulator") plt.plot(opt_process_exp, linestyle="", marker="o", color="r", label="ionq_qpu") plt.xlabel("Number of Iteration") plt.ylabel("Energy (Hartree)") plt.legend() plt.show()
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/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')