repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from sklearn.datasets import load_iris iris_data = load_iris() print(iris_data.DESCR) features = iris_data.data labels = iris_data.target from sklearn.preprocessing import MinMaxScaler features = MinMaxScaler().fit_transform(features) import pandas as pd import seaborn as sns df = pd.DataFrame(iris_data.data, columns=iris_data.feature_names) df["class"] = pd.Series(iris_data.target) sns.pairplot(df, hue="class", palette="tab10") from sklearn.model_selection import train_test_split from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 123 train_features, test_features, train_labels, test_labels = train_test_split( features, labels, train_size=0.8, random_state=algorithm_globals.random_seed ) from sklearn.svm import SVC svc = SVC() _ = svc.fit(train_features, train_labels) # suppress printing the return value train_score_c4 = svc.score(train_features, train_labels) test_score_c4 = svc.score(test_features, test_labels) print(f"Classical SVC on the training dataset: {train_score_c4:.2f}") print(f"Classical SVC on the test dataset: {test_score_c4:.2f}") from qiskit.circuit.library import ZZFeatureMap num_features = features.shape[1] feature_map = ZZFeatureMap(feature_dimension=num_features, reps=1) feature_map.decompose().draw(output="mpl", fold=20) from qiskit.circuit.library import RealAmplitudes ansatz = RealAmplitudes(num_qubits=num_features, reps=3) ansatz.decompose().draw(output="mpl", fold=20) from qiskit.algorithms.optimizers import COBYLA optimizer = COBYLA(maxiter=100) from qiskit.primitives import Sampler sampler = Sampler() from matplotlib import pyplot as plt from IPython.display import clear_output objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) def callback_graph(weights, obj_func_eval): clear_output(wait=True) objective_func_vals.append(obj_func_eval) plt.title("Objective function value against iteration") plt.xlabel("Iteration") plt.ylabel("Objective function value") plt.plot(range(len(objective_func_vals)), objective_func_vals) plt.show() import time from qiskit_machine_learning.algorithms.classifiers import VQC vqc = VQC( sampler=sampler, feature_map=feature_map, ansatz=ansatz, optimizer=optimizer, callback=callback_graph, ) # clear objective value history objective_func_vals = [] start = time.time() vqc.fit(train_features, train_labels) elapsed = time.time() - start print(f"Training time: {round(elapsed)} seconds") train_score_q4 = vqc.score(train_features, train_labels) test_score_q4 = vqc.score(test_features, test_labels) print(f"Quantum VQC on the training dataset: {train_score_q4:.2f}") print(f"Quantum VQC on the test dataset: {test_score_q4:.2f}") from sklearn.decomposition import PCA features = PCA(n_components=2).fit_transform(features) plt.rcParams["figure.figsize"] = (6, 6) sns.scatterplot(x=features[:, 0], y=features[:, 1], hue=labels, palette="tab10") train_features, test_features, train_labels, test_labels = train_test_split( features, labels, train_size=0.8, random_state=algorithm_globals.random_seed ) svc.fit(train_features, train_labels) train_score_c2 = svc.score(train_features, train_labels) test_score_c2 = svc.score(test_features, test_labels) print(f"Classical SVC on the training dataset: {train_score_c2:.2f}") print(f"Classical SVC on the test dataset: {test_score_c2:.2f}") num_features = features.shape[1] feature_map = ZZFeatureMap(feature_dimension=num_features, reps=1) ansatz = RealAmplitudes(num_qubits=num_features, reps=3) optimizer = COBYLA(maxiter=40) vqc = VQC( sampler=sampler, feature_map=feature_map, ansatz=ansatz, optimizer=optimizer, callback=callback_graph, ) # clear objective value history objective_func_vals = [] # make the objective function plot look nicer. plt.rcParams["figure.figsize"] = (12, 6) start = time.time() vqc.fit(train_features, train_labels) elapsed = time.time() - start print(f"Training time: {round(elapsed)} seconds") train_score_q2_ra = vqc.score(train_features, train_labels) test_score_q2_ra = vqc.score(test_features, test_labels) print(f"Quantum VQC on the training dataset using RealAmplitudes: {train_score_q2_ra:.2f}") print(f"Quantum VQC on the test dataset using RealAmplitudes: {test_score_q2_ra:.2f}") from qiskit.circuit.library import EfficientSU2 ansatz = EfficientSU2(num_qubits=num_features, reps=3) optimizer = COBYLA(maxiter=40) vqc = VQC( sampler=sampler, feature_map=feature_map, ansatz=ansatz, optimizer=optimizer, callback=callback_graph, ) # clear objective value history objective_func_vals = [] start = time.time() vqc.fit(train_features, train_labels) elapsed = time.time() - start print(f"Training time: {round(elapsed)} seconds") train_score_q2_eff = vqc.score(train_features, train_labels) test_score_q2_eff = vqc.score(test_features, test_labels) print(f"Quantum VQC on the training dataset using EfficientSU2: {train_score_q2_eff:.2f}") print(f"Quantum VQC on the test dataset using EfficientSU2: {test_score_q2_eff:.2f}") print(f"Model | Test Score | Train Score") print(f"SVC, 4 features | {train_score_c4:10.2f} | {test_score_c4:10.2f}") print(f"VQC, 4 features, RealAmplitudes | {train_score_q4:10.2f} | {test_score_q4:10.2f}") print(f"----------------------------------------------------------") print(f"SVC, 2 features | {train_score_c2:10.2f} | {test_score_c2:10.2f}") print(f"VQC, 2 features, RealAmplitudes | {train_score_q2_ra:10.2f} | {test_score_q2_ra:10.2f}") print(f"VQC, 2 features, EfficientSU2 | {train_score_q2_eff:10.2f} | {test_score_q2_eff:10.2f}") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test QuantumCircuit.find_bit.""" from ddt import ddt, data, unpack from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Qubit, Clbit, AncillaRegister from qiskit.circuit.exceptions import CircuitError from qiskit.test import QiskitTestCase @ddt class TestQuantumCircuitFindBit(QiskitTestCase): """Test cases for QuantumCircuit.find_bit.""" @data(Qubit, Clbit) def test_bit_not_in_circuit(self, bit_type): """Verify we raise if the bit has not been attached to the circuit.""" qc = QuantumCircuit() bit = bit_type() with self.assertRaisesRegex(CircuitError, r"Could not locate provided bit"): qc.find_bit(bit) @data(Qubit, Clbit) def test_registerless_bit_constructor(self, bit_type): """Verify we find individual bits added via QuantumCircuit constructor.""" bits = [bit_type() for _ in range(5)] qc = QuantumCircuit(bits) for idx, bit in enumerate(bits): self.assertEqual(qc.find_bit(bit), (idx, [])) @data(Qubit, Clbit) def test_registerless_add_bits(self, bit_type): """Verify we find individual bits added via QuantumCircuit.add_bits.""" bits = [bit_type() for _ in range(5)] qc = QuantumCircuit() qc.add_bits(bits) for idx, bit in enumerate(bits): self.assertEqual(qc.find_bit(bit), (idx, [])) def test_registerless_add_int(self): """Verify we find bits and implicit registers added via QuantumCircuit(int, int).""" qc = QuantumCircuit(5, 2) qubits = qc.qubits clbits = qc.clbits # N.B. After deprecation of implicit register creation via # QuantumCircuit(int, int) in PR#6582 and subsequent removal, this test # should be updated to verify no registers are found. qr = qc.qregs[0] cr = qc.cregs[0] for idx, bit in enumerate(qubits): self.assertEqual(qc.find_bit(bit), (idx, [(qr, idx)])) for idx, bit in enumerate(clbits): self.assertEqual(qc.find_bit(bit), (idx, [(cr, idx)])) @data(QuantumRegister, ClassicalRegister) def test_register_bit_reg_constructor(self, reg_type): """Verify we find register bits added via QuantumCicrcuit(reg).""" reg = reg_type(5, "reg") qc = QuantumCircuit(reg) for idx, bit in enumerate(reg): self.assertEqual(qc.find_bit(bit), (idx, [(reg, idx)])) @data(QuantumRegister, ClassicalRegister) def test_register_bit_add_reg(self, reg_type): """Verify we find register bits added QuantumCircuit.add_register.""" reg = reg_type(5, "reg") qc = QuantumCircuit() qc.add_register(reg) for idx, bit in enumerate(reg): self.assertEqual(qc.find_bit(bit), (idx, [(reg, idx)])) def test_ancilla_register_add_register(self): """Verify AncillaRegisters are found by find_bit by their locations in qubits/qregs.""" qreg = QuantumRegister(3, "qr") areg = AncillaRegister(5, "ar") qc = QuantumCircuit() qc.add_register(qreg) qc.add_register(areg) for idx, bit in enumerate(areg): self.assertEqual(qc.find_bit(bit), (idx + len(qreg), [(areg, idx)])) @data([Qubit, QuantumRegister], [Clbit, ClassicalRegister]) @unpack def test_multiple_register_from_bit(self, bit_type, reg_type): """Verify we find individual bits in multiple registers.""" bits = [bit_type() for _ in range(10)] even_reg = reg_type(bits=bits[::2]) odd_reg = reg_type(bits=bits[1::2]) fwd_reg = reg_type(bits=bits) rev_reg = reg_type(bits=bits[::-1]) qc = QuantumCircuit() qc.add_bits(bits) qc.add_register(even_reg, odd_reg, fwd_reg, rev_reg) for idx, bit in enumerate(bits): if idx % 2: self.assertEqual( qc.find_bit(bit), (idx, [(odd_reg, idx // 2), (fwd_reg, idx), (rev_reg, 9 - idx)]), ) else: self.assertEqual( qc.find_bit(bit), (idx, [(even_reg, idx // 2), (fwd_reg, idx), (rev_reg, 9 - idx)]), ) @data(QuantumRegister, ClassicalRegister) def test_multiple_register_from_reg(self, reg_type): """Verify we find register bits in multiple registers.""" reg1 = reg_type(6, "reg1") reg2 = reg_type(4, "reg2") even_reg = reg_type(bits=(reg1[:] + reg2[:])[::2]) odd_reg = reg_type(bits=(reg1[:] + reg2[:])[1::2]) qc = QuantumCircuit(reg1, reg2, even_reg, odd_reg) for idx, bit in enumerate(reg1): if idx % 2: self.assertEqual(qc.find_bit(bit), (idx, [(reg1, idx), (odd_reg, idx // 2)])) else: self.assertEqual(qc.find_bit(bit), (idx, [(reg1, idx), (even_reg, idx // 2)])) for idx, bit in enumerate(reg2): circ_idx = len(reg1) + idx if idx % 2: self.assertEqual( qc.find_bit(bit), (circ_idx, [(reg2, idx), (odd_reg, circ_idx // 2)]) ) else: self.assertEqual( qc.find_bit(bit), (circ_idx, [(reg2, idx), (even_reg, circ_idx // 2)]) )
https://github.com/orpgol/quantum_algorithms_qiskit
orpgol
import numpy as np from qiskit import BasicAer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, execute from qiskit.visualization import plot_histogram from qiskit import IBMQ, assemble, transpile from qiskit.tools.monitor import job_monitor import argparse, sys import time provider = IBMQ.load_account() parser = argparse.ArgumentParser() parser.add_argument('--bits', help = 'Enter the number of bits you want to run with.') parser.add_argument('--algo', help = 'Enter either "constant" or "balanced".') class Deutsch_Jozsa(object): def __init__(self, n, algo): self.n = n self.algo = algo #change to self def _dj_oracle(self): oracle_qc = QuantumCircuit(self.n+1) if self.algo == "balanced": b = np.random.randint(1,2**self.n) b_str = format(b, '0'+str(self.n)+'b') for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) for qubit in range(self.n): oracle_qc.cx(qubit, self.n) for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) if self.algo == "constant": output = np.random.randint(2) if output == 1: oracle_qc.x(self.n) return oracle_qc.to_gate() def _dj_algorithm(self, oracle): dj_circuit = QuantumCircuit(self.n+1, self.n) dj_circuit.x(self.n) dj_circuit.barrier() dj_circuit.h(self.n) dj_circuit.barrier() for qubit in range(self.n): dj_circuit.h(qubit) dj_circuit.barrier() dj_circuit.append(oracle, range(n+1)) for qubit in range(self.n): dj_circuit.h(qubit) dj_circuit.barrier() for i in range(self.n): dj_circuit.measure(i, i) backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= len(self.qubits) and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) shots = 8000 job = execute(dj_circuit, backend=backend, shots=shots, optimization_level=3) job_monitor(job, interval = 2) try: result = job.result() except: print(job.error_message()) return -1, -1 answer = result.get_counts(dj_circuit) print(answer) fi = plot_histogram(answer) fi.savefig(fname = "dj_results5_8000.png") #fig = dj_circuit.draw(output = "mpl") #fig.savefig(fname = "dj6.png") print("--%s seconds--" % result.time_taken) if __name__ == '__main__': start_time = time.time() args = parser.parse_args() n = int((args.bits)) if n < 1: raise AssertionError("n must be a number of bits greater than 0") if args.algo != ('constant') and args.algo != ('balanced'): raise AssertionError("algo must be either balanced or constant") dj = Deutsch_Jozsa(n, args.algo) oracle_gate = dj._dj_oracle() dj_circuit = dj._dj_algorithm(oracle_gate)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """ Quantum Shannon Decomposition. Method is described in arXiv:quant-ph/0406176. """ from __future__ import annotations import scipy import numpy as np from qiskit.circuit import QuantumCircuit, QuantumRegister from qiskit.quantum_info.synthesis import two_qubit_decompose, one_qubit_decompose from qiskit.quantum_info.operators.predicates import is_hermitian_matrix from qiskit.extensions.quantum_initializer.uc_pauli_rot import UCPauliRotGate, _EPS def qs_decomposition( mat: np.ndarray, opt_a1: bool = True, opt_a2: bool = True, decomposer_1q=None, decomposer_2q=None, *, _depth=0, ): """ Decomposes unitary matrix into one and two qubit gates using Quantum Shannon Decomposition. ┌───┐ ┌───┐ ┌───┐ ┌───┐ ─┤ ├─ ───────┤ Rz├─────┤ Ry├─────┤ Rz├───── │ │ ≃ ┌───┐└─┬─┘┌───┐└─┬─┘┌───┐└─┬─┘┌───┐ /─┤ ├─ /─┤ ├──□──┤ ├──□──┤ ├──□──┤ ├ └───┘ └───┘ └───┘ └───┘ └───┘ The number of CX gates generated with the decomposition without optimizations is, .. math:: \frac{9}{16} 4^n - frac{3}{2} 2^n If opt_a1 = True, the default, the CX count is reduced by, .. math:: \frac{1}{3} 4^{n - 2} - 1. If opt_a2 = True, the default, the CX count is reduced by, .. math:: 4^{n-2} - 1. This decomposition is described in arXiv:quant-ph/0406176. Arguments: mat (ndarray): unitary matrix to decompose opt_a1 (bool): whether to try optimization A.1 from Shende. This should eliminate 1 cnot per call. If True CZ gates are left in the output. If desired these can be further decomposed to CX. opt_a2 (bool): whether to try optimization A.2 from Shende. This decomposes two qubit unitaries into a diagonal gate and a two cx unitary and reduces overal cx count by 4^(n-2) - 1. decomposer_1q (None or Object): optional 1Q decomposer. If None, uses :class:`~qiskit.quantum_info.synthesis.one_qubit_decomposer.OneQubitEulerDecomser` decomposer_2q (None or Object): optional 2Q decomposer. If None, uses :class:`~qiskit.quantum_info.synthesis.two_qubit_decomposer.two_qubit_cnot_decompose Return: QuantumCircuit: Decomposed quantum circuit. """ # _depth (int): Internal use parameter to track recursion depth. dim = mat.shape[0] nqubits = int(np.log2(dim)) if np.allclose(np.identity(dim), mat): return QuantumCircuit(nqubits) if dim == 2: if decomposer_1q is None: decomposer_1q = one_qubit_decompose.OneQubitEulerDecomposer() circ = decomposer_1q(mat) elif dim == 4: if decomposer_2q is None: if opt_a2 and _depth > 0: from qiskit.extensions.unitary import UnitaryGate # pylint: disable=cyclic-import def decomp_2q(mat): ugate = UnitaryGate(mat) qc = QuantumCircuit(2, name="qsd2q") qc.append(ugate, [0, 1]) return qc decomposer_2q = decomp_2q else: decomposer_2q = two_qubit_decompose.two_qubit_cnot_decompose circ = decomposer_2q(mat) else: qr = QuantumRegister(nqubits) circ = QuantumCircuit(qr) dim_o2 = dim // 2 # perform cosine-sine decomposition (u1, u2), vtheta, (v1h, v2h) = scipy.linalg.cossin(mat, separate=True, p=dim_o2, q=dim_o2) # left circ left_circ = _demultiplex(v1h, v2h, opt_a1=opt_a1, opt_a2=opt_a2, _depth=_depth) circ.append(left_circ.to_instruction(), qr) # middle circ if opt_a1: nangles = len(vtheta) half_size = nangles // 2 # get UCG in terms of CZ circ_cz = _get_ucry_cz(nqubits, (2 * vtheta).tolist()) circ.append(circ_cz.to_instruction(), range(nqubits)) # merge final cz with right-side generic multiplexer u2[:, half_size:] = np.negative(u2[:, half_size:]) else: circ.ucry((2 * vtheta).tolist(), qr[:-1], qr[-1]) # right circ right_circ = _demultiplex(u1, u2, opt_a1=opt_a1, opt_a2=opt_a2, _depth=_depth) circ.append(right_circ.to_instruction(), qr) if opt_a2 and _depth == 0 and dim > 4: return _apply_a2(circ) return circ def _demultiplex(um0, um1, opt_a1=False, opt_a2=False, *, _depth=0): """Decompose a generic multiplexer. ────□──── ┌──┴──┐ /─┤ ├─ └─────┘ represented by the block diagonal matrix ┏ ┓ ┃ um0 ┃ ┃ um1 ┃ ┗ ┛ to ┌───┐ ───────┤ Rz├────── ┌───┐└─┬─┘┌───┐ /─┤ w ├──□──┤ v ├─ └───┘ └───┘ where v and w are general unitaries determined from decomposition. Args: um0 (ndarray): applied if MSB is 0 um1 (ndarray): applied if MSB is 1 opt_a1 (bool): whether to try optimization A.1 from Shende. This should elliminate 1 cnot per call. If True CZ gates are left in the output. If desired these can be further decomposed opt_a2 (bool): whether to try optimization A.2 from Shende. This decomposes two qubit unitaries into a diagonal gate and a two cx unitary and reduces overal cx count by 4^(n-2) - 1. _depth (int): This is an internal variable to track the recursion depth. Returns: QuantumCircuit: decomposed circuit """ dim = um0.shape[0] + um1.shape[0] # these should be same dimension nqubits = int(np.log2(dim)) um0um1 = um0 @ um1.T.conjugate() if is_hermitian_matrix(um0um1): eigvals, vmat = scipy.linalg.eigh(um0um1) else: evals, vmat = scipy.linalg.schur(um0um1, output="complex") eigvals = evals.diagonal() dvals = np.lib.scimath.sqrt(eigvals) dmat = np.diag(dvals) wmat = dmat @ vmat.T.conjugate() @ um1 circ = QuantumCircuit(nqubits) # left gate left_gate = qs_decomposition( wmat, opt_a1=opt_a1, opt_a2=opt_a2, _depth=_depth + 1 ).to_instruction() circ.append(left_gate, range(nqubits - 1)) # multiplexed Rz angles = 2 * np.angle(np.conj(dvals)) circ.ucrz(angles.tolist(), list(range(nqubits - 1)), [nqubits - 1]) # right gate right_gate = qs_decomposition( vmat, opt_a1=opt_a1, opt_a2=opt_a2, _depth=_depth + 1 ).to_instruction() circ.append(right_gate, range(nqubits - 1)) return circ def _get_ucry_cz(nqubits, angles): """ Get uniformly controlled Ry gate in in CZ-Ry as in UCPauliRotGate. """ nangles = len(angles) qc = QuantumCircuit(nqubits) q_controls = qc.qubits[:-1] q_target = qc.qubits[-1] if not q_controls: if np.abs(angles[0]) > _EPS: qc.ry(angles[0], q_target) else: angles = angles.copy() UCPauliRotGate._dec_uc_rotations(angles, 0, len(angles), False) for (i, angle) in enumerate(angles): if np.abs(angle) > _EPS: qc.ry(angle, q_target) if not i == len(angles) - 1: binary_rep = np.binary_repr(i + 1) q_contr_index = len(binary_rep) - len(binary_rep.rstrip("0")) else: # Handle special case: q_contr_index = len(q_controls) - 1 # leave off last CZ for merging with adjacent UCG if i < nangles - 1: qc.cz(q_controls[q_contr_index], q_target) return qc def _apply_a2(circ): from qiskit import transpile from qiskit.quantum_info import Operator # from qiskit.extensions.unitary import UnitaryGate import qiskit.extensions.unitary decomposer = two_qubit_decompose.TwoQubitDecomposeUpToDiagonal() ccirc = transpile(circ, basis_gates=["u", "cx", "qsd2q"], optimization_level=0) ind2q = [] # collect 2q instrs for i, instruction in enumerate(ccirc.data): if instruction.operation.name == "qsd2q": ind2q.append(i) if not ind2q: return ccirc # rolling over diagonals ind2 = None # lint for ind1, ind2 in zip(ind2q[0:-1:], ind2q[1::]): # get neigboring 2q gates separated by controls instr1 = ccirc.data[ind1] mat1 = Operator(instr1.operation).data instr2 = ccirc.data[ind2] mat2 = Operator(instr2.operation).data # rollover dmat, qc2cx = decomposer(mat1) ccirc.data[ind1] = instr1.replace(operation=qc2cx.to_gate()) mat2 = mat2 @ dmat ccirc.data[ind2] = instr2.replace(qiskit.extensions.unitary.UnitaryGate(mat2)) qc3 = two_qubit_decompose.two_qubit_cnot_decompose(mat2) ccirc.data[ind2] = ccirc.data[ind2].replace(operation=qc3.to_gate()) return ccirc
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.timeline import draw, IQXSimple from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial') draw(qc, style=IQXSimple())
https://github.com/minnukota381/Quantum-Computing-Qiskit
minnukota381
from qiskit import * from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram # Create a quantum circuit with 2 qubits # The default initial state of qubits will be |0> or [1,0] BS1 = QuantumCircuit(2) #Applying the CNOT gate BS1.h(0) BS1.cx(0,1) #Draw the circuit # qc.draw() BS1.draw('mpl') #Get the backend for the circuit to display unitary matrix backend = Aer.get_backend('unitary_simulator') #execute the circuit using the backend out = execute(BS1,backend).result().get_unitary() #import qiskit_textbook and display the combined unitary matrix from qiskit_textbook.tools import array_to_latex array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ") #Get the backend for the circuit (simulator or realtime system) backend = Aer.get_backend('statevector_simulator') #execute the circuit using the backend out = execute(BS1,backend).result().get_statevector() #import qiskit_textbook and display the statevector #from qiskit_textbook.tools import array_to_latex array_to_latex(out, pretext = "\\text{Statevector} = ") #execute the circuit and get the plain result out = execute(BS1,backend).result() #getting the count of the result counts = out.get_counts() #plotting the histogram plot_histogram(counts) # Create a quantum circuit with 2 qubits # The default initial state of qubits will be |0> or [1,0] BS2 = QuantumCircuit(2) BS2.x(0) BS2.h(0) BS2.cx(0,1) #Draw the circuit # qc.draw() BS2.draw('mpl') #Get the backend for the circuit to display unitary matrix backend = Aer.get_backend('unitary_simulator') #execute the circuit using the backend out = execute(BS2,backend).result().get_unitary() #import qiskit_textbook and display the combined unitary matrix from qiskit_textbook.tools import array_to_latex array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ") #Get the backend for the circuit (simulator or realtime system) backend = Aer.get_backend('statevector_simulator') #execute the circuit using the backend out = execute(BS2,backend).result().get_statevector() #import qiskit_textbook and display the statevector #from qiskit_textbook.tools import array_to_latex array_to_latex(out, pretext = "\\text{Statevector} = ") #execute the circuit and get the plain result out = execute(BS2,backend).result() #getting the count of the result counts = out.get_counts() #plotting the histogram plot_histogram(counts) BS3=QuantumCircuit(2) BS3.h(0) BS3.x(1) BS3.cx(0,1) BS3.draw('mpl') #Get the backend for the circuit to display unitary matrix backend = Aer.get_backend('unitary_simulator') #execute the circuit using the backend out = execute(BS3,backend).result().get_unitary() #import qiskit_textbook and display the combined unitary matrix from qiskit_textbook.tools import array_to_latex array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ") #Get the backend for the circuit (simulator or realtime system) backend = Aer.get_backend('statevector_simulator') out = execute(BS3,backend).result().get_statevector() array_to_latex(out, pretext = "\\text{Statevector} = ") #execute the circuit and get the plain result out = execute(BS3,backend).result() #getting the count of the result counts = out.get_counts() #plotting the histogram plot_histogram(counts) BS4=QuantumCircuit(2) BS4.h(0) BS4.z(0) BS4.x(1) BS4.z(1) BS4.cx(0,1) BS4.draw('mpl') #Get the backend for the circuit to display unitary matrix backend = Aer.get_backend('unitary_simulator') #execute the circuit using the backend out = execute(BS4,backend).result().get_unitary() #import qiskit_textbook and display the combined unitary matrix from qiskit_textbook.tools import array_to_latex array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ") #Get the backend for the circuit (simulator or realtime system) backend = Aer.get_backend('statevector_simulator') #execute the circuit using the backend out = execute(BS4,backend).result().get_statevector() #import qiskit_textbook and display the statevector #from qiskit_textbook.tools import array_to_latex array_to_latex(out, pretext = "\\text{Statevector} = ") #execute the circuit and get the plain result out = execute(BS4,backend).result() #getting the count of the result counts = out.get_counts() #plotting the histogram plot_histogram(counts) from qiskit import QuantumCircuit, Aer, transpile, assemble, execute from qiskit.visualization import plot_histogram # Create a quantum circuit with two qubits bell_circuit = QuantumCircuit(2, 2) # Apply a Hadamard gate to the first qubit bell_circuit.h(0) # Apply a CNOT gate with the first qubit as the control and the second qubit as the target bell_circuit.cx(0, 1) # The resulting state is a Bell state bell_circuit.measure([0, 1], [0, 1]) # Simulate the circuit using the Aer simulator simulator = Aer.get_backend('qasm_simulator') # Transpile the circuit for the simulator transpiled_bell_circuit = transpile(bell_circuit, simulator) # Run the simulation result = execute(transpiled_bell_circuit, simulator).result() # Display the measurement results counts = result.get_counts(bell_circuit) plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeAuckland backend = FakeAuckland() ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) ghz.draw(output='mpl')
https://github.com/maximusron/qgss_2021_labs
maximusron
# General tools import numpy as np import matplotlib.pyplot as plt # Qiskit Circuit Functions from qiskit import execute,QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile import qiskit.quantum_info as qi # Tomography functions from qiskit.ignis.verification.tomography import process_tomography_circuits, ProcessTomographyFitter from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter import warnings warnings.filterwarnings('ignore') target = QuantumCircuit(2) target.h(0) target.h(1) target.rx(np.pi/2,0) target.rx(np.pi/2,1) target.cx(0,1) target.p(np.pi,1) target.cx(0,1) target_unitary = qi.Operator(target) from qc_grader import grade_lab5_ex1 # Note that the grading function is expecting a quantum circuit with no measurements grade_lab5_ex1(target) simulator = Aer.get_backend('qasm_simulator') qpt_circs = process_tomography_circuits(target, measured_qubits = [0,1]) qpt_job = execute(qpt_circs,simulator,seed_simulator=3145,seed_transpiler=3145,shots=8192) qpt_result = qpt_job.result() # YOUR CODE HERE qpt_tomo = ProcessTomographyFitter(qpt_result, qpt_circs) qpt_lstq = qpt_tomo.fit(method='lstsq') fidelity = qi.average_gate_fidelity(qpt_lstq, target_unitary) print(fidelity) from qc_grader import grade_lab5_ex2 # Note that the grading function is expecting a floating point number grade_lab5_ex2(fidelity) # T1 and T2 values for qubits 0-3 T1s = [15000, 19000, 22000, 14000] T2s = [30000, 25000, 18000, 28000] # Instruction times (in nanoseconds) time_u1 = 0 # virtual gate time_u2 = 50 # (single X90 pulse) time_u3 = 100 # (two X90 pulses) time_cx = 300 time_reset = 1000 # 1 microsecond time_measure = 1000 # 1 microsecond from qiskit.providers.aer.noise import thermal_relaxation_error from qiskit.providers.aer.noise import NoiseModel # QuantumError objects errors_reset = [thermal_relaxation_error(t1, t2, time_reset) for t1, t2 in zip(T1s, T2s)] errors_measure = [thermal_relaxation_error(t1, t2, time_measure) for t1, t2 in zip(T1s, T2s)] errors_u1 = [thermal_relaxation_error(t1, t2, time_u1) for t1, t2 in zip(T1s, T2s)] errors_u2 = [thermal_relaxation_error(t1, t2, time_u2) for t1, t2 in zip(T1s, T2s)] errors_u3 = [thermal_relaxation_error(t1, t2, time_u3) for t1, t2 in zip(T1s, T2s)] errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand( thermal_relaxation_error(t1b, t2b, time_cx)) for t1a, t2a in zip(T1s, T2s)] for t1b, t2b in zip(T1s, T2s)] # Add errors to noise model noise_thermal = NoiseModel() for j in range(4): noise_thermal.add_quantum_error(errors_reset[j], "reset", [j]) noise_thermal.add_quantum_error(errors_measure[j], "measure", [j]) noise_thermal.add_quantum_error(errors_u1[j], "u1", [j]) noise_thermal.add_quantum_error(errors_u2[j], "u2", [j]) noise_thermal.add_quantum_error(errors_u3[j], "u3", [j]) for k in range(4): noise_thermal.add_quantum_error(errors_cx[j][k], "cx", [j,k]) noise_thermal # YOUR CODE HERE from qc_grader import grade_lab5_ex3 # Note that the grading function is expecting a NoiseModel grade_lab5_ex3(noise_thermal) np.random.seed(0) # YOUR CODE HERE noisy_qpt_job = execute(qpt_circs,simulator,seed_simulator=3145,seed_transpiler=3145,shots=8192, noise_model=noise_thermal) noisy_qpt_result = noisy_qpt_job.result() noisy_qpt_tomo = ProcessTomographyFitter(noisy_qpt_result, qpt_circs) noisy_qpt_lstsq = noisy_qpt_tomo.fit(method='lstsq') noisy_fidelity = qi.average_gate_fidelity(noisy_qpt_lstsq, target_unitary) print(noisy_fidelity) from qc_grader import grade_lab5_ex4 # Note that the grading function is expecting a floating point number grade_lab5_ex4(noisy_fidelity) np.random.seed(0) meas_cal_circs, state_labels = complete_meas_cal(qubit_list = [0,1]) print(state_labels) qpt_ex5 = execute(meas_cal_circs,simulator, seed_simulator=3145, seed_transpiler=3145,shots=8192, noise_model=noise_thermal) nqpt_result = qpt_ex5.result() meas_fitter = CompleteMeasFitter(nqpt_result, state_labels = state_labels) meas_fitter.plot_calibration() meas_fitter = meas_fitter.filter noisy_qpt_result = meas_fitter.apply(noisy_qpt_result) process = ProcessTomographyFitter(noisy_qpt_result, qpt_circs) lstsq = (process.fit(method = 'lstsq')) noisy_fidelity = qi.average_gate_fidelity(lstsq, target_unitary) print(noisy_fidelity) from qc_grader import grade_lab5_ex5 # Note that the grading function is expecting a floating point number grade_lab5_ex5(noisy_fidelity)
https://github.com/qBraid/qBraid
qBraid
# 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 basic functionality of the transpile function""" import copy import io import math import os import sys import unittest from logging import StreamHandler, getLogger from test import combine # pylint: disable=wrong-import-order from unittest.mock import patch import numpy as np import rustworkx as rx from ddt import data, ddt, unpack from qiskit import BasicAer, ClassicalRegister, QuantumCircuit, QuantumRegister, pulse, qasm3, qpy from qiskit.circuit import ( Clbit, ControlFlowOp, ForLoopOp, Gate, IfElseOp, Parameter, Qubit, Reset, SwitchCaseOp, WhileLoopOp, ) from qiskit.circuit.classical import expr from qiskit.circuit.delay import Delay from qiskit.circuit.library import ( CXGate, CZGate, HGate, RXGate, RYGate, RZGate, SXGate, U1Gate, U2Gate, UGate, XGate, ) from qiskit.circuit.measure import Measure from qiskit.compiler import transpile from qiskit.converters import circuit_to_dag from qiskit.dagcircuit import DAGOpNode, DAGOutNode from qiskit.exceptions import QiskitError from qiskit.providers.backend import BackendV2 from qiskit.providers.fake_provider import ( FakeBoeblingen, FakeMelbourne, FakeMumbaiV2, FakeNairobiV2, FakeRueschlikon, FakeSherbrooke, FakeVigo, ) from qiskit.providers.options import Options from qiskit.pulse import InstructionScheduleMap from qiskit.quantum_info import Operator, random_unitary from qiskit.test import QiskitTestCase, slow_test from qiskit.tools import parallel from qiskit.transpiler import CouplingMap, Layout, PassManager, TransformationPass from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.passes import BarrierBeforeFinalMeasurements, GateDirection, VF2PostLayout from qiskit.transpiler.passmanager_config import PassManagerConfig from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager, level_0_pass_manager from qiskit.transpiler.target import InstructionProperties, Target class CustomCX(Gate): """Custom CX gate representation.""" def __init__(self): super().__init__("custom_cx", 2, []) def _define(self): self._definition = QuantumCircuit(2) self._definition.cx(0, 1) def connected_qubits(physical: int, coupling_map: CouplingMap) -> set: """Get the physical qubits that have a connection to this one in the coupling map.""" for component in coupling_map.connected_components(): if physical in (qubits := set(component.graph.nodes())): return qubits raise ValueError(f"physical qubit {physical} is not in the coupling map") @ddt class TestTranspile(QiskitTestCase): """Test transpile function.""" def test_empty_transpilation(self): """Test that transpiling an empty list is a no-op. Regression test of gh-7287.""" self.assertEqual(transpile([]), []) def test_pass_manager_none(self): """Test passing the default (None) pass manager to the transpiler. It should perform the default qiskit flow: unroll, swap_mapper, cx_direction, cx_cancellation, optimize_1q_gates and should be equivalent to using tools.compile """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) coupling_map = [[1, 0]] basis_gates = ["u1", "u2", "u3", "cx", "id"] backend = BasicAer.get_backend("qasm_simulator") circuit2 = transpile( circuit, backend=backend, coupling_map=coupling_map, basis_gates=basis_gates, ) circuit3 = transpile( circuit, backend=backend, coupling_map=coupling_map, basis_gates=basis_gates ) self.assertEqual(circuit2, circuit3) def test_transpile_basis_gates_no_backend_no_coupling_map(self): """Verify transpile() works with no coupling_map or backend.""" qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) basis_gates = ["u1", "u2", "u3", "cx", "id"] circuit2 = transpile(circuit, basis_gates=basis_gates, optimization_level=0) resources_after = circuit2.count_ops() self.assertEqual({"u2": 2, "cx": 4}, resources_after) def test_transpile_non_adjacent_layout(self): """Transpile pipeline can handle manual layout on non-adjacent qubits. circuit: .. parsed-literal:: ┌───┐ qr_0: ┤ H ├──■──────────── -> 1 └───┘┌─┴─┐ qr_1: ─────┤ X ├──■─────── -> 2 └───┘┌─┴─┐ qr_2: ──────────┤ X ├──■── -> 3 └───┘┌─┴─┐ qr_3: ───────────────┤ X ├ -> 5 └───┘ device: 0 - 1 - 2 - 3 - 4 - 5 - 6 | | | | | | 13 - 12 - 11 - 10 - 9 - 8 - 7 """ qr = QuantumRegister(4, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[2]) circuit.cx(qr[2], qr[3]) coupling_map = FakeMelbourne().configuration().coupling_map basis_gates = FakeMelbourne().configuration().basis_gates initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]] new_circuit = transpile( circuit, basis_gates=basis_gates, coupling_map=coupling_map, initial_layout=initial_layout, ) qubit_indices = {bit: idx for idx, bit in enumerate(new_circuit.qubits)} for instruction in new_circuit.data: if isinstance(instruction.operation, CXGate): self.assertIn([qubit_indices[x] for x in instruction.qubits], coupling_map) def test_transpile_qft_grid(self): """Transpile pipeline can handle 8-qubit QFT on 14-qubit grid.""" qr = QuantumRegister(8) circuit = QuantumCircuit(qr) for i, _ in enumerate(qr): for j in range(i): circuit.cp(math.pi / float(2 ** (i - j)), qr[i], qr[j]) circuit.h(qr[i]) coupling_map = FakeMelbourne().configuration().coupling_map basis_gates = FakeMelbourne().configuration().basis_gates new_circuit = transpile(circuit, basis_gates=basis_gates, coupling_map=coupling_map) qubit_indices = {bit: idx for idx, bit in enumerate(new_circuit.qubits)} for instruction in new_circuit.data: if isinstance(instruction.operation, CXGate): self.assertIn([qubit_indices[x] for x in instruction.qubits], coupling_map) def test_already_mapped_1(self): """Circuit not remapped if matches topology. See: https://github.com/Qiskit/qiskit-terra/issues/342 """ backend = FakeRueschlikon() coupling_map = backend.configuration().coupling_map basis_gates = backend.configuration().basis_gates qr = QuantumRegister(16, "qr") cr = ClassicalRegister(16, "cr") qc = QuantumCircuit(qr, cr) qc.cx(qr[3], qr[14]) qc.cx(qr[5], qr[4]) qc.h(qr[9]) qc.cx(qr[9], qr[8]) qc.x(qr[11]) qc.cx(qr[3], qr[4]) qc.cx(qr[12], qr[11]) qc.cx(qr[13], qr[4]) qc.measure(qr, cr) new_qc = transpile( qc, coupling_map=coupling_map, basis_gates=basis_gates, initial_layout=Layout.generate_trivial_layout(qr), ) qubit_indices = {bit: idx for idx, bit in enumerate(new_qc.qubits)} cx_qubits = [instr.qubits for instr in new_qc.data if instr.operation.name == "cx"] cx_qubits_physical = [ [qubit_indices[ctrl], qubit_indices[tgt]] for [ctrl, tgt] in cx_qubits ] self.assertEqual( sorted(cx_qubits_physical), [[3, 4], [3, 14], [5, 4], [9, 8], [12, 11], [13, 4]] ) def test_already_mapped_via_layout(self): """Test that a manual layout that satisfies a coupling map does not get altered. See: https://github.com/Qiskit/qiskit-terra/issues/2036 circuit: .. parsed-literal:: ┌───┐ ┌───┐ ░ ┌─┐ qn_0: ┤ H ├──■────────────■──┤ H ├─░─┤M├─── -> 9 └───┘ │ │ └───┘ ░ └╥┘ qn_1: ───────┼────────────┼────────░──╫──── -> 6 │ │ ░ ║ qn_2: ───────┼────────────┼────────░──╫──── -> 5 │ │ ░ ║ qn_3: ───────┼────────────┼────────░──╫──── -> 0 │ │ ░ ║ qn_4: ───────┼────────────┼────────░──╫──── -> 1 ┌───┐┌─┴─┐┌──────┐┌─┴─┐┌───┐ ░ ║ ┌─┐ qn_5: ┤ H ├┤ X ├┤ P(2) ├┤ X ├┤ H ├─░──╫─┤M├ -> 4 └───┘└───┘└──────┘└───┘└───┘ ░ ║ └╥┘ cn: 2/════════════════════════════════╩══╩═ 0 1 device: 0 -- 1 -- 2 -- 3 -- 4 | | 5 -- 6 -- 7 -- 8 -- 9 | | 10 - 11 - 12 - 13 - 14 | | 15 - 16 - 17 - 18 - 19 """ basis_gates = ["u1", "u2", "u3", "cx", "id"] coupling_map = [ [0, 1], [0, 5], [1, 0], [1, 2], [2, 1], [2, 3], [3, 2], [3, 4], [4, 3], [4, 9], [5, 0], [5, 6], [5, 10], [6, 5], [6, 7], [7, 6], [7, 8], [7, 12], [8, 7], [8, 9], [9, 4], [9, 8], [9, 14], [10, 5], [10, 11], [10, 15], [11, 10], [11, 12], [12, 7], [12, 11], [12, 13], [13, 12], [13, 14], [14, 9], [14, 13], [14, 19], [15, 10], [15, 16], [16, 15], [16, 17], [17, 16], [17, 18], [18, 17], [18, 19], [19, 14], [19, 18], ] q = QuantumRegister(6, name="qn") c = ClassicalRegister(2, name="cn") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[5]) qc.cx(q[0], q[5]) qc.p(2, q[5]) qc.cx(q[0], q[5]) qc.h(q[0]) qc.h(q[5]) qc.barrier(q) qc.measure(q[0], c[0]) qc.measure(q[5], c[1]) initial_layout = [ q[3], q[4], None, None, q[5], q[2], q[1], None, None, q[0], None, None, None, None, None, None, None, None, None, None, ] new_qc = transpile( qc, coupling_map=coupling_map, basis_gates=basis_gates, initial_layout=initial_layout ) qubit_indices = {bit: idx for idx, bit in enumerate(new_qc.qubits)} cx_qubits = [instr.qubits for instr in new_qc.data if instr.operation.name == "cx"] cx_qubits_physical = [ [qubit_indices[ctrl], qubit_indices[tgt]] for [ctrl, tgt] in cx_qubits ] self.assertEqual(sorted(cx_qubits_physical), [[9, 4], [9, 4]]) def test_transpile_bell(self): """Test Transpile Bell. If all correct some should exists. """ backend = BasicAer.get_backend("qasm_simulator") qubit_reg = QuantumRegister(2, name="q") clbit_reg = ClassicalRegister(2, name="c") qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) circuits = transpile(qc, backend) self.assertIsInstance(circuits, QuantumCircuit) def test_transpile_one(self): """Test transpile a single circuit. Check that the top-level `transpile` function returns a single circuit.""" backend = BasicAer.get_backend("qasm_simulator") qubit_reg = QuantumRegister(2) clbit_reg = ClassicalRegister(2) qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) circuit = transpile(qc, backend) self.assertIsInstance(circuit, QuantumCircuit) def test_transpile_two(self): """Test transpile two circuits. Check that the transpiler returns a list of two circuits. """ backend = BasicAer.get_backend("qasm_simulator") qubit_reg = QuantumRegister(2) clbit_reg = ClassicalRegister(2) qubit_reg2 = QuantumRegister(2) clbit_reg2 = ClassicalRegister(2) qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) qc_extra = QuantumCircuit(qubit_reg, qubit_reg2, clbit_reg, clbit_reg2, name="extra") qc_extra.measure(qubit_reg, clbit_reg) circuits = transpile([qc, qc_extra], backend) self.assertIsInstance(circuits, list) self.assertEqual(len(circuits), 2) for circuit in circuits: self.assertIsInstance(circuit, QuantumCircuit) def test_transpile_singleton(self): """Test transpile a single-element list with a circuit. Check that `transpile` returns a single-element list. See https://github.com/Qiskit/qiskit-terra/issues/5260 """ backend = BasicAer.get_backend("qasm_simulator") qubit_reg = QuantumRegister(2) clbit_reg = ClassicalRegister(2) qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) circuits = transpile([qc], backend) self.assertIsInstance(circuits, list) self.assertEqual(len(circuits), 1) self.assertIsInstance(circuits[0], QuantumCircuit) def test_mapping_correction(self): """Test mapping works in previous failed case.""" backend = FakeRueschlikon() qr = QuantumRegister(name="qr", size=11) cr = ClassicalRegister(name="qc", size=11) circuit = QuantumCircuit(qr, cr) circuit.u(1.564784764685993, -1.2378965763410095, 2.9746763177861713, qr[3]) circuit.u(1.2269835563676523, 1.1932982847014162, -1.5597357740824318, qr[5]) circuit.cx(qr[5], qr[3]) circuit.p(0.856768317675967, qr[3]) circuit.u(-3.3911273825190915, 0.0, 0.0, qr[5]) circuit.cx(qr[3], qr[5]) circuit.u(2.159209321625547, 0.0, 0.0, qr[5]) circuit.cx(qr[5], qr[3]) circuit.u(0.30949966910232335, 1.1706201763833217, 1.738408691990081, qr[3]) circuit.u(1.9630571407274755, -0.6818742967975088, 1.8336534616728195, qr[5]) circuit.u(1.330181833806101, 0.6003162754946363, -3.181264980452862, qr[7]) circuit.u(0.4885914820775024, 3.133297443244865, -2.794457469189904, qr[8]) circuit.cx(qr[8], qr[7]) circuit.p(2.2196187596178616, qr[7]) circuit.u(-3.152367609631023, 0.0, 0.0, qr[8]) circuit.cx(qr[7], qr[8]) circuit.u(1.2646005789809263, 0.0, 0.0, qr[8]) circuit.cx(qr[8], qr[7]) circuit.u(0.7517780502091939, 1.2828514296564781, 1.6781179605443775, qr[7]) circuit.u(0.9267400575390405, 2.0526277839695153, 2.034202361069533, qr[8]) circuit.u(2.550304293455634, 3.8250017126569698, -2.1351609599720054, qr[1]) circuit.u(0.9566260876600556, -1.1147561503064538, 2.0571590492298797, qr[4]) circuit.cx(qr[4], qr[1]) circuit.p(2.1899329069137394, qr[1]) circuit.u(-1.8371715243173294, 0.0, 0.0, qr[4]) circuit.cx(qr[1], qr[4]) circuit.u(0.4717053496327104, 0.0, 0.0, qr[4]) circuit.cx(qr[4], qr[1]) circuit.u(2.3167620677708145, -1.2337330260253256, -0.5671322899563955, qr[1]) circuit.u(1.0468499525240678, 0.8680750644809365, -1.4083720073192485, qr[4]) circuit.u(2.4204244021892807, -2.211701932616922, 3.8297006565735883, qr[10]) circuit.u(0.36660280497727255, 3.273119149343493, -1.8003362351299388, qr[6]) circuit.cx(qr[6], qr[10]) circuit.p(1.067395863586385, qr[10]) circuit.u(-0.7044917541291232, 0.0, 0.0, qr[6]) circuit.cx(qr[10], qr[6]) circuit.u(2.1830003849921527, 0.0, 0.0, qr[6]) circuit.cx(qr[6], qr[10]) circuit.u(2.1538343756723917, 2.2653381826084606, -3.550087952059485, qr[10]) circuit.u(1.307627685019188, -0.44686656993522567, -2.3238098554327418, qr[6]) circuit.u(2.2046797998462906, 0.9732961754855436, 1.8527865921467421, qr[9]) circuit.u(2.1665254613904126, -1.281337664694577, -1.2424905413631209, qr[0]) circuit.cx(qr[0], qr[9]) circuit.p(2.6209599970201007, qr[9]) circuit.u(0.04680566321901303, 0.0, 0.0, qr[0]) circuit.cx(qr[9], qr[0]) circuit.u(1.7728411151289603, 0.0, 0.0, qr[0]) circuit.cx(qr[0], qr[9]) circuit.u(2.4866395967434443, 0.48684511243566697, -3.0069186877854728, qr[9]) circuit.u(1.7369112924273789, -4.239660866163805, 1.0623389015296005, qr[0]) circuit.barrier(qr) circuit.measure(qr, cr) circuits = transpile(circuit, backend) self.assertIsInstance(circuits, QuantumCircuit) def test_transpiler_layout_from_intlist(self): """A list of ints gives layout to correctly map circuit. virtual physical q1_0 - 4 ---[H]--- q2_0 - 5 q2_1 - 6 ---[H]--- q3_0 - 8 q3_1 - 9 q3_2 - 10 ---[H]--- """ qr1 = QuantumRegister(1, "qr1") qr2 = QuantumRegister(2, "qr2") qr3 = QuantumRegister(3, "qr3") qc = QuantumCircuit(qr1, qr2, qr3) qc.h(qr1[0]) qc.h(qr2[1]) qc.h(qr3[2]) layout = [4, 5, 6, 8, 9, 10] cmap = [ [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], ] new_circ = transpile( qc, backend=None, coupling_map=cmap, basis_gates=["u2"], initial_layout=layout ) qubit_indices = {bit: idx for idx, bit in enumerate(new_circ.qubits)} mapped_qubits = [] for instruction in new_circ.data: mapped_qubits.append(qubit_indices[instruction.qubits[0]]) self.assertEqual(mapped_qubits, [4, 6, 10]) def test_mapping_multi_qreg(self): """Test mapping works for multiple qregs.""" backend = FakeRueschlikon() qr = QuantumRegister(3, name="qr") qr2 = QuantumRegister(1, name="qr2") qr3 = QuantumRegister(4, name="qr3") cr = ClassicalRegister(3, name="cr") qc = QuantumCircuit(qr, qr2, qr3, cr) qc.h(qr[0]) qc.cx(qr[0], qr2[0]) qc.cx(qr[1], qr3[2]) qc.measure(qr, cr) circuits = transpile(qc, backend) self.assertIsInstance(circuits, QuantumCircuit) def test_transpile_circuits_diff_registers(self): """Transpile list of circuits with different qreg names.""" backend = FakeRueschlikon() circuits = [] for _ in range(2): qr = QuantumRegister(2) cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.measure(qr, cr) circuits.append(circuit) circuits = transpile(circuits, backend) self.assertIsInstance(circuits[0], QuantumCircuit) def test_wrong_initial_layout(self): """Test transpile with a bad initial layout.""" backend = FakeMelbourne() qubit_reg = QuantumRegister(2, name="q") clbit_reg = ClassicalRegister(2, name="c") qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) bad_initial_layout = [ QuantumRegister(3, "q")[0], QuantumRegister(3, "q")[1], QuantumRegister(3, "q")[2], ] with self.assertRaises(TranspilerError): transpile(qc, backend, initial_layout=bad_initial_layout) def test_parameterized_circuit_for_simulator(self): """Verify that a parameterized circuit can be transpiled for a simulator backend.""" qr = QuantumRegister(2, name="qr") qc = QuantumCircuit(qr) theta = Parameter("theta") qc.rz(theta, qr[0]) transpiled_qc = transpile(qc, backend=BasicAer.get_backend("qasm_simulator")) expected_qc = QuantumCircuit(qr) expected_qc.append(RZGate(theta), [qr[0]]) self.assertEqual(expected_qc, transpiled_qc) def test_parameterized_circuit_for_device(self): """Verify that a parameterized circuit can be transpiled for a device backend.""" qr = QuantumRegister(2, name="qr") qc = QuantumCircuit(qr) theta = Parameter("theta") qc.rz(theta, qr[0]) transpiled_qc = transpile( qc, backend=FakeMelbourne(), initial_layout=Layout.generate_trivial_layout(qr) ) qr = QuantumRegister(14, "q") expected_qc = QuantumCircuit(qr, global_phase=-1 * theta / 2.0) expected_qc.append(U1Gate(theta), [qr[0]]) self.assertEqual(expected_qc, transpiled_qc) def test_parameter_expression_circuit_for_simulator(self): """Verify that a circuit including expressions of parameters can be transpiled for a simulator backend.""" qr = QuantumRegister(2, name="qr") qc = QuantumCircuit(qr) theta = Parameter("theta") square = theta * theta qc.rz(square, qr[0]) transpiled_qc = transpile(qc, backend=BasicAer.get_backend("qasm_simulator")) expected_qc = QuantumCircuit(qr) expected_qc.append(RZGate(square), [qr[0]]) self.assertEqual(expected_qc, transpiled_qc) def test_parameter_expression_circuit_for_device(self): """Verify that a circuit including expressions of parameters can be transpiled for a device backend.""" qr = QuantumRegister(2, name="qr") qc = QuantumCircuit(qr) theta = Parameter("theta") square = theta * theta qc.rz(square, qr[0]) transpiled_qc = transpile( qc, backend=FakeMelbourne(), initial_layout=Layout.generate_trivial_layout(qr) ) qr = QuantumRegister(14, "q") expected_qc = QuantumCircuit(qr, global_phase=-1 * square / 2.0) expected_qc.append(U1Gate(square), [qr[0]]) self.assertEqual(expected_qc, transpiled_qc) def test_final_measurement_barrier_for_devices(self): """Verify BarrierBeforeFinalMeasurements pass is called in default pipeline for devices.""" qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm") circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "example.qasm")) layout = Layout.generate_trivial_layout(*circ.qregs) orig_pass = BarrierBeforeFinalMeasurements() with patch.object(BarrierBeforeFinalMeasurements, "run", wraps=orig_pass.run) as mock_pass: transpile( circ, coupling_map=FakeRueschlikon().configuration().coupling_map, initial_layout=layout, ) self.assertTrue(mock_pass.called) def test_do_not_run_gatedirection_with_symmetric_cm(self): """When the coupling map is symmetric, do not run GateDirection.""" qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm") circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "example.qasm")) layout = Layout.generate_trivial_layout(*circ.qregs) coupling_map = [] for node1, node2 in FakeRueschlikon().configuration().coupling_map: coupling_map.append([node1, node2]) coupling_map.append([node2, node1]) orig_pass = GateDirection(CouplingMap(coupling_map)) with patch.object(GateDirection, "run", wraps=orig_pass.run) as mock_pass: transpile(circ, coupling_map=coupling_map, initial_layout=layout) self.assertFalse(mock_pass.called) def test_optimize_to_nothing(self): """Optimize gates up to fixed point in the default pipeline See https://github.com/Qiskit/qiskit-terra/issues/2035 """ # ┌───┐ ┌───┐┌───┐┌───┐ ┌───┐ # q0_0: ┤ H ├──■──┤ X ├┤ Y ├┤ Z ├──■──┤ H ├──■────■── # └───┘┌─┴─┐└───┘└───┘└───┘┌─┴─┐└───┘┌─┴─┐┌─┴─┐ # q0_1: ─────┤ X ├───────────────┤ X ├─────┤ X ├┤ X ├ # └───┘ └───┘ └───┘└───┘ qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.h(qr[0]) circ.cx(qr[0], qr[1]) circ.x(qr[0]) circ.y(qr[0]) circ.z(qr[0]) circ.cx(qr[0], qr[1]) circ.h(qr[0]) circ.cx(qr[0], qr[1]) circ.cx(qr[0], qr[1]) after = transpile(circ, coupling_map=[[0, 1], [1, 0]], basis_gates=["u3", "u2", "u1", "cx"]) expected = QuantumCircuit(QuantumRegister(2, "q"), global_phase=-np.pi / 2) msg = f"after:\n{after}\nexpected:\n{expected}" self.assertEqual(after, expected, msg=msg) def test_pass_manager_empty(self): """Test passing an empty PassManager() to the transpiler. It should perform no transformations on the circuit. """ qr = QuantumRegister(2) circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) resources_before = circuit.count_ops() pass_manager = PassManager() out_circuit = pass_manager.run(circuit) resources_after = out_circuit.count_ops() self.assertDictEqual(resources_before, resources_after) def test_move_measurements(self): """Measurements applied AFTER swap mapping.""" backend = FakeRueschlikon() cmap = backend.configuration().coupling_map qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm") circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "move_measurements.qasm")) lay = [0, 1, 15, 2, 14, 3, 13, 4, 12, 5, 11, 6] out = transpile(circ, initial_layout=lay, coupling_map=cmap, routing_method="stochastic") out_dag = circuit_to_dag(out) meas_nodes = out_dag.named_nodes("measure") for meas_node in meas_nodes: is_last_measure = all( isinstance(after_measure, DAGOutNode) for after_measure in out_dag.quantum_successors(meas_node) ) self.assertTrue(is_last_measure) @data(0, 1, 2, 3) def test_init_resets_kept_preset_passmanagers(self, optimization_level): """Test initial resets kept at all preset transpilation levels""" num_qubits = 5 qc = QuantumCircuit(num_qubits) qc.reset(range(num_qubits)) num_resets = transpile(qc, optimization_level=optimization_level).count_ops()["reset"] self.assertEqual(num_resets, num_qubits) @data(0, 1, 2, 3) def test_initialize_reset_is_not_removed(self, optimization_level): """The reset in front of initializer should NOT be removed at beginning""" qr = QuantumRegister(1, "qr") qc = QuantumCircuit(qr) qc.initialize([1.0 / math.sqrt(2), 1.0 / math.sqrt(2)], [qr[0]]) qc.initialize([1.0 / math.sqrt(2), -1.0 / math.sqrt(2)], [qr[0]]) after = transpile(qc, basis_gates=["reset", "u3"], optimization_level=optimization_level) self.assertEqual(after.count_ops()["reset"], 2, msg=f"{after}\n does not have 2 resets.") def test_initialize_FakeMelbourne(self): """Test that the zero-state resets are remove in a device not supporting them.""" desired_vector = [1 / math.sqrt(2), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(2)] qr = QuantumRegister(3, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1], qr[2]]) out = transpile(qc, backend=FakeMelbourne()) out_dag = circuit_to_dag(out) reset_nodes = out_dag.named_nodes("reset") self.assertEqual(len(reset_nodes), 3) def test_non_standard_basis(self): """Test a transpilation with a non-standard basis""" qr1 = QuantumRegister(1, "q1") qr2 = QuantumRegister(2, "q2") qr3 = QuantumRegister(3, "q3") qc = QuantumCircuit(qr1, qr2, qr3) qc.h(qr1[0]) qc.h(qr2[1]) qc.h(qr3[2]) layout = [4, 5, 6, 8, 9, 10] cmap = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] circuit = transpile( qc, backend=None, coupling_map=cmap, basis_gates=["h"], initial_layout=layout ) dag_circuit = circuit_to_dag(circuit) resources_after = dag_circuit.count_ops() self.assertEqual({"h": 3}, resources_after) def test_hadamard_to_rot_gates(self): """Test a transpilation from H to Rx, Ry gates""" qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.h(0) expected = QuantumCircuit(qr, global_phase=np.pi / 2) expected.append(RYGate(theta=np.pi / 2), [0]) expected.append(RXGate(theta=np.pi), [0]) circuit = transpile(qc, basis_gates=["rx", "ry"], optimization_level=0) self.assertEqual(circuit, expected) def test_basis_subset(self): """Test a transpilation with a basis subset of the standard basis""" qr = QuantumRegister(1, "q1") qc = QuantumCircuit(qr) qc.h(qr[0]) qc.x(qr[0]) qc.t(qr[0]) layout = [4] cmap = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] circuit = transpile( qc, backend=None, coupling_map=cmap, basis_gates=["u3"], initial_layout=layout ) dag_circuit = circuit_to_dag(circuit) resources_after = dag_circuit.count_ops() self.assertEqual({"u3": 1}, resources_after) def test_check_circuit_width(self): """Verify transpilation of circuit with virtual qubits greater than physical qubits raises error""" cmap = [ [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], ] qc = QuantumCircuit(15, 15) with self.assertRaises(TranspilerError): transpile(qc, coupling_map=cmap) @data(0, 1, 2, 3) def test_ccx_routing_method_none(self, optimization_level): """CCX without routing method.""" qc = QuantumCircuit(3) qc.cx(0, 1) qc.cx(1, 2) out = transpile( qc, routing_method="none", basis_gates=["u", "cx"], initial_layout=[0, 1, 2], seed_transpiler=0, coupling_map=[[0, 1], [1, 2]], optimization_level=optimization_level, ) self.assertTrue(Operator(qc).equiv(out)) @data(0, 1, 2, 3) def test_ccx_routing_method_none_failed(self, optimization_level): """CCX without routing method cannot be routed.""" qc = QuantumCircuit(3) qc.ccx(0, 1, 2) with self.assertRaises(TranspilerError): transpile( qc, routing_method="none", basis_gates=["u", "cx"], initial_layout=[0, 1, 2], seed_transpiler=0, coupling_map=[[0, 1], [1, 2]], optimization_level=optimization_level, ) @data(0, 1, 2, 3) def test_ms_unrolls_to_cx(self, optimization_level): """Verify a Rx,Ry,Rxx circuit transpile to a U3,CX target.""" qc = QuantumCircuit(2) qc.rx(math.pi / 2, 0) qc.ry(math.pi / 4, 1) qc.rxx(math.pi / 4, 0, 1) out = transpile(qc, basis_gates=["u3", "cx"], optimization_level=optimization_level) self.assertTrue(Operator(qc).equiv(out)) @data(0, 1, 2, 3) def test_ms_can_target_ms(self, optimization_level): """Verify a Rx,Ry,Rxx circuit can transpile to an Rx,Ry,Rxx target.""" qc = QuantumCircuit(2) qc.rx(math.pi / 2, 0) qc.ry(math.pi / 4, 1) qc.rxx(math.pi / 4, 0, 1) out = transpile(qc, basis_gates=["rx", "ry", "rxx"], optimization_level=optimization_level) self.assertTrue(Operator(qc).equiv(out)) @data(0, 1, 2, 3) def test_cx_can_target_ms(self, optimization_level): """Verify a U3,CX circuit can transpiler to a Rx,Ry,Rxx target.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.rz(math.pi / 4, [0, 1]) out = transpile(qc, basis_gates=["rx", "ry", "rxx"], optimization_level=optimization_level) self.assertTrue(Operator(qc).equiv(out)) @data(0, 1, 2, 3) def test_measure_doesnt_unroll_ms(self, optimization_level): """Verify a measure doesn't cause an Rx,Ry,Rxx circuit to unroll to U3,CX.""" qc = QuantumCircuit(2, 2) qc.rx(math.pi / 2, 0) qc.ry(math.pi / 4, 1) qc.rxx(math.pi / 4, 0, 1) qc.measure([0, 1], [0, 1]) out = transpile(qc, basis_gates=["rx", "ry", "rxx"], optimization_level=optimization_level) self.assertEqual(qc, out) @data( ["cx", "u3"], ["cz", "u3"], ["cz", "rx", "rz"], ["rxx", "rx", "ry"], ["iswap", "rx", "rz"], ) def test_block_collection_runs_for_non_cx_bases(self, basis_gates): """Verify block collection is run when a single two qubit gate is in the basis.""" twoq_gate, *_ = basis_gates qc = QuantumCircuit(2) qc.cx(0, 1) qc.cx(1, 0) qc.cx(0, 1) qc.cx(0, 1) out = transpile(qc, basis_gates=basis_gates, optimization_level=3) self.assertLessEqual(out.count_ops()[twoq_gate], 2) @unpack @data( (["u3", "cx"], {"u3": 1, "cx": 1}), (["rx", "rz", "iswap"], {"rx": 6, "rz": 12, "iswap": 2}), (["rx", "ry", "rxx"], {"rx": 6, "ry": 5, "rxx": 1}), ) def test_block_collection_reduces_1q_gate(self, basis_gates, gate_counts): """For synthesis to non-U3 bases, verify we minimize 1q gates.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) out = transpile(qc, basis_gates=basis_gates, optimization_level=3) self.assertTrue(Operator(out).equiv(qc)) self.assertTrue(set(out.count_ops()).issubset(basis_gates)) for basis_gate in basis_gates: self.assertLessEqual(out.count_ops()[basis_gate], gate_counts[basis_gate]) @combine( optimization_level=[0, 1, 2, 3], basis_gates=[ ["u3", "cx"], ["rx", "rz", "iswap"], ["rx", "ry", "rxx"], ], ) def test_translation_method_synthesis(self, optimization_level, basis_gates): """Verify translation_method='synthesis' gets to the basis.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) out = transpile( qc, translation_method="synthesis", basis_gates=basis_gates, optimization_level=optimization_level, ) self.assertTrue(Operator(out).equiv(qc)) self.assertTrue(set(out.count_ops()).issubset(basis_gates)) def test_transpiled_custom_gates_calibration(self): """Test if transpiled calibrations is equal to custom gates circuit calibrations.""" custom_180 = Gate("mycustom", 1, [3.14]) custom_90 = Gate("mycustom", 1, [1.57]) circ = QuantumCircuit(2) circ.append(custom_180, [0]) circ.append(custom_90, [1]) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) with pulse.build() as q1_y90: pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), pulse.DriveChannel(1)) # Add calibration circ.add_calibration(custom_180, [0], q0_x180) circ.add_calibration(custom_90, [1], q1_y90) backend = FakeBoeblingen() transpiled_circuit = transpile( circ, backend=backend, layout_method="trivial", ) self.assertEqual(transpiled_circuit.calibrations, circ.calibrations) self.assertEqual(list(transpiled_circuit.count_ops().keys()), ["mycustom"]) self.assertEqual(list(transpiled_circuit.count_ops().values()), [2]) def test_transpiled_basis_gates_calibrations(self): """Test if the transpiled calibrations is equal to basis gates circuit calibrations.""" circ = QuantumCircuit(2) circ.h(0) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) # Add calibration circ.add_calibration("h", [0], q0_x180) backend = FakeBoeblingen() transpiled_circuit = transpile( circ, backend=backend, ) self.assertEqual(transpiled_circuit.calibrations, circ.calibrations) def test_transpile_calibrated_custom_gate_on_diff_qubit(self): """Test if the custom, non calibrated gate raises QiskitError.""" custom_180 = Gate("mycustom", 1, [3.14]) circ = QuantumCircuit(2) circ.append(custom_180, [0]) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) # Add calibration circ.add_calibration(custom_180, [1], q0_x180) backend = FakeBoeblingen() with self.assertRaises(QiskitError): transpile(circ, backend=backend, layout_method="trivial") def test_transpile_calibrated_nonbasis_gate_on_diff_qubit(self): """Test if the non-basis gates are transpiled if they are on different qubit that is not calibrated.""" circ = QuantumCircuit(2) circ.h(0) circ.h(1) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) # Add calibration circ.add_calibration("h", [1], q0_x180) backend = FakeBoeblingen() transpiled_circuit = transpile( circ, backend=backend, ) self.assertEqual(transpiled_circuit.calibrations, circ.calibrations) self.assertEqual(set(transpiled_circuit.count_ops().keys()), {"u2", "h"}) def test_transpile_subset_of_calibrated_gates(self): """Test transpiling a circuit with both basis gate (not-calibrated) and a calibrated gate on different qubits.""" x_180 = Gate("mycustom", 1, [3.14]) circ = QuantumCircuit(2) circ.h(0) circ.append(x_180, [0]) circ.h(1) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) circ.add_calibration(x_180, [0], q0_x180) circ.add_calibration("h", [1], q0_x180) # 'h' is calibrated on qubit 1 transpiled_circ = transpile(circ, FakeBoeblingen(), layout_method="trivial") self.assertEqual(set(transpiled_circ.count_ops().keys()), {"u2", "mycustom", "h"}) def test_parameterized_calibrations_transpile(self): """Check that gates can be matched to their calibrations before and after parameter assignment.""" tau = Parameter("tau") circ = QuantumCircuit(3, 3) circ.append(Gate("rxt", 1, [2 * 3.14 * tau]), [0]) def q0_rxt(tau): with pulse.build() as q0_rxt: pulse.play(pulse.library.Gaussian(20, 0.4 * tau, 3.0), pulse.DriveChannel(0)) return q0_rxt circ.add_calibration("rxt", [0], q0_rxt(tau), [2 * 3.14 * tau]) transpiled_circ = transpile(circ, FakeBoeblingen(), layout_method="trivial") self.assertEqual(set(transpiled_circ.count_ops().keys()), {"rxt"}) circ = circ.assign_parameters({tau: 1}) transpiled_circ = transpile(circ, FakeBoeblingen(), layout_method="trivial") self.assertEqual(set(transpiled_circ.count_ops().keys()), {"rxt"}) def test_inst_durations_from_calibrations(self): """Test that circuit calibrations can be used instead of explicitly supplying inst_durations. """ qc = QuantumCircuit(2) qc.append(Gate("custom", 1, []), [0]) with pulse.build() as cal: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) qc.add_calibration("custom", [0], cal) out = transpile(qc, scheduling_method="alap") self.assertEqual(out.duration, cal.duration) @data(0, 1, 2, 3) def test_multiqubit_gates_calibrations(self, opt_level): """Test multiqubit gate > 2q with calibrations works Adapted from issue description in https://github.com/Qiskit/qiskit-terra/issues/6572 """ circ = QuantumCircuit(5) custom_gate = Gate("my_custom_gate", 5, []) circ.append(custom_gate, [0, 1, 2, 3, 4]) circ.measure_all() backend = FakeBoeblingen() with pulse.build(backend, name="custom") as my_schedule: pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(1) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(2) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(3) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(4) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(1) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(2) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(3) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(4) ) circ.add_calibration("my_custom_gate", [0, 1, 2, 3, 4], my_schedule, []) trans_circ = transpile(circ, backend, optimization_level=opt_level, layout_method="trivial") self.assertEqual({"measure": 5, "my_custom_gate": 1, "barrier": 1}, trans_circ.count_ops()) @data(0, 1, 2, 3) def test_circuit_with_delay(self, optimization_level): """Verify a circuit with delay can transpile to a scheduled circuit.""" qc = QuantumCircuit(2) qc.h(0) qc.delay(500, 1) qc.cx(0, 1) out = transpile( qc, scheduling_method="alap", basis_gates=["h", "cx"], instruction_durations=[("h", 0, 200), ("cx", [0, 1], 700)], optimization_level=optimization_level, ) self.assertEqual(out.duration, 1200) def test_delay_converts_to_dt(self): """Test that a delay instruction is converted to units of dt given a backend.""" qc = QuantumCircuit(2) qc.delay(1000, [0], unit="us") backend = FakeRueschlikon() backend.configuration().dt = 0.5e-6 out = transpile([qc, qc], backend) self.assertEqual(out[0].data[0].operation.unit, "dt") self.assertEqual(out[1].data[0].operation.unit, "dt") out = transpile(qc, dt=1e-9) self.assertEqual(out.data[0].operation.unit, "dt") def test_scheduling_backend_v2(self): """Test that scheduling method works with Backendv2.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() backend = FakeMumbaiV2() out = transpile([qc, qc], backend, scheduling_method="alap") self.assertIn("delay", out[0].count_ops()) self.assertIn("delay", out[1].count_ops()) @data(1, 2, 3) def test_no_infinite_loop(self, optimization_level): """Verify circuit cost always descends and optimization does not flip flop indefinitely.""" qc = QuantumCircuit(1) qc.ry(0.2, 0) out = transpile( qc, basis_gates=["id", "p", "sx", "cx"], optimization_level=optimization_level ) # Expect a -pi/2 global phase for the U3 to RZ/SX conversion, and # a -0.5 * theta phase for RZ to P twice, once at theta, and once at 3 pi # for the second and third RZ gates in the U3 decomposition. expected = QuantumCircuit( 1, global_phase=-np.pi / 2 - 0.5 * (-0.2 + np.pi) - 0.5 * 3 * np.pi ) expected.p(-np.pi, 0) expected.sx(0) expected.p(np.pi - 0.2, 0) expected.sx(0) error_message = ( f"\nOutput circuit:\n{out!s}\n{Operator(out).data}\n" f"Expected circuit:\n{expected!s}\n{Operator(expected).data}" ) self.assertEqual(out, expected, error_message) @data(0, 1, 2, 3) def test_transpile_preserves_circuit_metadata(self, optimization_level): """Verify that transpile preserves circuit metadata in the output.""" circuit = QuantumCircuit(2, metadata={"experiment_id": "1234", "execution_number": 4}) circuit.h(0) circuit.cx(0, 1) cmap = [ [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], ] res = transpile( circuit, basis_gates=["id", "p", "sx", "cx"], coupling_map=cmap, optimization_level=optimization_level, ) self.assertEqual(circuit.metadata, res.metadata) @data(0, 1, 2, 3) def test_transpile_optional_registers(self, optimization_level): """Verify transpile accepts circuits without registers end-to-end.""" qubits = [Qubit() for _ in range(3)] clbits = [Clbit() for _ in range(3)] qc = QuantumCircuit(qubits, clbits) qc.h(0) qc.cx(0, 1) qc.cx(1, 2) qc.measure(qubits, clbits) out = transpile(qc, FakeBoeblingen(), optimization_level=optimization_level) self.assertEqual(len(out.qubits), FakeBoeblingen().configuration().num_qubits) self.assertEqual(len(out.clbits), len(clbits)) @data(0, 1, 2, 3) def test_translate_ecr_basis(self, optimization_level): """Verify that rewriting in ECR basis is efficient.""" circuit = QuantumCircuit(2) circuit.append(random_unitary(4, seed=1), [0, 1]) circuit.barrier() circuit.cx(0, 1) circuit.barrier() circuit.swap(0, 1) circuit.barrier() circuit.iswap(0, 1) res = transpile(circuit, basis_gates=["u", "ecr"], optimization_level=optimization_level) self.assertEqual(res.count_ops()["ecr"], 9) self.assertTrue(Operator(res).equiv(circuit)) def test_optimize_ecr_basis(self): """Test highest optimization level can optimize over ECR.""" circuit = QuantumCircuit(2) circuit.swap(1, 0) circuit.iswap(0, 1) res = transpile(circuit, basis_gates=["u", "ecr"], optimization_level=3) self.assertEqual(res.count_ops()["ecr"], 1) self.assertTrue(Operator(res).equiv(circuit)) def test_approximation_degree_invalid(self): """Test invalid approximation degree raises.""" circuit = QuantumCircuit(2) circuit.swap(0, 1) with self.assertRaises(QiskitError): transpile(circuit, basis_gates=["u", "cz"], approximation_degree=1.1) def test_approximation_degree(self): """Test more approximation gives lower-cost circuit.""" circuit = QuantumCircuit(2) circuit.swap(0, 1) circuit.h(0) circ_10 = transpile( circuit, basis_gates=["u", "cx"], translation_method="synthesis", approximation_degree=0.1, ) circ_90 = transpile( circuit, basis_gates=["u", "cx"], translation_method="synthesis", approximation_degree=0.9, ) self.assertLess(circ_10.depth(), circ_90.depth()) @data(0, 1, 2, 3) def test_synthesis_translation_method_with_single_qubit_gates(self, optimization_level): """Test that synthesis basis translation works for solely 1q circuit""" qc = QuantumCircuit(3) qc.h(0) qc.h(1) qc.h(2) res = transpile( qc, basis_gates=["id", "rz", "x", "sx", "cx"], translation_method="synthesis", optimization_level=optimization_level, ) expected = QuantumCircuit(3, global_phase=3 * np.pi / 4) expected.rz(np.pi / 2, 0) expected.rz(np.pi / 2, 1) expected.rz(np.pi / 2, 2) expected.sx(0) expected.sx(1) expected.sx(2) expected.rz(np.pi / 2, 0) expected.rz(np.pi / 2, 1) expected.rz(np.pi / 2, 2) self.assertEqual(res, expected) @data(0, 1, 2, 3) def test_synthesis_translation_method_with_gates_outside_basis(self, optimization_level): """Test that synthesis translation works for circuits with single gates outside bassis""" qc = QuantumCircuit(2) qc.swap(0, 1) res = transpile( qc, basis_gates=["id", "rz", "x", "sx", "cx"], translation_method="synthesis", optimization_level=optimization_level, ) if optimization_level != 3: self.assertTrue(Operator(qc).equiv(res)) self.assertNotIn("swap", res.count_ops()) else: # Optimization level 3 eliminates the pointless swap self.assertEqual(res, QuantumCircuit(2)) @data(0, 1, 2, 3) def test_target_ideal_gates(self, opt_level): """Test that transpile() with a custom ideal sim target works.""" theta = Parameter("θ") phi = Parameter("ϕ") lam = Parameter("λ") target = Target(num_qubits=2) target.add_instruction(UGate(theta, phi, lam), {(0,): None, (1,): None}) target.add_instruction(CXGate(), {(0, 1): None}) target.add_instruction(Measure(), {(0,): None, (1,): None}) qubit_reg = QuantumRegister(2, name="q") clbit_reg = ClassicalRegister(2, name="c") qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) result = transpile(qc, target=target, optimization_level=opt_level) self.assertEqual(Operator.from_circuit(result), Operator.from_circuit(qc)) @data(0, 1, 2, 3) def test_transpile_with_custom_control_flow_target(self, opt_level): """Test transpile() with a target and constrol flow ops.""" target = FakeMumbaiV2().target target.add_instruction(ForLoopOp, name="for_loop") target.add_instruction(WhileLoopOp, name="while_loop") target.add_instruction(IfElseOp, name="if_else") target.add_instruction(SwitchCaseOp, name="switch_case") circuit = QuantumCircuit(6, 1) circuit.h(0) circuit.measure(0, 0) circuit.cx(0, 1) circuit.cz(0, 2) circuit.append(CustomCX(), [1, 2], []) with circuit.for_loop((1,)): circuit.cx(0, 1) circuit.cz(0, 2) circuit.append(CustomCX(), [1, 2], []) with circuit.if_test((circuit.clbits[0], True)) as else_: circuit.cx(0, 1) circuit.cz(0, 2) circuit.append(CustomCX(), [1, 2], []) with else_: circuit.cx(3, 4) circuit.cz(3, 5) circuit.append(CustomCX(), [4, 5], []) with circuit.while_loop((circuit.clbits[0], True)): circuit.cx(3, 4) circuit.cz(3, 5) circuit.append(CustomCX(), [4, 5], []) with circuit.switch(circuit.cregs[0]) as case_: with case_(0): circuit.cx(0, 1) circuit.cz(0, 2) circuit.append(CustomCX(), [1, 2], []) with case_(1): circuit.cx(1, 2) circuit.cz(1, 3) circuit.append(CustomCX(), [2, 3], []) transpiled = transpile( circuit, optimization_level=opt_level, target=target, seed_transpiler=12434 ) # Tests of the complete validity of a circuit are mostly done at the indiviual pass level; # here we're just checking that various passes do appear to have run. self.assertIsInstance(transpiled, QuantumCircuit) # Assert layout ran. self.assertIsNot(getattr(transpiled, "_layout", None), None) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: qargs = tuple(qubit_mapping[x] for x in instruction.qubits) self.assertTrue(target.instruction_supported(instruction.operation.name, qargs)) if isinstance(instruction.operation, ControlFlowOp): for block in instruction.operation.blocks: new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) # Assert unrolling ran. self.assertNotIsInstance(instruction.operation, CustomCX) # Assert translation ran. self.assertNotIsInstance(instruction.operation, CZGate) # Assert routing ran. _visit_block( transpiled, qubit_mapping={qubit: index for index, qubit in enumerate(transpiled.qubits)}, ) @data(1, 2, 3) def test_transpile_identity_circuit_no_target(self, opt_level): """Test circuit equivalent to identity is optimized away for all optimization levels >0. Reproduce taken from https://github.com/Qiskit/qiskit-terra/issues/9217 """ qr1 = QuantumRegister(3, "state") qr2 = QuantumRegister(2, "ancilla") cr = ClassicalRegister(2, "c") qc = QuantumCircuit(qr1, qr2, cr) qc.h(qr1[0]) qc.cx(qr1[0], qr1[1]) qc.cx(qr1[1], qr1[2]) qc.cx(qr1[1], qr1[2]) qc.cx(qr1[0], qr1[1]) qc.h(qr1[0]) empty_qc = QuantumCircuit(qr1, qr2, cr) result = transpile(qc, optimization_level=opt_level) self.assertEqual(empty_qc, result) @data(0, 1, 2, 3) def test_initial_layout_with_loose_qubits(self, opt_level): """Regression test of gh-10125.""" qc = QuantumCircuit([Qubit(), Qubit()]) qc.cx(0, 1) transpiled = transpile(qc, initial_layout=[1, 0], optimization_level=opt_level) self.assertIsNotNone(transpiled.layout) self.assertEqual( transpiled.layout.initial_layout, Layout({0: qc.qubits[1], 1: qc.qubits[0]}) ) @data(0, 1, 2, 3) def test_initial_layout_with_overlapping_qubits(self, opt_level): """Regression test of gh-10125.""" qr1 = QuantumRegister(2, "qr1") qr2 = QuantumRegister(bits=qr1[:]) qc = QuantumCircuit(qr1, qr2) qc.cx(0, 1) transpiled = transpile(qc, initial_layout=[1, 0], optimization_level=opt_level) self.assertIsNotNone(transpiled.layout) self.assertEqual( transpiled.layout.initial_layout, Layout({0: qc.qubits[1], 1: qc.qubits[0]}) ) @combine(opt_level=[0, 1, 2, 3], basis=[["rz", "x"], ["rx", "z"], ["rz", "y"], ["ry", "x"]]) def test_paulis_to_constrained_1q_basis(self, opt_level, basis): """Test that Pauli-gate circuits can be transpiled to constrained 1q bases that do not contain any root-Pauli gates.""" qc = QuantumCircuit(1) qc.x(0) qc.barrier() qc.y(0) qc.barrier() qc.z(0) transpiled = transpile(qc, basis_gates=basis, optimization_level=opt_level) self.assertGreaterEqual(set(basis) | {"barrier"}, transpiled.count_ops().keys()) self.assertEqual(Operator(qc), Operator(transpiled)) @ddt class TestPostTranspileIntegration(QiskitTestCase): """Test that the output of `transpile` is usable in various other integration contexts.""" def _regular_circuit(self): a = Parameter("a") regs = [ QuantumRegister(2, name="q0"), QuantumRegister(3, name="q1"), ClassicalRegister(2, name="c0"), ] bits = [Qubit(), Qubit(), Clbit()] base = QuantumCircuit(*regs, bits) base.h(0) base.measure(0, 0) base.cx(0, 1) base.cz(0, 2) base.cz(0, 3) base.cz(1, 4) base.cx(1, 5) base.measure(1, 1) base.append(CustomCX(), [3, 6]) base.append(CustomCX(), [5, 4]) base.append(CustomCX(), [5, 3]) base.append(CustomCX(), [2, 4]).c_if(base.cregs[0], 3) base.ry(a, 4) base.measure(4, 2) return base def _control_flow_circuit(self): a = Parameter("a") regs = [ QuantumRegister(2, name="q0"), QuantumRegister(3, name="q1"), ClassicalRegister(2, name="c0"), ] bits = [Qubit(), Qubit(), Clbit()] base = QuantumCircuit(*regs, bits) base.h(0) base.measure(0, 0) with base.if_test((base.cregs[0], 1)) as else_: base.cx(0, 1) base.cz(0, 2) base.cz(0, 3) with else_: base.cz(1, 4) with base.for_loop((1, 2)): base.cx(1, 5) base.measure(2, 2) with base.while_loop((2, False)): base.append(CustomCX(), [3, 6]) base.append(CustomCX(), [5, 4]) base.append(CustomCX(), [5, 3]) base.append(CustomCX(), [2, 4]) base.ry(a, 4) base.measure(4, 2) with base.switch(base.cregs[0]) as case_: with case_(0, 1): base.cz(3, 5) with case_(case_.DEFAULT): base.cz(1, 4) base.append(CustomCX(), [2, 4]) base.append(CustomCX(), [3, 4]) return base def _control_flow_expr_circuit(self): a = Parameter("a") regs = [ QuantumRegister(2, name="q0"), QuantumRegister(3, name="q1"), ClassicalRegister(2, name="c0"), ] bits = [Qubit(), Qubit(), Clbit()] base = QuantumCircuit(*regs, bits) base.h(0) base.measure(0, 0) with base.if_test(expr.equal(base.cregs[0], 1)) as else_: base.cx(0, 1) base.cz(0, 2) base.cz(0, 3) with else_: base.cz(1, 4) with base.for_loop((1, 2)): base.cx(1, 5) base.measure(2, 2) with base.while_loop(expr.logic_not(bits[2])): base.append(CustomCX(), [3, 6]) base.append(CustomCX(), [5, 4]) base.append(CustomCX(), [5, 3]) base.append(CustomCX(), [2, 4]) base.ry(a, 4) base.measure(4, 2) with base.switch(expr.bit_and(base.cregs[0], 2)) as case_: with case_(0, 1): base.cz(3, 5) with case_(case_.DEFAULT): base.cz(1, 4) base.append(CustomCX(), [2, 4]) base.append(CustomCX(), [3, 4]) return base @data(0, 1, 2, 3) def test_qpy_roundtrip(self, optimization_level): """Test that the output of a transpiled circuit can be round-tripped through QPY.""" transpiled = transpile( self._regular_circuit(), backend=FakeMelbourne(), optimization_level=optimization_level, seed_transpiler=2022_10_17, ) # Round-tripping the layout is out-of-scope for QPY while it's a private attribute. transpiled._layout = None buffer = io.BytesIO() qpy.dump(transpiled, buffer) buffer.seek(0) round_tripped = qpy.load(buffer)[0] self.assertEqual(round_tripped, transpiled) @data(0, 1, 2, 3) def test_qpy_roundtrip_backendv2(self, optimization_level): """Test that the output of a transpiled circuit can be round-tripped through QPY.""" transpiled = transpile( self._regular_circuit(), backend=FakeMumbaiV2(), optimization_level=optimization_level, seed_transpiler=2022_10_17, ) # Round-tripping the layout is out-of-scope for QPY while it's a private attribute. transpiled._layout = None buffer = io.BytesIO() qpy.dump(transpiled, buffer) buffer.seek(0) round_tripped = qpy.load(buffer)[0] self.assertEqual(round_tripped, transpiled) @data(0, 1, 2, 3) def test_qpy_roundtrip_control_flow(self, optimization_level): """Test that the output of a transpiled circuit with control flow can be round-tripped through QPY.""" if optimization_level == 3 and sys.platform == "win32": self.skipTest( "This test case triggers a bug in the eigensolver routine on windows. " "See #10345 for more details." ) backend = FakeMelbourne() transpiled = transpile( self._control_flow_circuit(), backend=backend, basis_gates=backend.configuration().basis_gates + ["if_else", "for_loop", "while_loop", "switch_case"], optimization_level=optimization_level, seed_transpiler=2022_10_17, ) # Round-tripping the layout is out-of-scope for QPY while it's a private attribute. transpiled._layout = None buffer = io.BytesIO() qpy.dump(transpiled, buffer) buffer.seek(0) round_tripped = qpy.load(buffer)[0] self.assertEqual(round_tripped, transpiled) @data(0, 1, 2, 3) def test_qpy_roundtrip_control_flow_backendv2(self, optimization_level): """Test that the output of a transpiled circuit with control flow can be round-tripped through QPY.""" backend = FakeMumbaiV2() backend.target.add_instruction(IfElseOp, name="if_else") backend.target.add_instruction(ForLoopOp, name="for_loop") backend.target.add_instruction(WhileLoopOp, name="while_loop") backend.target.add_instruction(SwitchCaseOp, name="switch_case") transpiled = transpile( self._control_flow_circuit(), backend=backend, optimization_level=optimization_level, seed_transpiler=2022_10_17, ) # Round-tripping the layout is out-of-scope for QPY while it's a private attribute. transpiled._layout = None buffer = io.BytesIO() qpy.dump(transpiled, buffer) buffer.seek(0) round_tripped = qpy.load(buffer)[0] self.assertEqual(round_tripped, transpiled) @data(0, 1, 2, 3) def test_qpy_roundtrip_control_flow_expr(self, optimization_level): """Test that the output of a transpiled circuit with control flow including `Expr` nodes can be round-tripped through QPY.""" if optimization_level == 3 and sys.platform == "win32": self.skipTest( "This test case triggers a bug in the eigensolver routine on windows. " "See #10345 for more details." ) backend = FakeMelbourne() transpiled = transpile( self._control_flow_expr_circuit(), backend=backend, basis_gates=backend.configuration().basis_gates + ["if_else", "for_loop", "while_loop", "switch_case"], optimization_level=optimization_level, seed_transpiler=2023_07_26, ) buffer = io.BytesIO() qpy.dump(transpiled, buffer) buffer.seek(0) round_tripped = qpy.load(buffer)[0] self.assertEqual(round_tripped, transpiled) @data(0, 1, 2, 3) def test_qpy_roundtrip_control_flow_expr_backendv2(self, optimization_level): """Test that the output of a transpiled circuit with control flow including `Expr` nodes can be round-tripped through QPY.""" backend = FakeMumbaiV2() backend.target.add_instruction(IfElseOp, name="if_else") backend.target.add_instruction(ForLoopOp, name="for_loop") backend.target.add_instruction(WhileLoopOp, name="while_loop") backend.target.add_instruction(SwitchCaseOp, name="switch_case") transpiled = transpile( self._control_flow_circuit(), backend=backend, optimization_level=optimization_level, seed_transpiler=2023_07_26, ) buffer = io.BytesIO() qpy.dump(transpiled, buffer) buffer.seek(0) round_tripped = qpy.load(buffer)[0] self.assertEqual(round_tripped, transpiled) @data(0, 1, 2, 3) def test_qasm3_output(self, optimization_level): """Test that the output of a transpiled circuit can be dumped into OpenQASM 3.""" transpiled = transpile( self._regular_circuit(), backend=FakeMelbourne(), optimization_level=optimization_level, seed_transpiler=2022_10_17, ) # TODO: There's not a huge amount we can sensibly test for the output here until we can # round-trip the OpenQASM 3 back into a Terra circuit. Mostly we're concerned that the dump # itself doesn't throw an error, though. self.assertIsInstance(qasm3.dumps(transpiled).strip(), str) @data(0, 1, 2, 3) def test_qasm3_output_control_flow(self, optimization_level): """Test that the output of a transpiled circuit with control flow can be dumped into OpenQASM 3.""" backend = FakeMumbaiV2() backend.target.add_instruction(IfElseOp, name="if_else") backend.target.add_instruction(ForLoopOp, name="for_loop") backend.target.add_instruction(WhileLoopOp, name="while_loop") backend.target.add_instruction(SwitchCaseOp, name="switch_case") transpiled = transpile( self._control_flow_circuit(), backend=backend, optimization_level=optimization_level, seed_transpiler=2022_10_17, ) # TODO: There's not a huge amount we can sensibly test for the output here until we can # round-trip the OpenQASM 3 back into a Terra circuit. Mostly we're concerned that the dump # itself doesn't throw an error, though. self.assertIsInstance( qasm3.dumps(transpiled, experimental=qasm3.ExperimentalFeatures.SWITCH_CASE_V1).strip(), str, ) @data(0, 1, 2, 3) def test_qasm3_output_control_flow_expr(self, optimization_level): """Test that the output of a transpiled circuit with control flow and `Expr` nodes can be dumped into OpenQASM 3.""" backend = FakeMumbaiV2() backend.target.add_instruction(IfElseOp, name="if_else") backend.target.add_instruction(ForLoopOp, name="for_loop") backend.target.add_instruction(WhileLoopOp, name="while_loop") backend.target.add_instruction(SwitchCaseOp, name="switch_case") transpiled = transpile( self._control_flow_circuit(), backend=backend, optimization_level=optimization_level, seed_transpiler=2023_07_26, ) # TODO: There's not a huge amount we can sensibly test for the output here until we can # round-trip the OpenQASM 3 back into a Terra circuit. Mostly we're concerned that the dump # itself doesn't throw an error, though. self.assertIsInstance( qasm3.dumps(transpiled, experimental=qasm3.ExperimentalFeatures.SWITCH_CASE_V1).strip(), str, ) @data(0, 1, 2, 3) def test_transpile_target_no_measurement_error(self, opt_level): """Test that transpile with a target which contains ideal measurement works Reproduce from https://github.com/Qiskit/qiskit-terra/issues/8969 """ target = Target() target.add_instruction(Measure(), {(0,): None}) qc = QuantumCircuit(1, 1) qc.measure(0, 0) res = transpile(qc, target=target, optimization_level=opt_level) self.assertEqual(qc, res) def test_transpile_final_layout_updated_with_post_layout(self): """Test that the final layout is correctly set when vf2postlayout runs. Reproduce from #10457 """ def _get_index_layout(transpiled_circuit: QuantumCircuit, num_source_qubits: int): """Return the index layout of a transpiled circuit""" layout = transpiled_circuit.layout if layout is None: return list(range(num_source_qubits)) pos_to_virt = {v: k for k, v in layout.input_qubit_mapping.items()} qubit_indices = [] for index in range(num_source_qubits): qubit_idx = layout.initial_layout[pos_to_virt[index]] if layout.final_layout is not None: qubit_idx = layout.final_layout[transpiled_circuit.qubits[qubit_idx]] qubit_indices.append(qubit_idx) return qubit_indices vf2_post_layout_called = False def callback(**kwargs): nonlocal vf2_post_layout_called if isinstance(kwargs["pass_"], VF2PostLayout): vf2_post_layout_called = True self.assertIsNotNone(kwargs["property_set"]["post_layout"]) backend = FakeVigo() qubits = 3 qc = QuantumCircuit(qubits) for i in range(5): qc.cx(i % qubits, int(i + qubits / 2) % qubits) tqc = transpile(qc, backend=backend, seed_transpiler=4242, callback=callback) self.assertTrue(vf2_post_layout_called) self.assertEqual([3, 2, 1], _get_index_layout(tqc, qubits)) class StreamHandlerRaiseException(StreamHandler): """Handler class that will raise an exception on formatting errors.""" def handleError(self, record): raise sys.exc_info() class TestLogTranspile(QiskitTestCase): """Testing the log_transpile option.""" def setUp(self): super().setUp() logger = getLogger() self.addCleanup(logger.setLevel, logger.level) logger.setLevel("DEBUG") self.output = io.StringIO() logger.addHandler(StreamHandlerRaiseException(self.output)) self.circuit = QuantumCircuit(QuantumRegister(1)) def assertTranspileLog(self, log_msg): """Runs the transpiler and check for logs containing specified message""" transpile(self.circuit) self.output.seek(0) # Filter unrelated log lines output_lines = self.output.readlines() transpile_log_lines = [x for x in output_lines if log_msg in x] self.assertTrue(len(transpile_log_lines) > 0) def test_transpile_log_time(self): """Check Total Transpile Time is logged""" self.assertTranspileLog("Total Transpile Time") class TestTranspileCustomPM(QiskitTestCase): """Test transpile function with custom pass manager""" def test_custom_multiple_circuits(self): """Test transpiling with custom pass manager and multiple circuits. This tests created a deadlock, so it needs to be monitored for timeout. See: https://github.com/Qiskit/qiskit-terra/issues/3925 """ qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) pm_conf = PassManagerConfig( initial_layout=None, basis_gates=["u1", "u2", "u3", "cx"], coupling_map=CouplingMap([[0, 1]]), backend_properties=None, seed_transpiler=1, ) passmanager = level_0_pass_manager(pm_conf) transpiled = passmanager.run([qc, qc]) expected = QuantumCircuit(QuantumRegister(2, "q")) expected.append(U2Gate(0, 3.141592653589793), [0]) expected.cx(0, 1) self.assertEqual(len(transpiled), 2) self.assertEqual(transpiled[0], expected) self.assertEqual(transpiled[1], expected) @ddt class TestTranspileParallel(QiskitTestCase): """Test transpile() in parallel.""" def setUp(self): super().setUp() # Force parallel execution to True to test multiprocessing for this class original_val = parallel.PARALLEL_DEFAULT def restore_default(): parallel.PARALLEL_DEFAULT = original_val self.addCleanup(restore_default) parallel.PARALLEL_DEFAULT = True @data(0, 1, 2, 3) def test_parallel_multiprocessing(self, opt_level): """Test parallel dispatch works with multiprocessing.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() backend = FakeMumbaiV2() pm = generate_preset_pass_manager(opt_level, backend) res = pm.run([qc, qc]) for circ in res: self.assertIsInstance(circ, QuantumCircuit) @data(0, 1, 2, 3) def test_parallel_with_target(self, opt_level): """Test that parallel dispatch works with a manual target.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() target = FakeMumbaiV2().target res = transpile([qc] * 3, target=target, optimization_level=opt_level) self.assertIsInstance(res, list) for circ in res: self.assertIsInstance(circ, QuantumCircuit) @data(0, 1, 2, 3) def test_parallel_dispatch(self, opt_level): """Test that transpile in parallel works for all optimization levels.""" backend = FakeRueschlikon() qr = QuantumRegister(16) cr = ClassicalRegister(16) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) for k in range(1, 15): qc.cx(qr[0], qr[k]) qc.measure(qr, cr) qlist = [qc for k in range(15)] tqc = transpile( qlist, backend=backend, optimization_level=opt_level, seed_transpiler=424242 ) result = backend.run(tqc, seed_simulator=4242424242, shots=1000).result() counts = result.get_counts() for count in counts: self.assertTrue(math.isclose(count["0000000000000000"], 500, rel_tol=0.1)) self.assertTrue(math.isclose(count["0111111111111111"], 500, rel_tol=0.1)) def test_parallel_dispatch_lazy_cal_loading(self): """Test adding calibration by lazy loading in parallel environment.""" class TestAddCalibration(TransformationPass): """A fake pass to test lazy pulse qobj loading in parallel environment.""" def __init__(self, target): """Instantiate with target.""" super().__init__() self.target = target def run(self, dag): """Run test pass that adds calibration of SX gate of qubit 0.""" dag.add_calibration( "sx", qubits=(0,), schedule=self.target["sx"][(0,)].calibration, # PulseQobj is parsed here ) return dag backend = FakeMumbaiV2() # This target has PulseQobj entries that provides a serialized schedule data pass_ = TestAddCalibration(backend.target) pm = PassManager(passes=[pass_]) self.assertIsNone(backend.target["sx"][(0,)]._calibration._definition) qc = QuantumCircuit(1) qc.sx(0) qc_copied = [qc for _ in range(10)] qcs_cal_added = pm.run(qc_copied) ref_cal = backend.target["sx"][(0,)].calibration for qc_test in qcs_cal_added: added_cal = qc_test.calibrations["sx"][((0,), ())] self.assertEqual(added_cal, ref_cal) @data(0, 1, 2, 3) def test_backendv2_and_basis_gates(self, opt_level): """Test transpile() with BackendV2 and basis_gates set.""" backend = FakeNairobiV2() qc = QuantumCircuit(5) qc.h(0) qc.cz(0, 1) qc.cz(0, 2) qc.cz(0, 3) qc.cz(0, 4) qc.measure_all() tqc = transpile( qc, backend=backend, basis_gates=["u", "cz"], optimization_level=opt_level, seed_transpiler=12345678942, ) op_count = set(tqc.count_ops()) self.assertEqual({"u", "cz", "measure", "barrier"}, op_count) for inst in tqc.data: if inst.operation.name not in {"u", "cz"}: continue qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) self.assertIn(qubits, backend.target.qargs) @data(0, 1, 2, 3) def test_backendv2_and_coupling_map(self, opt_level): """Test transpile() with custom coupling map.""" backend = FakeNairobiV2() qc = QuantumCircuit(5) qc.h(0) qc.cz(0, 1) qc.cz(0, 2) qc.cz(0, 3) qc.cz(0, 4) qc.measure_all() cmap = CouplingMap.from_line(5, bidirectional=False) tqc = transpile( qc, backend=backend, coupling_map=cmap, optimization_level=opt_level, seed_transpiler=12345678942, ) op_count = set(tqc.count_ops()) self.assertTrue({"rz", "sx", "x", "cx", "measure", "barrier"}.issuperset(op_count)) for inst in tqc.data: if len(inst.qubits) == 2: qubit_0 = tqc.find_bit(inst.qubits[0]).index qubit_1 = tqc.find_bit(inst.qubits[1]).index self.assertEqual(qubit_1, qubit_0 + 1) def test_transpile_with_multiple_coupling_maps(self): """Test passing a different coupling map for every circuit""" backend = FakeNairobiV2() qc = QuantumCircuit(3) qc.cx(0, 2) # Add a connection between 0 and 2 so that transpile does not change # the gates cmap = CouplingMap.from_line(7) cmap.add_edge(0, 2) with self.assertRaisesRegex(TranspilerError, "Only a single input coupling"): # Initial layout needed to prevent transpiler from relabeling # qubits to avoid doing the swap transpile( [qc] * 2, backend, coupling_map=[backend.coupling_map, cmap], initial_layout=(0, 1, 2), ) @data(0, 1, 2, 3) def test_backend_and_custom_gate(self, opt_level): """Test transpile() with BackendV2, custom basis pulse gate.""" backend = FakeNairobiV2() inst_map = InstructionScheduleMap() inst_map.add("newgate", [0, 1], pulse.ScheduleBlock()) newgate = Gate("newgate", 2, []) circ = QuantumCircuit(2) circ.append(newgate, [0, 1]) tqc = transpile( circ, backend, inst_map=inst_map, basis_gates=["newgate"], optimization_level=opt_level ) self.assertEqual(len(tqc.data), 1) self.assertEqual(tqc.data[0].operation, newgate) qubits = tuple(tqc.find_bit(x).index for x in tqc.data[0].qubits) self.assertIn(qubits, backend.target.qargs) @ddt class TestTranspileMultiChipTarget(QiskitTestCase): """Test transpile() with a disjoint coupling map.""" def setUp(self): super().setUp() class FakeMultiChip(BackendV2): """Fake multi chip backend.""" def __init__(self): super().__init__() graph = rx.generators.directed_heavy_hex_graph(3) num_qubits = len(graph) * 3 rng = np.random.default_rng(seed=12345678942) rz_props = {} x_props = {} sx_props = {} measure_props = {} delay_props = {} self._target = Target("Fake multi-chip backend", num_qubits=num_qubits) for i in range(num_qubits): qarg = (i,) rz_props[qarg] = InstructionProperties(error=0.0, duration=0.0) x_props[qarg] = InstructionProperties( error=rng.uniform(1e-6, 1e-4), duration=rng.uniform(1e-8, 9e-7) ) sx_props[qarg] = InstructionProperties( error=rng.uniform(1e-6, 1e-4), duration=rng.uniform(1e-8, 9e-7) ) measure_props[qarg] = InstructionProperties( error=rng.uniform(1e-3, 1e-1), duration=rng.uniform(1e-8, 9e-7) ) delay_props[qarg] = None self._target.add_instruction(XGate(), x_props) self._target.add_instruction(SXGate(), sx_props) self._target.add_instruction(RZGate(Parameter("theta")), rz_props) self._target.add_instruction(Measure(), measure_props) self._target.add_instruction(Delay(Parameter("t")), delay_props) cz_props = {} for i in range(3): for root_edge in graph.edge_list(): offset = i * len(graph) edge = (root_edge[0] + offset, root_edge[1] + offset) cz_props[edge] = InstructionProperties( error=rng.uniform(1e-5, 5e-3), duration=rng.uniform(1e-8, 9e-7) ) self._target.add_instruction(CZGate(), cz_props) @property def target(self): return self._target @property def max_circuits(self): return None @classmethod def _default_options(cls): return Options(shots=1024) def run(self, circuit, **kwargs): raise NotImplementedError self.backend = FakeMultiChip() @data(0, 1, 2, 3) def test_basic_connected_circuit(self, opt_level): """Test basic connected circuit on disjoint backend""" qc = QuantumCircuit(5) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.measure_all() tqc = transpile(qc, self.backend, optimization_level=opt_level) for inst in tqc.data: qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) op_name = inst.operation.name if op_name == "barrier": continue self.assertIn(qubits, self.backend.target[op_name]) @data(0, 1, 2, 3) def test_triple_circuit(self, opt_level): """Test a split circuit with one circuit component per chip.""" qc = QuantumCircuit(30) qc.h(0) qc.h(10) qc.h(20) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.cx(0, 5) qc.cx(0, 6) qc.cx(0, 7) qc.cx(0, 8) qc.cx(0, 9) qc.ecr(10, 11) qc.ecr(10, 12) qc.ecr(10, 13) qc.ecr(10, 14) qc.ecr(10, 15) qc.ecr(10, 16) qc.ecr(10, 17) qc.ecr(10, 18) qc.ecr(10, 19) qc.cy(20, 21) qc.cy(20, 22) qc.cy(20, 23) qc.cy(20, 24) qc.cy(20, 25) qc.cy(20, 26) qc.cy(20, 27) qc.cy(20, 28) qc.cy(20, 29) qc.measure_all() if opt_level == 0: with self.assertRaises(TranspilerError): tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42) return tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42) for inst in tqc.data: qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) op_name = inst.operation.name if op_name == "barrier": continue self.assertIn(qubits, self.backend.target[op_name]) def test_disjoint_control_flow(self): """Test control flow circuit on disjoint coupling map.""" qc = QuantumCircuit(6, 1) qc.h(0) qc.ecr(0, 1) qc.cx(0, 2) qc.measure(0, 0) with qc.if_test((qc.clbits[0], True)): qc.reset(0) qc.cz(1, 0) qc.h(3) qc.cz(3, 4) qc.cz(3, 5) target = self.backend.target target.add_instruction(Reset(), {(i,): None for i in range(target.num_qubits)}) target.add_instruction(IfElseOp, name="if_else") tqc = transpile(qc, target=target) edges = set(target.build_coupling_map().graph.edge_list()) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: if instruction.operation.name == "barrier": continue qargs = tuple(qubit_mapping[x] for x in instruction.qubits) self.assertTrue(target.instruction_supported(instruction.operation.name, qargs)) if isinstance(instruction.operation, ControlFlowOp): for block in instruction.operation.blocks: new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) elif len(qargs) == 2: self.assertIn(qargs, edges) self.assertIn(instruction.operation.name, target) _visit_block( tqc, qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)}, ) def test_disjoint_control_flow_shared_classical(self): """Test circuit with classical data dependency between connected components.""" creg = ClassicalRegister(19) qc = QuantumCircuit(25) qc.add_register(creg) qc.h(0) for i in range(18): qc.cx(0, i + 1) for i in range(18): qc.measure(i, creg[i]) with qc.if_test((creg, 0)): qc.h(20) qc.ecr(20, 21) qc.ecr(20, 22) qc.ecr(20, 23) qc.ecr(20, 24) target = self.backend.target target.add_instruction(Reset(), {(i,): None for i in range(target.num_qubits)}) target.add_instruction(IfElseOp, name="if_else") tqc = transpile(qc, target=target) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: if instruction.operation.name == "barrier": continue qargs = tuple(qubit_mapping[x] for x in instruction.qubits) self.assertTrue(target.instruction_supported(instruction.operation.name, qargs)) if isinstance(instruction.operation, ControlFlowOp): for block in instruction.operation.blocks: new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) _visit_block( tqc, qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)}, ) @slow_test @data(2, 3) def test_six_component_circuit(self, opt_level): """Test input circuit with more than 1 component per backend component.""" qc = QuantumCircuit(42) qc.h(0) qc.h(10) qc.h(20) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.cx(0, 5) qc.cx(0, 6) qc.cx(0, 7) qc.cx(0, 8) qc.cx(0, 9) qc.ecr(10, 11) qc.ecr(10, 12) qc.ecr(10, 13) qc.ecr(10, 14) qc.ecr(10, 15) qc.ecr(10, 16) qc.ecr(10, 17) qc.ecr(10, 18) qc.ecr(10, 19) qc.cy(20, 21) qc.cy(20, 22) qc.cy(20, 23) qc.cy(20, 24) qc.cy(20, 25) qc.cy(20, 26) qc.cy(20, 27) qc.cy(20, 28) qc.cy(20, 29) qc.h(30) qc.cx(30, 31) qc.cx(30, 32) qc.cx(30, 33) qc.h(34) qc.cx(34, 35) qc.cx(34, 36) qc.cx(34, 37) qc.h(38) qc.cx(38, 39) qc.cx(39, 40) qc.cx(39, 41) qc.measure_all() tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42) for inst in tqc.data: qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) op_name = inst.operation.name if op_name == "barrier": continue self.assertIn(qubits, self.backend.target[op_name]) def test_six_component_circuit_level_1(self): """Test input circuit with more than 1 component per backend component.""" opt_level = 1 qc = QuantumCircuit(42) qc.h(0) qc.h(10) qc.h(20) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.cx(0, 5) qc.cx(0, 6) qc.cx(0, 7) qc.cx(0, 8) qc.cx(0, 9) qc.ecr(10, 11) qc.ecr(10, 12) qc.ecr(10, 13) qc.ecr(10, 14) qc.ecr(10, 15) qc.ecr(10, 16) qc.ecr(10, 17) qc.ecr(10, 18) qc.ecr(10, 19) qc.cy(20, 21) qc.cy(20, 22) qc.cy(20, 23) qc.cy(20, 24) qc.cy(20, 25) qc.cy(20, 26) qc.cy(20, 27) qc.cy(20, 28) qc.cy(20, 29) qc.h(30) qc.cx(30, 31) qc.cx(30, 32) qc.cx(30, 33) qc.h(34) qc.cx(34, 35) qc.cx(34, 36) qc.cx(34, 37) qc.h(38) qc.cx(38, 39) qc.cx(39, 40) qc.cx(39, 41) qc.measure_all() tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42) for inst in tqc.data: qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) op_name = inst.operation.name if op_name == "barrier": continue self.assertIn(qubits, self.backend.target[op_name]) @data(0, 1, 2, 3) def test_shared_classical_between_components_condition(self, opt_level): """Test a condition sharing classical bits between components.""" creg = ClassicalRegister(19) qc = QuantumCircuit(25) qc.add_register(creg) qc.h(0) for i in range(18): qc.cx(0, i + 1) for i in range(18): qc.measure(i, creg[i]) qc.ecr(20, 21).c_if(creg, 0) tqc = transpile(qc, self.backend, optimization_level=opt_level) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: if instruction.operation.name == "barrier": continue qargs = tuple(qubit_mapping[x] for x in instruction.qubits) self.assertTrue( self.backend.target.instruction_supported(instruction.operation.name, qargs) ) if isinstance(instruction.operation, ControlFlowOp): for block in instruction.operation.blocks: new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) _visit_block( tqc, qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)}, ) @data(0, 1, 2, 3) def test_shared_classical_between_components_condition_large_to_small(self, opt_level): """Test a condition sharing classical bits between components.""" creg = ClassicalRegister(2) qc = QuantumCircuit(25) qc.add_register(creg) # Component 0 qc.h(24) qc.cx(24, 23) qc.measure(24, creg[0]) qc.measure(23, creg[1]) # Component 1 qc.h(0).c_if(creg, 0) for i in range(18): qc.ecr(0, i + 1).c_if(creg, 0) tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=123456789) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: if instruction.operation.name == "barrier": continue qargs = tuple(qubit_mapping[x] for x in instruction.qubits) self.assertTrue( self.backend.target.instruction_supported(instruction.operation.name, qargs) ) if isinstance(instruction.operation, ControlFlowOp): for block in instruction.operation.blocks: new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) _visit_block( tqc, qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)}, ) # Check that virtual qubits that interact with each other via quantum links are placed into # the same component of the coupling map. initial_layout = tqc.layout.initial_layout coupling_map = self.backend.target.build_coupling_map() components = [ connected_qubits(initial_layout[qc.qubits[23]], coupling_map), connected_qubits(initial_layout[qc.qubits[0]], coupling_map), ] self.assertLessEqual({initial_layout[qc.qubits[i]] for i in [23, 24]}, components[0]) self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(19)}, components[1]) # Check clbits are in order. # Traverse the output dag over the sole clbit, checking that the qubits of the ops # go in order between the components. This is a sanity check to ensure that routing # doesn't reorder a classical data dependency between components. Inside a component # we have the dag ordering so nothing should be out of order within a component. tqc_dag = circuit_to_dag(tqc) qubit_map = {qubit: index for index, qubit in enumerate(tqc_dag.qubits)} input_node = tqc_dag.input_map[tqc_dag.clbits[0]] first_meas_node = tqc_dag._multi_graph.find_successors_by_edge( input_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] # The first node should be a measurement self.assertIsInstance(first_meas_node.op, Measure) # This should be in the first component self.assertIn(qubit_map[first_meas_node.qargs[0]], components[0]) op_node = tqc_dag._multi_graph.find_successors_by_edge( first_meas_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] while isinstance(op_node, DAGOpNode): self.assertIn(qubit_map[op_node.qargs[0]], components[1]) op_node = tqc_dag._multi_graph.find_successors_by_edge( op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] @data(1, 2, 3) def test_shared_classical_between_components_condition_large_to_small_reverse_index( self, opt_level ): """Test a condition sharing classical bits between components.""" creg = ClassicalRegister(2) qc = QuantumCircuit(25) qc.add_register(creg) # Component 0 qc.h(0) qc.cx(0, 1) qc.measure(0, creg[0]) qc.measure(1, creg[1]) # Component 1 qc.h(24).c_if(creg, 0) for i in range(23, 5, -1): qc.ecr(24, i).c_if(creg, 0) tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=2023) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: if instruction.operation.name == "barrier": continue qargs = tuple(qubit_mapping[x] for x in instruction.qubits) self.assertTrue( self.backend.target.instruction_supported(instruction.operation.name, qargs) ) if isinstance(instruction.operation, ControlFlowOp): for block in instruction.operation.blocks: new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) _visit_block( tqc, qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)}, ) # Check that virtual qubits that interact with each other via quantum links are placed into # the same component of the coupling map. initial_layout = tqc.layout.initial_layout coupling_map = self.backend.target.build_coupling_map() components = [ connected_qubits(initial_layout[qc.qubits[0]], coupling_map), connected_qubits(initial_layout[qc.qubits[6]], coupling_map), ] self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(2)}, components[0]) self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(6, 25)}, components[1]) # Check clbits are in order. # Traverse the output dag over the sole clbit, checking that the qubits of the ops # go in order between the components. This is a sanity check to ensure that routing # doesn't reorder a classical data dependency between components. Inside a component # we have the dag ordering so nothing should be out of order within a component. tqc_dag = circuit_to_dag(tqc) qubit_map = {qubit: index for index, qubit in enumerate(tqc_dag.qubits)} input_node = tqc_dag.input_map[tqc_dag.clbits[0]] first_meas_node = tqc_dag._multi_graph.find_successors_by_edge( input_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] # The first node should be a measurement self.assertIsInstance(first_meas_node.op, Measure) # This shoulde be in the first ocmponent self.assertIn(qubit_map[first_meas_node.qargs[0]], components[0]) op_node = tqc_dag._multi_graph.find_successors_by_edge( first_meas_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] while isinstance(op_node, DAGOpNode): self.assertIn(qubit_map[op_node.qargs[0]], components[1]) op_node = tqc_dag._multi_graph.find_successors_by_edge( op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] @data(1, 2, 3) def test_chained_data_dependency(self, opt_level): """Test 3 component circuit with shared clbits between each component.""" creg = ClassicalRegister(1) qc = QuantumCircuit(30) qc.add_register(creg) # Component 0 qc.h(0) for i in range(9): qc.cx(0, i + 1) measure_op = Measure() qc.append(measure_op, [9], [creg[0]]) # Component 1 qc.h(10).c_if(creg, 0) for i in range(11, 20): qc.ecr(10, i).c_if(creg, 0) measure_op = Measure() qc.append(measure_op, [19], [creg[0]]) # Component 2 qc.h(20).c_if(creg, 0) for i in range(21, 30): qc.cz(20, i).c_if(creg, 0) measure_op = Measure() qc.append(measure_op, [29], [creg[0]]) tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=2023) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: if instruction.operation.name == "barrier": continue qargs = tuple(qubit_mapping[x] for x in instruction.qubits) self.assertTrue( self.backend.target.instruction_supported(instruction.operation.name, qargs) ) if isinstance(instruction.operation, ControlFlowOp): for block in instruction.operation.blocks: new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) _visit_block( tqc, qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)}, ) # Check that virtual qubits that interact with each other via quantum links are placed into # the same component of the coupling map. initial_layout = tqc.layout.initial_layout coupling_map = self.backend.target.build_coupling_map() components = [ connected_qubits(initial_layout[qc.qubits[0]], coupling_map), connected_qubits(initial_layout[qc.qubits[10]], coupling_map), connected_qubits(initial_layout[qc.qubits[20]], coupling_map), ] self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(10)}, components[0]) self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(10, 20)}, components[1]) self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(20, 30)}, components[2]) # Check clbits are in order. # Traverse the output dag over the sole clbit, checking that the qubits of the ops # go in order between the components. This is a sanity check to ensure that routing # doesn't reorder a classical data dependency between components. Inside a component # we have the dag ordering so nothing should be out of order within a component. tqc_dag = circuit_to_dag(tqc) qubit_map = {qubit: index for index, qubit in enumerate(tqc_dag.qubits)} input_node = tqc_dag.input_map[tqc_dag.clbits[0]] first_meas_node = tqc_dag._multi_graph.find_successors_by_edge( input_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] self.assertIsInstance(first_meas_node.op, Measure) self.assertIn(qubit_map[first_meas_node.qargs[0]], components[0]) op_node = tqc_dag._multi_graph.find_successors_by_edge( first_meas_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] while not isinstance(op_node.op, Measure): self.assertIn(qubit_map[op_node.qargs[0]], components[1]) op_node = tqc_dag._multi_graph.find_successors_by_edge( op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] self.assertIn(qubit_map[op_node.qargs[0]], components[1]) op_node = tqc_dag._multi_graph.find_successors_by_edge( op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] while not isinstance(op_node.op, Measure): self.assertIn(qubit_map[op_node.qargs[0]], components[2]) op_node = tqc_dag._multi_graph.find_successors_by_edge( op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] self.assertIn(qubit_map[op_node.qargs[0]], components[2]) @data("sabre", "stochastic", "basic", "lookahead") def test_basic_connected_circuit_dense_layout(self, routing_method): """Test basic connected circuit on disjoint backend""" qc = QuantumCircuit(5) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.measure_all() tqc = transpile( qc, self.backend, layout_method="dense", routing_method=routing_method, seed_transpiler=42, ) for inst in tqc.data: qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) op_name = inst.operation.name if op_name == "barrier": continue self.assertIn(qubits, self.backend.target[op_name]) # Lookahead swap skipped for performance @data("sabre", "stochastic", "basic") def test_triple_circuit_dense_layout(self, routing_method): """Test a split circuit with one circuit component per chip.""" qc = QuantumCircuit(30) qc.h(0) qc.h(10) qc.h(20) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.cx(0, 5) qc.cx(0, 6) qc.cx(0, 7) qc.cx(0, 8) qc.cx(0, 9) qc.ecr(10, 11) qc.ecr(10, 12) qc.ecr(10, 13) qc.ecr(10, 14) qc.ecr(10, 15) qc.ecr(10, 16) qc.ecr(10, 17) qc.ecr(10, 18) qc.ecr(10, 19) qc.cy(20, 21) qc.cy(20, 22) qc.cy(20, 23) qc.cy(20, 24) qc.cy(20, 25) qc.cy(20, 26) qc.cy(20, 27) qc.cy(20, 28) qc.cy(20, 29) qc.measure_all() tqc = transpile( qc, self.backend, layout_method="dense", routing_method=routing_method, seed_transpiler=42, ) for inst in tqc.data: qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) op_name = inst.operation.name if op_name == "barrier": continue self.assertIn(qubits, self.backend.target[op_name]) @data("sabre", "stochastic", "basic", "lookahead") def test_triple_circuit_invalid_layout(self, routing_method): """Test a split circuit with one circuit component per chip.""" qc = QuantumCircuit(30) qc.h(0) qc.h(10) qc.h(20) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.cx(0, 5) qc.cx(0, 6) qc.cx(0, 7) qc.cx(0, 8) qc.cx(0, 9) qc.ecr(10, 11) qc.ecr(10, 12) qc.ecr(10, 13) qc.ecr(10, 14) qc.ecr(10, 15) qc.ecr(10, 16) qc.ecr(10, 17) qc.ecr(10, 18) qc.ecr(10, 19) qc.cy(20, 21) qc.cy(20, 22) qc.cy(20, 23) qc.cy(20, 24) qc.cy(20, 25) qc.cy(20, 26) qc.cy(20, 27) qc.cy(20, 28) qc.cy(20, 29) qc.measure_all() with self.assertRaises(TranspilerError): transpile( qc, self.backend, layout_method="trivial", routing_method=routing_method, seed_transpiler=42, ) # Lookahead swap skipped for performance reasons @data("sabre", "stochastic", "basic") def test_six_component_circuit_dense_layout(self, routing_method): """Test input circuit with more than 1 component per backend component.""" qc = QuantumCircuit(42) qc.h(0) qc.h(10) qc.h(20) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.cx(0, 5) qc.cx(0, 6) qc.cx(0, 7) qc.cx(0, 8) qc.cx(0, 9) qc.ecr(10, 11) qc.ecr(10, 12) qc.ecr(10, 13) qc.ecr(10, 14) qc.ecr(10, 15) qc.ecr(10, 16) qc.ecr(10, 17) qc.ecr(10, 18) qc.ecr(10, 19) qc.cy(20, 21) qc.cy(20, 22) qc.cy(20, 23) qc.cy(20, 24) qc.cy(20, 25) qc.cy(20, 26) qc.cy(20, 27) qc.cy(20, 28) qc.cy(20, 29) qc.h(30) qc.cx(30, 31) qc.cx(30, 32) qc.cx(30, 33) qc.h(34) qc.cx(34, 35) qc.cx(34, 36) qc.cx(34, 37) qc.h(38) qc.cx(38, 39) qc.cx(39, 40) qc.cx(39, 41) qc.measure_all() tqc = transpile( qc, self.backend, layout_method="dense", routing_method=routing_method, seed_transpiler=42, ) for inst in tqc.data: qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) op_name = inst.operation.name if op_name == "barrier": continue self.assertIn(qubits, self.backend.target[op_name]) @data(0, 1, 2, 3) def test_transpile_target_with_qubits_without_ops(self, opt_level): """Test qubits without operations aren't ever used.""" target = Target(num_qubits=5) target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)}) target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)}) target.add_instruction( CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0)]} ) qc = QuantumCircuit(3) qc.x(0) qc.cx(0, 1) qc.cx(0, 2) tqc = transpile(qc, target=target, optimization_level=opt_level) invalid_qubits = {3, 4} self.assertEqual(tqc.num_qubits, 5) for inst in tqc.data: for bit in inst.qubits: self.assertNotIn(tqc.find_bit(bit).index, invalid_qubits) @data(0, 1, 2, 3) def test_transpile_target_with_qubits_without_ops_with_routing(self, opt_level): """Test qubits without operations aren't ever used.""" target = Target(num_qubits=5) target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(4)}) target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(4)}) target.add_instruction( CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0), (2, 3)]}, ) qc = QuantumCircuit(4) qc.x(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(1, 3) qc.cx(0, 3) tqc = transpile(qc, target=target, optimization_level=opt_level) invalid_qubits = { 4, } self.assertEqual(tqc.num_qubits, 5) for inst in tqc.data: for bit in inst.qubits: self.assertNotIn(tqc.find_bit(bit).index, invalid_qubits) @data(0, 1, 2, 3) def test_transpile_target_with_qubits_without_ops_circuit_too_large(self, opt_level): """Test qubits without operations aren't ever used and error if circuit needs them.""" target = Target(num_qubits=5) target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)}) target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)}) target.add_instruction( CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0)]} ) qc = QuantumCircuit(4) qc.x(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) with self.assertRaises(TranspilerError): transpile(qc, target=target, optimization_level=opt_level) @data(0, 1, 2, 3) def test_transpile_target_with_qubits_without_ops_circuit_too_large_disconnected( self, opt_level ): """Test qubits without operations aren't ever used if a disconnected circuit needs them.""" target = Target(num_qubits=5) target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)}) target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)}) target.add_instruction( CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0)]} ) qc = QuantumCircuit(5) qc.x(0) qc.x(1) qc.x(3) qc.x(4) with self.assertRaises(TranspilerError): transpile(qc, target=target, optimization_level=opt_level) @data(0, 1, 2, 3) def test_transpile_does_not_affect_backend_coupling(self, opt_level): """Test that transpiliation of a circuit does not mutate the `CouplingMap` stored by a V2 backend. Regression test of gh-9997.""" if opt_level == 3: raise unittest.SkipTest("unitary resynthesis fails due to gh-10004") qc = QuantumCircuit(127) for i in range(1, 127): qc.ecr(0, i) backend = FakeSherbrooke() original_map = copy.deepcopy(backend.coupling_map) transpile(qc, backend, optimization_level=opt_level) self.assertEqual(original_map, backend.coupling_map) @combine( optimization_level=[0, 1, 2, 3], scheduling_method=["asap", "alap"], ) def test_transpile_target_with_qubits_without_delays_with_scheduling( self, optimization_level, scheduling_method ): """Test qubits without operations aren't ever used.""" no_delay_qubits = [1, 3, 4] target = Target(num_qubits=5, dt=1) target.add_instruction( XGate(), {(i,): InstructionProperties(duration=160) for i in range(4)} ) target.add_instruction( HGate(), {(i,): InstructionProperties(duration=160) for i in range(4)} ) target.add_instruction( CXGate(), { edge: InstructionProperties(duration=800) for edge in [(0, 1), (1, 2), (2, 0), (2, 3)] }, ) target.add_instruction( Delay(Parameter("t")), {(i,): None for i in range(4) if i not in no_delay_qubits} ) qc = QuantumCircuit(4) qc.x(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(1, 3) qc.cx(0, 3) tqc = transpile( qc, target=target, optimization_level=optimization_level, scheduling_method=scheduling_method, ) invalid_qubits = { 4, } self.assertEqual(tqc.num_qubits, 5) for inst in tqc.data: for bit in inst.qubits: self.assertNotIn(tqc.find_bit(bit).index, invalid_qubits) if isinstance(inst.operation, Delay): self.assertNotIn(tqc.find_bit(bit).index, no_delay_qubits)
https://github.com/NesyaLab/qaoa
NesyaLab
import warnings warnings.filterwarnings('ignore') import os os.chdir('..') from functions import maxcut_utilities import networkx from classes import Problems G = networkx.Graph() G.add_edges_from([[0,3],[0,4],[1,3],[1,4],[2,3],[2,4]]) instance = Problems.Problems(G=G) maxcut = maxcut_utilities.compute_max_cut_exactly(instance) print(maxcut) counts = {'11000': 1, '00011': 29, '01011': 24} rearranged_counts = maxcut_utilities.invert_counts(counts) print(rearranged_counts) cut_value = maxcut_utilities.get_maxcut_number_of_edges(instance,"10011") print(-cut_value) approximate_result = maxcut_utilities.compute_maxcut_energy(instance,counts) print(approximate_result) from classes import Qaoa instance = Problems.Problems() qaoa = Qaoa.Qaoa(p=3, G=instance) from functions import qaoa_optimizers init_point = qaoa.betas + qaoa.gammas maxcut_value = qaoa_optimizers.objective_function(init_point,qaoa,shots=100) print("energy", maxcut_value) qaoa_optimizers.callback([]) x, f = qaoa_optimizers.simple_optimization(qaoa) from functions import qaoa_utilities two_random_angles = qaoa_utilities.generate_parameters(2,1) print(two_random_angles) #pip install --no-binary pynauty pynauty from functions import symmetry_utilities instance = Problems.Problems(G=G) adjacency_dict = instance.get_adjacency_dict() num_automorphisms = symmetry_utilities.get_number_of_automorphisms(G=instance, adjacency_dict=adjacency_dict) print(num_automorphisms) generators = symmetry_utilities.get_symmetry_generators(G=instance, adjacency_dict=adjacency_dict) print(generators) num_orbits, orbits = symmetry_utilities.get_symmetry_orbits(G=instance, adjacency_dict=adjacency_dict) print(num_orbits, orbits)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=too-many-function-args, unexpected-keyword-arg """THIS FILE IS DEPRECATED AND WILL BE REMOVED IN RELEASE 0.9. """ import warnings from qiskit.converters import dag_to_circuit, circuit_to_dag from qiskit.transpiler import CouplingMap from qiskit import compiler from qiskit.transpiler.preset_passmanagers import (default_pass_manager_simulator, default_pass_manager) def transpile(circuits, backend=None, basis_gates=None, coupling_map=None, initial_layout=None, seed_mapper=None, pass_manager=None): """transpile one or more circuits. Args: circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile backend (BaseBackend): a backend to compile for basis_gates (list[str]): list of basis gate names supported by the target. Default: ['u1','u2','u3','cx','id'] coupling_map (list): coupling map (perhaps custom) to target in mapping initial_layout (Layout or dict or list): Initial position of virtual qubits on physical qubits. The final layout is not guaranteed to be the same, as the transpiler may permute qubits through swaps or other means. seed_mapper (int): random seed for the swap_mapper pass_manager (PassManager): a pass_manager for the transpiler stages Returns: QuantumCircuit or list[QuantumCircuit]: transpiled circuit(s). Raises: TranspilerError: in case of bad inputs to transpiler or errors in passes """ warnings.warn("qiskit.transpiler.transpile() has been deprecated and will be " "removed in the 0.9 release. Use qiskit.compiler.transpile() instead.", DeprecationWarning) return compiler.transpile(circuits=circuits, backend=backend, basis_gates=basis_gates, coupling_map=coupling_map, initial_layout=initial_layout, seed_transpiler=seed_mapper, pass_manager=pass_manager) def transpile_dag(dag, basis_gates=None, coupling_map=None, initial_layout=None, seed_mapper=None, pass_manager=None): """Deprecated - Use qiskit.compiler.transpile for transpiling from circuits to circuits. Transform a dag circuit into another dag circuit (transpile), through consecutive passes on the dag. Args: dag (DAGCircuit): dag circuit to transform via transpilation basis_gates (list[str]): list of basis gate names supported by the target. Default: ['u1','u2','u3','cx','id'] coupling_map (list): A graph of coupling:: [ [control0(int), target0(int)], [control1(int), target1(int)], ] eg. [[0, 2], [1, 2], [1, 3], [3, 4]} initial_layout (Layout or None): A layout object seed_mapper (int): random seed_mapper for the swap mapper pass_manager (PassManager): pass manager instance for the transpilation process If None, a default set of passes are run. Otherwise, the passes defined in it will run. If contains no passes in it, no dag transformations occur. Returns: DAGCircuit: transformed dag """ warnings.warn("transpile_dag has been deprecated and will be removed in the " "0.9 release. Circuits can be transpiled directly to other " "circuits with the transpile function.", DeprecationWarning) if basis_gates is None: basis_gates = ['u1', 'u2', 'u3', 'cx', 'id'] if pass_manager is None: # default set of passes # if a coupling map is given compile to the map if coupling_map: pass_manager = default_pass_manager(basis_gates, CouplingMap(coupling_map), initial_layout, seed_transpiler=seed_mapper) else: pass_manager = default_pass_manager_simulator(basis_gates) # run the passes specified by the pass manager # TODO return the property set too. See #1086 name = dag.name circuit = dag_to_circuit(dag) circuit = pass_manager.run(circuit) dag = circuit_to_dag(circuit) dag.name = name return dag
https://github.com/benkoehlL/Qiskit_Playground
benkoehlL
''' This program implements Shor's algorithm which determines a number's prime factors. [unfinished] ''' from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit,\ execute, IBMQ, Aer from qiskit.visualization import circuit_drawer as drawer from qiskit.tools.visualization import plot_histogram import numpy as np from matplotlib.pyplot import plot, draw, show M = 15 a = 3 e = 8 print("a**2 mod M = ", (a**2)%M) def NQbitCircuit(p, w, c): circuit = QuantumCircuit(w, p, c) # prepare initial state 1 in primary register circuit.x(p[0]) circuit.barrier(p) circuit.barrier(w) # add a Hadamard gate to the working register for qubit in w: circuit.h(qubit) # add additional multiplication by 'a' to the primary register circuit.cx(w[0], p[1]) circuit.cx(w[0], p[3]) return(circuit) def NBitQFT(q, c, n): circuit = QuantumCircuit(q, c) # Start with the most significant bit for k in range(n): j = n-k # add Hadamard to qubit j-1 circuit.h(q[j-1]) # there is one conditional rotation # for each qubit with lower significance for i in reversed(range(j-1)): circuit.cp(2*np.pi/2**(j-i), q[i], q[j-1]) # swap qubits for i in range(n//2): circuit.swap(q[i], q[n-i-1]) return circuit def Shor_Algorithm(a, n): # create registers and circuit p = QuantumRegister(4, 'p') w = QuantumRegister(n, 'w') c = ClassicalRegister(n, "c") circuit = QuantumCircuit(w, p, c) # add Hadamard gates to working registers for qubit in w: circuit.h(qubit) # add multiplication by 'a' to primary register circuit.cx(w[0], p[1]) circuit.cx(w[0], p[3]) # build the QFT part starting with the most significant bit for k in range(n): j = n - k # add Hadamard to qubit j-1 if(j-1) != 2: circuit.h(w[j-1]) # there is one conditional rotation # for each qubit with lower significance for i in reversed(range(j-1)): circuit.cp(2*np.pi/2**(j-i), w[i], w[j-1]) # add the measurements circuit.barrier(w) for i in range(len(w)): circuit.measure(w[i], c[len(w)-1-i]) return circuit p = QuantumRegister(4, 'p') w = QuantumRegister(3, 'w') c = ClassicalRegister(len(w), 'c') qc = NQbitCircuit(p, w, c) drawer(qc, output='mpl') draw() show(block=True) backend = Aer.get_backend('statevector_simulator') job = execute(qc, backend) state = np.around(job.result().get_statevector(), 2) print('Non-zero states:') for i in range(2**(len(p)+len(w))): if(state[i] != 0): print("|",i,"> --->", state[i]) print('Expected amplitudes up to normalisation:') for s in range(2**(len(w))): x = a**s % M print("|", x*e + s, "> = |", x, ">|", s, ">") # // is the floor division print('Non-zero states and their decomposition: |s> = |s // e> |s mod e> :') for i in range(2**(len(w)+len(p))): if(state[i] != 0): # // is the floor division print("|", i, "> = |", i // e, ">|", i % e, "> ---> ", state[i]) qc = QuantumCircuit.compose(qc, NBitQFT(w, c,3)) qc.barrier(w) qc.measure(w, c) drawer(qc, output='mpl') draw() show(block=True) backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend) counts = job.result().get_counts() plt = plot_histogram(counts) draw() show(block=True) qc = Shor_Algorithm(a,3) backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend) counts = job.result().get_counts() plt = plot_histogram(counts) draw() show(block=True)
https://github.com/TheGupta2012/QPE-Algorithms
TheGupta2012
from qiskit import QuantumCircuit, execute, transpile, Aer from qiskit.extensions import UnitaryGate, Initialize from qiskit.providers.ibmq.managed import IBMQJobManager import numpy as np from sys import stdout from scipy.stats import unitary_group class bundled_changed_SPEA: def __init__(self, unitary, resolution=100, error=3, max_iters=20): # handle resolution if not isinstance(resolution, int): raise TypeError("Please enter the number of intervals as an integer value") if resolution < 10 or resolution > 1e6: raise ValueError( "Resolution needs to be atleast 0.1 and greater than 0.000001" ) self.resolution = resolution # handle unitary if ( not isinstance(unitary, np.ndarray) and not isinstance(unitary, QuantumCircuit) and not isinstance(unitary, UnitaryGate) ): raise TypeError( "A numpy array or Quantum Circuit or UnitaryGate needs to be passed as the unitary matrix" ) # convert circuit to numpy array for uniformity if isinstance(unitary, UnitaryGate): U = unitary.to_matrix() else: # both QC and ndarray type U = unitary # note - the unitary here is not just a single qubit unitary if isinstance(U, np.ndarray): self.dims = U.shape[0] else: self.dims = 2 ** (U.num_qubits) if isinstance(U, np.ndarray): self.c_unitary_gate = UnitaryGate(data=U).control( num_ctrl_qubits=1, label="CU", ctrl_state="1" ) else: self.c_unitary_gate = U.control( num_ctrl_qubits=1, label="CU", ctrl_state="1" ) # handle error if not isinstance(error, int): raise TypeError( "The allowable error should be provided as an int. Interpreted as 10**(-error)" ) if error <= 0: raise ValueError("The error threshold must be finite and greater than 0.") self.error = error # handle max_iters if not isinstance(max_iters, int): raise TypeError("Max iterations must be of integer type") if max_iters <= 0 and max_iters > 1e5: raise ValueError("Max iterations should be atleast 1 and less than 1e5") self.iterations = max_iters self.basis = [] def get_basis_vectors(self, randomize=True): # get the d dimensional basis for the unitary provided if randomize == True: UR = unitary_group.rvs(self.dims) else: UR = np.identity(self.dims) basis = [] for k in UR: basis.append(np.array(k, dtype=complex)) return basis def get_circuits(self, angles, state): """Given an initial state and a set of angles, return the circuits that are generated with those angles""" result = {"cost": -1, "theta": -1} # all theta values are iterated over for the same state phi = Initialize(state) shots = 512 circuits = [] for theta in angles: qc = QuantumCircuit(1 + int(np.log2(self.dims)), 1) # initialize the circuit qc = qc.compose(phi, qubits=list(range(1, int(np.log2(self.dims)) + 1))) # add hadamard qc.h(0) # add unitary which produces a phase kickback on control qubit qc = qc.compose( self.c_unitary_gate, qubits=range(1 + int(np.log2(self.dims))) ) # add the inv rotation qc.p(-2 * np.pi * theta, 0) # add hadamard qc.h(0) # measure qc.measure([0], [0]) # generate all the circuits... circuits.append(qc) return circuits def get_cost(self, angles, counts, shots): """Generate the best cost and theta pair for the particular state""" result = {"cost": -1, "theta": -1} # get the cost for this theta for k, theta in zip(counts, angles): # for all experiments you ran try: C_val = (k["0"]) / shots except: C_val = 0 if C_val > result["cost"]: # means this is a better theta value result["theta"] = theta result["cost"] = C_val return result def get_eigen_pair(self, backend, progress=False, randomize=True): """Finding the eigenstate pair for the unitary""" if not isinstance(progress, bool): raise TypeError("Progress must be a boolean variable") if not isinstance(randomize, bool): raise Exception("Randomize must be a boolean variable") results = dict() # first initialize the state phi self.basis = self.get_basis_vectors(randomize) # choose a random index ind = np.random.choice(self.dims) phi = self.basis[ind] # doing the method 1 of our algorithm # define resolution of angles and precision precision = 1 / 10 ** self.error samples = self.resolution # initialization of range left, right = 0, 1 shots = 512 # generate the angles angles = np.linspace(left, right, samples) # First execution can be done without JobManager also... circs = self.get_circuits(angles, phi) job = execute(circs, backend=backend, shots=shots) counts = job.result().get_counts() result = self.get_cost(angles, counts, shots) # get initial estimates cost = result["cost"] theta_max = result["theta"] best_phi = phi # the range upto which theta extends iin each iteration angle_range = 0.5 # a parameter a = 1 # start algorithm iters = 0 found = True plus = (1 / np.sqrt(2)) * np.array([1, 1]) minus = (1 / np.sqrt(2)) * np.array([1, -1]) # define IBMQManager instance manager = IBMQJobManager() while 1 - cost >= precision: # get angles, note if theta didn't change, then we need to # again generate the same range again right = min(1, theta_max + angle_range / 2) left = max(0, theta_max - angle_range / 2) if progress: print("Right :", right) print("Left :", left) # generate the angles only if the theta has been updated if found == True: angles = np.linspace(left, right, samples) found = False # for this iteration if progress: print("ITERATION NUMBER", iters + 1, "...") # generate a cost dict for each of the iterations # final result lists thetas, costs, states = [], [], [] # circuit list circuits = [] # list to store intermediate states phis = [] # 1. Circuit generation loop for i in range((2 * self.dims)): # everyone is supplied with the same range of theta in one iteration # define z # make a list of the circuits if i < self.dims: z = 1 else: z = 1j # alter and normalise phi curr_phi = best_phi + z * a * (1 - cost) * self.basis[i % self.dims] curr_phi = curr_phi / np.linalg.norm(curr_phi) phis.append(curr_phi) # bundle the circuits together ... circs = self.get_circuits(angles, curr_phi) circuits = circuits + circs # now each iteration would see the same state as the best phi # is updated once at the end of the iteration # also, the cost is also updated only once at the end of the iteration # 2. run the generated circuits if progress: print("Transpiling circuits...") circuits = transpile(circuits=circuits, backend=backend) job_set = manager.run( circuits, backend=backend, name="Job_set" + str(iters), shots=shots ) if progress: print("Transpilation Done!\nJob sent...") job_result = job_set.results() # now get the circuits in chunks of resolution each if progress: print("Job has returned") # 3. Result generation loop for i in range((2 * self.dims)): # get the results of this basis state # it will have resolution number of circuits... counts = [] for j in range(i * self.resolution, (i + 1) * self.resolution): # in this you'll get the counts counts.append(job_result.get_counts(j)) result = self.get_cost(counts, angles, shots) # get the estimates for this basis curr_theta = result["theta"] curr_cost = result["cost"] curr_phi = phis[i] # the result was generated pertaining to this phi if ( curr_cost > cost ): # then only add this cost in the cost and states list thetas.append(float(curr_theta)) costs.append(float(curr_cost)) states.append(curr_phi) found = True if progress: stdout.write("\r") stdout.write("%f %%completed" % (100 * (i + 1) / (2 * self.dims))) stdout.flush() if found == False: # phi was not updated , change a a = a / 2 if progress: print("\nNo change, updating a...") else: # if found is actually true, then only update # O(n) , would update this though index = np.argmax(costs) # update the parameters of the model cost = costs[index] theta_max = thetas[index] best_phi = states[index] if progress: print("Best Phi is :", best_phi) print("Theta estimate :", theta_max) print("Current cost :", cost) angle_range /= 2 # updated phi and thus theta too -> refine theta range # update the iterations iters += 1 if progress: print("\nCOST :", cost) print("THETA :", theta_max) if iters >= self.iterations: print( "Maximum iterations reached for the estimation.\nTerminating algorithm..." ) break # add cost, eigenvector and theta to the dict results["cost"] = cost results["theta"] = theta_max results["state"] = best_phi return results
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeVigoV2 from qiskit.visualization import plot_circuit_layout from qiskit.tools.monitor import job_monitor from qiskit.providers.fake_provider import FakeVigoV2 import matplotlib.pyplot as plt ghz = QuantumCircuit(3, 3) ghz.h(0) for idx in range(1,3): ghz.cx(0,idx) ghz.measure(range(3), range(3)) backend = FakeVigoV2() new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3) plot_circuit_layout(new_circ_lv3, backend)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.tools.visualization import circuit_drawer q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) circuit_drawer(qc, output='mpl', style={'backgroundcolor': '#EEEEEE'})
https://github.com/sooodos/Quantum-Computing-Learning-Gate
sooodos
from qiskit import IBMQ from qiskit import ( QuantumCircuit, execute, Aer) class HelloWorld: @classmethod def run(cls): with open('./credentials/token', 'r') as file: token = file.read() IBMQ.save_account(token, overwrite=True) # Use Aer's qasm_simulator simulator = Aer.get_backend('qasm_simulator') # Create a Quantum Circuit acting on the q register circuit = QuantumCircuit(2, 2) # Add a H gate on qubit 0 circuit.h(0) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1 circuit.cx(0, 1) # Map the quantum measurement to the classical bits circuit.measure([0, 1], [0, 1]) # Execute the circuit on the qasm simulator job = execute(circuit, simulator, shots=1024) # Grab results from the job result = job.result() # Returns counts counts = result.get_counts(circuit) print("Results for the Bell State experiment.") print("\nTotal count for 00 and 11 are:", counts) # Draw the circuit print(circuit)
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# 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 unittest import qiskit from qiskit.circuit.library import TwoLocal from qiskit import BasicAer from qiskit.utils import QuantumInstance from qiskit.opflow import Z, I from volta.vqd import VQD from volta.utils import classical_solver class TestVQDSWAP(unittest.TestCase): def setUp(self): optimizer = qiskit.algorithms.optimizers.COBYLA() backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000, seed_simulator=42, seed_transpiler=42, ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=2) self.Algo = VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="swap", ) self.Algo.run(verbose=0) self.eigenvalues, _ = classical_solver(hamiltonian) def test_energies_0(self): decimal_place = 1 want = self.eigenvalues[0] got = self.Algo.energies[0] message = ( "VQD with SWAP not working for the ground state of 1/2*((Z^I) + (Z^Z))" ) self.assertAlmostEqual(want, got, decimal_place, message) def test_energies_1(self): decimal_place = 1 want = self.eigenvalues[1] got = self.Algo.energies[1] message = "VQD with SWAP not working for the first excited state of 1/2*((Z^I) + (Z^Z))" self.assertAlmostEqual(want, got, decimal_place, message) class TestVQDDSWAP(unittest.TestCase): def setUp(self): optimizer = qiskit.algorithms.optimizers.COBYLA() # backend = BasicAer.get_backend("qasm_simulator") backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000, seed_simulator=42, seed_transpiler=42, ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=1) self.Algo = VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="dswap", ) self.Algo.run(verbose=0) self.eigenvalues, _ = classical_solver(hamiltonian) def test_energies_0(self): decimal_place = 1 want = self.eigenvalues[0] got = self.Algo.energies[0] self.assertAlmostEqual( want, got, decimal_place, "VQD with DSWAP not working for the ground state of 1/2*((Z^I) + (Z^Z))", ) def test_energies_1(self): decimal_place = 1 want = self.eigenvalues[1] got = self.Algo.energies[1] self.assertAlmostEqual( want, got, decimal_place, "VQD with DSWAP not working for the first excited state of 1/2*((Z^I) + (Z^Z))", ) class TestVQDAmplitude(unittest.TestCase): def setUp(self): optimizer = qiskit.algorithms.optimizers.COBYLA() backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000, seed_simulator=42, seed_transpiler=42, ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=1) self.Algo = VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="amplitude", ) self.Algo.run(verbose=0) self.eigenvalues, _ = classical_solver(hamiltonian) def test_energies_0(self): decimal_place = 1 want = self.eigenvalues[0] got = self.Algo.energies[0] self.assertAlmostEqual( want, got, decimal_place, "VQD with Excitation Amplitude not working for the ground state of 1/2*((Z^I) + (Z^Z))", ) def test_energies_1(self): decimal_place = 1 want = self.eigenvalues[1] got = self.Algo.energies[1] self.assertAlmostEqual( want, got, decimal_place, "VQD with Excitation Amplitude not working for the first excited state of 1/2*((Z^I) + (Z^Z))", ) class VQDRaiseError(unittest.TestCase): def test_not_implemented_overlapping_method(self): optimizer = qiskit.algorithms.optimizers.COBYLA() backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000 ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=2) with self.assertRaises(NotImplementedError): VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="test", ), if __name__ == "__main__": unittest.main(argv=[""], verbosity=2, exit=False)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.visualization.timeline import draw as timeline_draw from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeBoeblingen backend = FakeBoeblingen() ghz = QuantumCircuit(5) ghz.h(0) ghz.cx(0,range(1,5)) circ = transpile(ghz, backend, scheduling_method="asap") timeline_draw(circ)
https://github.com/anpaschool/QC-School-Fall2020
anpaschool
#initialization import matplotlib.pyplot as plt import numpy as np # importing Qiskit from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.quantum_info import Statevector # import basic plot tools from qiskit.visualization import plot_histogram Circuit = QuantumCircuit(2) Circuit.draw('mpl') Circuit.h(0) Circuit.h(1) Circuit.draw('mpl') #apply Oracle U_f Circuit.cz(0,1) Circuit.draw('mpl') #apply diffuser U_S Circuit.h(0) Circuit.h(1) Circuit.z(0) Circuit.z(1) Circuit.cz(0,1) Circuit.h(0) Circuit.h(1) Circuit.draw('mpl') sv_sim = Aer.get_backend('statevector_simulator') job_sim = execute(Circuit, sv_sim) statevec = job_sim.result().get_statevector() from qiskit_textbook.tools import vector2latex vector2latex(statevec, pretext="|\\psi\\rangle =") Circuit.measure_all() qasm_simulator = Aer.get_backend('qasm_simulator') shots = 1-24 results = execute(Circuit, backend=qasm_simulator, shots=shots).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/lmarza/QuantumDeskCalculator
lmarza
import math from qiskit import * from utils import bcolors, executeQFT, evolveQFTStateSum, inverseQFT pie = math.pi def multiply(a, secondDec, result, qc): n = len(a) -1 # Compute the Fourier transform of register 'result' for i in range(n+1): executeQFT(qc, result, n-i, pie) # Add the two numbers by evolving the Fourier transform F(ψ(reg_a))> # to |F(ψ((second * reg_a))>, where we loop on the sum as many times as 'second' says, # doing incremental sums for j in range(secondDec): for i in range(n+1): evolveQFTStateSum(qc, result, a, n-i, pie) # Compute the inverse Fourier transform of register a for i in range(n+1): inverseQFT(qc, result, i, pie)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# useful additional packages import matplotlib.pyplot as plt import numpy as np import networkx as nx from qiskit_aer import Aer from qiskit.tools.visualization import plot_histogram from qiskit.circuit.library import TwoLocal from qiskit_optimization.applications import Maxcut, Tsp from qiskit.algorithms.minimum_eigensolvers import SamplingVQE, NumPyMinimumEigensolver from qiskit.algorithms.optimizers import SPSA from qiskit.utils import algorithm_globals from qiskit.primitives import Sampler from qiskit_optimization.algorithms import MinimumEigenOptimizer # Generating a graph of 4 nodes n = 4 # Number of nodes in graph G = nx.Graph() G.add_nodes_from(np.arange(0, n, 1)) elist = [(0, 1, 1.0), (0, 2, 1.0), (0, 3, 1.0), (1, 2, 1.0), (2, 3, 1.0)] # tuple is (i,j,weight) where (i,j) is the edge G.add_weighted_edges_from(elist) colors = ["r" for node in G.nodes()] pos = nx.spring_layout(G) def draw_graph(G, colors, pos): default_axes = plt.axes(frameon=True) nx.draw_networkx(G, node_color=colors, node_size=600, alpha=0.8, ax=default_axes, pos=pos) edge_labels = nx.get_edge_attributes(G, "weight") nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels) draw_graph(G, colors, pos) # Computing the weight matrix from the random graph w = np.zeros([n, n]) for i in range(n): for j in range(n): temp = G.get_edge_data(i, j, default=0) if temp != 0: w[i, j] = temp["weight"] print(w) best_cost_brute = 0 for b in range(2**n): x = [int(t) for t in reversed(list(bin(b)[2:].zfill(n)))] cost = 0 for i in range(n): for j in range(n): cost = cost + w[i, j] * x[i] * (1 - x[j]) if best_cost_brute < cost: best_cost_brute = cost xbest_brute = x print("case = " + str(x) + " cost = " + str(cost)) colors = ["r" if xbest_brute[i] == 0 else "c" for i in range(n)] draw_graph(G, colors, pos) print("\nBest solution = " + str(xbest_brute) + " cost = " + str(best_cost_brute)) max_cut = Maxcut(w) qp = max_cut.to_quadratic_program() print(qp.prettyprint()) qubitOp, offset = qp.to_ising() print("Offset:", offset) print("Ising Hamiltonian:") print(str(qubitOp)) # solving Quadratic Program using exact classical eigensolver exact = MinimumEigenOptimizer(NumPyMinimumEigensolver()) result = exact.solve(qp) print(result.prettyprint()) # Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector ee = NumPyMinimumEigensolver() result = ee.compute_minimum_eigenvalue(qubitOp) x = max_cut.sample_most_likely(result.eigenstate) print("energy:", result.eigenvalue.real) print("max-cut objective:", result.eigenvalue.real + offset) print("solution:", x) print("solution objective:", qp.objective.evaluate(x)) colors = ["r" if x[i] == 0 else "c" for i in range(n)] draw_graph(G, colors, pos) algorithm_globals.random_seed = 123 seed = 10598 # construct SamplingVQE optimizer = SPSA(maxiter=300) ry = TwoLocal(qubitOp.num_qubits, "ry", "cz", reps=5, entanglement="linear") vqe = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=optimizer) # run SamplingVQE result = vqe.compute_minimum_eigenvalue(qubitOp) # print results x = max_cut.sample_most_likely(result.eigenstate) print("energy:", result.eigenvalue.real) print("time:", result.optimizer_time) print("max-cut objective:", result.eigenvalue.real + offset) print("solution:", x) print("solution objective:", qp.objective.evaluate(x)) # plot results colors = ["r" if x[i] == 0 else "c" for i in range(n)] draw_graph(G, colors, pos) # create minimum eigen optimizer based on SamplingVQE vqe_optimizer = MinimumEigenOptimizer(vqe) # solve quadratic program result = vqe_optimizer.solve(qp) print(result.prettyprint()) colors = ["r" if result.x[i] == 0 else "c" for i in range(n)] draw_graph(G, colors, pos) # Generating a graph of 3 nodes n = 3 num_qubits = n**2 tsp = Tsp.create_random_instance(n, seed=123) adj_matrix = nx.to_numpy_array(tsp.graph) print("distance\n", adj_matrix) colors = ["r" for node in tsp.graph.nodes] pos = [tsp.graph.nodes[node]["pos"] for node in tsp.graph.nodes] draw_graph(tsp.graph, colors, pos) from itertools import permutations def brute_force_tsp(w, N): a = list(permutations(range(1, N))) last_best_distance = 1e10 for i in a: distance = 0 pre_j = 0 for j in i: distance = distance + w[j, pre_j] pre_j = j distance = distance + w[pre_j, 0] order = (0,) + i if distance < last_best_distance: best_order = order last_best_distance = distance print("order = " + str(order) + " Distance = " + str(distance)) return last_best_distance, best_order best_distance, best_order = brute_force_tsp(adj_matrix, n) print( "Best order from brute force = " + str(best_order) + " with total distance = " + str(best_distance) ) def draw_tsp_solution(G, order, colors, pos): G2 = nx.DiGraph() G2.add_nodes_from(G) n = len(order) for i in range(n): j = (i + 1) % n G2.add_edge(order[i], order[j], weight=G[order[i]][order[j]]["weight"]) default_axes = plt.axes(frameon=True) nx.draw_networkx( G2, node_color=colors, edge_color="b", node_size=600, alpha=0.8, ax=default_axes, pos=pos ) edge_labels = nx.get_edge_attributes(G2, "weight") nx.draw_networkx_edge_labels(G2, pos, font_color="b", edge_labels=edge_labels) draw_tsp_solution(tsp.graph, best_order, colors, pos) qp = tsp.to_quadratic_program() print(qp.prettyprint()) from qiskit_optimization.converters import QuadraticProgramToQubo qp2qubo = QuadraticProgramToQubo() qubo = qp2qubo.convert(qp) qubitOp, offset = qubo.to_ising() print("Offset:", offset) print("Ising Hamiltonian:") print(str(qubitOp)) result = exact.solve(qubo) print(result.prettyprint()) # Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector ee = NumPyMinimumEigensolver() result = ee.compute_minimum_eigenvalue(qubitOp) print("energy:", result.eigenvalue.real) print("tsp objective:", result.eigenvalue.real + offset) x = tsp.sample_most_likely(result.eigenstate) print("feasible:", qubo.is_feasible(x)) z = tsp.interpret(x) print("solution:", z) print("solution objective:", tsp.tsp_value(z, adj_matrix)) draw_tsp_solution(tsp.graph, z, colors, pos) algorithm_globals.random_seed = 123 seed = 10598 optimizer = SPSA(maxiter=300) ry = TwoLocal(qubitOp.num_qubits, "ry", "cz", reps=5, entanglement="linear") vqe = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=optimizer) result = vqe.compute_minimum_eigenvalue(qubitOp) print("energy:", result.eigenvalue.real) print("time:", result.optimizer_time) x = tsp.sample_most_likely(result.eigenstate) print("feasible:", qubo.is_feasible(x)) z = tsp.interpret(x) print("solution:", z) print("solution objective:", tsp.tsp_value(z, adj_matrix)) draw_tsp_solution(tsp.graph, z, colors, pos) algorithm_globals.random_seed = 123 seed = 10598 # create minimum eigen optimizer based on SamplingVQE vqe_optimizer = MinimumEigenOptimizer(vqe) # solve quadratic program result = vqe_optimizer.solve(qp) print(result.prettyprint()) z = tsp.interpret(x) print("solution:", z) print("solution objective:", tsp.tsp_value(z, adj_matrix)) draw_tsp_solution(tsp.graph, z, colors, pos) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Qiskit-Extensions/qiskit-ibm-experiment
Qiskit-Extensions
# 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. """Templates for use with unit tests.""" RUNTIME_PROGRAM = """ import random import time import warnings import logging from qiskit import transpile from qiskit.circuit.random import random_circuit logger = logging.getLogger("qiskit-test") def prepare_circuits(backend): circuit = random_circuit(num_qubits=5, depth=4, measure=True, seed=random.randint(0, 1000)) return transpile(circuit, backend) def main(backend, user_messenger, **kwargs): iterations = kwargs['iterations'] sleep_per_iteration = kwargs.pop('sleep_per_iteration', 0) interim_results = kwargs.pop('interim_results', {}) final_result = kwargs.pop("final_result", {}) for it in range(iterations): time.sleep(sleep_per_iteration) qc = prepare_circuits(backend) user_messenger.publish({"iteration": it, "interim_results": interim_results}) backend.run(qc).result() user_messenger.publish(final_result, final=True) print("this is a stdout message") warnings.warn("this is a stderr message") logger.info("this is an info log") """ RUNTIME_PROGRAM_METADATA = { "max_execution_time": 600, "description": "Qiskit test program", } PROGRAM_PREFIX = "qiskit-test"
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector excited = Statevector.from_int(1, 2) plot_bloch_multivector(excited.data) from qiskit.tools.jupyter import * from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main') backend = provider.get_backend('ibmq_armonk') backend_config = backend.configuration() assert backend_config.open_pulse, "Backend doesn't support Pulse" dt = backend_config.dt print(f"Sampling time: {dt*1e9} ns") backend_defaults = backend.defaults() import numpy as np # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz us = 1.0e-6 # Microseconds ns = 1.0e-9 # Nanoseconds # We will find the qubit frequency for the following qubit. qubit = 0 # The Rabi sweep will be at the given qubit frequency. center_frequency_Hz = backend_defaults.qubit_freq_est[qubit] # The default frequency is given in Hz # warning: this will change in a future release print(f"Qubit {qubit} has an estimated frequency of {center_frequency_Hz / GHz} GHz.") from qiskit import pulse, assemble # This is where we access all of our Pulse features! from qiskit.pulse import Play from qiskit.pulse import pulse_lib # This Pulse module helps us build sampled pulses for common pulse shapes ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) inst_sched_map = backend_defaults.instruction_schedule_map measure = inst_sched_map.get('measure', qubits=[0]) # Rabi experiment parameters # Drive amplitude values to iterate over: 50 amplitudes evenly spaced from 0 to 0.75 num_rabi_points = 50 drive_amp_min = 0 drive_amp_max = 0.75 drive_amps = np.linspace(drive_amp_min, drive_amp_max, num_rabi_points) # drive waveforms mush be in units of 16 drive_sigma = 80 # in dt drive_samples = 8*drive_sigma # in dt # Build the Rabi experiments: # A drive pulse at the qubit frequency, followed by a measurement, # where we vary the drive amplitude each time. rabi_schedules = [] for drive_amp in drive_amps: rabi_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_amp, sigma=drive_sigma, name=f"Rabi drive amplitude = {drive_amp}") this_schedule = pulse.Schedule(name=f"Rabi drive amplitude = {drive_amp}") this_schedule += Play(rabi_pulse, drive_chan) # The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration this_schedule += measure << this_schedule.duration rabi_schedules.append(this_schedule) rabi_schedules[-1].draw(label=True, scaling=1.0) # assemble the schedules into a Qobj num_shots_per_point = 1024 rabi_experiment_program = assemble(rabi_schedules, backend=backend, meas_level=1, meas_return='avg', shots=num_shots_per_point, schedule_los=[{drive_chan: center_frequency_Hz}] * num_rabi_points) # RUN the job on a real device #job = backend.run(rabi_experiment_program) #print(job.job_id()) #from qiskit.tools.monitor import job_monitor #job_monitor(job) # OR retreive result from previous run job = backend.retrieve_job("5ef3bf17dc3044001186c011") rabi_results = job.result() import matplotlib.pyplot as plt plt.style.use('dark_background') scale_factor = 1e-14 # center data around 0 def baseline_remove(values): return np.array(values) - np.mean(values) rabi_values = [] for i in range(num_rabi_points): # Get the results for `qubit` from the ith experiment rabi_values.append(rabi_results.get_memory(i)[qubit]*scale_factor) rabi_values = np.real(baseline_remove(rabi_values)) plt.xlabel("Drive amp [a.u.]") plt.ylabel("Measured signal [a.u.]") plt.scatter(drive_amps, rabi_values, color='white') # plot real part of Rabi values plt.show() from scipy.optimize import curve_fit def fit_function(x_values, y_values, function, init_params): fitparams, conv = curve_fit(function, x_values, y_values, init_params) y_fit = function(x_values, *fitparams) return fitparams, y_fit fit_params, y_fit = fit_function(drive_amps, rabi_values, lambda x, A, B, drive_period, phi: (A*np.cos(2*np.pi*x/drive_period - phi) + B), [10, 0.1, 0.6, 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(drive_period/2, color='red', linestyle='--') plt.axvline(drive_period, color='red', linestyle='--') plt.annotate("", xy=(drive_period, 0), xytext=(drive_period/2,0), arrowprops=dict(arrowstyle="<->", color='red')) plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() pi_amp = abs(drive_period / 2) print(f"Pi Amplitude = {pi_amp}") # Drive parameters # The drive amplitude for pi/2 is simply half the amplitude of the pi pulse drive_amp = pi_amp / 2 # x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees x90_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_amp, sigma=drive_sigma, name='x90_pulse') # Ramsey experiment parameters time_max_us = 1.8 time_step_us = 0.025 times_us = np.arange(0.1, time_max_us, time_step_us) # Convert to units of dt delay_times_dt = times_us * us / dt # create schedules for Ramsey experiment ramsey_schedules = [] for delay in delay_times_dt: this_schedule = pulse.Schedule(name=f"Ramsey delay = {delay * dt / us} us") this_schedule += Play(x90_pulse, drive_chan) this_schedule += Play(x90_pulse, drive_chan) << this_schedule.duration + int(delay) this_schedule += measure << this_schedule.duration ramsey_schedules.append(this_schedule) ramsey_schedules[-1].draw(label=True, scaling=1.0) # Execution settings num_shots = 256 detuning_MHz = 2 ramsey_frequency = round(center_frequency_Hz + detuning_MHz * MHz, 6) # need ramsey freq in Hz ramsey_program = assemble(ramsey_schedules, backend=backend, meas_level=1, meas_return='avg', shots=num_shots, schedule_los=[{drive_chan: ramsey_frequency}]*len(ramsey_schedules) ) # RUN the job on a real device #job = backend.run(ramsey_experiment_program) #print(job.job_id()) #from qiskit.tools.monitor import job_monitor #job_monitor(job) # OR retreive job from previous run job = backend.retrieve_job('5ef3ed3a84b1b70012374317') ramsey_results = job.result() ramsey_values = [] for i in range(len(times_us)): ramsey_values.append(ramsey_results.get_memory(i)[qubit]*scale_factor) fit_params, y_fit = fit_function(times_us, np.real(ramsey_values), lambda x, A, del_f_MHz, C, B: ( A * np.cos(2*np.pi*del_f_MHz*x - C) + B ), [5, 1./0.4, 0, 0.25] ) # Off-resonance component _, del_f_MHz, _, _, = fit_params # 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:.2f} MHz") plt.xlim(0, np.max(times_us)) plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15) plt.ylabel('Measured Signal [a.u.]', fontsize=15) plt.title('Ramsey Experiment', fontsize=15) plt.legend() plt.show()
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 core IPython display method from IPython.core.display import display # The core Grover functions def create_oracle(oracle_type,size): from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister global qr, cr qr = QuantumRegister(size) cr = ClassicalRegister(size) oracleCircuit=QuantumCircuit(qr,cr) oracle_type_rev=oracle_type[::-1] for n in range(size-1,-1,-1): if oracle_type_rev[n] =="0": oracleCircuit.x(qr[n]) oracleCircuit.h(qr[size-1]) if size==2: oracleCircuit.cx(qr[size-2],qr[size-1]); if size==3: oracleCircuit.ccx(qr[size-3],qr[size-2],qr[size-1]) if size==4: oracleCircuit.mcx([qr[size-4],qr[size-3],qr[size-2]],qr[size-1]) if size>=5: oracleCircuit.mcx([qr[size-5],qr[size-4],qr[size-3],qr[size-2]],qr[size-1]) oracleCircuit.h(qr[size-1]) for n in range(size-1,-1,-1): if oracle_type_rev[n] =="0": oracleCircuit.x(qr[n]) return(oracleCircuit) def create_amplifier(size): from qiskit import QuantumCircuit # Let's create the amplifier circuit for two qubits. amplifierCircuit=QuantumCircuit(qr,cr) amplifierCircuit.barrier(qr) amplifierCircuit.h(qr) amplifierCircuit.x(qr) amplifierCircuit.h(qr[size-1]) if size==2: amplifierCircuit.cx(qr[size-2],qr[size-1]); if size==3: amplifierCircuit.ccx(qr[size-3],qr[size-2],qr[size-1]) if size==4: amplifierCircuit.mcx([qr[size-4],qr[size-3],qr[size-2]],qr[size-1]) if size>=5: amplifierCircuit.mcx([qr[size-5],qr[size-4],qr[size-3],qr[size-2]],qr[size-1]) amplifierCircuit.h(qr[size-1]) amplifierCircuit.barrier(qr) amplifierCircuit.x(qr) amplifierCircuit.h(qr) return(amplifierCircuit) def create_grover(oracleCircuit,amplifierCircuit,showstep): from qiskit import QuantumCircuit from math import sqrt, pow, pi groverCircuit = QuantumCircuit(qr,cr) # Initiate the Grover with Hadamards if showstep: display_circuit(groverCircuit,True,False) groverCircuit.h(qr) groverCircuit.barrier(qr) if showstep: display_circuit(groverCircuit,True,False) # Add the oracle and the inversion for n in range(int(pi/4*(sqrt(pow(2,oracleCircuit.num_qubits))))): groverCircuit+=oracleCircuit if showstep: display_circuit(groverCircuit,True,False) groverCircuit+=amplifierCircuit if showstep: display_circuit(groverCircuit,True,False) # Add measurements groverCircuit.measure(qr,cr) return(groverCircuit) # The visualizarion functions def print_psi(psi): if len(psi)==2: print("Statevector:\n", round(psi[0].real,3),"|0\u27E9 ", round(psi[1].real,3),"|1\u27E9 ") elif len(psi)==4: print("Statevector:\n", round(psi[0].real,3),"|00\u27E9 ", round(psi[1].real,3),"|01\u27E9 ", round(psi[2].real,3),"|10\u27E9 ", round(psi[3].real,3),"|11\u27E9 ") elif len(psi)==8: print("Statevector:\n", round(psi[0].real,3),"|000\u27E9 ", round(psi[1].real,3),"|001\u27E9 ", round(psi[2].real,3),"|010\u27E9 ", round(psi[3].real,3),"|011\u27E9 ", round(psi[4].real,3),"|100\u27E9 ", round(psi[5].real,3),"|101\u27E9 ", round(psi[6].real,3),"|110\u27E9 ", round(psi[7].real,3),"|111\u27E9 ") else: print("Statevector:\n", psi) def get_psi(circuit, vis): from qiskit.visualization import plot_bloch_multivector, plot_state_qsphere from qiskit import Aer, execute global psi backend = Aer.get_backend('statevector_simulator') psi = execute(circuit, backend).result().get_statevector(circuit) if vis=="Q": display(plot_state_qsphere(psi)) elif vis=="M": print(psi) elif vis=="B": display(plot_bloch_multivector(psi)) vis="" print_psi(psi) return(psi) def print_unitary(circuit): from qiskit import BasicAer, execute import numpy numpy.set_printoptions(formatter={'float': lambda x: "{0:0.2f}".format(x)}) backend = BasicAer.get_backend('unitary_simulator') unit=execute(circuit, backend).result().get_unitary(circuit) print("Unitary matrix:\n") print(unit.real) def display_circuit(circuit,psi,unitary): disp=True if disp: display(circuit.draw(output="mpl")) if psi: get_psi(circuit,"Q") if unitary: print_unitary(circuit) # The execute functions def get_backend(back): from qiskit import Aer, IBMQ from qiskit.providers.ibmq import least_busy if back=="IBMQ": global ibmqbackend print("Loading IBMQ account...") IBMQ.load_account() print("Getting least busy backend...") provider = IBMQ.get_provider() ibmqbackend = least_busy(provider.backends(n_qubits=5, operational=True, simulator=False)) backend = ibmqbackend else: backend = Aer.get_backend('qasm_simulator') return(backend) def run_grover(oracle_type,groverCircuit,backend): from qiskit import execute from qiskit.tools.visualization import plot_histogram from qiskit.tools.monitor import job_monitor print("Sending job to: "+str(backend.name())) shots = 8192 job = execute(groverCircuit, backend, shots=shots) job_monitor(job) results = job.result() answer = results.get_counts() print("Grover search outcome for |"+str(oracle_type)+"\u27E9 oracle") title = "Grover on "+str(backend.name()) display(plot_histogram(answer, title=title)) return(results,backend) def mitigated_results(backend,circuit,results,results_sim): from qiskit import Aer, execute from qiskit import QuantumRegister # Import the required classes from qiskit.providers.aer.noise import NoiseModel from qiskit.ignis.mitigation.measurement import (complete_meas_cal,CompleteMeasFitter) from qiskit.tools.visualization import plot_histogram import numpy numpy.set_printoptions(formatter={'float': lambda x: "{0:0.2f}".format(x)}) # Get noise model for backend noise_model = NoiseModel.from_backend(backend) # Create the measurement fitter qr = QuantumRegister(circuit.num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') job = execute(meas_calibs, backend=Aer.get_backend('qasm_simulator'), shots=8192, noise_model=noise_model) cal_results = job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') print(meas_fitter.cal_matrix) # Get the filter object meas_filter = meas_fitter.filter # Results with mitigation mitigated_results = meas_filter.apply(results) mitigated_counts = mitigated_results.get_counts(0) title = "Mitigated Grover on "+str(ibmqbackend.name()) display(plot_histogram([results_sim.get_counts(),results.get_counts(), mitigated_counts], title=title, legend=['sim','noisy', 'mitigated'])) return(mitigated_counts) def transpile_circuit(circuit,backend): from qiskit.compiler import transpile trans_circ = transpile(circuit, backend) display(trans_circ.draw(output="mpl")) print("Circuit data\n\nDepth: ",trans_circ.depth(),"\nWidth: ",trans_circ.width(),"\nSize: ",trans_circ.size())
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/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit from qiskit import execute from qiskit import BasicAer import numpy as np np.set_printoptions(precision=3, suppress=True) backend = BasicAer.get_backend('qasm_simulator') q = QuantumRegister(1) c = ClassicalRegister(1) circuit = QuantumCircuit(q, c) circuit.measure(q[0], c[0]) job = execute(circuit, backend, shots=100) result = job.result() result.get_counts(circuit) backend = BasicAer.get_backend('statevector_simulator') circuit = QuantumCircuit(q, c) circuit.iden(q[0]) job = execute(circuit, backend) state = job.result().get_statevector(circuit) print(state) from qiskit.tools.visualization import circuit_drawer q = QuantumRegister(1) c = ClassicalRegister(1) circuit = QuantumCircuit(q, c) circuit.measure(q[0], c[0]) circuit_drawer(circuit) from qiskit.tools.visualization import plot_bloch_multivector backend = BasicAer.get_backend('statevector_simulator') circuit = QuantumCircuit(q, c) circuit.iden(q[0]) job = execute(circuit, backend) state = job.result().get_statevector(circuit) print("Initial state") plot_bloch_multivector(state) circuit.h(q[0]) job = execute(circuit, backend) state = job.result().get_statevector(circuit) print("After a Hadamard gate") plot_bloch_multivector(state) from qiskit.tools.visualization import plot_histogram backend = BasicAer.get_backend('qasm_simulator') q = QuantumRegister(1) c = ClassicalRegister(1) circuit = QuantumCircuit(q, c) circuit.measure(q[0], c[0]) job = execute(circuit, backend, shots=1000) print("Initial state statistics") plot_histogram(job.result().get_counts(circuit)) circuit = QuantumCircuit(q, c) circuit.h(q[0]) circuit.measure(q[0], c[0]) job = execute(circuit, backend, shots=1000) print("Statistics if we apply a Hadamard gate") plot_histogram(job.result().get_counts(circuit))
https://github.com/MariosTsatsos/4qubitGrover
MariosTsatsos
#initialization import matplotlib.pyplot as plt %matplotlib inline %config InlineBackend.figure_format = 'svg' # Makes the images look nice 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.visualization import plot_histogram from qiskit.circuit import Parameter from math import pi as pi def n_controlled_Z(circuit, controls, target): """Implement a Z gate with multiple controls""" if (len(controls) > 3): raise ValueError('The controlled Z with more than 3 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) elif (len(controls) == 3): circuit.cu1(pi/4, controls[0], target) circuit.cx(controls[0], controls[1]) circuit.cu1(-pi/4, controls[1],target) circuit.cx(controls[0], controls[1]) circuit.cu1(pi/4, controls[1], target) circuit.cx(controls[1], controls[2]) circuit.cu1(-pi/4, controls[2], target) circuit.cx(controls[0], controls[2]) circuit.cu1(pi/4, controls[2], target) circuit.cx(controls[1], controls[2]) circuit.cu1(-pi/4, controls[2], target) circuit.cx(controls[0], controls[2]) circuit.cu1(pi/4, controls[2], target) def grover_n(circuit, qr, N, barriers = True): j = 0 while j < N: ##################################### ### Oracle for 0010 circuit.x(qr[0]) circuit.x(qr[2]) circuit.x(qr[3]) ######### cccZ ##################### n_controlled_Z(circuit, [qr[i] for i in range(n-1)], qr[n-1]) if barriers: circuit.barrier() circuit.x(qr[0]) circuit.x(qr[2]) circuit.x(qr[3]) if barriers: circuit.barrier() ###################################### #### Amplification circuit.h(qr) circuit.x(qr) ######## cccZ ########### n_controlled_Z(circuit, [qr[i] for i in range(n-1)], qr[n-1]) if barriers: circuit.barrier() circuit.x(qr) circuit.h(qr) if barriers: circuit.barrier() j += 1 print("I implemented gate M.H.B.H",j,"time.") barriers = True theta = Parameter('θ') n = 4 qr = QuantumRegister(n) cr = ClassicalRegister(n) groverCircuit = QuantumCircuit(qr,cr) ########################## ### Initialization groverCircuit.h(qr) if barriers: groverCircuit.barrier() ######################### ### Grover gate - N times grover_n(groverCircuit, qr, 3) ######################### ### measure groverCircuit.measure(qr,cr) groverCircuit.draw(output="mpl") backend = BasicAer.get_backend('qasm_simulator') shots = 2**12 results = execute(groverCircuit, backend=backend, shots=shots).result() answer = results.get_counts() plot_histogram(answer) # Load IBM Q account and get the least busy backend device provider = IBMQ.load_account() device = least_busy(provider.backends(simulator=False)) print("Running on current least busy device: ", device) backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 4 and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.tools.monitor import job_monitor shots = 2**12 job = execute(groverCircuit, backend=backend, shots=shots) job_monitor(job, interval = 2) # Get the results from the computation results = job.result() answer = results.get_counts(groverCircuit) plot_histogram(answer)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.quantum_info import SparsePauliOp H2_op = SparsePauliOp.from_list( [ ("II", -1.052373245772859), ("IZ", 0.39793742484318045), ("ZI", -0.39793742484318045), ("ZZ", -0.01128010425623538), ("XX", 0.18093119978423156), ] ) from qiskit.circuit.library import TwoLocal from qiskit.algorithms.optimizers import SLSQP ansatz = TwoLocal(3, rotation_blocks=["ry", "rz"], entanglement_blocks="cz", reps=1) optimizer = SLSQP() ansatz.decompose().draw('mpl') from qiskit.primitives import Sampler, Estimator from qiskit.algorithms.state_fidelities import ComputeUncompute estimator = Estimator() sampler = Sampler() fidelity = ComputeUncompute(sampler) k = 3 betas = [33, 33, 33] counts = [] values = [] steps = [] def callback(eval_count, params, value, meta, step): counts.append(eval_count) values.append(value) steps.append(step) from qiskit.algorithms.eigensolvers import VQD vqd = VQD(estimator, fidelity, ansatz, optimizer, k=k, betas=betas, callback=callback) result = vqd.compute_eigenvalues(operator = H2_op) vqd_values = result.optimal_values print(vqd_values) import numpy as np import pylab pylab.rcParams["figure.figsize"] = (12, 8) steps = np.asarray(steps) counts = np.asarray(counts) values = np.asarray(values) for i in range(1,4): _counts = counts[np.where(steps == i)] _values = values[np.where(steps == i)] pylab.plot(_counts, _values, label=f"State {i-1}") pylab.xlabel("Eval count") pylab.ylabel("Energy") pylab.title("Energy convergence for each computed state") pylab.legend(loc="upper right"); from qiskit.algorithms.eigensolvers import NumPyEigensolver from qiskit.opflow import PauliSumOp exact_solver = NumPyEigensolver(k=3) exact_result = exact_solver.compute_eigenvalues(PauliSumOp(H2_op)) ref_values = exact_result.eigenvalues print(f"Reference values: {ref_values}") print(f"VQD values: {vqd_values}") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-dell-runtime
qiskit-community
# 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. # Copyright 2021 Dell (www.dell.com) # # 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. from dell_runtime import DellRuntimeProvider import unittest from qiskit import QuantumCircuit, execute, transpile from time import sleep import logging RUNTIME_PROGRAM = """ from qiskit.compiler import transpile, schedule def main( backend, user_messenger, circuits, **kwargs, ): user_messenger.publish({'results': 'intermittently'}) circuits = transpile( circuits, ) if not isinstance(circuits, list): circuits = [circuits] # Compute raw results result = backend.run(circuits, **kwargs).result() user_messenger.publish({'results': 'finally'}) user_messenger.publish(result.to_dict(), final=True) print("job complete successfully") """ FAIL_PROGRAM = """ from qiskit.compiler import transpile, schedule def main( backend, user_messenger, circuits, **kwargs, ): raise Exception('test failure') """ RUNTIME_PROGRAM_METADATA = { "max_execution_time": 600, "description": "Qiskit test program" } logger = logging.getLogger(__name__) class MultiLocalBackendTest(unittest.TestCase): def test_get_results_emulator_backend(self): provider = DellRuntimeProvider() program_id = provider.runtime.upload_program(RUNTIME_PROGRAM, metadata=RUNTIME_PROGRAM_METADATA) qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) program_inputs = { 'circuits': qc, 'backend_name': 'emulator' } job = provider.runtime.run(program_id, options=None, inputs=program_inputs) response = job.result(timeout=120) results = response['results'][0] self.assertIsNotNone(results) self.assertTrue(results['success']) self.assertTrue(results['success']) self.assertEqual("DONE", results['status']) shots = results['shots'] count = results['data']['counts']['0x0'] self.assertGreater(count, (0.45 * shots)) self.assertLess(count, (0.55 * shots)) def test_get_results_aer_backend(self): provider = DellRuntimeProvider() program_id = provider.runtime.upload_program(RUNTIME_PROGRAM, metadata=RUNTIME_PROGRAM_METADATA) qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) program_inputs = { 'circuits': qc, 'backend_name': 'aer_simulator' } job = provider.runtime.run(program_id, options=None, inputs=program_inputs) response = job.result(timeout=120) results = response['results'][0] self.assertIsNotNone(results) self.assertTrue(results['success']) self.assertTrue(results['success']) self.assertEqual("DONE", results['status']) shots = results['shots'] count = results['data']['counts']['0x0'] self.assertGreater(count, (0.45 * shots)) self.assertLess(count, (0.55 * shots))
https://github.com/Rodri-rf/playing_with_quantum_computing
Rodri-rf
from qiskit.synthesis import QDrift from qiskit.circuit.library import PauliEvolutionGate from qiskit import QuantumCircuit from qiskit.quantum_info import Pauli # Define the Hamiltonian XX = Pauli('XX') YY = Pauli('YY') ZZ = Pauli('ZZ') a = 1 b = -1 c = 1 # A simple Hamiltonian: a XX + b YY + c ZZ. Use the appropriate Pauli compose method to do this. hamiltonian = a * XX.compose(b*ZZ) reps = 10 time = 1 evo_gate = PauliEvolutionGate(hamiltonian, time, synthesis=QDrift(reps=reps)) qc = QuantumCircuit(2) qc.append(evo_gate, [0, 1]) qc.draw('mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.second_q.problems import BaseProblem dummy_hamiltonian = None base_problem = BaseProblem(dummy_hamiltonian) print(base_problem.properties) from qiskit_nature.second_q.properties import AngularMomentum print("AngularMomentum is in problem.properties:", AngularMomentum in base_problem.properties) print("Adding AngularMomentum to problem.properties...") base_problem.properties.add(AngularMomentum(2)) print("AngularMomentum is in problem.properties:", AngularMomentum in base_problem.properties) print("Discarding AngularMomentum from problem.properties...") base_problem.properties.discard(AngularMomentum) print("AngularMomentum is in problem.properties:", AngularMomentum in base_problem.properties) from qiskit_nature.second_q.drivers import PySCFDriver es_problem = PySCFDriver().run() print(es_problem.properties.particle_number) print(es_problem.properties.angular_momentum) print(es_problem.properties.magnetization) print(es_problem.properties.electronic_dipole_moment) print(es_problem.properties.electronic_density) from qiskit_nature.second_q.properties import ElectronicDensity density = ElectronicDensity.from_orbital_occupation( es_problem.orbital_occupations, es_problem.orbital_occupations_b, ) es_problem.properties.electronic_density = density 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.timeline import draw, IQXDebugging from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial') draw(qc, style=IQXDebugging())
https://github.com/qiskit-community/community.qiskit.org
qiskit-community
#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 q = QuantumRegister(3, 'q') c = ClassicalRegister(2, 'c') qpe = QuantumCircuit(q, c) qpe.x(q[2]) qpe.h(q[0]) qpe.h(q[1]) # controlled unitary from q[0] is the identity matrix # controlled unitary from q[1] is a controlled-Z gate qpe.cz(q[1], q[2]); def qft(circ, q, n): """n-qubit QFT on q in circ.""" for j in range(n): circ.h(q[j]) for k in range(j+1,n): circ.cu1(math.pi/float(2**(k-j)), q[k], q[j]) def qft_dagger(circ, q, n): """n-qubit QFTdagger on q in circ.""" for j in range(n): k = (n-1) - j for m in range(k): circ.cu1(-math.pi/float(2**(k-m)), q[k], q[m]) circ.h(q[k]) qft_dagger(qpe, q, 2) qpe.measure(q[0],c[0]) qpe.measure(q[1],c[1]) qpe.draw(output="mpl") nancilla = 4 q2 = QuantumRegister(nancilla+2, 'q') c2 = ClassicalRegister(nancilla, 'c') qpe2 = QuantumCircuit(q2, c2) qpe2.x(q2[nancilla]) qpe2.x(q2[nancilla+1]) for i in range(nancilla): qpe2.h(q2[i]) # controlled unitary from q[0] is the identity matrix # controlled unitary from q[1] is the identity matrix # controlled unitary from q[2] is a controlled-Z gate qpe2.h(q2[nancilla+1]) qpe2.ccx(q2[nancilla-1], q2[nancilla], q2[nancilla+1]) qpe2.h(q2[nancilla+1]) qft_dagger(qpe2, q2, nancilla) for i in range(nancilla): qpe2.measure(q2[i],c2[i]) qpe2.draw(output="mpl") backend = BasicAer.get_backend('qasm_simulator') shots = 2048 results = execute(qpe, backend=backend, shots=shots).result() answer = results.get_counts() plot_histogram(answer) results2 = execute(qpe2, backend=backend, shots=shots).result() answer2 = results2.get_counts() plot_histogram(answer2) # Load our saved IBMQ accounts and get the least busy backend device IBMQ.load_account() IBMQ.get_provider(hub='ibm-q') provider.backends() backend = provider.get_backend('ibmq_vigo') from qiskit.tools.monitor import job_monitor shots = 2048 job_exp = execute(qpe, backend=backend, shots=shots) job_monitor(job_exp, interval = 2) # get the results from the computation results = job_exp.result() answer = results.get_counts(qpe) plot_histogram(answer)
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. """The two-local gate circuit.""" from __future__ import annotations import typing from collections.abc import Callable, Sequence from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit import Gate, Instruction, Parameter from .n_local import NLocal from ..standard_gates import ( IGate, XGate, YGate, ZGate, RXGate, RYGate, RZGate, HGate, SGate, SdgGate, TGate, TdgGate, RXXGate, RYYGate, RZXGate, RZZGate, SwapGate, CXGate, CYGate, CZGate, CRXGate, CRYGate, CRZGate, CHGate, ) if typing.TYPE_CHECKING: import qiskit # pylint: disable=cyclic-import class TwoLocal(NLocal): r"""The two-local circuit. The two-local circuit is a parameterized circuit consisting of alternating rotation layers and entanglement layers. The rotation layers are single qubit gates applied on all qubits. The entanglement layer uses two-qubit gates to entangle the qubits according to a strategy set using ``entanglement``. Both the rotation and entanglement gates can be specified as string (e.g. ``'ry'`` or ``'cx'``), as gate-type (e.g. ``RYGate`` or ``CXGate``) or as QuantumCircuit (e.g. a 1-qubit circuit or 2-qubit circuit). A set of default entanglement strategies is provided: * ``'full'`` entanglement is each qubit is entangled with all the others. * ``'linear'`` entanglement is qubit :math:`i` entangled with qubit :math:`i + 1`, for all :math:`i \in \{0, 1, ... , n - 2\}`, where :math:`n` is the total number of qubits. * ``'reverse_linear'`` entanglement is qubit :math:`i` entangled with qubit :math:`i + 1`, for all :math:`i \in \{n-2, n-3, ... , 1, 0\}`, where :math:`n` is the total number of qubits. Note that if ``entanglement_blocks = 'cx'`` then this option provides the same unitary as ``'full'`` with fewer entangling gates. * ``'pairwise'`` entanglement is one layer where qubit :math:`i` is entangled with qubit :math:`i + 1`, for all even values of :math:`i`, and then a second layer where qubit :math:`i` is entangled with qubit :math:`i + 1`, for all odd values of :math:`i`. * ``'circular'`` entanglement is linear entanglement but with an additional entanglement of the first and last qubit before the linear part. * ``'sca'`` (shifted-circular-alternating) entanglement is a generalized and modified version of the proposed circuit 14 in `Sim et al. <https://arxiv.org/abs/1905.10876>`__. It consists of circular entanglement where the 'long' entanglement connecting the first with the last qubit is shifted by one each block. Furthermore the role of control and target qubits are swapped every block (therefore alternating). The entanglement can further be specified using an entangler map, which is a list of index pairs, such as >>> entangler_map = [(0, 1), (1, 2), (2, 0)] If different entanglements per block should be used, provide a list of entangler maps. See the examples below on how this can be used. >>> entanglement = [entangler_map_layer_1, entangler_map_layer_2, ... ] Barriers can be inserted in between the different layers for better visualization using the ``insert_barriers`` attribute. For each parameterized gate a new parameter is generated using a :class:`~qiskit.circuit.library.ParameterVector`. The name of these parameters can be chosen using the ``parameter_prefix``. Examples: >>> two = TwoLocal(3, 'ry', 'cx', 'linear', reps=2, insert_barriers=True) >>> print(two) # decompose the layers into standard gates ┌──────────┐ ░ ░ ┌──────────┐ ░ ░ ┌──────────┐ q_0: ┤ Ry(θ[0]) ├─░───■────────░─┤ Ry(θ[3]) ├─░───■────────░─┤ Ry(θ[6]) ├ ├──────────┤ ░ ┌─┴─┐ ░ ├──────────┤ ░ ┌─┴─┐ ░ ├──────────┤ q_1: ┤ Ry(θ[1]) ├─░─┤ X ├──■───░─┤ Ry(θ[4]) ├─░─┤ X ├──■───░─┤ Ry(θ[7]) ├ ├──────────┤ ░ └───┘┌─┴─┐ ░ ├──────────┤ ░ └───┘┌─┴─┐ ░ ├──────────┤ q_2: ┤ Ry(θ[2]) ├─░──────┤ X ├─░─┤ Ry(θ[5]) ├─░──────┤ X ├─░─┤ Ry(θ[8]) ├ └──────────┘ ░ └───┘ ░ └──────────┘ ░ └───┘ ░ └──────────┘ >>> two = TwoLocal(3, ['ry','rz'], 'cz', 'full', reps=1, insert_barriers=True) >>> qc = QuantumCircuit(3) >>> qc += two >>> print(qc.decompose().draw()) ┌──────────┐┌──────────┐ ░ ░ ┌──────────┐ ┌──────────┐ q_0: ┤ Ry(θ[0]) ├┤ Rz(θ[3]) ├─░──■──■─────░─┤ Ry(θ[6]) ├─┤ Rz(θ[9]) ├ ├──────────┤├──────────┤ ░ │ │ ░ ├──────────┤┌┴──────────┤ q_1: ┤ Ry(θ[1]) ├┤ Rz(θ[4]) ├─░──■──┼──■──░─┤ Ry(θ[7]) ├┤ Rz(θ[10]) ├ ├──────────┤├──────────┤ ░ │ │ ░ ├──────────┤├───────────┤ q_2: ┤ Ry(θ[2]) ├┤ Rz(θ[5]) ├─░─────■──■──░─┤ Ry(θ[8]) ├┤ Rz(θ[11]) ├ └──────────┘└──────────┘ ░ ░ └──────────┘└───────────┘ >>> entangler_map = [[0, 1], [1, 2], [2, 0]] # circular entanglement for 3 qubits >>> two = TwoLocal(3, 'x', 'crx', entangler_map, reps=1) >>> print(two) # note: no barriers inserted this time! ┌───┐ ┌──────────┐┌───┐ q_0: |0>┤ X ├─────■───────────────────────┤ Rx(θ[2]) ├┤ X ├ ├───┤┌────┴─────┐ ┌───┐└─────┬────┘└───┘ q_1: |0>┤ X ├┤ Rx(θ[0]) ├─────■──────┤ X ├──────┼────────── ├───┤└──────────┘┌────┴─────┐└───┘ │ ┌───┐ q_2: |0>┤ X ├────────────┤ Rx(θ[1]) ├───────────■─────┤ X ├ └───┘ └──────────┘ └───┘ >>> entangler_map = [[0, 3], [0, 2]] # entangle the first and last two-way >>> two = TwoLocal(4, [], 'cry', entangler_map, reps=1) >>> circuit = two + two >>> print(circuit.decompose().draw()) # note, that the parameters are the same! q_0: ─────■───────────■───────────■───────────■────── │ │ │ │ q_1: ─────┼───────────┼───────────┼───────────┼────── │ ┌────┴─────┐ │ ┌────┴─────┐ q_2: ─────┼──────┤ Ry(θ[1]) ├─────┼──────┤ Ry(θ[1]) ├ ┌────┴─────┐└──────────┘┌────┴─────┐└──────────┘ q_3: ┤ Ry(θ[0]) ├────────────┤ Ry(θ[0]) ├──────────── └──────────┘ └──────────┘ >>> layer_1 = [(0, 1), (0, 2)] >>> layer_2 = [(1, 2)] >>> two = TwoLocal(3, 'x', 'cx', [layer_1, layer_2], reps=2, insert_barriers=True) >>> print(two) ┌───┐ ░ ░ ┌───┐ ░ ░ ┌───┐ q_0: ┤ X ├─░───■────■───░─┤ X ├─░───────░─┤ X ├ ├───┤ ░ ┌─┴─┐ │ ░ ├───┤ ░ ░ ├───┤ q_1: ┤ X ├─░─┤ X ├──┼───░─┤ X ├─░───■───░─┤ X ├ ├───┤ ░ └───┘┌─┴─┐ ░ ├───┤ ░ ┌─┴─┐ ░ ├───┤ q_2: ┤ X ├─░──────┤ X ├─░─┤ X ├─░─┤ X ├─░─┤ X ├ └───┘ ░ └───┘ ░ └───┘ ░ └───┘ ░ └───┘ """ def __init__( self, num_qubits: int | None = None, rotation_blocks: str | type | qiskit.circuit.Instruction | QuantumCircuit | list[str | type | qiskit.circuit.Instruction | QuantumCircuit] | None = None, entanglement_blocks: str | type | qiskit.circuit.Instruction | QuantumCircuit | list[str | type | qiskit.circuit.Instruction | QuantumCircuit] | None = None, entanglement: str | list[list[int]] | Callable[[int], list[int]] = "full", reps: int = 3, skip_unentangled_qubits: bool = False, skip_final_rotation_layer: bool = False, parameter_prefix: str = "θ", insert_barriers: bool = False, initial_state: QuantumCircuit | None = None, name: str = "TwoLocal", flatten: bool | None = None, ) -> None: """ Args: num_qubits: The number of qubits of the two-local circuit. rotation_blocks: The gates used in the rotation layer. Can be specified via the name of a gate (e.g. ``'ry'``) or the gate type itself (e.g. :class:`.RYGate`). If only one gate is provided, the gate same gate is applied to each qubit. If a list of gates is provided, all gates are applied to each qubit in the provided order. See the Examples section for more detail. entanglement_blocks: The gates used in the entanglement layer. Can be specified in the same format as ``rotation_blocks``. entanglement: Specifies the entanglement structure. Can be a string (``'full'``, ``'linear'``, ``'reverse_linear'``, ``'circular'`` or ``'sca'``), a list of integer-pairs specifying the indices of qubits entangled with one another, or a callable returning such a list provided with the index of the entanglement layer. Default to ``'full'`` entanglement. Note that if ``entanglement_blocks = 'cx'``, then ``'full'`` entanglement provides the same unitary as ``'reverse_linear'`` but the latter option has fewer entangling gates. See the Examples section for more detail. reps: Specifies how often a block consisting of a rotation layer and entanglement layer is repeated. skip_unentangled_qubits: If ``True``, the single qubit gates are only applied to qubits that are entangled with another qubit. If ``False``, the single qubit gates are applied to each qubit in the ansatz. Defaults to ``False``. skip_final_rotation_layer: If ``False``, a rotation layer is added at the end of the ansatz. If ``True``, no rotation layer is added. parameter_prefix: The parameterized gates require a parameter to be defined, for which we use instances of :class:`~qiskit.circuit.Parameter`. The name of each parameter will be this specified prefix plus its index. insert_barriers: If ``True``, barriers are inserted in between each layer. If ``False``, no barriers are inserted. Defaults to ``False``. initial_state: A :class:`.QuantumCircuit` object to prepend to the circuit. flatten: Set this to ``True`` to output a flat circuit instead of nesting it inside multiple layers of gate objects. By default currently the contents of the output circuit will be wrapped in nested objects for cleaner visualization. However, if you're using this circuit for anything besides visualization its **strongly** recommended to set this flag to ``True`` to avoid a large performance overhead for parameter binding. """ super().__init__( num_qubits=num_qubits, rotation_blocks=rotation_blocks, entanglement_blocks=entanglement_blocks, entanglement=entanglement, reps=reps, skip_final_rotation_layer=skip_final_rotation_layer, skip_unentangled_qubits=skip_unentangled_qubits, insert_barriers=insert_barriers, initial_state=initial_state, parameter_prefix=parameter_prefix, name=name, flatten=flatten, ) def _convert_to_block(self, layer: str | type | Gate | QuantumCircuit) -> QuantumCircuit: """For a layer provided as str (e.g. ``'ry'``) or type (e.g. :class:`.RYGate`) this function returns the according layer type along with the number of parameters (e.g. ``(RYGate, 1)``). Args: layer: The qubit layer. Returns: The specified layer with the required number of parameters. Raises: TypeError: The type of ``layer`` is invalid. ValueError: The type of ``layer`` is str but the name is unknown. ValueError: The type of ``layer`` is type but the layer type is unknown. Note: Outlook: If layers knew their number of parameters as static property, we could also allow custom layer types. """ if isinstance(layer, QuantumCircuit): return layer # check the list of valid layers # this could be a lot easier if the standard layers would have ``name`` and ``num_params`` # as static types, which might be something they should have anyway theta = Parameter("θ") valid_layers = { "ch": CHGate(), "cx": CXGate(), "cy": CYGate(), "cz": CZGate(), "crx": CRXGate(theta), "cry": CRYGate(theta), "crz": CRZGate(theta), "h": HGate(), "i": IGate(), "id": IGate(), "iden": IGate(), "rx": RXGate(theta), "rxx": RXXGate(theta), "ry": RYGate(theta), "ryy": RYYGate(theta), "rz": RZGate(theta), "rzx": RZXGate(theta), "rzz": RZZGate(theta), "s": SGate(), "sdg": SdgGate(), "swap": SwapGate(), "x": XGate(), "y": YGate(), "z": ZGate(), "t": TGate(), "tdg": TdgGate(), } # try to exchange `layer` from a string to a gate instance if isinstance(layer, str): try: layer = valid_layers[layer] except KeyError as ex: raise ValueError(f"Unknown layer name `{layer}`.") from ex # try to exchange `layer` from a type to a gate instance if isinstance(layer, type): # iterate over the layer types and look for the specified layer instance = None for gate in valid_layers.values(): if isinstance(gate, layer): instance = gate if instance is None: raise ValueError(f"Unknown layer type`{layer}`.") layer = instance if isinstance(layer, Instruction): circuit = QuantumCircuit(layer.num_qubits) circuit.append(layer, list(range(layer.num_qubits))) return circuit raise TypeError( f"Invalid input type {type(layer)}. " + "`layer` must be a type, str or QuantumCircuit." ) def get_entangler_map( self, rep_num: int, block_num: int, num_block_qubits: int ) -> Sequence[Sequence[int]]: """Overloading to handle the special case of 1 qubit where the entanglement are ignored.""" if self.num_qubits <= 1: return [] return super().get_entangler_map(rep_num, block_num, num_block_qubits)
https://github.com/farhad-abdi/InSilicoQ
farhad-abdi
""" A collection of quantum graph based algorithms, the algorthms are mostly based on Grover Serach algorithm""" from qiskit import QuantumCircuit class MST: """ Mininum Spanning Tree Implementation """ def __init__(self, num_qubit): self.num_q = num_qubit def oracle_mst(self): oracle = QuantumCircuit(self.num_q) return oracle def diffuser_mst(self): diffuser = QuantumCircuit(self.num_q) return diffuser
https://github.com/JayantiSingh/Quant_co_Qiskit
JayantiSingh
# X-gate the quantum equivalent of the NOT gate /bit-flip gate q = QuantumRegister (1) qc = QuantumCircuit (q) qc.x(q[0]) qc.draw(output='mpl') # Z-gate /Phase-shift gate q = QuantumRegister (1) qc = QuantumCircuit (q) qc.z(q[0]) qc.draw(output='mpl') # H-gate a measurement will have equal probabilities to become 1 or 0 creating a 'superposition' of states /Hadamard gate q = QuantumRegister (1) qc = QuantumCircuit (q) qc.h(q[0]) qc.draw(output='mpl') # CX-gate performs the NOT operation (equivalent to applying an X gate) on the second qubit only when the first qubit is |1>, and otherwise leaves it unchanged./CNOT gate q = QuantumRegister (2) qc = QuantumCircuit (q) qc.cx(q[0],q[1]) qc.draw(output='mpl') # CZ-gate It flips the sign of the target qubit if and only if the control qubit is |1>. q = QuantumRegister (2) qc = QuantumCircuit (q) qc.cz(q[0],q[1]) qc.draw(output='mpl') # CZ-gate costructed from CX-gate and H-gate q = QuantumRegister (2) qc = QuantumCircuit (q) qc.h(q[1]) qc.cx(q[0],q[1]) qc.h(q[1]) qc.draw(output='mpl')
https://github.com/tanmaybisen31/Quantum-Teleportation
tanmaybisen31
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit,execute, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() from qiskit.visualization import plot_state_qsphere from qiskit.visualization import plot_bloch_multivector qc=QuantumCircuit(1) statevector_simulator = Aer.get_backend('statevector_simulator') result=execute(qc,statevector_simulator).result() statevector_results=result.get_statevector(qc) plot_bloch_multivector(statevector_results) plot_state_qsphere(statevector_results) qc.x(0) result=execute(qc,statevector_simulator).result() statevector_results=result.get_statevector(qc) plot_bloch_multivector(statevector_results) plot_state_qsphere(statevector_results) qc.h(0) result=execute(qc,statevector_simulator).result() statevector_results=result.get_statevector(qc) plot_bloch_multivector(statevector_results) plot_state_qsphere(statevector_results)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np import pylab from qiskit import LegacySimulators from qiskit_chemistry import QiskitChemistry import time # Input dictionary to configure Qiskit Chemistry for the chemistry problem. qiskit_chemistry_dict = { 'driver': {'name': 'PYSCF'}, 'PYSCF': {'atom': '', 'basis': 'sto3g'}, 'operator': {'name': 'hamiltonian', 'transformation': 'full', 'qubit_mapping': 'parity'}, 'algorithm': {'name': ''}, 'initial_state': {'name': 'HartreeFock'}, } molecule = 'H .0 .0 -{0}; H .0 .0 {0}' algorithms = [ { 'name': 'IQPE', 'num_iterations': 16, 'num_time_slices': 3000, 'expansion_mode': 'trotter', 'expansion_order': 1, }, { 'name': 'ExactEigensolver' } ] backends = [ LegacySimulators.get_backend('qasm_simulator'), None ] start = 0.5 # Start distance by = 0.5 # How much to increase distance by steps = 20 # Number of steps to increase by energies = np.empty([len(algorithms), steps+1]) hf_energies = np.empty(steps+1) distances = np.empty(steps+1) import concurrent.futures import multiprocessing as mp import copy def subrountine(i, qiskit_chemistry_dict, d, backend, algorithm): solver = QiskitChemistry() qiskit_chemistry_dict['PYSCF']['atom'] = molecule.format(d/2) qiskit_chemistry_dict['algorithm'] = algorithm result = solver.run(qiskit_chemistry_dict, backend=backend) return i, d, result['energy'], result['hf_energy'] start_time = time.time() max_workers = max(4, mp.cpu_count()) with concurrent.futures.ProcessPoolExecutor(max_workers=max_workers) as executor: futures = [] for j in range(len(algorithms)): algorithm = algorithms[j] backend = backends[j] for i in range(steps+1): d = start + i*by/steps future = executor.submit( subrountine, i, copy.deepcopy(qiskit_chemistry_dict), d, backend, algorithm ) futures.append(future) for future in concurrent.futures.as_completed(futures): i, d, energy, hf_energy = future.result() energies[j][i] = energy hf_energies[i] = hf_energy distances[i] = d print(' --- complete') print('Distances: ', distances) print('Energies:', energies) print('Hartree-Fock energies:', hf_energies) print("--- %s seconds ---" % (time.time() - start_time)) pylab.plot(distances, hf_energies, label='Hartree-Fock') for j in range(len(algorithms)): pylab.plot(distances, energies[j], label=algorithms[j]['name']) pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('H2 Ground State Energy') pylab.legend(loc='upper right') pylab.show() pylab.plot(distances, np.subtract(hf_energies, energies[1]), label='Hartree-Fock') pylab.plot(distances, np.subtract(energies[0], energies[1]), label='IQPE') pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('Energy difference from ExactEigensolver') pylab.legend(loc='upper right') pylab.show()
https://github.com/acfilok96/Quantum-Computation
acfilok96
import qiskit from qiskit import * print(qiskit.__version__) %matplotlib inline from qiskit.tools.visualization import plot_histogram from ibm_quantum_widgets import draw_circuit circuit = QuantumCircuit(2,2) circuit circuit.draw(output='mpl') circuit.x(0) circuit.draw(output='mpl') circuit.h(0) circuit.draw(output='mpl') circuit.cx(0,1) circuit.draw(output='mpl') circuit.measure([0,1],[1,1]) circuit.draw(output='mpl') draw_circuit(circuit) simulator = Aer.get_backend('qasm_simulator') simulator job = execute(circuit, backend=simulator, shots=1024) job result = job.result() result counts = result.get_counts() counts plot_histogram(counts)
https://github.com/abbarreto/qiskit2
abbarreto
import numpy as np import matplotlib from matplotlib import pyplot as plt import math th = np.arange(0, 2*math.pi, 0.1) prE3 = 2*(1-(math.sqrt(2)*(np.sin(th/2)**2))/(1+math.sqrt(2))) matplotlib.rcParams.update({'font.size':10}) plt.figure(figsize = (5,3), dpi = 100) plt.plot(th, prE3) plt.xlabel(r'$\theta$') plt.ylabel(r'$Pr(E_{3})$') plt.show()
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
# 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 * # useful to have pi import math pi=math.pi # Loading your IBM Q account(s) provider = IBMQ.load_account() device = provider.get_backend('ibmq_5_yorktown') qc=QuantumCircuit(3) qc.ccx(0,1,2) new_circuit = transpile(qc,backend=device) new_circuit.draw(output='mpl') qc = QuantumCircuit(3) theta = pi # Theta can be anything (pi chosen arbitrarily) # qc.h(2) gets replaced with qc.rz(pi/2, 2) qc.sx(2) qc.rz(pi/2, 2) #already basic gate qc.cx(1,2) # qc.tdg(2) gets replaced with qc.rz(7*pi/4, 2) #already basic gate qc.cx(0,2) # qc.t(2) gets replaced with qc.rz(pi/4, 2) #Already a basic gate qc.cx(1,2) # qc.tdg(2) gets replaced with qc.rz(7*pi/4, 2) #already a basic gate qc.cx(0,2) # qc.t(1) gets replaced with qc.rz(pi/4, 1) # qc.t(2) gets replaced with qc.rz(pi/4, 2) # qc.h(2) gets replaced with qc.rz(pi/2, 2) qc.sx(2) qc.rz(pi/2, 2) #Already a basic gate qc.cx(0,1) # qc.t(0) gets replaced with qc.rz(pi/4, 0) # qc.tdg(1) gets replaced with qc.rz(pi/4, 1) #already a basic gate qc.cx(0,1) qc.draw()
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from scipy.stats import kruskal, f_oneway import pandas as pd import numpy as np #if p value less than alpha reject qiskit_data = np.concatenate((np.full(245, 0.75), np.full(264, 0.5), np.full(243, 0.25), np.full(248, 0))) cirq_data = np.concatenate((np.full(259, 0.75), np.full(234, 0.5), np.full(249, 0.25), np.full(258, 0))) qs_data = np.concatenate((np.full(260, 0.75), np.full(234, 0.5), np.full(264, 0.25), np.full(242, 0))) kruskal(qiskit_data, cirq_data, qs_data) #if p value less than alpha reject qiskit_data = np.concatenate((np.full(254, 0.75), np.full(254, 0.5), np.full(230, 0.25), np.full(262, 0))) cirq_data = np.concatenate((np.full(251, 0.75), np.full(258, 0.5), np.full(269, 0.25), np.full(222, 0))) qs_data = np.concatenate((np.full(254, 0.75), np.full(232, 0.5), np.full(268, 0.25), np.full(246, 0))) kruskal(qiskit_data, cirq_data, qs_data) #if p value less than alpha reject qiskit_data = np.concatenate((np.full(486, 0.5), np.full(514, 0))) cirq_data = np.concatenate((np.full(483, 0.5), np.full(517, 0))) qs_data = np.concatenate((np.full(491, 0.5), np.full(509, 0))) kruskal(qiskit_data, cirq_data, qs_data) #if p value less than alpha reject qiskit_data = np.concatenate((np.full(246, 0.75), np.full(226, 0.5), np.full(237, 0.25), np.full(291, 0))) cirq_data = np.concatenate((np.full(247, 0.75), np.full(272, 0.5), np.full(230, 0.25), np.full(251, 0))) qs_data = np.concatenate((np.full(262, 0.75), np.full(243, 0.5), np.full(251, 0.25), np.full(244, 0))) kruskal(qiskit_data, cirq_data, qs_data) #if p value less than alpha reject qiskit_data = np.concatenate((np.full(651, 3+5), np.full(349, 3))) cirq_data = np.concatenate((np.full(685, 3+5), np.full(315, 3))) qs_data = np.concatenate((np.full(662, 3+5), np.full(338, 3))) kruskal(qiskit_data, cirq_data, qs_data) #if p value less than alpha reject qiskit_data = np.concatenate((np.full(1000, 3+5), np.full(0, 3))) cirq_data = np.concatenate((np.full(1000, 3+5), np.full(0, 3))) qs_data = np.concatenate((np.full(1000, 3+5), np.full(0, 3))) kruskal(qiskit_data, cirq_data, qs_data)
https://github.com/Tojarieh97/VQE
Tojarieh97
%load_ext autoreload %autoreload 2 import nbimporter from typing import Dict, Tuple, List import numpy as np from tqdm import tqdm QUBITS_NUM = 4 N = 16 K = 4 NUM_SHOTS = 1024 NUM_ITERATIONS = 50 w = 0.5 approximated_energies = [] from qiskit import Aer from qiskit.utils import QuantumInstance, algorithm_globals seed = 50 algorithm_globals.random_seed = seed simulator_backend = Aer.get_backend('qasm_simulator') from scipy.optimize import minimize from utiles import * input_states = get_first_k_eigenvectors_from_n_computational_basis(K, N) from ansatz_circuit_item2 import get_full_variational_quantum_circuit init_circuit_params = { "thetas": np.random.uniform(low=0, high=2*np.pi, size=8), "phis": np.random.uniform(low=0, high=2*np.pi, size=4), "D1": 2, "D2": 6 } def prepare_circuit_params(thetas) -> Dict: return { "thetas": thetas[4:], "phis": thetas[:4], "D1": 2, "D2": 6 } def get_ansatz_state(circuit_params, input_state): circuit_params_with_input_state = {**circuit_params, "input_state": input_state} return get_full_variational_quantum_circuit(**circuit_params_with_input_state) def transfrom_hamiltonian_into_pauli_strings(hamiltonian) -> List: pauli_operators = hamiltonian.to_pauli_op().settings['oplist'] pauli_coeffs = list(map(lambda pauli_operator: pauli_operator.coeff, pauli_operators)) pauli_strings = list(map(lambda pauli_operator: pauli_operator.primitive, pauli_operators)) return pauli_coeffs, pauli_strings from qiskit.circuit.library.standard_gates import HGate, SGate from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister reducing_to_pauli_z_mapping = { 'I': 'I', 'Z': 'Z', 'X': 'Z', 'Y': 'Z' } def reduce_pauli_matrixes_into_sigma_z(pauli_string) -> str: reduced_pauli_string = "" for matrix_index in range(QUBITS_NUM): pauli_matrix = str(pauli_string[matrix_index]) reduced_pauli_matrix = reducing_to_pauli_z_mapping[pauli_matrix] reduced_pauli_string = reduced_pauli_matrix + reduced_pauli_string return reduced_pauli_string def add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string, quantum_circuit): quantum_registers = QuantumRegister(QUBITS_NUM, name="qubit") additional_circuit_layer = QuantumCircuit(quantum_registers) for quantum_register_index, pauli_matrix in enumerate(pauli_string): if pauli_matrix == "X": additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]]) if pauli_string == "Y": additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]]) additional_circuit_layer.append(SGate(), [quantum_registers[quantum_register_index]]) extended_quantum_circuit = quantum_circuit.compose(additional_circuit_layer) return extended_quantum_circuit def get_probability_distribution(counts: Dict) -> Dict: proba_distribution = {state: (count / NUM_SHOTS) for state, count in counts.items()} return proba_distribution def calculate_probabilities_of_measurments_in_computational_basis(quantum_state_circuit) -> Dict: quantum_state_circuit.measure_all() transpiled_quantum_state_circuit = transpile(quantum_state_circuit, simulator_backend) Qobj = assemble(transpiled_quantum_state_circuit) result = simulator_backend.run(Qobj).result() counts = result.get_counts(quantum_state_circuit) return get_probability_distribution(counts) def sort_probas_dict_by_qubits_string_keys(proba_distribution: Dict) -> Dict: return dict(sorted(proba_distribution.items())) def reset_power_of_minus_1(power_of_minus_1): power_of_minus_1 = 0 return power_of_minus_1 def convert_pauli_string_into_str(pauli_string) -> str: return str(pauli_string) def calculate_expectation_value_of_pauli_string_by_measurments_probas(pauli_string, ansatz_circuit): pauli_string_expectation_value = 0 power_of_minus_1 = 0 pauli_string_str = convert_pauli_string_into_str(pauli_string) extended_ansatz_circuit = add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string_str, ansatz_circuit) probas_distribution = calculate_probabilities_of_measurments_in_computational_basis(extended_ansatz_circuit) reduced_pauli_string = reduce_pauli_matrixes_into_sigma_z(pauli_string) sorted_probas_distribuition = sort_probas_dict_by_qubits_string_keys(probas_distribution) for qubits_string, proba in sorted_probas_distribuition.items(): for string_index in range(QUBITS_NUM): if(str(qubits_string[string_index])=="1" and str(pauli_string[string_index])=="Z"): power_of_minus_1 += 1 pauli_string_expectation_value += pow(-1, power_of_minus_1)*proba power_of_minus_1 = reset_power_of_minus_1(power_of_minus_1) return pauli_string_expectation_value def get_expectation_value(ansatz_circuit, pauli_coeffs, pauli_strings): total_expection_value = 0 for pauli_coeff, pauli_string in zip(pauli_coeffs, pauli_strings): total_expection_value += pauli_coeff*calculate_expectation_value_of_pauli_string_by_measurments_probas( pauli_string, ansatz_circuit) return total_expection_value from qiskit import assemble, transpile def cost_function(thetas, hamiltonian): circuit_params = prepare_circuit_params(thetas) computational_eigenvectors = get_first_k_eigenvectors_from_n_computational_basis(K, N) pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian) k_ansatz_state = get_ansatz_state(circuit_params, computational_eigenvectors[K-1]) approximated_energey = get_expectation_value(k_ansatz_state, pauli_coeffs, pauli_strings) insert_approximated_energy_to_list_of_all_approximated_energies(approximated_energey) L_w = w*approximated_energey for j in range(K-1): ansatz_state = get_ansatz_state(circuit_params, computational_eigenvectors[j]) L_w += get_expectation_value(ansatz_state, pauli_coeffs, pauli_strings) return L_w def get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian): initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=12) optimizer_result = minimize(cost_function,x0=initial_thetas,args=(hamiltonian),method="BFGS",options={"maxiter":NUM_ITERATIONS}) optimal_thetas = prepare_circuit_params(optimizer_result.x) return optimal_thetas def get_approximated_eigenvalue_of_hamiltonian(hamiltonian): optimal_thetas = get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian) print(optimal_thetas) computational_eigenvectors = get_first_k_eigenvectors_from_n_computational_basis(K, N) optimal_ansatz_state = get_ansatz_state(optimal_thetas, computational_eigenvectors[K-1]) pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian) approximated_eigenvalue = get_expectation_value(optimal_ansatz_state, pauli_coeffs, pauli_strings) return approximated_eigenvalue from numpy import linalg as LA def get_approximation_error(exact_eigenvalue, approximated_eigenvalue): return abs(abs(exact_eigenvalue)-abs(approximated_eigenvalue))/abs(exact_eigenvalue) def get_k_exact_eigenvalue_of_hamiltonian(hamiltonian, k): eigen_values = LA.eig(hamiltonian.to_matrix())[0] print(sorted(eigen_values, reverse=True)) return sorted(eigen_values,reverse=True)[k-1] def compare_exact_and_approximated_eigenvalue(hamiltonian, approximated_eigenvalue): exact_eigenvalue = get_k_exact_eigenvalue_of_hamiltonian(hamiltonian, K) print("Exact Eigenvalue:") print(exact_eigenvalue) print("Approximated K Eigenvalues:") print(approximated_eigenvalue) print("Approximation Error") print(get_approximation_error(exact_eigenvalue, approximated_eigenvalue)) def insert_approximated_energy_to_list_of_all_approximated_energies(energy): approximated_energies.append(energy) import matplotlib.pyplot as plt def plot_convergence_of_optimization_process(approximated_energies, exact_eigenvalue, margin): plt.title("convergence of optimization process to the exact eigenvalue") plt.margins(0, margin) plt.plot(approximated_energies[-NUM_ITERATIONS:]) plt.axhline(y = exact_eigenvalue, color = 'r', linestyle = '-') plt.grid() plt.xlabel("# of iterations") plt.ylabel("Energy") def plot_fidelity(): plt.plot(LiH_approximated_energies) plt.xlabel("# of iterations") plt.ylabel("Energy") from qiskit.opflow import X, Z, I, H, Y LiH_molecule_4_qubits = -7.49894690201071*(I^I^I^I) + \ -0.0029329964409502266*(X^X^Y^Y) + \ 0.0029329964409502266*(X^Y^Y^X) + \ 0.01291078027311749*(X^Z^X^I) + \ -0.0013743761078958677*(X^Z^X^Z) + \ 0.011536413200774975*(X^I^X^I) + \ 0.0029329964409502266*(Y^X^X^Y) + \ -0.0029329964409502266*(Y^Y^X^X) + \ 0.01291078027311749*(Y^Z^Y^I) + \ -0.0013743761078958677*(Y^Z^Y^Z) + \ 0.011536413200774975*(Y^I^Y^I) + \ 0.16199475388004184*(Z^I^I^I) + \ 0.011536413200774975*(Z^X^Z^X) + \ 0.011536413200774975*(Z^Y^Z^Y) + \ 0.12444770133137588*(Z^Z^I^I) + \ 0.054130445793298836*(Z^I^Z^I) + \ 0.05706344223424907*(Z^I^I^Z) + \ 0.012910780273117487*(I^X^Z^X) + \ -0.0013743761078958677*(I^X^I^X) + \ 0.012910780273117487*(I^Y^Z^Y) + \ -0.0013743761078958677*(I^Y^I^Y) + \ 0.16199475388004186*(I^Z^I^I) + \ 0.05706344223424907*(I^Z^Z^I) + \ 0.054130445793298836*(I^Z^I^Z) + \ -0.013243698330265966*(I^I^Z^I) + \ 0.08479609543670981*(I^I^Z^Z) + \ -0.013243698330265952*(I^I^I^Z) %%time LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits) compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue) print(approximated_energies) approximated_energies = [] LiH_approximated_energies = [-7.5811722185398285, -7.59159646344728, -7.591712498431583, -7.5823144711155255, -7.601228227804495, -7.5736138923664065, -7.599055184917277, -7.595389384370309, -7.586873555877376, -7.586779572764962, -7.587446891289177, -7.58816416037616, -7.606319025241597, -7.5468150612323015, -7.54795274923913, -7.561365217492775, -7.560844694104422, -7.548328551094029, -7.556729381819861, -7.5501822152874825, -7.552787397268313, -7.567509848511693, -7.573107964123815, -7.541648049799553, -7.546799664950377, -7.53654352129788, -7.589160003564084, -7.578598759247515, -7.590933004721402, -7.588143540217285, -7.594244897237276, -7.587510169441045, -7.5868306475144776, -7.587602605379268, -7.59225930178968, -7.5988486139694436, -7.573672664147123, -7.587077981079782, -7.589894569667096, -7.593989957965422, -7.5934638061012665, -7.586978945437706, -7.576471075379983, -7.586002143566326, -7.593009863418946, -7.594930172385808, -7.588512242648442, -7.60293471934649, -7.591877985644651, -7.580969380150128, -7.596119932713606, -7.615516216961582, -7.596055304700592, -7.5996270334260725, -7.586983361838935, -7.596246225349671, -7.590777615173849, -7.5935751302098256, -7.592837174684869, -7.603790076682524, -7.6093363504202145, -7.60522230882189, -7.577824083506902, -7.583940898791256, -7.585838556976443, -7.591352114525316, -7.586985421943245, -7.590516288197774, -7.592645661018166, -7.6022590957403695, -7.591330646171517, -7.594369777609106, -7.588063188591844, -7.590887567834473, -7.58529252287314, -7.590260727471608, -7.592442375670534, -7.588704468391091, -7.589907345471134, -7.594705545462669, -7.6098627506974665, -7.595941589491842, -7.594781927195355, -7.583709436067628, -7.601491453462858, -7.597492855351171, -7.596534669869249, -7.588718115470418, -7.580497184080997, -7.583102004301224, -7.591826652364619, -7.5996868685846355, -7.588597363608952, -7.5813554074546055, -7.583835495117783, -7.59064434908851, -7.58437365137141, -7.590315760666925, -7.597855922766573, -7.590740727486217, -7.596056737044825, -7.5902279046692325, -7.609184282492802, -7.591748265755058, -7.602981872142157, -7.59998915723516, -7.588200490143084, -7.591025078502806, -7.588051902013782, -7.611052590540253, -7.587486622263765, -7.591803731736747, -7.589835728854846, -7.593340824035681, -7.581866774777097, -7.58836662913097, -7.6053870554693805, -7.590489094786991, -7.580771153453858, -7.5905219906055565, -7.602079027418958, -7.59869534734383, -7.592327067764258, -7.586492679563721, -7.5900307096383495, -7.605871180701457, -7.583686251845164, -7.59084383030994, -7.591011259270283, -7.609378670021997, -7.602092819996155, -7.5890139534539784, -7.586869308169689, -7.585646372448603, -7.58076297152655, -7.609251035755286, -7.591515311689081, -7.59257083904225, -7.584083715434293, -7.586450125487619, -7.593598728550749, -7.580488061773295, -7.605496242684976, -7.593414651298946, -7.60217927693839, -7.576912879829302, -7.604154147713128, -7.6084567317964975, -7.578611304029224, -7.591686370715707, -7.596609189738003, -7.5779236456467185, -7.600899390110624, -7.589656688978693, -7.591824476469537, -7.588295121277478, -7.604646934476692, -7.599305159948481, -7.601823274459693, -7.599153286574935, -7.59398640868234, -7.594623264414274, -7.563535780759224, -7.5907374418716795, -7.584497327439853, -7.598880523136912, -7.589930732585632, -7.596773581756135, -7.5820404386071925, -7.591745408563035, -7.595021082718484, -7.591871643380514, -7.5923783623174295, -7.588662444757317, -7.601348684176666, -7.604692130795216, -7.581271720491602, -7.592316763268401, -7.599557460899818, -7.590233868866651, -7.60106633139657, -7.591029502106871, -7.590946526294125, -7.578047392804944, -7.584371216579831, -7.58297181596419, -7.593260068364673, -7.588794164898488, -7.595498777698822, -7.57844959725151, -7.601455854688926, -7.591515635688625, -7.5844746837553405, -7.590480735122996, -7.59115080196329, -7.583228595085926, -7.591838539639781, -7.5880938775924935, -7.591635548561748, -7.591955549690062, -7.598088450438071, -7.582096714835912, -7.588480649207663, -7.575017322673416, -7.591209269166958, -7.582617613707098, -7.596106095701603, -7.562895071846649, -7.581176362485807, -7.578569198893786, -7.591395966192013, -7.589017847713364, -7.576334250015566, -7.587794803768129, -7.616990543910279, -7.5906539038020435, -7.586853063919036, -7.585559440057858, -7.584803368513558, -7.597555640231412, -7.595228097920501, -7.595190095630545, -7.590903350802588, -7.591718676589801, -7.586795506030791, -7.580612481966594, -7.593603416733997, -7.598238714945253, -7.605972868167942, -7.584061079920518, -7.587272086190425, -7.60479190195469, -7.6013951681300655, -7.593690915438579, -7.599320500571691, -7.58002377916205, -7.597620308675762, -7.595205045762717, -7.601282182510587, -7.5764528159136475, -7.58003542137329, -7.577500526862233, -7.585601464645433, -7.594348998755124, -7.594659687853514, -7.584691274533544, -7.579260346160663, -7.589381346695482, -7.581942488616398, -7.585761838931412, -7.5888806656223, -7.5906512594778786, -7.59460061471894, -7.598291131300036, -7.566077017354454, -7.598568920462468, -7.588458586865334, -7.580516851783573, -7.581120795801359, -7.573401531185061, -7.587906649375854, -7.577894400309903, -7.588650004367097, -7.601671473700583, -7.6045987582499, -7.587960747276149, -7.586668925102221, -7.598896396820583, -7.584992838351697, -7.588738488491178, -7.592081956817983, -7.594450290229943, -7.577207933669749, -7.592589318566335, -7.591631016036065, -7.586822528718511, -7.5865236423006515, -7.575498534956321, -7.574278911271381, -7.584707709876169, -7.590472728393561, -7.599499257712318, -7.589231395611416, -7.597168903183947, -7.590381517053034, -7.603836632255566, -7.593864793429861, -7.600191191390682, -7.586817716211005, -7.587970682164855, -7.588438308757338, -7.586491923661776, -7.5849299950060445, -7.5726557026548, -7.605430277807631, -7.583551608530619, -7.590313233780737, -7.582464090187332, -7.587898000394051, -7.57869966024508, -7.59814204971804, -7.58368253706408, -7.583281132917466, -7.596340009605541, -7.580639556870499, -7.594986105182591, -7.597986634078884, -7.605014774124471, -7.595227520703942, -7.6126847535198445, -7.599313575341617, -7.569816760702087, -7.594416054247172, -7.605083757930927, -7.582868819170454, -7.586396258585806, -7.604414920719065, -7.599387572834845, -7.594782011899959, -7.606698086162534, -7.599912812617114, -7.609221282226267, -7.588232008218757, -7.60346462535037, -7.57588689646886, -7.588493577576002, -7.587845316302236, -7.577824438147921, -7.59972110610129, -7.601255963829907, -7.591292742933581, -7.591643875142415, -7.595608436976339, -7.604907684584499, -7.586236901477843, -7.599687143227731, -7.6019079185697205, -7.582693582623832, -7.599300342093287, -7.600243633211197, -7.592954405838291, -7.58819349398165, -7.601064555573852, -7.598241391296196, -7.596549098561609, -7.599227365949463, -7.594832883549281, -7.582626984810636, -7.5759575479403365, -7.587274253615891, -7.592166994254732, -7.599369142236348, -7.592745920229135, -7.574743004640935, -7.6065301484133485, -7.6110277743814025, -7.577220966905672, -7.596052441127596, -7.594975868864067, -7.583058349968933, -7.58912555988364, -7.593591137603428, -7.598784448149547, -7.596526026783077, -7.584847627840902, -7.593575746597375, -7.590229568191782, -7.579561798198312, -7.57274335076671, -7.595408728174156, -7.616555806795029] plot_convergence_of_optimization_process(LiH_approximated_energies, exact_eigenvalue=-7.7140566916607005,margin=1) H2_molecule_Hamiltonian_4_qubits = -0.8105479805373279 * (I^I^I^I) \ + 0.1721839326191554 * (I^I^I^Z) \ - 0.22575349222402372 * (I^I^Z^I) \ + 0.17218393261915543 * (I^Z^I^I) \ - 0.2257534922240237 * (Z^I^I^I) \ + 0.12091263261776627 * (I^I^Z^Z) \ + 0.16892753870087907 * (I^Z^I^Z) \ + 0.045232799946057826 * (Y^Y^Y^Y) \ + 0.045232799946057826 * (X^X^Y^Y) \ + 0.045232799946057826 * (Y^Y^X^X) \ + 0.045232799946057826 * (X^X^X^X) \ + 0.1661454325638241 * (Z^I^I^Z) \ + 0.1661454325638241 * (I^Z^Z^I) \ + 0.17464343068300453 * (Z^I^Z^I) \ + 0.12091263261776627 * (Z^Z^I^I) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits) compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue) print(approximated_energies) approximated_energies = [] H2_approximated_energies = [-0.6197535280860968, -0.63113013317311, -0.641885414639814, -0.6482547418356555, -0.65455000829844, -0.6441486895522341, -0.6186687021257633, -0.6337374526097435, -0.63137130321273, -0.6515250743774067, -0.6579678475184173, -0.6398929213318618, -0.6555847628548984, -0.40354990528583756, -0.42633959272606203, -0.39180257499975996, -0.419385140488104, -0.4052452163765543, -0.3968392598264421, -0.41327196278701983, -0.3897682032307278, -0.41190320628798593, -0.4155349659846535, -0.38689315655724943, -0.39488576584884966, -0.4101577563997251, -0.646246089992425, -0.64640556215564, -0.6408025316083132, -0.6481729361748543, -0.6321210801588072, -0.6169734445936428, -0.6531880101925263, -0.6516595101969759, -0.6370106901252102, -0.6410493390206395, -0.6549643568126738, -0.6434282271634354, -0.6374465180654254, -0.6998006222609853, -0.6989411616133739, -0.7113515779782615, -0.6845563444533804, -0.6912851288084605, -0.6823206756219158, -0.6715092561687758, -0.6950950360064898, -0.7048125041323035, -0.6949055673239051, -0.6876195557523046, -0.6871916327390696, -0.6920620441807598, -0.6754031102431696, -0.6405037528920269, -0.6479106194443648, -0.6571243727534537, -0.6585210677012743, -0.6619852684486195, -0.6306692686820092, -0.6426806791628032, -0.6605101341410042, -0.6581734283582826, -0.6602845191858175, -0.6403463546120416, -0.6838573980740288, -0.6367601998705805, -0.6389697979320161, -0.6342448131512901, -0.6275459264150375, -0.6397639594996816, -0.6516652787828084, -0.6568333186072677, -0.6337354077401545, -0.6534843394293214, -0.6561183148929468, -0.6394550125097977, -0.6282040909709646, -0.6566726955439391, -0.6480962237754406, -0.6391249852824691, -0.6302805184048759, -0.6134825837204779, -0.6324807924099654, -0.648200184148801, -0.6411199725353807, -0.6368985204497558, -0.6299450915767432, -0.6077929487594798, -0.650795244723779, -0.6364396855992979, -0.6561074752564185, -0.6411855472811453, -0.6636963692795997, -0.644828181245867, -0.6426381659395819, -0.6395444214753829, -0.6428019435419277, -0.6477507227847618, -0.6245247077953339, -0.6524683695964778, -0.657026854334116, -0.6358256453202371, -0.6549216159614076, -0.6414823984346717, -0.6559324505625062, -0.6184921814281965, -0.6243527663890307, -0.6347039342445667, -0.6423667818441274, -0.6416632437237163, -0.6355679476249553, -0.6101453551739199, -0.6428657380183808, -0.6371993803542474, -0.6190951873626491, -0.6300491872725141, -0.6443076254087124, -0.6346503527906344, -0.6374022072525142, -0.6365415695138426, -0.6215329044766564, -0.6025672090796137, -0.6262126292580317, -0.6121655900183715, -0.6372581587495586, -0.6532601474080465, -0.6502386208320281, -0.6374473928211839, -0.649108661977176, -0.6428978019524852, -0.6377680232901412, -0.62148731332837, -0.6295014947278836, -0.6303577746392046, -0.6311824700622705, -0.6485908334116913, -0.6555308247607579, -0.6387533756242247, -0.6387831688041341, -0.6362224138123854, -0.6321326357150927, -0.622886094438443, -0.6381661184242305, -0.6207598749285432, -0.633337235851305, -0.6433014163336428, -0.6216780295166963, -0.640547648407052, -0.6504721343163778, -0.6289231121104825, -0.6420313548519503, -0.6491871272384829, -0.6303753733515429, -0.6422070448022406, -0.6283882694196357, -0.6379372975401341, -0.6298035124355486, -0.6376118905742243, -0.6112071558166968, -0.6243668348101994, -0.601586210931813, -0.6246804576520302, -0.6225112843707201, -0.6385828114683393, -0.6308445065147489, -0.6459667238092578, -0.6420608286322824, -0.6284852174798609, -0.619517446532688, -0.6502311414153916, -0.6209974249236357, -0.6500441487817326, -0.6270160102758754, -0.6321138163295283, -0.6318213468032534, -0.6308663247351938, -0.6351155382454959, -0.6206589579897115, -0.6230425476232493, -0.6457261606370266, -0.638217697666363, -0.5967596291858532, -0.6308080357393553, -0.645343139596654, -0.6361652737273936, -0.6216439843718955, -0.6381345598638063, -0.6436054044017382, -0.6402634016890136, -0.6286637688911421, -0.6176910501936059, -0.6426835317643965, -0.6392144191408344, -0.6379698862857323, -0.6294007310483538, -0.6536384710745602, -0.6358065891830973, -0.6281936714944539, -0.6198882142883465, -0.6667152509756108, -0.6478727132696764, -0.639743219643381, -0.6594605134740277, -0.6208263182667817, -0.6484844194562659, -0.6560350644220397, -0.6400305393668726, -0.6082390327656634, -0.6177097860668552, -0.6444776983490096, -0.6405638061358565, -0.6531983360761086, -0.6384666560316292, -0.6026381248979216, -0.6205265201994276, -0.6580811400893553, -0.6242879958522837, -0.6256237085721144, -0.6370627576610521, -0.6193780381228698, -0.6110480817069229, -0.6348741804124418, -0.6469297212858536, -0.6284047197112129, -0.6425857646008404, -0.6227145680975487, -0.6543951355139729, -0.6135377860147931, -0.6151008019528299, -0.6332371262963544, -0.6213803615123089, -0.6197342220002152, -0.6553553047211762, -0.6542865700842904, -0.6447201703460987, -0.607866355025946, -0.6300084394962439, -0.6411144050158086, -0.6178965245521646, -0.616191998658104, -0.6348708952923955, -0.623907264080751, -0.641086457337346, -0.6444154604034792, -0.621800174387, -0.6244882763185394, -0.6376556734303133, -0.6375013731590747, -0.6275068048204745, -0.6623644844595649, -0.630649046531283, -0.6548727406536676, -0.6362997093395338, -0.6061815282744116, -0.6546951895602897, -0.6309023807683508, -0.6508388161226021, -0.6385027712100855, -0.6190137561886869, -0.6696046214509908, -0.6562145856438492, -0.6186112558608597, -0.6473301190677272, -0.6462712478136641, -0.673403768067784, -0.6530082059325099, -0.6543125213926978, -0.6378511211667697, -0.6345475633154861, -0.6368035646034413, -0.6420046649037825, -0.6415451595381126, -0.6447601324975634, -0.6308090659348322, -0.6442243984560325, -0.6337552468237352, -0.6652098463681152, -0.6450651275200792, -0.6415608484514996, -0.6297426007842335, -0.628971981721844, -0.6290368436378584, -0.6296828008139378, -0.6326057245473052, -0.6287268748618635, -0.6523495046628819, -0.654514736278266, -0.6503390006896462, -0.6267667849085593, -0.6518861485724909, -0.6213049629142335, -0.6152511068093129, -0.6444920885486036, -0.6538763157213386, -0.6169162063050543, -0.6374557936296323, -0.639117369570508, -0.636462951162852, -0.6517593736006154, -0.6076877031233741, -0.6403602223149248, -0.6298396251235469, -0.6637221198146037, -0.64886754893841, -0.6345453470146507, -0.6382894853660541, -0.6177025318805094, -0.652638852060324, -0.622038295932382, -0.6415029691455418, -0.6482039684567894, -0.6444058652688481, -0.6431931740464266, -0.6348402433271942, -0.6526661449410499, -0.6274506541843567, -0.6588510196703152, -0.6552920830042773, -0.6460730559750325, -0.6595908999970469, -0.6246926245873604, -0.6332020529350273, -0.6548958894755552, -0.6261489147202579] plot_convergence_of_optimization_process(H2_approximated_energies, exact_eigenvalue=-1.2445845498133272, margin=5) transverse_ising_4_qubits = 0.0 * (I^I^I^I) \ + 0.8398088405253477 * (X^I^I^I) \ + 0.7989496312070936 * (I^X^I^I) \ + 0.38189710487113193 * (Z^Z^I^I) \ + 0.057753122422666725 * (I^I^X^I) \ + 0.5633292636970458 * (Z^I^Z^I) \ + 0.3152740621483513 * (I^Z^Z^I) \ + 0.07209487981989715 * (I^I^I^X) \ + 0.17892334004292654 * (Z^I^I^Z) \ + 0.2273896497668042 * (I^Z^I^Z) \ + 0.09762902934216211 * (I^I^Z^Z) %%time TI_approximated_eigen_value = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits) compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue) print(approximated_energies) approximated_energies = [] TI_approximated_energies = [1.8984375, 1.943359375, 1.9619140625, 1.978515625, 1.984375, 1.9873046875, 1.9931640625, 1.9248046875, 1.962890625, 1.9248046875, 1.9150390625, 1.9052734375, 1.9267578125, 1.802734375, 1.81640625, 1.86328125, 1.8623046875, 1.7939453125, 1.8623046875, 1.89453125, 1.880859375, 1.8388671875, 1.8720703125, 1.83984375, 1.8837890625, 1.8359375, 1.701171875, 1.7470703125, 1.69140625, 1.73828125, 1.833984375, 1.69921875, 1.7744140625, 1.7529296875, 1.7353515625, 1.7265625, 1.7666015625, 1.708984375, 1.7421875, 1.79296875, 1.8671875, 1.91015625, 1.8828125, 1.884765625, 1.875, 1.86328125, 1.85546875, 1.8134765625, 1.84375, 1.79296875, 1.865234375, 1.8916015625, 1.908203125, 1.900390625, 1.8837890625, 1.876953125, 1.896484375, 1.9921875, 1.9208984375, 1.94921875, 1.96875, 1.8466796875, 1.92578125, 1.8740234375, 1.9716796875, 1.9130859375, 1.939453125, 1.9599609375, 1.9716796875, 1.9150390625, 1.98828125, 1.865234375, 1.9248046875, 1.890625, 2.0146484375, 1.9560546875, 1.947265625, 1.9619140625, 1.955078125, 1.9208984375, 1.955078125, 1.9384765625, 1.96484375, 1.9150390625, 1.923828125, 1.9580078125, 1.958984375, 2.013671875, 1.935546875, 1.9443359375, 2.0546875, 2.001953125, 1.958984375, 1.98828125, 1.962890625, 2.0205078125, 2.0029296875, 1.93359375, 1.91015625, 1.9765625, 1.9365234375, 1.8984375, 1.9072265625, 1.939453125, 1.9033203125, 2.0556640625, 1.947265625, 1.9267578125, 1.9541015625, 1.962890625, 1.9287109375, 1.9072265625, 1.962890625, 1.966796875, 1.9560546875, 1.970703125, 1.9580078125, 1.9833984375, 2.013671875, 1.966796875, 1.9599609375, 1.943359375, 1.974609375, 1.9619140625, 1.9462890625, 1.974609375, 1.9482421875, 1.943359375, 1.9697265625, 1.9033203125, 1.9794921875, 1.98828125, 1.94140625, 1.9658203125, 2.0078125, 1.9912109375, 1.916015625, 1.916015625, 2.0068359375, 1.9130859375, 1.9267578125, 1.90234375, 1.921875, 1.943359375, 1.9755859375, 1.90234375, 1.95703125, 1.9482421875, 1.97265625, 1.9658203125, 1.990234375, 1.9384765625, 1.935546875, 1.916015625, 1.91796875, 1.99609375, 1.87109375, 1.9599609375, 1.919921875, 1.951171875, 1.9521484375, 1.9716796875, 1.9736328125, 1.9794921875, 1.99609375, 1.9765625, 1.9228515625, 1.9482421875, 1.9462890625, 1.986328125, 1.927734375, 1.9482421875, 2.0771484375, 2.0009765625, 1.9267578125, 1.9638671875, 1.904296875, 1.9365234375, 1.962890625, 1.958984375, 1.96875, 1.9521484375, 1.8935546875, 1.916015625, 1.939453125, 1.98046875, 1.9560546875, 1.9541015625, 1.955078125, 1.9228515625, 1.9951171875, 1.93359375, 1.9736328125, 1.9443359375, 1.96484375, 1.984375, 1.8681640625, 1.923828125, 1.947265625, 1.96484375, 1.94140625, 1.9375, 1.96875, 1.94921875, 1.943359375, 1.8935546875, 1.9638671875, 1.912109375, 2.0, 1.921875, 2.064453125, 1.95703125, 1.9287109375, 1.951171875, 1.982421875, 1.8955078125, 1.9482421875, 1.9970703125, 1.9423828125, 1.9697265625, 1.90625, 1.9306640625, 1.9716796875, 1.92578125, 1.98046875, 1.9521484375, 1.9072265625, 1.962890625, 1.9365234375, 1.9609375, 1.9560546875, 1.9462890625, 2.0166015625, 1.9609375, 1.9287109375, 1.962890625, 1.9677734375, 1.9169921875, 1.876953125, 1.9443359375, 1.984375, 1.9697265625, 1.978515625, 1.958984375, 1.9677734375, 2.0341796875, 1.9697265625, 1.93359375, 1.966796875, 1.9482421875, 1.9345703125, 1.9453125, 1.9912109375, 1.986328125, 1.955078125, 1.927734375, 2.03125, 1.921875, 1.951171875, 1.9990234375, 1.8955078125, 1.9794921875, 2.0078125, 1.9580078125, 1.986328125, 1.9287109375, 1.9853515625, 1.9990234375, 1.9365234375, 2.0048828125, 1.9462890625, 1.9580078125, 1.970703125, 1.951171875, 1.91015625, 1.8662109375, 1.9013671875, 1.9267578125, 1.943359375, 1.9814453125, 1.927734375, 1.99609375, 1.9580078125, 1.904296875, 1.912109375, 1.978515625, 1.9453125, 1.990234375, 1.97265625, 1.9580078125, 1.93359375, 1.9599609375, 1.986328125, 1.970703125, 1.966796875, 1.947265625, 1.875, 1.953125, 1.966796875, 1.931640625, 1.9140625, 1.98828125, 1.919921875, 1.970703125, 1.8916015625, 2.0615234375, 2.015625, 1.8466796875, 1.916015625, 1.96875, 1.9697265625, 2.0029296875, 1.9326171875, 1.939453125, 1.873046875, 1.9345703125, 1.9501953125, 1.927734375, 1.9453125, 2.005859375, 1.96484375, 1.9384765625, 1.9609375, 1.990234375, 1.951171875, 1.951171875, 1.994140625, 2.015625, 1.9462890625, 1.94140625, 2.0439453125, 1.9755859375, 1.9326171875, 2.0224609375, 1.9248046875, 1.990234375, 2.0, 1.9091796875, 1.9267578125, 1.951171875, 1.95703125, 1.9521484375] plot_convergence_of_optimization_process(TI_approximated_energies, exact_eigenvalue=-1.7583827504312988, margin=3)
https://github.com/quantum-tokyo/qiskit-handson
quantum-tokyo
# Qiskitライブラリーを導入 from qiskit import * # 描画のためのライブラリーを導入 import matplotlib.pyplot as plt %matplotlib inline qiskit.__qiskit_version__ grover11=QuantumCircuit(2,2) grover11.draw(output='mpl') # 問題-1 上の回路図を作ってください。 # 正解 grover11.h([0,1]) # ← これが(一番記述が短い正解) grover11.draw(output='mpl') # 問題-2 上の回路図(問題-1に赤枠部分を追加したもの)を作ってください。 grover11.h(1) # 正解 grover11.cx(0,1) # 正解 grover11.h(1) # 正解 grover11.draw(output='mpl') #問題-3 上の回路図(問題-2に赤枠部分を追加したもの)を作ってください。 grover11.i(0) # 回路の見栄えを整えるために、恒等ゲートを差し込む。無くても動くが、表示の見栄えが崩れるのを防止するために、残しておく。 grover11.h([0,1]) # ← 正解 grover11.x([0,1]) # ← 正解 grover11.h(1) # ← 正解 grover11.cx(0,1) # ← 正解 grover11.h(1) # ← 正解 grover11.i(0) # ← 正解 grover11.x([0,1]) # ← 正解 grover11.h([0,1]) # ← 正解 grover11.draw(output='mpl') grover11.measure(0,0) grover11.measure(1,1) grover11.draw(output='mpl') backend = Aer.get_backend('statevector_simulator') # 実行環境の定義 job = execute(grover11, backend) # 処理の実行 result = job.result() # 実行結果 counts = result.get_counts(grover11) # 実行結果の詳細を取り出し print(counts) from qiskit.visualization import * plot_histogram(counts) # ヒストグラムで表示
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=no-member,invalid-name,missing-docstring,no-name-in-module # pylint: disable=attribute-defined-outside-init,unsubscriptable-object from qiskit import transpile from qiskit.transpiler import CouplingMap from .utils import build_ripple_adder_circuit class RippleAdderConstruction: params = ([10, 50, 100, 200, 500],) param_names = ["size"] version = 1 timeout = 600 def time_build_ripple_adder(self, size): build_ripple_adder_circuit(size) class RippleAdderTranspile: params = ([10, 20], [0, 1, 2, 3]) param_names = ["size", "level"] version = 1 timeout = 600 def setup(self, size, _): edge_len = int((2 * size + 2) ** 0.5) + 1 self.coupling_map = CouplingMap.from_grid(edge_len, edge_len) self.circuit = build_ripple_adder_circuit(size) def time_transpile_square_grid_ripple_adder(self, _, level): transpile( self.circuit, coupling_map=self.coupling_map, basis_gates=["u1", "u2", "u3", "cx", "id"], optimization_level=level, seed_transpiler=20220125, ) def track_depth_transpile_square_grid_ripple_adder(self, _, level): return transpile( self.circuit, coupling_map=self.coupling_map, basis_gates=["u1", "u2", "u3", "cx", "id"], optimization_level=level, seed_transpiler=20220125, ).depth()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit.result import QuasiDistribution from qiskit_aer.primitives import Sampler from qiskit_finance.applications.optimization import PortfolioOptimization from qiskit_finance.data_providers import RandomDataProvider from qiskit_optimization.algorithms import MinimumEigenOptimizer import numpy as np import matplotlib.pyplot as plt import datetime # set number of assets (= number of qubits) num_assets = 4 seed = 123 # Generate expected return and covariance matrix from (random) time-series stocks = [("TICKER%s" % i) for i in range(num_assets)] data = RandomDataProvider( tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=seed, ) data.run() mu = data.get_period_return_mean_vector() sigma = data.get_period_return_covariance_matrix() # plot sigma plt.imshow(sigma, interpolation="nearest") plt.show() q = 0.5 # set risk factor budget = num_assets // 2 # set budget penalty = num_assets # set parameter to scale the budget penalty term portfolio = PortfolioOptimization( expected_returns=mu, covariances=sigma, risk_factor=q, budget=budget ) qp = portfolio.to_quadratic_program() qp def print_result(result): selection = result.x value = result.fval print("Optimal: selection {}, value {:.4f}".format(selection, value)) eigenstate = result.min_eigen_solver_result.eigenstate probabilities = ( eigenstate.binary_probabilities() if isinstance(eigenstate, QuasiDistribution) else {k: np.abs(v) ** 2 for k, v in eigenstate.to_dict().items()} ) print("\n----------------- Full result ---------------------") print("selection\tvalue\t\tprobability") print("---------------------------------------------------") probabilities = sorted(probabilities.items(), key=lambda x: x[1], reverse=True) for k, v in probabilities: x = np.array([int(i) for i in list(reversed(k))]) value = portfolio.to_quadratic_program().objective.evaluate(x) print("%10s\t%.4f\t\t%.4f" % (x, value, v)) exact_mes = NumPyMinimumEigensolver() exact_eigensolver = MinimumEigenOptimizer(exact_mes) result = exact_eigensolver.solve(qp) print_result(result) from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=500) ry = TwoLocal(num_assets, "ry", "cz", reps=3, entanglement="full") vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla) vqe = MinimumEigenOptimizer(vqe_mes) result = vqe.solve(qp) print_result(result) algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=250) qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3) qaoa = MinimumEigenOptimizer(qaoa_mes) result = qaoa.solve(qp) print_result(result) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
mcoggins96
from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute,IBMQ from qiskit.circuit.library import Permutation from qiskit.tools.monitor import job_monitor IBMQ.enable_account('ENTER API Key HERE') provider = IBMQ.get_provider(hub='ibm-q') backend = provider.get_backend('ibmq_qasm_simulator') q = QuantumRegister(8, 'q') c = ClassicalRegister(8, 'c') ########### PERMUTATION WITH PATTERN 7,0,6,1,5,2,4,3 circuit = QuantumCircuit(q, c) circuit.x(q[0]) circuit.x(q[1]) circuit.x(q[2]) circuit.x(q[3]) circuit += Permutation(num_qubits = 8, pattern = [7,0,6,1,5,2,4,3]) circuit.measure(q, c) job = execute(circuit, backend, shots=100) job_monitor(job) counts = job.result().get_counts() print(circuit) print(counts) ####### RANDOM PERMUTATION CIRCUIT circuit = QuantumCircuit(q, c) circuit.x(q[0]) circuit.x(q[1]) circuit.x(q[2]) circuit.x(q[3]) circuit += Permutation(num_qubits = 8) circuit.measure(q, c) job = execute(circuit, backend, shots=100) job_monitor(job) counts = job.result().get_counts() print(circuit) print(counts)
https://github.com/LeanderThiessen/antisymmetrization-circuit
LeanderThiessen
#General Imports import numpy as np import matplotlib.pyplot as plt import time from itertools import product,permutations from string import ascii_lowercase as asc import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) #Qiskit Imports from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile from qiskit.circuit.library.standard_gates import MCXGate, CXGate, XGate, CSwapGate from qiskit.circuit.library import Diagonal from qiskit.quantum_info import partial_trace,purity #############FUNCTIONS########################################################################################################### #wrapper for measuring time taken by function 'func' def timeis(func): def wrap(*args,**kwargs): start = time.time() result = func(*args,**kwargs) end = time.time() if measure_time: print("{} took {:.2f}s".format(func.__name__,end-start)) return result return wrap #check if inputs are valid def check_inputs(n,m): if n == 1: print("Case n=1 currently not supported") correct = 1 if m>2**n: correct == 0 if correct == 1: print("Inputs valid") return 0 #initialize quantum circuit with electron register, swap_ancillas, record_ancillas, collision_ancillas def initialize_circuit(n,m,L): circuit = QuantumCircuit() #add main electron register (seed/target) for e in range(m): r_q = QuantumRegister(n,'{}'.format(asc[e]))#asc[i]=ith letter of the alphabe c = QuantumCircuit(r_q) circuit = circuit.combine(c) #add ancillas for comparator_swaps for k in range(int(np.ceil(m/2))): anc_q = QuantumRegister(n-1,'anc_{}'.format(k)) c = QuantumCircuit(anc_q) circuit = circuit.combine(c) #add 'record' register for storing outcomes of comparators for l in range(L): anc_q = QuantumRegister(1,'record_{}'.format(l)) c = QuantumCircuit(anc_q) circuit = circuit.combine(c) #add ancillas to store the occurence of collisions between pairs of electrons for c in range(m-1): anc_q = QuantumRegister(1,'coll_record_{}'.format(c)) c = QuantumCircuit(anc_q) circuit = circuit.combine(c) #add one ancilla to store if all other collision ancillas are '1' anc_q = QuantumRegister(1,'collision_test') c = QuantumCircuit(anc_q) circuit = circuit.combine(c) return circuit #returns x in binary format as string of length n, incl leading zeros def binary_n(x,n): return bin(x)[2:].zfill(n) #initializes j-th electron register with number x def binary_init(circuit,n,m,input): for k,e in enumerate(input): e_bin = binary_n(e,n) for i in range(n): if e_bin[i]=='1': circuit.append(XGate(),[i+k*n]) return circuit #Apply a Hadamard gate to each qubit in the electron register def Hadamard(circuit,n,m): for q in range(n*m): circuit.h(q) return circuit #Compare bits at positions x and y, only output=(x<y) to position anc def bit_compare(circuit,cbits,control,debug=True): x = cbits[0] y = cbits[1] anc = cbits[2] if debug: circuit.barrier() #control='01' for initial sorting and '10' for collision detection circuit.append(MCXGate(2,ctrl_state=control),[x,y,anc]) if debug: circuit.barrier() return circuit #split the array 'index' into array of pairs of adjacent indices; first entry is (e.g.) [0] if number of entries of index is odd def get_subsets(index): #index = [0,1,2,3] -> result = [[0,1],[2,3]] #index = [0,1,2,3,4] -> result = [[0],[1,2],[3,4]] M = len(index) result = [] if M % 2 != 0: result.append(np.array([0])) n_split = int((M-1)/2) for s in np.split(index[1:M],n_split): result.append(s) else: result = np.split(index,M/2) return result #get position of first qubit in swap_control ancilla register def get_first_swap_ctrl(n,m): #n_comp_parallel is the number of comparators that are applied in each layer #n*m = main register for storing electron registers; #(n_comp_parallel)*(n-1) = fixed ancilla register needed for compare_n n_comp_parallel = int(np.ceil(m/2)) ctrl_0 = n*m + (n-1)*n_comp_parallel return ctrl_0 #get position of first qubit in collision_control ancilla register def get_first_coll_ctrl(n,m,L): coll_0 = get_first_swap_ctrl(n,m) + L return coll_0 #return pairs of electron indices that need to be compared in collision-detection step def get_coll_sets(m): ind = np.arange(m) if m == 2: sets_a = [np.array([0,1])] sets_b = [] return sets_a,sets_b if m % 2 == 0: sets_a = np.split(ind,m/2) sets_b = np.split(ind[1:-1],(m-2)/2) else: sets_a = np.split(ind[:-1],(m-1)/2) sets_b = np.split(ind[1:],(m-1)/2) #all gates in sets_a can be applied in parallel #all gates in sets_b can be applied in parallel return sets_a,sets_b #returns the first qubit position of the ancilla register used for swap of i and j (only really tested for m<6) def get_anc(n,m,i,j): if abs(j-i) == 1: anc_reg = int( np.min([i,j])/2 ) elif abs(j-i) == 2: anc_reg = int( np.ceil( np.min([i,j])/2 )) else: anc_reg = int( np.min([i,j]) ) anc = n*m + anc_reg*(n-1) return anc #Implement 'Compare2' function (Fig 3); input: two 2bit numbers, output: two 1bit numbers with same ordering def compare_2(circuit,x_0,x_1,y_0,y_1,anc): #Notation: x = 2^1*x_0 + x_1 (reverse from paper!!) #compares numbers x,y and outputs two bits x',y' (at positions x_1 and y_1) with the same ordering circuit.append(XGate(),[anc]) circuit.append(CXGate(),[y_0,x_0]) circuit.append(CXGate(),[y_1,x_1]) circuit.append(CSwapGate(),[x_0,x_1,anc]) circuit.append(CSwapGate(),[x_0,y_0,y_1]) circuit.append(CXGate(),[y_1,x_1]) return circuit #Generalisation of 'compare2' two nbit numbers, output: two 1bit numbers with same ordering at positions x1,y1 def compare_n(circuit,n,m,i,j,l,L,debug): index = np.arange(n) subsets = get_subsets(index) M = len(subsets) anc = get_anc(n,m,i,j) for s in subsets: if len(s)==2: if debug: circuit.barrier() x_0 = s[0] + i*n x_1 = s[1] + i*n y_0 = s[0] + j*n y_1 = s[1] + j*n circuit = compare_2(circuit,x_0,x_1,y_0,y_1,anc) anc += 1 while (len(subsets)>1): index = np.array([subsets[k][-1] for k in range(M)]) subsets = get_subsets(index) M = len(subsets) for s in subsets: if len(s)==2: if debug: circuit.barrier() x_0 = s[0] + i*n x_1 = s[1] + i*n y_0 = s[0] + j*n y_1 = s[1] + j*n circuit = compare_2(circuit,x_0,x_1,y_0,y_1,anc) anc += 1 ######################################################################################################################################## #at this point the bits x_1 and y_1 have the same ordering as numbers stored in registers i and j #e(i)<e(j) -> x_1=0 and y_1=1 #e(i)>e(j) -> x_1=1 and y_1=0 #e(i)=e(j) -> x_1=0 y_1=0 if e(i) even or x_1=1 y_1=1 if e(i) odd #prepare output for bit_compare function; anc iterates through the second ancilla register (+1 for each comparator) #l = current swap; each new swap gets a new ancilla for storing the outcome anc = get_first_swap_ctrl(n,m) + l cbits = x_1,y_1,anc return circuit,cbits #apply diagonal phase shift to qubit i, conditioned on qubit 'ctrl' def cphase_shift(circuit,ctrl,i): target = i*n CDiag = Diagonal([-1,-1]).control(1) CDiag = CDiag.to_gate() CDiag.label = "D" #doesn't work currently circuit.append(CDiag,[ctrl,target]) return circuit #performs swap of registers i and j conditioned on ancilla qubit 'ctrl' def swap_registers(circuit,n,i,j,ctrl,debug): for g in range(n): circuit.append(CSwapGate(),[ctrl,i*n+g,j*n+g]) if debug: circuit.barrier() return circuit #compare electron registers i and j; swap registers iff e(i)<(j); l=current swap (0 to L) def comparator_swap(n,m,i,j,l,L,phase,debug): #Perform comparison to generate output qubits "cbits" circuit_compute = initialize_circuit(n,m,L) circuit_compute,cbits = compare_n(circuit_compute,n,m,i,j,l,L,debug) #Add bit_compare between the two output qubits and store in ancilla circuit_bit_compare = initialize_circuit(n,m,L) circuit_bit_compare = bit_compare(circuit_bit_compare,cbits,'10',debug) #add uncomputing step only of the comparison circuit circuit_uncompute = circuit_compute.inverse() #Swap registers based on control ancilla circuit_swap = initialize_circuit(n,m,L) #apply a conditioned phase shift to the first qubit of the register pair; is only called when sn is applied backwards, that's why it's (phase,swap) and not (swap,phase) if phase: circuit_swap = cphase_shift(circuit_swap,cbits[2],i) circuit_swap = swap_registers(circuit_swap,n,i,j,cbits[2],debug) #Combine circuits circuit_comparator = circuit_compute + circuit_bit_compare + circuit_uncompute + circuit_swap return circuit_comparator #Apply the sorting network sn, where each comparator stores the outcome in ctrl_register def apply_sorting_network(circuit,n,m,sn,L,phase,debug): for l,swap in enumerate(sn): #swap = [i, j, direction]; dir = 0 : descending (from the top); dir = 1 : ascending (from the top) if swap[2]==0: i = swap[0] j = swap[1] if swap[2]==1: i = swap[1] j = swap[0] circuit_comparator = comparator_swap(n,m,i,j,l,L,phase,debug) circuit = circuit + circuit_comparator return circuit #Apply the reverse of the sorting networkl sn for antisymmetrizing the input state def apply_reverse_sorting_network(circuit,n,m,sn,L,phase,debug): circuit_sn = initialize_circuit(n,m,L) circuit_sn = apply_sorting_network(circuit_sn,n,m,sn,L,phase,debug) #reverse all gates in the circuit circuit_reverse_sn = circuit_sn.inverse() circuit = circuit + circuit_reverse_sn return circuit #reset first register to [|0>,|0>,|0>,...] (all zeros) def reset_electrons(circuit,n,m): circuit.barrier() for g in range(m): g_indices = np.arange(g*n,(g+1)*n) #classical register positions for electron g for g_i in g_indices: circuit.reset(g_i) return circuit #reset all registers except for the main electron register def reset_ancillas(circuit,n,m,L): circuit.barrier() start = n*m end = get_first_coll_ctrl(n,m,L) + m for q in range(start,end): circuit.reset(q) return circuit #Perform comparisons between all adjacent electron registers, with ctrl ancilla in the coll_register def collision_compare(circuit,n,m,L,debug): #all sets in sets_a can be applied simultaneously (same for sets_b); both for loops are otherwise identical and could be combined sets_a,sets_b = get_coll_sets(m) c = 0 for s in sets_a: circuit_coll_test = initialize_circuit(n,m,L) i = s[0] j = s[1] circuit_coll_test,cbits = compare_n(circuit_coll_test,n,m,i,j,0,L,debug) x_1 = cbits[0] y_1 = cbits[1] coll_anc = get_first_coll_ctrl(n,m,L) + c cbits = [x_1,y_1,coll_anc] circuit_coll_test_reverse = circuit_coll_test.inverse() circuit = circuit + circuit_coll_test circuit = bit_compare(circuit,cbits,'01',debug) circuit = circuit + circuit_coll_test_reverse c+=1 for s in sets_b: circuit_coll_test = initialize_circuit(n,m,L) i = s[0] j = s[1] circuit_coll_test,cbits = compare_n(circuit_coll_test,n,m,i,j,0,L,debug) x_1 = cbits[0] y_1 = cbits[1] coll_anc = get_first_coll_ctrl(n,m,L) + c cbits = [x_1,y_1,coll_anc] circuit_coll_test_reverse = circuit_coll_test.inverse() circuit = circuit + circuit_coll_test circuit = bit_compare(circuit,cbits,'01',debug) circuit = circuit + circuit_coll_test_reverse c+=1 return circuit #apply X gate on last qubit, conditioned on all other coll_ancillas being 1 (which means that all elctron registers are different) def collision_test(circuit,n,m,L,debug): coll_ctrl_0 = get_first_coll_ctrl(n,m,L) control = '' qubits = [] for i in range(m-1): control = control + '1' qubits.append(coll_ctrl_0+i) qubits.append(coll_ctrl_0+m-1) circuit.append(MCXGate(m-1,ctrl_state=control),qubits) return circuit #not necessary #returns True if output contains only unique elements; returns False otherwise (if two or more elements are the same) def collision_check_old(output): if len(output) == len(set(output)): return True else: return False #Perform measurement on last qubit in coll_register def measure_collisions(circuit,n,m,L): #add classical register to store measurement result c_q = QuantumRegister(0) c_reg = ClassicalRegister(1,'collision_check') c = QuantumCircuit(c_q,c_reg) circuit = circuit.combine(c) #perform measurements on each electron register and store in separate memorey circuit.measure(get_first_coll_ctrl(n,m,L) + m - 1, 0) return circuit #Add classical registers and apply measurements on the main electron register def measure_electrons(circuit,n,m): circuit.barrier() for g in range(m): #Add classicla register to store measurement outcomes c_q = QuantumRegister(0) c_reg = ClassicalRegister(n,'mem_{}'.format(asc[g])) c = QuantumCircuit(c_q,c_reg) circuit = circuit.combine(c) #perform measurements on each electron register and store in separate memorey circuit.measure(np.arange(g*n,(g+1)*n),np.arange(g*n + 1,(g+1)*n + 1)) return circuit #Build the circuit with all gates and measurements @timeis def build_circuit(n,m,input,sn,L,debug=True): #Initialize the circuit with the right number of qubits and ancillas circuit = initialize_circuit(n,m,L) #Apply Hadamard gates to each qubit in the first register circuit = Hadamard(circuit,n,m) #Apply the sorting network sn phase = False circuit = apply_sorting_network(circuit,n,m,sn,L,phase,debug) #apply comparisons between all adjacent electron registers and store outcome in coll_register circuit = collision_compare(circuit,n,m,L,debug) #check if outcome of all comparisons is "not_equal"; flip last qubit in coll_register if this is the case circuit = collision_test(circuit,n,m,L,debug) #measure last qubit in coll_register, which stores (no collisions = 1) or (collisions = 0); result is kept until the end of the simulation and result accepted if (no collisions == True) circuit = measure_collisions(circuit,n,m,L) #Measurements: classical register 0 stores the random sorted array that can still include collisions #circuit = measure_electrons(circuit,n,m) #Reset main electron register circuit = reset_electrons(circuit,n,m) #Initialize main electron register in given input product state circuit = binary_init(circuit,n,m,input) #Apply the reverse of 'apply_sorting_network' and add a conditioned phase shift after each swap (this antisymmetrizes the input state) phase = True circuit = apply_reverse_sorting_network(circuit,n,m,sn,L,phase,debug) #Reset all ancilla qubits and only keep the main electron register (disable for testing final state for antisymmetry) #circuit = reset_ancillas(circuit,n,m,L) #Measure electron register (for testing) #circuit = measure_electrons(circuit,n,m) return circuit #Simulate circuit using specified backend and return simulation result @timeis def simulate(circuit,backend,shots): simulator = Aer.get_backend(backend) #transpile the circuit into the supported set of gates circuit = transpile(circuit,backend=simulator) result = simulator.run(circuit,shots=shots).result() return result #turns simulation result 'counts' into list of decimal numbers corresponding to the electron registers; only use if shots=1 or all outcomes are the same def convert_output_to_decimal(counts,n,m): output_list = list(counts.keys())[0][::-1] coll_test = output_list[0] output_list = output_list[2:] output = [] offset = 0 for g in range(m): start = g*n + offset end = (g+1)*n + offset g_out = int(output_list[start:end],2) output.append(g_out) offset += 1 output_0 = output[0:m] return coll_test,output_0 #draw the circuit using size,name as input if plot==True @timeis def draw_circuit(circuit,plot_scale,fname): circuit.draw(output='mpl',fold=-1,scale=plot_scale,plot_barriers=True) plt.savefig(fname,dpi=700) return 0 def plot_circuit(circuit,plot_scale,fname,plot=True): if plot: draw_circuit(circuit,plot_scale,fname) plt.show() return 0 print("Plot disabled") return 0 #plot sorting network by itself, using cnot as directed comparator (only for visualizationo) def plot_sorting_network(sn,m): circuit_sn = QuantumCircuit(m) for s in sn: if s[2] == 0: i,j = s[0],s[1] else: i,j = s[1],s[0] circuit_sn.cz(i,j) circuit_sn.draw(output='mpl') plt.show() return 0 #Generate a bitonic sorting network for m electrons; dir=0 (descending), dir=1 (ascending) def sorting_network_bitonic(m,dir): sn = [] def compAndSwap(i,j,dir): sn.append([i,j,dir]) def bitonic_sort(low, cnt, dir): if cnt>1: k = cnt//2 dir_n = (dir + 1) % 2 bitonic_sort(low, k, dir_n)#n_dir bitonic_sort(low + k, cnt-k, dir)#dir bitonic_merge(low, cnt, dir) def bitonic_merge(low, cnt, dir): if cnt>1: k = greatestPowerOfTwoLessThan(cnt) i = low while i < low+cnt-k: compAndSwap(i, i+k, dir) i+=1 bitonic_merge(low,k,dir) bitonic_merge(low+k,cnt-k,dir) def greatestPowerOfTwoLessThan(cnt): i=1 while (2**i)<cnt: i+=1 return 2**(i-1) bitonic_sort(0,m,dir) L = len(sn) return sn,L #Test if sorting network correctly sorts all possible inputs def test_sn(sn,n,m): all_inputs = list(product(range(2**n),repeat=m)) fail = 0 count = 0 for input in all_inputs: input = np.array(input) temp = np.copy(input) for s in sn: if s[2]==0: i = s[0] j = s[1] if s[2]==1: i = s[1] j = s[0] if input[i]<input[j]: input[i],input[j] = input[j],input[i] should_be = np.sort(temp)[::-1] if (input == should_be).all(): fail += 0 else: fail += 1 print(f"Testing sorting network {count}/{len(all_inputs)}",end="\r") count+=1 print(" ", end = "\r") if fail == 0: print("Sorting network correct\n") return 1 else: print("Error in sorting network\n") return 0 #Returns all steps of sorting network with corresponding ancilla registers (for testing) def test_sn_anc(sn,n,m): for s in sn: i = s[0] j = s[1] anc = get_anc(n,m,i,j) anc_reg = int((anc-n*m)/(n-1)) print(f"[{i},{j}] anc_reg={anc_reg}") return 0 #Output density matrix of electron register (target) and compute purity, doesnt actually test antisymmetry yet! def test_antisymmetry(result,n,m,L): sv = result.get_statevector() trace_out = list(np.arange(n*m,get_first_coll_ctrl(n,m,L)+m)) #print(f"Tracing out qubits: {trace_out}") rho_e = partial_trace(sv,trace_out) if rho_e.is_valid(): print("Target state is valid density matrix\n") else: print("Target state is not valid density matrix") #print(rho_e) p = purity(rho_e) print(f"Purity of target state = {p}\n") return p ###################MAINPART############################################################################################################ #Parameters #n: number of qubits per electron; N = 2^n orbitals n=3 #m: number of electrons m=4 #input: list of orbitals the electrons are initialized in; needs to be in descending order, without repetitions input = [5,4,3,2] #dir: ordering descending (dir=0) or ascending (dir=1) dir = 0 #plot and save the circuit plot = True #include barriers between comparators in the circuit for visualization debug = False #measure time of functions: {build_circuit, simulate, draw_circuit} measure_time = True #size of the plot plot_scale = 0.2 #simulation method backend = 'statevector_simulator'#'aer_simulator' #number of circuit repetitions in 'simulate' shots = 1 #check valid inputs check_inputs(n,m) #Generate sorting network sn,L = sorting_network_bitonic(m,dir) #Test sorting network test_sn(sn,n,m) #Plot sorting network plot_sorting_network(sn,m) #Build circuit circuit = build_circuit(n,m,input,sn,L,debug) #Simulate result = simulate(circuit,backend,shots) counts = result.get_counts(circuit) print(f"Counts: {counts}\n") #Test if final state is antisymmetric test_antisymmetry(result,n,m,L) output_list = list(counts.keys())[0][::-1] coll_test = output_list[0] if coll_test == '1': print("No collisions detected - continue\n") else: print("Collisions detected - repeat\n") #plot circuit plot_circuit(circuit,plot_scale,f"Plots/Circuit_m{m}_n{n}_debug{debug}",plot)
https://github.com/hamburgerguy/Quantum-Algorithm-Implementations
hamburgerguy
"""Qiskit code for running Simon's algorithm on quantum hardware for 2 qubits and b = '11' """ # importing Qiskit from qiskit import IBMQ, BasicAer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, execute # import basic plot tools from qiskit.visualization import plot_histogram from qiskit_textbook.tools import simon_oracle #set b equal to '11' b = '11' #1) initialize qubits n = 2 simon_circuit_2 = QuantumCircuit(n*2, n) #2) Apply Hadamard gates before querying the oracle simon_circuit_2.h(range(n)) #3) Query oracle simon_circuit_2 += simon_oracle(b) #5) Apply Hadamard gates to the input register simon_circuit_2.h(range(n)) #3) and 6) Measure qubits simon_circuit_2.measure(range(n), range(n)) # Load saved IBMQ accounts and get the least busy backend device IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= n and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Execute and monitor the job from qiskit.tools.monitor import job_monitor shots = 1024 job = execute(simon_circuit_2, backend=backend, shots=shots, optimization_level=3) job_monitor(job, interval = 2) # Get results and plot counts device_counts = job.result().get_counts() plot_histogram(device_counts) #additionally, function for calculating dot product of results def bdotz(b, z): accum = 0 for i in range(len(b)): accum += int(b[i]) * int(z[i]) return (accum % 2) print('b = ' + b) for z in device_counts: print( '{}.{} = {} (mod 2) ({:.1f}%)'.format(b, z, bdotz(b,z), device_counts[z]*100/shots)) #the most significant results are those for which b dot z=0(mod 2). '''b = 11 11.00 = 0 (mod 2) (45.0%) 11.01 = 1 (mod 2) (6.2%) 11.10 = 1 (mod 2) (6.4%) 11.11 = 0 (mod 2) (42.4%)'''
https://github.com/hkhetawat/QArithmetic
hkhetawat
""" This file allows to test the various QFT implemented. The user must specify: 1) The number of qubits it wants the QFT to be implemented on 2) The kind of QFT want to implement, among the options: -> Normal QFT with SWAP gates at the end -> Normal QFT without SWAP gates at the end -> Inverse QFT with SWAP gates at the end -> Inverse QFT without SWAP gates at the end The user must can also specify, in the main function, the input quantum state. By default is a maximal superposition state This file uses as simulator the local simulator 'statevector_simulator' because this simulator saves the quantum state at the end of the circuit, which is exactly the goal of the test file. This simulator supports sufficient qubits to the size of the QFTs that are going to be used in Shor's Algorithm because the IBM simulator only supports up to 32 qubits """ """ Imports from qiskit""" from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, IBMQ, BasicAer """ Imports to Python functions """ import time """ Local Imports """ from qfunctions import create_QFT, create_inverse_QFT """ Function to properly print the final state of the simulation """ """ This is only possible in this way because the program uses the statevector_simulator """ def show_good_coef(results, n): i=0 max = pow(2,n) if max > 100: max = 100 """ Iterate to all possible states """ while i<max: binary = bin(i)[2:].zfill(n) number = results.item(i) number = round(number.real, 3) + round(number.imag, 3) * 1j """ Print the respective component of the state if it has a non-zero coefficient """ if number!=0: print('|{}>'.format(binary),number) i=i+1 """ Main program """ if __name__ == '__main__': """ Select how many qubits want to apply the QFT on """ n = int(input('\nPlease select how many qubits want to apply the QFT on: ')) """ Select the kind of QFT to apply using the variable what_to_test: what_to_test = 0: Apply normal QFT with the SWAP gates at the end what_to_test = 1: Apply normal QFT without the SWAP gates at the end what_to_test = 2: Apply inverse QFT with the SWAP gates at the end what_to_test = 3: Apply inverse QFT without the SWAP gates at the end """ print('\nSelect the kind of QFT to apply:') print('Select 0 to apply normal QFT with the SWAP gates at the end') print('Select 1 to apply normal QFT without the SWAP gates at the end') print('Select 2 to apply inverse QFT with the SWAP gates at the end') print('Select 3 to apply inverse QFT without the SWAP gates at the end\n') what_to_test = int(input('Select your option: ')) if what_to_test<0 or what_to_test>3: print('Please select one of the options') exit() print('\nTotal number of qubits used: {0}\n'.format(n)) print('Please check source file to change input quantum state. By default is a maximal superposition state with |+> in every qubit.\n') ts = time.time() """ Create quantum and classical registers """ quantum_reg = QuantumRegister(n) classic_reg = ClassicalRegister(n) """ Create Quantum Circuit """ circuit = QuantumCircuit(quantum_reg, classic_reg) """ Create the input state desired Please change this as you like, by default we put H gates in every qubit, initializing with a maximimal superposition state """ #circuit.h(quantum_reg) """ Test the right QFT according to the variable specified before""" if what_to_test == 0: create_QFT(circuit,quantum_reg,n,1) elif what_to_test == 1: create_QFT(circuit,quantum_reg,n,0) elif what_to_test == 2: create_inverse_QFT(circuit,quantum_reg,n,1) elif what_to_test == 3: create_inverse_QFT(circuit,quantum_reg,n,0) else: print('Noting to implement, exiting program') exit() """ show results of circuit creation """ create_time = round(time.time()-ts, 3) if n < 8: print(circuit) print(f"... circuit creation time = {create_time}") ts = time.time() """ Simulate the created Quantum Circuit """ simulation = execute(circuit, backend=BasicAer.get_backend('statevector_simulator'),shots=1) """ Get the results of the simulation in proper structure """ sim_result=simulation.result() """ Get the statevector of the final quantum state """ outputstate = sim_result.get_statevector(circuit, decimals=3) """ show execution time """ exec_time = round(time.time()-ts, 3) print(f"... circuit execute time = {exec_time}") """ Print final quantum state to user """ print('The final state after applying the QFT is:\n') show_good_coef(outputstate,n)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = t3_st_qcs # zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = False) # print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) # with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) # with open(filename, "wb") as f: # pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) # with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump(backend.properties(), f) retrieved_jobs = jobs retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: # mit_results = meas_fitter.filter.apply(job.result()) rho = StateTomographyFitter(job.result(), t3_zne_qcs).fit(method='lstsq') fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/WhenTheyCry96/qiskitHackathon2022
WhenTheyCry96
import os import warnings warnings.filterwarnings('ignore') ws_path = os.getcwd() import numpy as np from scipy.constants import c, h, pi, hbar, e from qiskit_metal.analyses.em.cpw_calculations import guided_wavelength # constants: phi0 = h/(2*e) varphi0 = phi0/(2*pi) # project target parameters f_qList = np.around(np.linspace(5.25, 5.75, 4),2) # GHz f_rList = f_qList + 1.8 # GHz L_JJList = np.around(varphi0**2/((f_qList*1e9+300e6)**2/(8*300e6))/h*1e9, 2) # nH # initial CPW readout lengths def find_resonator_length(frequency, line_width, line_gap, N): #frequency in GHz #line_width/line_gap in um #N -> 2 for lambda/2, 4 for lambda/4 [lambdaG, etfSqrt, q] = guided_wavelength(frequency*10**9, line_width*10**-6, line_gap*10**-6, 750*10**-6, 200*10**-9) return str(lambdaG/N*10**3)+" mm" find_resonator_length(f_rList, 10, 6, 2) find_resonator_length(np.around(np.linspace(8, 8.5, 4),2), 10, 6, 2) from qiskit_metal import designs, MetalGUI design = designs.DesignPlanar() design.overwrite_enabled = True design.chips.main.size_x = '12mm' design.chips.main.size_y = '10mm' gui = MetalGUI(design) from qiskit_metal.qlibrary.qubits.transmon_pocket_cl import TransmonPocketCL design.delete_all_components() design_span_x = 5 design_span_y = 3 half_chip_width = design_span_x / 2 half_chip_height = design_span_y / 2 connection_pads_options = dict( B1 = dict(loc_W=1, loc_H=-1), R= dict(loc_W=1, loc_H=1), B2 = dict(loc_W=-1, loc_H=-1) ) transmons = [] transmons.append(TransmonPocketCL(design, 'Q1', options=dict(pos_x=f'0mm', pos_y=f'{half_chip_height}mm', orientation=0, connection_pads=dict(**connection_pads_options)))) gui.rebuild() gui.autoscale() transmons.append(TransmonPocketCL(design, 'Q2', options=dict(pos_x=f'{half_chip_width}mm', pos_y=f'0mm', orientation=-90, connection_pads=dict(**connection_pads_options)))) gui.rebuild() gui.autoscale() transmons.append(TransmonPocketCL(design, 'Q3', options=dict(pos_x=f'{-half_chip_width}mm', pos_y=f'0mm', orientation=90, connection_pads=dict(**connection_pads_options)))) gui.rebuild() gui.autoscale() transmons.append(TransmonPocketCL(design, 'Q4', options=dict(pos_x=f'0mm', pos_y=f'{-half_chip_height}mm', orientation=180, connection_pads=dict(**connection_pads_options)))) gui.rebuild() gui.autoscale() from qiskit_metal.qlibrary.tlines.meandered import RouteMeander from qiskit_metal import Dict fillet='99.99um' options = Dict( meander=Dict( lead_start='0.1mm', lead_end='0.1mm', asymmetry='0 um') ) def connect(component_name: str, component1: str, pin1: str, component2: str, pin2: str, length: str, asymmetry='0 um', start_strght='0 um', end_strght='0 um', flip=False): """Connect two pins with a CPW.""" myoptions = Dict( pin_inputs=Dict( start_pin=Dict( component=component1, pin=pin1), end_pin=Dict( component=component2, pin=pin2)), lead=Dict( start_straight=start_strght, end_straight=end_strght ), total_length=length, fillet = '99.9um') myoptions.update(options) myoptions.meander.asymmetry = asymmetry myoptions.meander.lead_direction_inverted = 'true' if flip else 'false' return RouteMeander(design, component_name, myoptions) cpw = [] asym_h = 200 cpw.append(connect('cpw1', 'Q1', 'B1', 'Q2', 'B2', '7.60 mm', f'-{asym_h}um', '0.1mm', '0.1mm')) asym_h = 200 cpw.append(connect('cpw2', 'Q4', 'B2', 'Q2', 'B1', '7.45 mm', f'{asym_h}um', '0.1mm', '0.1mm')) asym_h = 200 cpw.append(connect('cpw3', 'Q1', 'B2', 'Q3', 'B1', '7.30 mm', f'{asym_h}um', '0.1mm', '0.1mm')) asym_h = 200 cpw.append(connect('cpw4', 'Q4', 'B1', 'Q3', 'B2', '7.15 mm', f'-{asym_h}um', '0.1mm', '0.1mm')) gui.rebuild() gui.autoscale() from qiskit_metal.qlibrary.terminations.launchpad_wb_coupled import LaunchpadWirebondCoupled readouts_lwc = [] control_lwc = [] #Readouts readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R1', options = dict( pos_x=f'3mm', pos_y=f'{half_chip_height+3}mm', orientation = 180, lead_length = '30um'))) readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R2', options = dict( pos_x=f'{half_chip_width+3}mm', pos_y=f'-3mm', orientation = 90, lead_length = '30um'))) readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R3', options = dict( pos_x=f'{-half_chip_width-3}mm', pos_y=f'3mm', orientation = 0, lead_length = '30um'))) readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R4', options = dict( pos_x = f'-3mm', pos_y = f'{-half_chip_height-3}mm', orientation = 0, lead_length = '30um'))) gui.rebuild() gui.autoscale() from qiskit_metal.qlibrary.tlines.pathfinder import RoutePathfinder from qiskit_metal.qlibrary.lumped.cap_3_interdigital import Cap3Interdigital cap_Q1 = Cap3Interdigital(design, 'cap_Q1', options= dict( pos_x='2mm', pos_y=f'{half_chip_height+2}mm', orientation='180', finger_length = '40um')) readout_lines = [] options = Dict( lead=Dict( start_straight='400um', end_straight='400um'), fillet='99.99um') asym = 800 readout_lines.append(connect('ol1_c', 'Q1', 'R', 'cap_Q1', 'a', '8.63 mm', f'-{asym}um')) TL_Q1 = RoutePathfinder(design, 'TL_Q1', options = dict( fillet='99um', lead=dict(end_straight='150um'), pin_inputs=Dict( start_pin=Dict( component='R1', pin='tie'), end_pin=Dict( component='cap_Q1', pin='b') ))) cap_Q2 = Cap3Interdigital(design, 'cap_Q2', options= dict( pos_x=f'{half_chip_width+2}mm', pos_y=f'-2mm', orientation='90', finger_length = '40um')) readout_lines.append(connect('ol2', 'Q2', 'R', 'cap_Q2', 'a', '8.42 mm', f'-{asym}um')) TL_Q2 = RoutePathfinder(design, 'TL_Q2', options = dict( fillet='99um', lead=dict(end_straight='150um'), pin_inputs=Dict( start_pin=Dict( component='R2', pin='tie'), end_pin=Dict( component='cap_Q2', pin='b') ))) cap_Q3 = Cap3Interdigital(design, 'cap_Q3', options= dict( pos_x=f'{-half_chip_width-2}mm', pos_y=f'2mm', orientation='270', finger_length = '40um')) readout_lines.append(connect('ol3', 'Q3', 'R', 'cap_Q3', 'a', '8.25 mm', f'-{asym}um')) TL_Q3 = RoutePathfinder(design, 'TL_Q3', options = dict( fillet='99um', lead=dict(end_straight='150um'), pin_inputs=Dict( start_pin=Dict( component='R3', pin='tie'), end_pin=Dict( component='cap_Q3', pin='b') ))) options = Dict( lead=Dict( start_straight='400um', end_straight='400um'), fillet='99.99um') cap_Q4 = Cap3Interdigital(design, 'cap_Q4', options= dict( pos_x=f'-2mm', pos_y=f'{-half_chip_height-2}mm', orientation='0', finger_length = '40um')) readout_lines.append(connect('ol4', 'Q4', 'R', 'cap_Q4', 'a', '8.05 mm', f'-{asym}um')) TL_Q4 = RoutePathfinder(design, 'TL_Q4', options = dict( fillet='99um', lead=dict(end_straight='150um'), pin_inputs=Dict( start_pin=Dict( component='R4', pin='tie'), end_pin=Dict( component='cap_Q4', pin='b') ))) gui.rebuild() gui.autoscale() #Controls control_lwc.append(LaunchpadWirebondCoupled(design, 'CL1', options = dict( pos_x = f'-3mm', pos_y = f'3mm', orientation=0, lead_length = '30um'))) control_lwc.append(LaunchpadWirebondCoupled(design, 'CL2', options = dict( pos_x = f'3mm', pos_y = f'3mm', orientation = -90, lead_length = '30um'))) control_lwc.append(LaunchpadWirebondCoupled(design, 'CL3', options = dict( pos_x = f'-3mm', pos_y = f'-3mm', orientation = 90, lead_length = '30um'))) control_lwc.append(LaunchpadWirebondCoupled(design, 'CL4', options = dict( pos_x = f'2mm', pos_y = f'-3mm', orientation = 90, lead_length = '30um'))) gui.rebuild() gui.autoscale() from qiskit_metal.qlibrary.tlines.anchored_path import RouteAnchors from collections import OrderedDict import numpy as np control_lines = [] def connectRouteAnchor(name: str, component1: str, pin1: str, component2: str, pin2: str, anchor_points: OrderedDict) -> RouteAnchors: options_line_cl = dict( pin_inputs = dict(start_pin = dict(component = component1, pin = pin1), end_pin = dict(component = component2, pin = pin2)), anchors = anchor_points, lead = dict(start_straight = '200um', end_straight = '225um'), fillet = fillet ) return RouteAnchors(design, name, options_line_cl) anchors1c = OrderedDict() anchors1c[0] = np.array([-4, -1.42]) anchors1c[1] = np.array([-4, 2]) control_lines.append(connectRouteAnchor('line_cl1', 'Q1', 'Charge_Line', 'CL1', 'tie', anchors1c)) anchors2c = OrderedDict() anchors2c[0] = np.array([0.08, 3.25]) anchors2c[1] = np.array([4, 3.25]) control_lines.append(connectRouteAnchor('line_cl2', 'Q2', 'Charge_Line', 'CL2', 'tie', anchors2c)) anchors3c = OrderedDict() anchors3c[0] = np.array([-0.08, -3.25]) anchors3c[1] = np.array([-4, -3.25]) control_lines.append(connectRouteAnchor('line_cl3', 'Q3', 'Charge_Line', 'CL3', 'tie', anchors3c)) anchors4c = OrderedDict() anchors4c[0] = np.array([4, 1.42]) anchors4c[1] = np.array([4, -2]) control_lines.append(connectRouteAnchor('line_cl4', 'Q4', 'Charge_Line', 'CL4', 'tie', anchors4c)) gui.rebuild() gui.autoscale() from qiskit_metal.analyses.quantization import EPRanalysis eig_res1 = EPRanalysis(design, "hfss") hfss1 = eig_res1.sim.renderer hfss1.start() transmons[0].options.pad_gap = '40um' transmons[0].options.pad_width = '405um' transmons[0].options.pad_height = '90um' gui.rebuild() hfss1.activate_ansys_design("Tune_Q1", 'eigenmode') hfss1.render_design(['Q1'], [('Q1', 'c'), ('Q1', 'a'),('Q1', 'b'),('Q1', 'Charge_Line')]) # Analysis properties setup1 = hfss1.pinfo.setup setup1.passes = 10 setup1.n_modes = 3 print(f""" Number of eigenmodes to find = {setup1.n_modes} Number of simulation passes = {setup1.passes} Convergence freq max delta percent diff = {setup1.delta_f} """) # Next 2 lines are counterinuitive, since there is no junction in this resonator. # However, these are necessary to make pyEPR work correctly. Please do note delete hfss1.pinfo.design.set_variable('Lj', '12 nH') hfss1.pinfo.design.set_variable('Cj', '1 fF') setup1.analyze() eig_res1.sim.convergence_t, eig_res1.sim.convergence_f, _ = hfss1.get_convergences() eig_res1.sim.plot_convergences()
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
PabloMartinezAngerosa
from tsp_qaoa import test_solution from qiskit.visualization import plot_histogram import networkx as nx import numpy as np job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution() plot_histogram(job_2.result().get_counts(), color='midnightblue', title="New Histogram", figsize=(30, 5)) plot_histogram(job_2.result().get_counts(), color='midnightblue', title="New Histogram", figsize=(30, 5)) G labels = nx.get_edge_attributes(G,'weight') labels import json # Array of JSON Objects products = [{"name": "HDD", "brand": "Samsung", "price": "$100"}, {"name": "Monitor", "brand": "Dell", "price": "$120"}, {"name": "Mouse", "brand": "Logitech", "price": "$10"}] # Print the original data print("The original JSON data:\n{0}".format(products)) # Sort the JSON data based on the value of the brand key products.sort(key=lambda x: x["price"]) # Print the sorted JSON data print("The sorted JSON data based on the value of the brand:\n{0}".format(products)) _LAMBDA UNIFORM_CONVERGENCE_SAMPLE import json # Array of JSON Objects # Sort the JSON data based on the value of the brand key UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["mean"]) # Print the sorted JSON data UNIFORM_CONVERGENCE_SAMPLE np.max(UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"] - UNIFORM_CONVERGENCE_SAMPLE[220]["probabilities"]) # generamos las distancias entre para la convergencia uniforme index = -1 for sample in UNIFORM_CONVERGENCE_SAMPLE: mean = sample["mean"] index += 1 distance_p_ground_state = np.max(np.abs(UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"] - sample["probabilities"])) UNIFORM_CONVERGENCE_SAMPLE[index]["distance_pgs"] = distance_p_ground_state UNIFORM_CONVERGENCE_SAMPLE import csv header = ['iteration', 'state', 'probability', 'mean'] header_q = ['iteration', 'distance'] with open('qaoa_cu.csv', 'w', encoding='UTF8') as f: with open('qaoa_distance.csv', 'w', encoding='UTF8') as q: writer = csv.writer(f) writer_q = csv.writer(q) # write the header writer.writerow(header) writer_q.writerow(header_q) iteration = 0 for sample in UNIFORM_CONVERGENCE_SAMPLE: iteration += 1 mean = sample["mean"] distance = sample["distance_pgs"] state = 0 for probability in sample["probabilities"]: state += 1 # write the data data = [iteration, state, probability, mean] writer.writerow(data) writer_q.writerow([iteration, distance]) #plot_histogram(job_2, color='midnightblue', title=str(mean), figsize=(30, 5)).savefig(str(contador) + "_2.png") #print(sample["mean"]) plot_histogram(job_2, color='midnightblue', title="New Histogram", figsize=(30, 5)).savefig('out.png')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# You can show the phase of each state and use # degrees instead of radians from qiskit.quantum_info import DensityMatrix import numpy as np from qiskit import QuantumCircuit from qiskit.visualization import plot_state_qsphere qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0,1) qc.ry(np.pi/3, 0) qc.rx(np.pi/5, 1) qc.z(1) matrix = DensityMatrix(qc) plot_state_qsphere(matrix, show_state_phases = True, use_degrees = True)
https://github.com/JavaFXpert/qiskit4devs-workshop-notebooks
JavaFXpert
# !pip install qiskit==0.7.1 # Include the necessary imports for this program import numpy as np from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute # Create a Quantum Register with 2 qubits qr = QuantumRegister(2) # Create a Classical Register with 2 bits cr = ClassicalRegister(2) # Create a Quantum Circuit from the quantum and classical registers circ = QuantumCircuit(qr, cr) # Place Hadamard gate on the top wire, putting this qubit in a superposition. circ.h(qr[0]) # Add a CX (CNOT) gate across the top two wires, entangling the qubits. circ.cx(qr[0], qr[1]) # Create a barrier that separates the gates from the measurements circ.barrier(qr) # Measure the qubits into the classical registers circ.measure(qr, cr) # Draw the new circuit circ.draw(output='mpl') # Use the BasicAer statevector_simulator backend from qiskit import BasicAer backend_sv_sim = BasicAer.get_backend('statevector_simulator') # Execute the circuit on the state vector simulator job_sim = execute(circ, backend_sv_sim) # Grab the results from the job. result_sim = job_sim.result() # Obtain the state vector for the quantum circuit quantum_state = result_sim.get_statevector(circ, decimals=3) # Output the quantum state vector in a manner that contains a comma-delimited string. quantum_state # Plot the state vector on a Q-sphere from qiskit.tools.visualization import plot_state_qsphere plot_state_qsphere(quantum_state) # Use the BasicAer qasm_simulator backend from qiskit import BasicAer backend_sim = BasicAer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator, running it 1000 times. job_sim = execute(circ, backend_sim, shots=1000) # Grab the results from the job. result_sim = job_sim.result() # Print the counts, which are contained in a Python dictionary counts = result_sim.get_counts(circ) print(counts) # Plot the results on a histogram from qiskit.tools.visualization import plot_histogram plot_histogram(counts) # Include the necessary imports for this program # Create a Quantum Register with 2 qubits # Create a Classical Register with 2 bits # Create a Quantum Circuit from the quantum and classical registers # Place appropriate gates on the wires to achieve the desired Bell state # Create a barrier that separates the gates from the measurements # Measure the qubits into the classical registers # Draw the circuit # Use the BasicAer statevector_simulator backend # Execute the circuit on the state vector simulator # Grab the results from the job. # Obtain the state vector for the quantum circuit # Output the quantum state vector in a manner that contains a comma-delimited string. # Plot the state vector on a Q-sphere # Use the BasicAer qasm_simulator backend # Execute the circuit on the qasm simulator, running it 1000 times. # Grab the results from the job. # Print the counts, which are contained in a Python dictionary # Plot the results on a histogram
https://github.com/qiskit-community/qiskit-cold-atom
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. """General Fermion simulator backend.""" from typing import Union, List, Dict, Any, Optional import uuid import warnings import time import datetime from qiskit.providers.models import BackendConfiguration from qiskit.providers import Options from qiskit import QuantumCircuit from qiskit.result import Result from qiskit_aer import AerJob from qiskit_cold_atom.fermions.fermion_circuit_solver import FermionCircuitSolver from qiskit_cold_atom.fermions.base_fermion_backend import BaseFermionBackend from qiskit_cold_atom.circuit_tools import CircuitTools class FermionSimulator(BaseFermionBackend): """A simulator to simulate general fermionic circuits. This general fermion simulator backend simulates fermionic circuits with gates that have generators described by fermionic Hamiltonians. It computes the statevector and unitary of a circuit and simulates measurements. """ _DEFAULT_CONFIGURATION = { "backend_name": "fermion_simulator", "backend_version": "0.0.1", "n_qubits": 20, "basis_gates": None, "gates": [], "local": False, "simulator": True, "conditional": False, "open_pulse": False, "memory": True, "max_shots": 1e5, "coupling_map": None, "description": "a base simulator for fermionic circuits. Instead of qubits, each wire represents" " a single fermionic mode", "supported_instructions": None, } def __init__(self, config_dict: Dict[str, Any] = None, provider=None): """Initializing the backend from a configuration dictionary""" if config_dict is None: config_dict = self._DEFAULT_CONFIGURATION super().__init__( configuration=BackendConfiguration.from_dict(config_dict), provider=provider ) @classmethod def _default_options(cls): return Options(shots=1) def _execute(self, data: Dict[str, Any], job_id: str = ""): """Helper function to execute a job. The circuit and all relevant parameters are given in the data dict. Performs validation checks on the received circuits and utilizes the FermionCircuitSolver to perform the numerical simulations. Args: data: Data dictionary that that contains the experiments to simulate, given in the shape: data = { "num_species": int, "shots": int, "seed": int, "experiments": Dict[str, QuantumCircuit], } job_id: The job id assigned by the run method Returns: result: A qiskit job result. """ # Start timer start = time.time() output = {"results": []} num_species = data["num_species"] shots = data["shots"] seed = data["seed"] solver = FermionCircuitSolver(num_species=num_species, shots=shots, seed=seed) for exp_i, exp_name in enumerate(data["experiments"]): experiment = data["experiments"][exp_name] circuit = experiment["circuit"] # perform compatibility checks with the backend configuration in case gates and supported # instructions are constrained by the backend's configuration if self.configuration().gates and self.configuration().supported_instructions: CircuitTools.validate_circuits(circuits=circuit, backend=self, shots=shots) # check whether all wires are measured measured_wires = [] for inst in circuit.data: name = inst[0].name if name == "measure": for wire in inst[1]: index = circuit.qubits.index(wire) if index in measured_wires: warnings.warn( f"Wire {index} has already been measured, " f"second measurement is ignored" ) else: measured_wires.append(index) if measured_wires and len(measured_wires) != len(circuit.qubits): warnings.warn( f"Number of wires in circuit ({len(circuit.qubits)}) exceeds number of wires " + f" with assigned measurement instructions ({len(measured_wires)}). " + "This simulator backend only supports measurement of the entire quantum register " "which will instead be performed." ) # If there are no measurements, set shots to None if not measured_wires: solver.shots = None simulation_result = solver(circuit) output["results"].append( { "header": {"name": exp_name, "random_seed": seed}, "shots": shots, "status": "DONE", "success": True, } ) # add the simulation result at the correct place in the result dictionary output["results"][exp_i]["data"] = simulation_result output["job_id"] = job_id output["date"] = datetime.datetime.now().isoformat() output["backend_name"] = self.name() output["backend_version"] = self.configuration().backend_version output["time_taken"] = time.time() - start output["success"] = True output["qobj_id"] = None return Result.from_dict(output) # pylint: disable=arguments-differ, unused-argument def run( self, circuits: Union[QuantumCircuit, List[QuantumCircuit]], shots: int = 1000, seed: Optional[int] = None, num_species: int = 1, **run_kwargs, ) -> AerJob: """ Method to run circuits on the backend. Args: circuits: QuantumCircuit applying fermionic gates to run on the backend shots: Number of measurement shots taken in case the circuit has measure instructions seed: seed for the random number generator of the measurement simulation num_species: number of different fermionic species described by the circuits run_kwargs: Additional keyword arguments that might be passed down when calling qiskit.execute() which will have no effect on this backend. Returns: aer_job: a job object containing the result of the simulation """ if isinstance(circuits, QuantumCircuit): circuits = [circuits] data = { "num_species": num_species, "shots": shots, "seed": seed, "experiments": {}, } for idx, circuit in enumerate(circuits): data["experiments"][f"experiment_{idx}"] = { "circuit": circuit, } job_id = str(uuid.uuid4()) aer_job = AerJob(self, job_id, self._execute, data) aer_job.submit() return aer_job @staticmethod def get_basis(circuit: QuantumCircuit, num_species: int = 1): """Get the basis of fermionic states in occupation number representation for the simulation of a given quantum circuit. Args: circuit: A quantum circuit using Fermionic Gates. num_species: Number of different fermionic species described by the circuit. Returns: basis: the fermionic basis in which the simulation of the circuit is performed. """ solver = FermionCircuitSolver(num_species=num_species) solver.preprocess_circuit(circuit) basis = solver.basis return basis def draw(self, qc: QuantumCircuit, **draw_options): """Draw the circuit by defaulting to the draw method of QuantumCircuit. Note that in the future this method may be modified and tailored to fermion quantum circuits. Args: qc: The quantum circuit to draw. draw_options: Key word arguments for the drawing of circuits. """ qc.draw(**draw_options)
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Utils for using with Qiskit unit tests.""" import logging import os import unittest from enum import Enum from qiskit import __path__ as qiskit_path class Path(Enum): """Helper with paths commonly used during the tests.""" # Main SDK path: qiskit/ SDK = qiskit_path[0] # test.python path: qiskit/test/python/ TEST = os.path.normpath(os.path.join(SDK, '..', 'test', 'python')) # Examples path: examples/ EXAMPLES = os.path.normpath(os.path.join(SDK, '..', 'examples')) # Schemas path: qiskit/schemas SCHEMAS = os.path.normpath(os.path.join(SDK, 'schemas')) # VCR cassettes path: qiskit/test/cassettes/ CASSETTES = os.path.normpath(os.path.join(TEST, '..', 'cassettes')) # Sample QASMs path: qiskit/test/python/qasm QASMS = os.path.normpath(os.path.join(TEST, 'qasm')) def setup_test_logging(logger, log_level, filename): """Set logging to file and stdout for a logger. Args: logger (Logger): logger object to be updated. log_level (str): logging level. filename (str): name of the output file. """ # Set up formatter. log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:' ' %(message)s'.format(logger.name)) formatter = logging.Formatter(log_fmt) # Set up the file handler. file_handler = logging.FileHandler(filename) file_handler.setFormatter(formatter) logger.addHandler(file_handler) # Set the logging level from the environment variable, defaulting # to INFO if it is not a valid level. level = logging._nameToLevel.get(log_level, logging.INFO) logger.setLevel(level) class _AssertNoLogsContext(unittest.case._AssertLogsContext): """A context manager used to implement TestCase.assertNoLogs().""" # pylint: disable=inconsistent-return-statements def __exit__(self, exc_type, exc_value, tb): """ This is a modified version of TestCase._AssertLogsContext.__exit__(...) """ self.logger.handlers = self.old_handlers self.logger.propagate = self.old_propagate self.logger.setLevel(self.old_level) if exc_type is not None: # let unexpected exceptions pass through return False if self.watcher.records: msg = 'logs of level {} or higher triggered on {}:\n'.format( logging.getLevelName(self.level), self.logger.name) for record in self.watcher.records: msg += 'logger %s %s:%i: %s\n' % (record.name, record.pathname, record.lineno, record.getMessage()) self._raiseFailure(msg)
https://github.com/usamisaori/qLipschitz
usamisaori
from sklearn.datasets import load_iris import pennylane as qml import numpy as np from pennylane.optimize import AdamOptimizer import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') X, Y = load_iris(return_X_y=True) X_train_0 = X[0:30] X_train_1 = X[50:80] X_train = np.vstack((X_train_0, X_train_1)) Y_train_0 = Y[0:30] Y_train_1 = Y[50:80] Y_train = np.vstack((Y_train_0, Y_train_1)).flatten() X, Y = load_iris(return_X_y=True) X_test_0 = X[30:50] X_test_1 = X[80:100] X_test = np.vstack((X_test_0, X_test_1)) Y_test_0 = Y[30:50] Y_test_1 = Y[80:100] Y_test = np.vstack((Y_test_0, Y_test_1)).flatten() X_train = (X_train - X_train.min(axis=0)) / (X_train.max(axis=0) - X_train.min(axis=0)) X_test = (X_test - X_test.min(axis=0)) / (X_test.max(axis=0) - X_test.min(axis=0)) qubits_num = 4 layers_num = 2 dev = qml.device("default.qubit", wires=qubits_num) class VQC: def __init__(self): # 3 => U3(theta, phi, lambda) self.params = (0.1 * np.random.randn(layers_num, qubits_num, 3)) self.bestparams = self.params self.bestcost = 10 self.opt = AdamOptimizer(0.125) self.weights = [] self.costs = [] self.accuracies = [] def fit(self, X_train, Y_train, epoch=300): batch_size = 20 for turn in range(epoch): # Update the weights by one optimizer step batch_index = np.random.randint(0, len(X_train), (batch_size,)) X_train_batch = X_train[batch_index] Y_train_batch = Y_train[batch_index] self.params = self.opt.step(lambda v: cost(v, X_train_batch, Y_train_batch), self.params) cost_now = cost(self.params, X_train, Y_train) acc_now = accuracy(self.params, X_train, Y_train) if cost_now < self.bestcost: self.bestcost = cost_now self.bestparams = self.params self.weights.append(self.params) self.costs.append(cost_now) self.accuracies.append(acc_now) print( "Turn: {:5d} | Cost: {:0.7f} | Accuracy: {:0.2f}% ".format( turn, cost_now, acc_now * 100 )) def score(self, X_test, Y_test): predictions = [ predict(self.bestparams, data) for data in X_test ] acc = accuracy(self.bestparams, X_test, Y_test) print("FINAL ACCURACY: {:0.2f}%".format(acc * 100)) @qml.qnode(dev) def circuit(params, data): angles = [ i * np.pi for i in data ] for i in range(qubits_num): qml.RX(angles[i], wires=i) qml.Rot( *params[0, i], wires=i ) qml.CZ(wires=[1, 0]) qml.CZ(wires=[1, 2]) qml.CZ(wires=[2, 3]) qml.CZ(wires=[0, 3]) for i in range(qubits_num): qml.Rot( *params[1, i], wires=i ) # PauliZ measure => 1 -> |0> while -1 -> |1> return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)), qml.expval(qml.PauliZ(2)), qml.expval(qml.PauliZ(3)) def cost(weights, datas, labels): loss = 0 for i, data in enumerate(datas): # like [-1, 1, 1] measured = circuit(weights, data) p = measured[0] if labels[i] == 0: loss += (1 - p) ** 2 else: loss += (-1 - p) ** 2 return loss / len(datas) import qiskit import numpy as np from qiskit import QuantumCircuit from qiskit import Aer, execute unitary_backend = Aer.get_backend('unitary_simulator') qasm_backend = Aer.get_backend('qasm_simulator') def predict(params, data): qcircuit = QuantumCircuit(4, 4) qubits = qcircuit.qubits for i, d in enumerate(data): qcircuit.rx(d * np.pi, qubits[i]) for i in range(qubits_num): qcircuit.u3(*params[0][i], qubits[i]) qcircuit.cz(qubits[0], qubits[1]) qcircuit.cz(qubits[1], qubits[2]) qcircuit.cz(qubits[2], qubits[3]) qcircuit.cz(qubits[0], qubits[3]) for i in range(qubits_num): qcircuit.u3(*params[1][i], qubits[i]) # the measurement qcircuit.measure([0, 1, 2, 3], [0, 1, 2, 3]) # job execution shots = 1000 job_sim = execute(qcircuit, qasm_backend, shots=shots) result_sim = job_sim.result() counts = result_sim.get_counts(qcircuit) p1 = (counts.get('1000', 0) + counts.get('1001', 0) + counts.get('1010', 0) + counts.get('1011',0) + \ counts.get('1100', 0) + counts.get('1101', 0) + counts.get('1110', 0) + counts.get('1111', 0)) / shots if p1 > 0.5: return 1 else: return 0 def accuracy(weights, datas, labels): predictions = [ predict(weights, data) for data in datas ] acc = 0 for i, p in enumerate(predictions): if p == labels[i]: acc += 1 return acc / len(predictions) vqc = VQC() vqc.fit(X_train, Y_train, epoch=10) vqc.score(X_test, Y_test) vqc.bestparams def createCircuit(params, data): qcircuit = QuantumCircuit(4, 4) qubits = qcircuit.qubits for i, d in enumerate(data): qcircuit.rx(d * np.pi, qubits[i]) for i in range(qubits_num): qcircuit.u3(*params[0][i], qubits[i]) qcircuit.cz(qubits[0], qubits[1]) qcircuit.cz(qubits[1], qubits[2]) qcircuit.cz(qubits[2], qubits[3]) qcircuit.cz(qubits[0], qubits[3]) for i in range(qubits_num): qcircuit.u3(*params[1][i], qubits[i]) return qcircuit qcircuit = createCircuit(vqc.bestparams, X_train[0]) qcircuit.draw(output='mpl')
https://github.com/QuSTaR/kaleidoscope
QuSTaR
# -*- coding: utf-8 -*- # This code is part of Kaleidoscope. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=unused-import """Tests for Bloch routines""" from qiskit import IBMQ, QuantumCircuit import kaleidoscope.qiskit PROVIDER = IBMQ.load_account() backend = PROVIDER.backends.ibmq_vigo def test_target_backend_attach(): """Tests attaching target backend""" qc = QuantumCircuit(5, 5) >> backend qc.h(0) qc.cx(0, range(1, 5)) qc.measure(range(5), range(5)) assert qc.target_backend == backend def test_target_backend_transpile(): """Tests target backend attached to transpiled circuit""" qc = QuantumCircuit(5, 5) >> backend qc.h(0) qc.cx(0, range(1, 5)) qc.measure(range(5), range(5)) new_qc = qc.transpile() assert new_qc.target_backend == backend
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi # the angles of rotations theta1 = pi/4 theta2 = pi/6 # the circuit with two qubits qreg = QuantumRegister(2) creg = ClassicalRegister(2) mycircuit = QuantumCircuit(qreg,creg) # when the second qubit is in |0>, the first qubit is rotated by theta1 mycircuit.x(qreg[1]) mycircuit.cu3(2*theta1,0,0,qreg[1],qreg[0]) mycircuit.x(qreg[1]) # when the second qubit is in |1>, the first qubit is rotated by theta2 mycircuit.cu3(2*theta2,0,0,qreg[1],qreg[0]) # we read the unitary matrix job = execute(mycircuit,Aer.get_backend('unitary_simulator')) u=job.result().get_unitary(mycircuit,decimals=3) # we print the unitary matrix in nice format for i in range(len(u)): s="" for j in range(len(u)): val = str(u[i][j].real) while(len(val)<8): val = " "+val s = s + val print(s) # # your code is here # from math import pi, sin, cos theta1 = pi/4 theta2 = pi/6 print(round(cos(theta1),3),-round(sin(theta1),3),0,0) print(round(sin(theta1),3),-round(cos(theta1),3),0,0) print(0,0,round(cos(theta2),3),-round(sin(theta2),3)) print(0,0,round(sin(theta2),3),-round(cos(theta2),3)) # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi, sin, cos # the angle of rotation theta1 = pi/23 theta2 = 2*pi/23 theta3 = 4*pi/23 precision = 3 print("a1 = theta3 => sin(a1) = ",round(sin(theta3),precision)) print("a2 = theta2+theta3 => sin(a2) = ",round(sin(theta2+theta3),precision)) print("a3 = theta1 => sin(a3) = ",round(sin(theta1),precision)) print("a4 = theta1+theta2 => sin(a4) = ",round(sin(theta1+theta2),precision)) print() qreg = QuantumRegister(3) creg = ClassicalRegister(3) circuit = QuantumCircuit(qreg,creg) # controlled rotation when the third qubit is |1> circuit.cu3(2*theta1,0,0,qreg[2],qreg[0]) # controlled rotation when the second qubit is |1> circuit.cu3(2*theta2,0,0,qreg[1],qreg[0]) # controlled rotation when the third qubit is |0> circuit.x(qreg[2]) circuit.cu3(2*theta3,0,0,qreg[2],qreg[0]) circuit.x(qreg[2]) # read the corresponding unitary matrix job = execute(circuit,Aer.get_backend('unitary_simulator')) unitary_matrix=job.result().get_unitary(circuit,decimals=precision) for i in range(len(unitary_matrix)): s="" for j in range(len(unitary_matrix)): val = str(unitary_matrix[i][j].real) while(len(val)<precision+4): val = " "+val s = s + val print(s) # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi, sin, cos from random import randrange # the angle of rotation k1 = randrange(1,31) theta1 = k1*2*pi/31 k2 = randrange(1,31) theta2 = k2*2*pi/31 k3 = randrange(1,31) theta3 = k3*2*pi/31 max_percentange = 0 # for each stream of length from 1 to 31 for i in range(1,32): # initialize the circuit qreg = QuantumRegister(3) creg = ClassicalRegister(3) circuit = QuantumCircuit(qreg,creg) # Hadamard operators before reading the stream for m in range(3): circuit.h(qreg[m]) # read the stream of length i print("stream of length",i,"is being read") for j in range(i): # controlled rotation when the third qubit is |1> circuit.cu3(2*theta1,0,0,qreg[2],qreg[0]) # controlled rotation when the second qubit is |1> circuit.cu3(2*theta2,0,0,qreg[1],qreg[0]) # controlled rotation when the third qubit is |0> circuit.x(qreg[2]) circuit.cu3(2*theta3,0,0,qreg[2],qreg[0]) circuit.x(qreg[2]) # Hadamard operators after reading the stream for m in range(3): circuit.h(qreg[m]) # we measure after reading the whole stream circuit.measure(qreg,creg) # execute the circuit N times N = 1000 job = execute(circuit,Aer.get_backend('qasm_simulator'),shots=N) counts = job.result().get_counts(circuit) print(counts) if '000' in counts.keys(): c = counts['000'] else: c = 0 print('000 is observed',c,'times out of',N) percentange = round(c/N*100,1) if max_percentange < percentange and i != 31: max_percentange = percentange print("the ration of 000 is ",percentange,"%") print() print("maximum percentage of observing unwanted '000' is",max_percentange) # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi # initialize the circuit qreg = QuantumRegister(4) circuit = QuantumCircuit(qreg) # we use the fourth qubit as the auxiliary # apply a rotation to the first qubit when the third and second qubits are in states |0> and |1> # change the state of the third qubit to |1> circuit.x(qreg[2]) # if both the third and second qubits are in states |1>, the state of auxiliary qubit is changed to |1> circuit.ccx(qreg[2],qreg[1],qreg[3]) # the rotation is applied to the first qubit if the state of auxiliary qubit is |1> circuit.cu3(2*pi/6,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[2]) circuit.draw() from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi,sin # the angles of rotations theta1 = pi/10 theta2 = 2*pi/10 theta3 = 3*pi/10 theta4 = 4*pi/10 # for verification, print sin(theta)'s print("sin(theta1) = ",round(sin(theta1),3)) print("sin(theta2) = ",round(sin(theta2),3)) print("sin(theta3) = ",round(sin(theta3),3)) print("sin(theta4) = ",round(sin(theta4),3)) print() qreg = QuantumRegister(4) circuit = QuantumCircuit(qreg) # the third qubit is in |0> # the second qubit is in |0> circuit.x(qreg[2]) circuit.x(qreg[1]) circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta1,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[1]) circuit.x(qreg[2]) # the third qubit is in |0> # the second qubit is in |1> circuit.x(qreg[2]) circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta2,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[2]) # the third qubit is in |1> # the second qubit is in |0> circuit.x(qreg[1]) circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta3,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[1]) # the third qubit is in |1> # the second qubit is in |1> circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta4,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) # read the corresponding unitary matrix job = execute(circuit,Aer.get_backend('unitary_simulator')) unitary_matrix=job.result().get_unitary(circuit,decimals=3) for i in range(len(unitary_matrix)): s="" for j in range(len(unitary_matrix)): val = str(unitary_matrix[i][j].real) while(len(val)<7): val = " "+val s = s + val print(s) # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi,sin # the angle of rotation k1 = randrange(1,61) theta1 = k1*2*pi/61 k2 = randrange(1,61) theta2 = k2*2*pi/61 k3 = randrange(1,61) theta3 = k3*2*pi/61 k4 = randrange(1,61) theta4 = k4*2*pi/61 max_percentange = 0 # for each stream of length of 1, 11, 21, 31, 41, 51, and 61 for i in [1,11,21,31,41,51,61]: #for i in range(1,62): # initialize the circuit qreg = QuantumRegister(4) creg = ClassicalRegister(4) circuit = QuantumCircuit(qreg,creg) # Hadamard operators before reading the stream for m in range(3): circuit.h(qreg[m]) # read the stream of length i print("stream of length",i,"is being read") for j in range(i): # the third qubit is in |0> # the second qubit is in |0> circuit.x(qreg[2]) circuit.x(qreg[1]) circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta1,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[1]) circuit.x(qreg[2]) # the third qubit is in |0> # the second qubit is in |1> circuit.x(qreg[2]) circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta2,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[2]) # the third qubit is in |1> # the second qubit is in |0> circuit.x(qreg[1]) circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta3,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[1]) # the third qubit is in |1> # the second qubit is in |1> circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta4,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) # Hadamard operators after reading the stream for m in range(3): circuit.h(qreg[m]) # we measure after reading the whole stream circuit.measure(qreg,creg) # execute the circuit N times N = 1000 job = execute(circuit,Aer.get_backend('qasm_simulator'),shots=N) counts = job.result().get_counts(circuit) print(counts) if '0000' in counts.keys(): c = counts['0000'] else: c = 0 print('0000 is observed',c,'times out of',N) percentange = round(c/N*100,1) if max_percentange < percentange and i != 61: max_percentange = percentange print("the ration of 0000 is ",percentange,"%") print() print("maximum percentage of observing unwanted '0000' is",max_percentange)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for SuperOp quantum channel representation class.""" import copy import unittest import numpy as np from numpy.testing import assert_allclose from qiskit import QiskitError, QuantumCircuit from qiskit.quantum_info.states import DensityMatrix from qiskit.quantum_info.operators import Operator from qiskit.quantum_info.operators.channel import SuperOp from .channel_test_case import ChannelTestCase class TestSuperOp(ChannelTestCase): """Tests for SuperOp channel representation.""" def test_init(self): """Test initialization""" chan = SuperOp(self.sopI) assert_allclose(chan.data, self.sopI) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) mat = np.zeros((4, 16)) chan = SuperOp(mat) assert_allclose(chan.data, mat) self.assertEqual(chan.dim, (4, 2)) self.assertIsNone(chan.num_qubits) chan = SuperOp(mat.T) assert_allclose(chan.data, mat.T) self.assertEqual(chan.dim, (2, 4)) self.assertIsNone(chan.num_qubits) # Wrong input or output dims should raise exception self.assertRaises(QiskitError, SuperOp, mat, input_dims=[4], output_dims=[4]) def test_circuit_init(self): """Test initialization from a circuit.""" # Test tensor product of 1-qubit gates circuit = QuantumCircuit(3) circuit.h(0) circuit.x(1) circuit.ry(np.pi / 2, 2) op = SuperOp(circuit) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = SuperOp(Operator(np.kron(y90, np.kron(self.UX, self.UH)))) self.assertEqual(target, op) # Test decomposition of Controlled-Phase gate lam = np.pi / 4 circuit = QuantumCircuit(2) circuit.cp(lam, 0, 1) op = SuperOp(circuit) target = SuperOp(Operator(np.diag([1, 1, 1, np.exp(1j * lam)]))) self.assertEqual(target, op) # Test decomposition of controlled-H gate circuit = QuantumCircuit(2) circuit.ch(0, 1) op = SuperOp(circuit) target = SuperOp( Operator(np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1]))) ) self.assertEqual(target, op) def test_circuit_init_except(self): """Test initialization from circuit with measure raises exception.""" circuit = self.simple_circuit_with_measure() self.assertRaises(QiskitError, SuperOp, circuit) def test_equal(self): """Test __eq__ method""" mat = self.rand_matrix(4, 4) self.assertEqual(SuperOp(mat), SuperOp(mat)) def test_copy(self): """Test copy method""" mat = np.eye(4) with self.subTest("Deep copy"): orig = SuperOp(mat) cpy = orig.copy() cpy._data[0, 0] = 0.0 self.assertFalse(cpy == orig) with self.subTest("Shallow copy"): orig = SuperOp(mat) clone = copy.copy(orig) clone._data[0, 0] = 0.0 self.assertTrue(clone == orig) def test_clone(self): """Test clone method""" mat = np.eye(4) orig = SuperOp(mat) clone = copy.copy(orig) clone._data[0, 0] = 0.0 self.assertTrue(clone == orig) def test_evolve(self): """Test evolve method.""" input_rho = DensityMatrix([[0, 0], [0, 1]]) # Identity channel chan = SuperOp(self.sopI) target_rho = DensityMatrix([[0, 0], [0, 1]]) self.assertEqual(input_rho.evolve(chan), target_rho) # Hadamard channel mat = np.array([[1, 1], [1, -1]]) / np.sqrt(2) chan = SuperOp(np.kron(mat.conj(), mat)) target_rho = DensityMatrix(np.array([[1, -1], [-1, 1]]) / 2) self.assertEqual(input_rho.evolve(chan), target_rho) # Completely depolarizing channel chan = SuperOp(self.depol_sop(1)) target_rho = DensityMatrix(np.eye(2) / 2) self.assertEqual(input_rho.evolve(chan), target_rho) def test_evolve_subsystem(self): """Test subsystem evolve method.""" # Single-qubit random superoperators op_a = SuperOp(self.rand_matrix(4, 4)) op_b = SuperOp(self.rand_matrix(4, 4)) op_c = SuperOp(self.rand_matrix(4, 4)) id1 = SuperOp(np.eye(4)) id2 = SuperOp(np.eye(16)) rho = DensityMatrix(self.rand_rho(8)) # Test evolving single-qubit of 3-qubit system op = op_a # Evolve on qubit 0 full_op = id2.tensor(op_a) rho_targ = rho.evolve(full_op) rho_test = rho.evolve(op, qargs=[0]) self.assertEqual(rho_test, rho_targ) # Evolve on qubit 1 full_op = id1.tensor(op_a).tensor(id1) rho_targ = rho.evolve(full_op) rho_test = rho.evolve(op, qargs=[1]) self.assertEqual(rho_test, rho_targ) # Evolve on qubit 2 full_op = op_a.tensor(id2) rho_targ = rho.evolve(full_op) rho_test = rho.evolve(op, qargs=[2]) self.assertEqual(rho_test, rho_targ) # Test 2-qubit evolution op = op_b.tensor(op_a) # Evolve on qubits [0, 2] full_op = op_b.tensor(id1).tensor(op_a) rho_targ = rho.evolve(full_op) rho_test = rho.evolve(op, qargs=[0, 2]) self.assertEqual(rho_test, rho_targ) # Evolve on qubits [2, 0] full_op = op_a.tensor(id1).tensor(op_b) rho_targ = rho.evolve(full_op) rho_test = rho.evolve(op, qargs=[2, 0]) self.assertEqual(rho_test, rho_targ) # Test 3-qubit evolution op = op_c.tensor(op_b).tensor(op_a) # Evolve on qubits [0, 1, 2] full_op = op rho_targ = rho.evolve(full_op) rho_test = rho.evolve(op, qargs=[0, 1, 2]) self.assertEqual(rho_test, rho_targ) # Evolve on qubits [2, 1, 0] full_op = op_a.tensor(op_b).tensor(op_c) rho_targ = rho.evolve(full_op) rho_test = rho.evolve(op, qargs=[2, 1, 0]) self.assertEqual(rho_test, rho_targ) def test_is_cptp(self): """Test is_cptp method.""" self.assertTrue(SuperOp(self.depol_sop(0.25)).is_cptp()) # Non-CPTP should return false self.assertFalse(SuperOp(1.25 * self.sopI - 0.25 * self.depol_sop(1)).is_cptp()) def test_conjugate(self): """Test conjugate method.""" mat = self.rand_matrix(4, 4) chan = SuperOp(mat) targ = SuperOp(np.conjugate(mat)) self.assertEqual(chan.conjugate(), targ) def test_transpose(self): """Test transpose method.""" mat = self.rand_matrix(4, 4) chan = SuperOp(mat) targ = SuperOp(np.transpose(mat)) self.assertEqual(chan.transpose(), targ) def test_adjoint(self): """Test adjoint method.""" mat = self.rand_matrix(4, 4) chan = SuperOp(mat) targ = SuperOp(np.transpose(np.conj(mat))) self.assertEqual(chan.adjoint(), targ) def test_compose_except(self): """Test compose different dimension exception""" self.assertRaises(QiskitError, SuperOp(np.eye(4)).compose, SuperOp(np.eye(16))) self.assertRaises(QiskitError, SuperOp(np.eye(4)).compose, 2) def test_compose(self): """Test compose method.""" # UnitaryChannel evolution chan1 = SuperOp(self.sopX) chan2 = SuperOp(self.sopY) chan = chan1.compose(chan2) targ = SuperOp(self.sopZ) self.assertEqual(chan, targ) # 50% depolarizing channel chan1 = SuperOp(self.depol_sop(0.5)) chan = chan1.compose(chan1) targ = SuperOp(self.depol_sop(0.75)) self.assertEqual(chan, targ) # Random superoperator mat1 = self.rand_matrix(4, 4) mat2 = self.rand_matrix(4, 4) chan1 = SuperOp(mat1) chan2 = SuperOp(mat2) targ = SuperOp(np.dot(mat2, mat1)) self.assertEqual(chan1.compose(chan2), targ) self.assertEqual(chan1 & chan2, targ) targ = SuperOp(np.dot(mat1, mat2)) self.assertEqual(chan2.compose(chan1), targ) self.assertEqual(chan2 & chan1, targ) # Compose different dimensions chan1 = SuperOp(self.rand_matrix(16, 4)) chan2 = SuperOp( self.rand_matrix(4, 16), ) chan = chan1.compose(chan2) self.assertEqual(chan.dim, (2, 2)) chan = chan2.compose(chan1) self.assertEqual(chan.dim, (4, 4)) def test_dot(self): """Test dot method.""" # UnitaryChannel evolution chan1 = SuperOp(self.sopX) chan2 = SuperOp(self.sopY) targ = SuperOp(self.sopZ) self.assertEqual(chan1.dot(chan2), targ) self.assertEqual(chan1 @ chan2, targ) # 50% depolarizing channel chan1 = SuperOp(self.depol_sop(0.5)) targ = SuperOp(self.depol_sop(0.75)) self.assertEqual(chan1.dot(chan1), targ) self.assertEqual(chan1 @ chan1, targ) # Random superoperator mat1 = self.rand_matrix(4, 4) mat2 = self.rand_matrix(4, 4) chan1 = SuperOp(mat1) chan2 = SuperOp(mat2) targ = SuperOp(np.dot(mat2, mat1)) self.assertEqual(chan2.dot(chan1), targ) targ = SuperOp(np.dot(mat1, mat2)) # Compose different dimensions chan1 = SuperOp(self.rand_matrix(16, 4)) chan2 = SuperOp(self.rand_matrix(4, 16)) chan = chan1.dot(chan2) self.assertEqual(chan.dim, (4, 4)) chan = chan1 @ chan2 self.assertEqual(chan.dim, (4, 4)) chan = chan2.dot(chan1) self.assertEqual(chan.dim, (2, 2)) chan = chan2 @ chan1 self.assertEqual(chan.dim, (2, 2)) def test_compose_front(self): """Test front compose method.""" # DEPRECATED # UnitaryChannel evolution chan1 = SuperOp(self.sopX) chan2 = SuperOp(self.sopY) chan = chan1.compose(chan2, front=True) targ = SuperOp(self.sopZ) self.assertEqual(chan, targ) # 50% depolarizing channel chan1 = SuperOp(self.depol_sop(0.5)) chan = chan1.compose(chan1, front=True) targ = SuperOp(self.depol_sop(0.75)) self.assertEqual(chan, targ) # Random superoperator mat1 = self.rand_matrix(4, 4) mat2 = self.rand_matrix(4, 4) chan1 = SuperOp(mat1) chan2 = SuperOp(mat2) targ = SuperOp(np.dot(mat2, mat1)) self.assertEqual(chan2.compose(chan1, front=True), targ) targ = SuperOp(np.dot(mat1, mat2)) self.assertEqual(chan1.compose(chan2, front=True), targ) # Compose different dimensions chan1 = SuperOp(self.rand_matrix(16, 4)) chan2 = SuperOp(self.rand_matrix(4, 16)) chan = chan1.compose(chan2, front=True) self.assertEqual(chan.dim, (4, 4)) chan = chan2.compose(chan1, front=True) self.assertEqual(chan.dim, (2, 2)) def test_compose_subsystem(self): """Test subsystem compose method.""" # 3-qubit superoperator mat = self.rand_matrix(64, 64) mat_a = self.rand_matrix(4, 4) mat_b = self.rand_matrix(4, 4) mat_c = self.rand_matrix(4, 4) iden = SuperOp(np.eye(4)) op = SuperOp(mat) op1 = SuperOp(mat_a) op2 = SuperOp(mat_b).tensor(SuperOp(mat_a)) op3 = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a)) # op3 qargs=[0, 1, 2] full_op = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a)) targ = np.dot(full_op.data, mat) self.assertEqual(op.compose(op3, qargs=[0, 1, 2]), SuperOp(targ)) self.assertEqual(op & op3([0, 1, 2]), SuperOp(targ)) # op3 qargs=[2, 1, 0] full_op = SuperOp(mat_a).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_c)) targ = np.dot(full_op.data, mat) self.assertEqual(op.compose(op3, qargs=[2, 1, 0]), SuperOp(targ)) self.assertEqual(op & op3([2, 1, 0]), SuperOp(targ)) # op2 qargs=[0, 1] full_op = iden.tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a)) targ = np.dot(full_op.data, mat) self.assertEqual(op.compose(op2, qargs=[0, 1]), SuperOp(targ)) self.assertEqual(op & op2([0, 1]), SuperOp(targ)) # op2 qargs=[2, 0] full_op = SuperOp(mat_a).tensor(iden).tensor(SuperOp(mat_b)) targ = np.dot(full_op.data, mat) self.assertEqual(op.compose(op2, qargs=[2, 0]), SuperOp(targ)) self.assertEqual(op & op2([2, 0]), SuperOp(targ)) # op1 qargs=[0] full_op = iden.tensor(iden).tensor(SuperOp(mat_a)) targ = np.dot(full_op.data, mat) self.assertEqual(op.compose(op1, qargs=[0]), SuperOp(targ)) self.assertEqual(op & op1([0]), SuperOp(targ)) # op1 qargs=[1] full_op = iden.tensor(SuperOp(mat_a)).tensor(iden) targ = np.dot(full_op.data, mat) self.assertEqual(op.compose(op1, qargs=[1]), SuperOp(targ)) self.assertEqual(op & op1([1]), SuperOp(targ)) # op1 qargs=[2] full_op = SuperOp(mat_a).tensor(iden).tensor(iden) targ = np.dot(full_op.data, mat) self.assertEqual(op.compose(op1, qargs=[2]), SuperOp(targ)) self.assertEqual(op & op1([2]), SuperOp(targ)) def test_dot_subsystem(self): """Test subsystem dot method.""" # 3-qubit operator mat = self.rand_matrix(64, 64) mat_a = self.rand_matrix(4, 4) mat_b = self.rand_matrix(4, 4) mat_c = self.rand_matrix(4, 4) iden = SuperOp(np.eye(4)) op = SuperOp(mat) op1 = SuperOp(mat_a) op2 = SuperOp(mat_b).tensor(SuperOp(mat_a)) op3 = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a)) # op3 qargs=[0, 1, 2] full_op = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a)) targ = np.dot(mat, full_op.data) self.assertEqual(op.dot(op3, qargs=[0, 1, 2]), SuperOp(targ)) # op3 qargs=[2, 1, 0] full_op = SuperOp(mat_a).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_c)) targ = np.dot(mat, full_op.data) self.assertEqual(op.dot(op3, qargs=[2, 1, 0]), SuperOp(targ)) # op2 qargs=[0, 1] full_op = iden.tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a)) targ = np.dot(mat, full_op.data) self.assertEqual(op.dot(op2, qargs=[0, 1]), SuperOp(targ)) # op2 qargs=[2, 0] full_op = SuperOp(mat_a).tensor(iden).tensor(SuperOp(mat_b)) targ = np.dot(mat, full_op.data) self.assertEqual(op.dot(op2, qargs=[2, 0]), SuperOp(targ)) # op1 qargs=[0] full_op = iden.tensor(iden).tensor(SuperOp(mat_a)) targ = np.dot(mat, full_op.data) self.assertEqual(op.dot(op1, qargs=[0]), SuperOp(targ)) # op1 qargs=[1] full_op = iden.tensor(SuperOp(mat_a)).tensor(iden) targ = np.dot(mat, full_op.data) self.assertEqual(op.dot(op1, qargs=[1]), SuperOp(targ)) # op1 qargs=[2] full_op = SuperOp(mat_a).tensor(iden).tensor(iden) targ = np.dot(mat, full_op.data) self.assertEqual(op.dot(op1, qargs=[2]), SuperOp(targ)) def test_compose_front_subsystem(self): """Test subsystem front compose method.""" # 3-qubit operator mat = self.rand_matrix(64, 64) mat_a = self.rand_matrix(4, 4) mat_b = self.rand_matrix(4, 4) mat_c = self.rand_matrix(4, 4) iden = SuperOp(np.eye(4)) op = SuperOp(mat) op1 = SuperOp(mat_a) op2 = SuperOp(mat_b).tensor(SuperOp(mat_a)) op3 = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a)) # op3 qargs=[0, 1, 2] full_op = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a)) targ = np.dot(mat, full_op.data) self.assertEqual(op.compose(op3, qargs=[0, 1, 2], front=True), SuperOp(targ)) # op3 qargs=[2, 1, 0] full_op = SuperOp(mat_a).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_c)) targ = np.dot(mat, full_op.data) self.assertEqual(op.compose(op3, qargs=[2, 1, 0], front=True), SuperOp(targ)) # op2 qargs=[0, 1] full_op = iden.tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a)) targ = np.dot(mat, full_op.data) self.assertEqual(op.compose(op2, qargs=[0, 1], front=True), SuperOp(targ)) # op2 qargs=[2, 0] full_op = SuperOp(mat_a).tensor(iden).tensor(SuperOp(mat_b)) targ = np.dot(mat, full_op.data) self.assertEqual(op.compose(op2, qargs=[2, 0], front=True), SuperOp(targ)) # op1 qargs=[0] full_op = iden.tensor(iden).tensor(SuperOp(mat_a)) targ = np.dot(mat, full_op.data) self.assertEqual(op.compose(op1, qargs=[0], front=True), SuperOp(targ)) # op1 qargs=[1] full_op = iden.tensor(SuperOp(mat_a)).tensor(iden) targ = np.dot(mat, full_op.data) self.assertEqual(op.compose(op1, qargs=[1], front=True), SuperOp(targ)) # op1 qargs=[2] full_op = SuperOp(mat_a).tensor(iden).tensor(iden) targ = np.dot(mat, full_op.data) self.assertEqual(op.compose(op1, qargs=[2], front=True), SuperOp(targ)) def test_expand(self): """Test expand method.""" rho0, rho1 = np.diag([1, 0]), np.diag([0, 1]) rho_init = DensityMatrix(np.kron(rho0, rho0)) chan1 = SuperOp(self.sopI) chan2 = SuperOp(self.sopX) # X \otimes I chan = chan1.expand(chan2) rho_targ = DensityMatrix(np.kron(rho1, rho0)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # I \otimes X chan = chan2.expand(chan1) rho_targ = DensityMatrix(np.kron(rho0, rho1)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) def test_tensor(self): """Test tensor method.""" rho0, rho1 = np.diag([1, 0]), np.diag([0, 1]) rho_init = DensityMatrix(np.kron(rho0, rho0)) chan1 = SuperOp(self.sopI) chan2 = SuperOp(self.sopX) # X \otimes I chan = chan2.tensor(chan1) rho_targ = DensityMatrix(np.kron(rho1, rho0)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) chan = chan2 ^ chan1 self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # I \otimes X chan = chan1.tensor(chan2) rho_targ = DensityMatrix(np.kron(rho0, rho1)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) chan = chan1 ^ chan2 self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) def test_power(self): """Test power method.""" # 10% depolarizing channel p_id = 0.9 depol = SuperOp(self.depol_sop(1 - p_id)) # Compose 3 times p_id3 = p_id**3 chan3 = depol.power(3) targ3 = SuperOp(self.depol_sop(1 - p_id3)) self.assertEqual(chan3, targ3) def test_add(self): """Test add method.""" mat1 = 0.5 * self.sopI mat2 = 0.5 * self.depol_sop(1) chan1 = SuperOp(mat1) chan2 = SuperOp(mat2) targ = SuperOp(mat1 + mat2) self.assertEqual(chan1._add(chan2), targ) self.assertEqual(chan1 + chan2, targ) targ = SuperOp(mat1 - mat2) self.assertEqual(chan1 - chan2, targ) def test_add_qargs(self): """Test add method with qargs.""" mat = self.rand_matrix(8**2, 8**2) mat0 = self.rand_matrix(4, 4) mat1 = self.rand_matrix(4, 4) op = SuperOp(mat) op0 = SuperOp(mat0) op1 = SuperOp(mat1) op01 = op1.tensor(op0) eye = SuperOp(self.sopI) with self.subTest(msg="qargs=[0]"): value = op + op0([0]) target = op + eye.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1]"): value = op + op0([1]) target = op + eye.tensor(op0).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[2]"): value = op + op0([2]) target = op + op0.tensor(eye).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 1]"): value = op + op01([0, 1]) target = op + eye.tensor(op1).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1, 0]"): value = op + op01([1, 0]) target = op + eye.tensor(op0).tensor(op1) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 2]"): value = op + op01([0, 2]) target = op + op1.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[2, 0]"): value = op + op01([2, 0]) target = op + op0.tensor(eye).tensor(op1) self.assertEqual(value, target) def test_sub_qargs(self): """Test subtract method with qargs.""" mat = self.rand_matrix(8**2, 8**2) mat0 = self.rand_matrix(4, 4) mat1 = self.rand_matrix(4, 4) op = SuperOp(mat) op0 = SuperOp(mat0) op1 = SuperOp(mat1) op01 = op1.tensor(op0) eye = SuperOp(self.sopI) with self.subTest(msg="qargs=[0]"): value = op - op0([0]) target = op - eye.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1]"): value = op - op0([1]) target = op - eye.tensor(op0).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[2]"): value = op - op0([2]) target = op - op0.tensor(eye).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 1]"): value = op - op01([0, 1]) target = op - eye.tensor(op1).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1, 0]"): value = op - op01([1, 0]) target = op - eye.tensor(op0).tensor(op1) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 2]"): value = op - op01([0, 2]) target = op - op1.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[2, 0]"): value = op - op01([2, 0]) target = op - op0.tensor(eye).tensor(op1) self.assertEqual(value, target) def test_add_except(self): """Test add method raises exceptions.""" chan1 = SuperOp(self.sopI) chan2 = SuperOp(np.eye(16)) self.assertRaises(QiskitError, chan1._add, chan2) self.assertRaises(QiskitError, chan1._add, 5) def test_multiply(self): """Test multiply method.""" chan = SuperOp(self.sopI) val = 0.5 targ = SuperOp(val * self.sopI) self.assertEqual(chan._multiply(val), targ) self.assertEqual(val * chan, targ) targ = SuperOp(self.sopI * val) self.assertEqual(chan * val, targ) def test_multiply_except(self): """Test multiply method raises exceptions.""" chan = SuperOp(self.sopI) self.assertRaises(QiskitError, chan._multiply, "s") self.assertRaises(QiskitError, chan.__rmul__, "s") self.assertRaises(QiskitError, chan._multiply, chan) self.assertRaises(QiskitError, chan.__rmul__, chan) def test_negate(self): """Test negate method""" chan = SuperOp(self.sopI) targ = SuperOp(-self.sopI) self.assertEqual(-chan, targ) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit_nature.second_q.hamiltonians import QuadraticHamiltonian # create Hamiltonian hermitian_part = np.array( [ [1.0, 2.0, 0.0, 0.0], [2.0, 1.0, 2.0, 0.0], [0.0, 2.0, 1.0, 2.0], [0.0, 0.0, 2.0, 1.0], ] ) antisymmetric_part = np.array( [ [0.0, 3.0, 0.0, 0.0], [-3.0, 0.0, 3.0, 0.0], [0.0, -3.0, 0.0, 3.0], [0.0, 0.0, -3.0, 0.0], ] ) constant = 4.0 hamiltonian = QuadraticHamiltonian( hermitian_part=hermitian_part, antisymmetric_part=antisymmetric_part, constant=constant, ) # convert it to a FermionicOp and print it hamiltonian_ferm = hamiltonian.second_q_op() print(hamiltonian_ferm) # get the transformation matrix W and orbital energies {epsilon_j} ( transformation_matrix, orbital_energies, transformed_constant, ) = hamiltonian.diagonalizing_bogoliubov_transform() print(f"Shape of matrix W: {transformation_matrix.shape}") print(f"Orbital energies: {orbital_energies}") print(f"Transformed constant: {transformed_constant}") from qiskit_nature.second_q.circuit.library import FermionicGaussianState occupied_orbitals = (0, 2) eig = np.sum(orbital_energies[list(occupied_orbitals)]) + transformed_constant print(f"Eigenvalue: {eig}") circuit = FermionicGaussianState(transformation_matrix, occupied_orbitals=occupied_orbitals) circuit.draw("mpl") from qiskit.quantum_info import Statevector from qiskit_nature.second_q.mappers import JordanWignerMapper # simulate the circuit to get the final state state = np.array(Statevector(circuit)) # convert the Hamiltonian to a matrix hamiltonian_jw = JordanWignerMapper().map(hamiltonian_ferm).to_matrix() # check that the state is an eigenvector with the expected eigenvalue np.testing.assert_allclose(hamiltonian_jw @ state, eig * state, atol=1e-8) # create Hamiltonian hermitian_part = np.array( [ [1.0, 2.0, 0.0, 0.0], [2.0, 1.0, 2.0, 0.0], [0.0, 2.0, 1.0, 2.0], [0.0, 0.0, 2.0, 1.0], ] ) constant = 4.0 hamiltonian = QuadraticHamiltonian( hermitian_part=hermitian_part, constant=constant, ) print(f"Hamiltonian conserves particle number: {hamiltonian.conserves_particle_number()}") # get the transformation matrix W and orbital energies {epsilon_j} ( transformation_matrix, orbital_energies, transformed_constant, ) = hamiltonian.diagonalizing_bogoliubov_transform() print(f"Shape of matrix W: {transformation_matrix.shape}") print(f"Orbital energies: {orbital_energies}") print(f"Transformed constant: {transformed_constant}") from qiskit_nature.second_q.circuit.library import SlaterDeterminant occupied_orbitals = (0, 2) eig = np.sum(orbital_energies[list(occupied_orbitals)]) + transformed_constant print(f"Eigenvalue: {eig}") circuit = SlaterDeterminant(transformation_matrix[list(occupied_orbitals)]) circuit.draw("mpl") from qiskit_nature.second_q.circuit.library import BogoliubovTransform from qiskit import QuantumCircuit, QuantumRegister from qiskit.quantum_info import random_hermitian, random_statevector, state_fidelity from scipy.linalg import expm # create Hamiltonian n_modes = 5 hermitian_part = np.array(random_hermitian(n_modes)) hamiltonian = QuadraticHamiltonian(hermitian_part=hermitian_part) # diagonalize Hamiltonian ( transformation_matrix, orbital_energies, _, ) = hamiltonian.diagonalizing_bogoliubov_transform() # set simulation time and construct time evolution circuit time = 1.0 register = QuantumRegister(n_modes) circuit = QuantumCircuit(register) bog_circuit = BogoliubovTransform(transformation_matrix) # change to the diagonal basis of the Hamiltonian circuit.append(bog_circuit.inverse(), register) # perform time evolution by applying z rotations for q, energy in zip(register, orbital_energies): circuit.rz(-energy * time, q) # change back to the original basis circuit.append(bog_circuit, register) # simulate the circuit initial_state = random_statevector(2**n_modes) final_state = initial_state.evolve(circuit) # compute the correct state by direct exponentiation hamiltonian_jw = JordanWignerMapper().map(hamiltonian.second_q_op()).to_matrix() exact_evolution_op = expm(-1j * time * hamiltonian_jw) expected_state = exact_evolution_op @ np.array(initial_state) # check that the simulated state is correct fidelity = state_fidelity(final_state, expected_state) np.testing.assert_allclose(fidelity, 1.0, atol=1e-8) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
min_qubits=2 max_qubits=8 max_circuits=1 num_shots=1000 backend_id="qasm_simulator" #backend_id="statevector_simulator" hub="ibm-q"; group="open"; project="main" provider_backend = None exec_options = {} # # ========================== # # *** If using IBMQ hardware, run this once to authenticate # from qiskit import IBMQ # IBMQ.save_account('YOUR_API_TOKEN_HERE') # # *** If you are part of an IBMQ group, set hub, group, and project name here # hub="YOUR_HUB_NAME"; group="YOUR_GROUP_NAME"; project="YOUR_PROJECT_NAME" # # *** This example shows how to specify an IBMQ backend using a known "backend_id" # exec_options = { "optimization_level":3, "use_sessions":True, "resilience_level":1} # backend_id="ibmq_belem" # # ========================== # # *** If using Azure Quantum, use this hub identifier and specify the desired backend_id # # Identify your resources with env variables AZURE_QUANTUM_RESOURCE_ID and AZURE_QUANTUM_LOCATION # hub="azure-quantum"; group="open"; project="QED-C App-Oriented Benchmarks - Qiskit Version" # backend_id="<YOUR_BACKEND_NAME_HERE>" # # ========================== # The remaining examples create a provider instance and get a backend from it # # An example using IonQ provider # from qiskit_ionq import IonQProvider # provider = IonQProvider() # Be sure to set the QISKIT_IONQ_API_TOKEN environment variable # provider_backend = provider.get_backend("ionq_qpu") # backend_id="ionq_qpu" # # An example using BlueQubit provider # import sys # sys.path.insert(1, "../..") # import os, bluequbit, _common.executors.bluequbit_executor as bluequbit_executor # provider_backend = bluequbit.init() # backend_id="BlueQubit-CPU" # exec_options = { "executor": bluequbit_executor.run, "device":'cpu' } # # *** Here's an example of using a typical custom provider backend (e.g. AQT simulator) # import os # from qiskit_aqt_provider import AQTProvider # provider = AQTProvider(os.environ.get('AQT_ACCESS_KEY')) # get your key from environment # provider_backend = provider.backends.aqt_qasm_simulator_noise_1 # backend_id="aqt_qasm_simulator_noise_1" # Custom optimization options can be specified in this cell (below is an example) import sys sys.path.insert(1, "../../") # # Example of pytket Transformer # import _common.transformers.tket_optimiser as tket_optimiser # exec_options.update({ "optimization_level": 0, "layout_method":'sabre', "routing_method":'sabre', "transformer": tket_optimiser.high_optimisation }) # # Define a custom noise model to be used during execution # import _common.custom.custom_qiskit_noise_model as custom_qiskit_noise_model # exec_options.update({ "noise_model": custom_qiskit_noise_model.my_noise_model() }) # # Example of mthree error mitigation # import _common.postprocessors.mthree.mthree_em as mthree_em # exec_options.update({ "postprocessor": mthree_em.get_mthree_handlers(backend_id, provider_backend) }) ################## # Addition options for exploring Hydrogen Lattice import sys sys.path.insert(1, "../../_common") sys.path.insert(1, "../../_common/qiskit") # Set these True to enable verbose and verbose_time execution import execute execute.verbose=False execute.verbose_time=False # Set noise model to None. This way the Sampler version uses same noise model as Estimator version execute.noise=None # Appendage for storing the data files and identifying the plots import metrics metrics.data_suffix="" import sys sys.path.insert(1, "hydrogen-lattice/qiskit") import hydrogen_lattice_benchmark # Arguments applicable to Hydrogen Lattice benchmark method (1) hl_app_args = dict( radius=0.75, # select single problem radius, None = use max_circuits problem thetas_array=None, # specify a custom thetas_array parameter_mode=1, # 1 - use single theta parameter, 2 - map multiple thetas to pairs parameterized=True, # use Parameter objects in circuit, cache transpiled circuits for performance use_estimator=False, # use the Estimator for execution of objective function ) # Run the benchmark in method 1 hydrogen_lattice_benchmark.run( min_qubits=min_qubits, max_qubits=max_qubits, max_circuits=max_circuits, num_shots=num_shots, method=1, backend_id=backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options, **hl_app_args) import sys sys.path.insert(1, "hydrogen-lattice/qiskit") import hydrogen_lattice_benchmark # Arguments specific to Hydrogen Lattice benchmark method (2) hl_app_args = dict( radius=0.75, # select single problem radius, None = use max_circuits problems thetas_array=None, # specify a custom thetas_array parameter_mode=1, # 1 - use single theta parameter, 2 - map multiple thetas to pairs parameterized=False, # use Parameter objects in circuit, cache transpiled circuits for performance use_estimator=False, # use the Estimator for execution of objective function max_iter=30, # maximum minimizer iterations to perform minimizer_tolerance=0.001, # tolerance passed to the minimizer comfort=True, # show 'comfort dots' during execution ) # Run the benchmark in method 2 hydrogen_lattice_benchmark.run( min_qubits=min_qubits, max_qubits=max_qubits, max_circuits=max_circuits, num_shots=num_shots, method=2, backend_id=backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options, **hl_app_args) import sys sys.path.insert(1, "hydrogen-lattice/qiskit") import hydrogen_lattice_benchmark # DEVNOTE: Estimator is using no noise by default import execute execute.noise = None # Arguments specific to Hydrogen Lattice benchmark method (2) hl_app_args = dict( radius=0.75, # select single problem radius, None = use max_circuits problems thetas_array=None, # specify a custom thetas_array parameter_mode=1, # 1 - use single theta parameter, 2 - map multiple thetas to pairs parameterized=False, # use Parameter objects in circuit, cache transpiled circuits for performance use_estimator=True, # use the Estimator for execution of objective function max_iter=30, # maximum minimizer iterations to perform minimizer_tolerance=0.001, # tolerance passed to the minimizer comfort=True, # show 'comfort dots' during execution ) # Run the benchmark in method 2 hydrogen_lattice_benchmark.run( min_qubits=min_qubits, max_qubits=max_qubits, max_circuits=max_circuits, num_shots=num_shots, method=2, backend_id=backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options, **hl_app_args)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeVigoV2 from qiskit.visualization import plot_circuit_layout from qiskit.tools.monitor import job_monitor from qiskit.providers.fake_provider import FakeVigoV2 import matplotlib.pyplot as plt ghz = QuantumCircuit(3, 3) ghz.h(0) for idx in range(1,3): ghz.cx(0,idx) ghz.measure(range(3), range(3)) backend = FakeVigoV2() new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3) plot_circuit_layout(new_circ_lv3, backend)
https://github.com/VicentePerezSoloviev/QAOA_BNSL_IBM
VicentePerezSoloviev
# all libraries used by some part of the VQLS-implementation from qiskit import ( QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute, transpile, assemble ) from qiskit.circuit import Gate, Instruction from qiskit.quantum_info.operators import Operator from qiskit.extensions import ZGate, YGate, XGate, IGate from scipy.optimize import ( minimize, basinhopping, differential_evolution, shgo, dual_annealing ) import random import numpy as np import cmath from typing import List, Set, Dict, Tuple, Optional, Union # import the params object of the GlobalParameters class # this provides the parameters used to desribed and model # the problem the minimizer is supposed to use. from GlobalParameters import params # import the vqls algorithm and corresponding code from vqls import ( generate_ansatz, hadamard_test, calculate_beta, calculate_delta, calculate_local_cost_function, minimize_local_cost_function, postCorrection, _format_alpha, _calculate_expectationValue_HadamardTest, _U_primitive ) # The user input for the VQLS-algorithm has to be given # when params is initialized within GlobalParameters.py # The decomposition for $A$ has to be manually # inserted into the code of # the class GlobalParameters. print( "This program will execute a simulation of the VQLS-algorithm " + "with 4 qubits, 4 layers in the Ansatz and a single Id-gate acting" + " on the second qubit.\n" + "To simulate another problem, one can either alter _U_primitive " + "in vqls.py to change |x_0>, GlobalParameters.py to change A " + "or its decomposition respectively." ) # Executing the VQLS-algorithm alpha_min = minimize_local_cost_function(params.method_minimization) """ Circuit with the $\vec{alpha}$ generated by the minimizer. """ # Create a circuit for the vqls-result qr_min = QuantumRegister(params.n_qubits) circ_min = QuantumCircuit(qr_min) # generate $V(\vec{alpha})$ and copy $A$ ansatz = generate_ansatz(alpha_min).to_gate() A_copy = params.A.copy() if isinstance(params.A, Operator): A_copy = A_copy.to_instruction() # apply $V(\vec{alpha})$ and $A$ to the circuit # this results in a state that is approximately $\ket{b}$ circ_min.append(ansatz, qr_min) circ_min.append(A_copy, qr_min) # apply post correction to fix for sign errors and a "mirroring" # of the result circ_min = postCorrection(circ_min) """ Reference circuit based on the definition of $\ket{b}$. """ circ_ref = _U_primitive() """ Simulate both circuits. """ # the minimizations result backend = Aer.get_backend( 'statevector_simulator') t_circ = transpile(circ_min, backend) qobj = assemble(t_circ) job = backend.run(qobj) result = job.result() print( "This is the result of the simulation.\n" + "Reminder: 4 qubits and an Id-gate on the second qubit." + "|x_0> was defined by Hadamard gates acting on qubits 0 and 3.\n" + "The return value of the minimizer (alpha_min):\n" + str(alpha_min) + "\nThe resulting statevector for a circuit to which " + "V(alpha_min) and A and the post correction were applied:\n" + str(result.get_statevector()) ) t_circ = transpile(circ_ref, backend) qobj = assemble(t_circ) job = backend.run(qobj) result = job.result() print( "And this is the statevector for the reference circuit: A |x_0>\n" + str(result.get_statevector()) ) print("these were Id gates and in U y on 0 and 1")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
mathelatics
from qiskit import * import numpy as np from numpy import linalg as la from qiskit.tools.monitor import job_monitor import qiskit.tools.jupyter qc = QuantumCircuit(1) #### your code goes here # z measurement of qubit 0 measure_z = QuantumCircuit(1,1) measure_z.measure(0,0) # x measurement of qubit 0 measure_x = QuantumCircuit(1,1) # your code goes here # y measurement of qubit 0 measure_y = QuantumCircuit(1,1) # your code goes here shots = 2**14 # number of samples used for statistics sim = Aer.get_backend('qasm_simulator') bloch_vector_measure = [] for measure_circuit in [measure_x, measure_y, measure_z]: # run the circuit with a the selected measurement and get the number of samples that output each bit value counts = execute(qc+measure_circuit, sim, shots=shots).result().get_counts() # calculate the probabilities for each bit value probs = {} for output in ['0','1']: if output in counts: probs[output] = counts[output]/shots else: probs[output] = 0 bloch_vector_measure.append( probs['0'] - probs['1'] ) # normalizing the bloch sphere vector bloch_vector = bloch_vector_measure/la.norm(bloch_vector_measure) print('The bloch sphere coordinates are [{0:4.3f}, {1:4.3f}, {2:4.3f}]' .format(*bloch_vector)) from kaleidoscope.interactive import bloch_sphere bloch_sphere(bloch_vector, vectors_annotation=True) from qiskit.visualization import plot_bloch_vector plot_bloch_vector( bloch_vector ) # circuit for the state Tri1 Tri1 = QuantumCircuit(2) # your code goes here # circuit for the state Tri2 Tri2 = QuantumCircuit(2) # your code goes here # circuit for the state Tri3 Tri3 = QuantumCircuit(2) # your code goes here # circuit for the state Sing Sing = QuantumCircuit(2) # your code goes here # <ZZ> measure_ZZ = QuantumCircuit(2) measure_ZZ.measure_all() # <XX> measure_XX = QuantumCircuit(2) # your code goes here # <YY> measure_YY = QuantumCircuit(2) # your code goes here shots = 2**14 # number of samples used for statistics A = 1.47e-6 #unit of A is eV E_sim = [] for state_init in [Tri1,Tri2,Tri3,Sing]: Energy_meas = [] for measure_circuit in [measure_XX, measure_YY, measure_ZZ]: # run the circuit with a the selected measurement and get the number of samples that output each bit value qc = state_init+measure_circuit counts = execute(qc, sim, shots=shots).result().get_counts() # calculate the probabilities for each computational basis probs = {} for output in ['00','01', '10', '11']: if output in counts: probs[output] = counts[output]/shots else: probs[output] = 0 Energy_meas.append( probs['00'] - probs['01'] - probs['10'] + probs['11'] ) E_sim.append(A * np.sum(np.array(Energy_meas))) # Run this cell to print out your results print('Energy expection value of the state Tri1 : {:.3e} eV'.format(E_sim[0])) print('Energy expection value of the state Tri2 : {:.3e} eV'.format(E_sim[1])) print('Energy expection value of the state Tri3 : {:.3e} eV'.format(E_sim[2])) print('Energy expection value of the state Sing : {:.3e} eV'.format(E_sim[3])) # reduced plank constant in (eV) and the speed of light(cgs units) hbar, c = 4.1357e-15, 3e10 # energy difference between the triplets and singlet E_del = abs(E_sim[0] - E_sim[3]) # frequency associated with the energy difference f = E_del/hbar # convert frequency to wavelength in (cm) wavelength = c/f print('The wavelength of the radiation from the transition\ in the hyperfine structure is : {:.1f} cm'.format(wavelength)) provider = IBMQ.load_account() backend = provider.get_backend('ibmq_athens') # run this cell to get the backend information through the widget backend # assign your choice for the initial layout to the list variable `initial_layout`. initial_layout = qc_all = [state_init+measure_circuit for state_init in [Tri1,Tri2,Tri3,Sing] for measure_circuit in [measure_XX, measure_YY, measure_ZZ] ] shots = 8192 job = execute(qc_all, backend, initial_layout=initial_layout, optimization_level=3, shots=shots) print(job.job_id()) job_monitor(job) # getting the results of your job results = job.result() ## To access the results of the completed job #results = backend.retrieve_job('job_id').result() def Energy(results, shots): """Compute the energy levels of the hydrogen ground state. Parameters: results (obj): results, results from executing the circuits for measuring a hamiltonian. shots (int): shots, number of shots used for the circuit execution. Returns: Energy (list): energy values of the four different hydrogen ground states """ E = [] A = 1.47e-6 for ind_state in range(4): Energy_meas = [] for ind_comp in range(3): counts = results.get_counts(ind_state*3+ind_comp) # calculate the probabilities for each computational basis probs = {} for output in ['00','01', '10', '11']: if output in counts: probs[output] = counts[output]/shots else: probs[output] = 0 Energy_meas.append( probs['00'] - probs['01'] - probs['10'] + probs['11'] ) E.append(A * np.sum(np.array(Energy_meas))) return E E = Energy(results, shots) print('Energy expection value of the state Tri1 : {:.3e} eV'.format(E[0])) print('Energy expection value of the state Tri2 : {:.3e} eV'.format(E[1])) print('Energy expection value of the state Tri3 : {:.3e} eV'.format(E[2])) print('Energy expection value of the state Sing : {:.3e} eV'.format(E[3])) from qiskit.ignis.mitigation.measurement import * # your code to create the circuits, meas_calibs, goes here meas_calibs, state_labels = # execute meas_calibs on your choice of the backend job = execute(meas_calibs, backend, shots = shots) print(job.job_id()) job_monitor(job) cal_results = job.result() ## To access the results of the completed job #cal_results = backend.retrieve_job('job_id').result() # your code to obtain the measurement filter object, 'meas_filter', goes here results_new = meas_filter.apply(results) E_new = Energy(results_new, shots) print('Energy expection value of the state Tri1 : {:.3e} eV'.format(E_new[0])) print('Energy expection value of the state Tri2 : {:.3e} eV'.format(E_new[1])) print('Energy expection value of the state Tri3 : {:.3e} eV'.format(E_new[2])) print('Energy expection value of the state Sing : {:.3e} eV'.format(E_new[3])) # results for the energy estimation from the simulation, # execution on a quantum system without error mitigation and # with error mitigation in numpy array format Energy_exact, Energy_exp_orig, Energy_exp_new = np.array(E_sim), np.array(E), np.array(E_new) # Calculate the relative errors of the energy values without error mitigation # and assign to the numpy array variable `Err_rel_orig` of size 4 Err_rel_orig = # Calculate the relative errors of the energy values with error mitigation # and assign to the numpy array variable `Err_rel_new` of size 4 Err_rel_new = np.set_printoptions(precision=3) print('The relative errors of the energy values for four bell basis\ without measurement error mitigation : {}'.format(Err_rel_orig)) np.set_printoptions(precision=3) print('The relative errors of the energy values for four bell basis\ with measurement error mitigation : {}'.format(Err_rel_new))
https://github.com/electricalgorithm/DeutschJozsaAlgorithm
electricalgorithm
""" This module implements the Deutsch-Jozsa algorithm using Qiskit. """ import numpy as np from qiskit import Aer from qiskit import QuantumCircuit, assemble, transpile from qiskit.circuit.instruction import Instruction class DJAlgorithm: """This class implements the Deutsch-Jozsa algorithm.""" @staticmethod def simulate(oracle_block: QuantumCircuit) -> dict: """ Run the Deutsch-Jozsa algorithm on the simulator. :param oracle_block: The oracle block to check with Deutsch-Jozsa algorithm. :return: The result of the algorithm as dictionary. Check "result" attribute. """ circuit = DJAlgorithm._construct_the_circuit(oracle_block) aer_sim = Aer.get_backend("aer_simulator") transpiled_dj_circuit = transpile(circuit, aer_sim) qobj = assemble(transpiled_dj_circuit) results = aer_sim.run(qobj).result() answer = results.get_counts() if "0" * (circuit.num_qubits - 1) in answer: return {"result": "Constant"} else: return {"result": "Balanced"} @staticmethod def give_a_balanced_function(inputs_count: int) -> Instruction: """Returns a balanced oracle function. :param inputs_count: The number of input qubits. :return: The balanced oracle function as Instruction. """ # Get the number of input qubits. random_number = np.random.randint(1, 2**inputs_count) inputs = format(random_number, "0" + str(inputs_count) + "b") # Create a quantum circuit with the number of input qubits + 1 output qubit. oracle = QuantumCircuit(inputs_count + 1, inputs_count) # Place X gates on the start of input qubit lines. for index, qubit in enumerate(reversed(inputs)): if qubit == "1": oracle.x(index) # Apply the oracle block. for index, qubit in enumerate(inputs): oracle.cx(index, inputs_count) # Place X-gates on the end of input qubits lines. for index, qubit in enumerate(reversed(inputs)): if qubit == "1": oracle.x(index) inst = oracle.to_instruction() inst.name = "BalancedOracle" return inst @staticmethod def give_a_constant_function(inputs_count: int) -> Instruction: """Returns a constant oracle function. :param inputs_count: The number of input qubits. :return: The balanced oracle function as Instruction. """ # Create a quantum circuit with the number of input qubits + 1 output qubit. oracle = QuantumCircuit(inputs_count + 1) if np.random.randint(2) == 1: oracle.x(inputs_count) inst = oracle.to_instruction() inst.name = "ConstantOracle" return inst @staticmethod def _construct_the_circuit(function_block: QuantumCircuit) -> QuantumCircuit: """It creates the circuit for the Deutsch-Jozsa algorithm. :param function_block: The oracle block to check with Deutsch-Jozsa algorithm. :return: The circuit for the Deutsch-Jozsa algorithm. """ # Get the number of input qubits. input_length = function_block.num_qubits - 1 _circuit = QuantumCircuit(input_length + 1, input_length) # Apply Hadamard gates to all input qubits. for qubit in range(input_length): _circuit.h(qubit) # Convert the last qubit to |-) state. _circuit.x(input_length) _circuit.h(input_length) _circuit.barrier() # Apply the oracle block. _circuit.append( function_block, range(function_block.num_qubits), range(function_block.num_clbits) ) _circuit.barrier() # Apply Hadamard gates to all input qubits. for qubit in range(input_length): _circuit.h(qubit) _circuit.barrier() # Measure all input qubits and put them to classical bits. for qubit in range(input_length): _circuit.measure(qubit, qubit) return _circuit if __name__ == "__main__": print("===================================") print("Deutsch-Jozsa Algorithm Simulation") print("===================================") # Get the number of input qubits. inputs_count = int(input("> Enter the number of input qubits: ")) # Get the oracle block. oracle_type = input("> Enter the type of function (c)onstant/(b)alanced: ") oracle_type = oracle_type.lower() if oracle_type == "constant" or oracle_type == "c": block_to_test = DJAlgorithm.give_a_constant_function(inputs_count) elif oracle_type == "balanced" or oracle_type == "b": block_to_test = DJAlgorithm.give_a_balanced_function(inputs_count) else: print("Invalid function type.") exit(1) # Run the algorithm. result = DJAlgorithm.simulate(block_to_test) print("Result: " + result["result"])
https://github.com/JavaFXpert/qiskit4devs-workshop-notebooks
JavaFXpert
# Do the necessary import for our program #!pip install qiskit-aqua from qiskit import BasicAer from qiskit.aqua.algorithms import Grover from qiskit.aqua.components.oracles import LogicalExpressionOracle from qiskit.tools.visualization import plot_histogram log_expr = '((A & B) | (C & D)) & ~(A & D)' algorithm = Grover(LogicalExpressionOracle(log_expr)) # Run the algorithm on a simulator, printing the most frequently occurring result backend = BasicAer.get_backend('qasm_simulator') result = algorithm.run(backend) print(result['top_measurement']) plot_histogram(result['measurement'])
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from math import pi import numpy as np import rustworkx as rx from qiskit_nature.second_q.hamiltonians.lattices import ( BoundaryCondition, HyperCubicLattice, Lattice, LatticeDrawStyle, LineLattice, SquareLattice, TriangularLattice, ) from qiskit_nature.second_q.hamiltonians import FermiHubbardModel num_nodes = 11 boundary_condition = BoundaryCondition.OPEN line_lattice = LineLattice(num_nodes=num_nodes, boundary_condition=boundary_condition) line_lattice.draw() num_nodes = 11 boundary_condition = BoundaryCondition.PERIODIC line_lattice = LineLattice(num_nodes=num_nodes, boundary_condition=boundary_condition) line_lattice.draw() line_lattice.draw_without_boundary() num_nodes = 11 boundary_condition = BoundaryCondition.PERIODIC edge_parameter = 1.0 + 1.0j onsite_parameter = 1.0 line_lattice = LineLattice( num_nodes=num_nodes, edge_parameter=edge_parameter, onsite_parameter=onsite_parameter, boundary_condition=boundary_condition, ) set(line_lattice.graph.weighted_edge_list()) line_lattice.to_adjacency_matrix() line_lattice.to_adjacency_matrix(weighted=True) rows = 5 cols = 4 boundary_condition = BoundaryCondition.OPEN square_lattice = SquareLattice(rows=rows, cols=cols, boundary_condition=boundary_condition) square_lattice.draw() rows = 5 cols = 4 boundary_condition = ( BoundaryCondition.OPEN, BoundaryCondition.PERIODIC, ) # open in the x-direction, periodic in the y-direction square_lattice = SquareLattice(rows=rows, cols=cols, boundary_condition=boundary_condition) square_lattice.draw() rows = 5 cols = 4 edge_parameter = (1.0, 1.0 + 1.0j) boundary_condition = ( BoundaryCondition.OPEN, BoundaryCondition.PERIODIC, ) # open in the x-direction, periodic in the y-direction onsite_parameter = 1.0 square_lattice = SquareLattice( rows=rows, cols=cols, edge_parameter=edge_parameter, onsite_parameter=onsite_parameter, boundary_condition=boundary_condition, ) set(square_lattice.graph.weighted_edge_list()) size = (3, 4, 5) boundary_condition = ( BoundaryCondition.OPEN, BoundaryCondition.OPEN, BoundaryCondition.OPEN, ) cubic_lattice = HyperCubicLattice(size=size, boundary_condition=boundary_condition) # function for setting the positions def indextocoord_3d(index: int, size: tuple, angle) -> list: z = index // (size[0] * size[1]) a = index % (size[0] * size[1]) y = a // size[0] x = a % size[0] vec_x = np.array([1, 0]) vec_y = np.array([np.cos(angle), np.sin(angle)]) vec_z = np.array([0, 1]) return_coord = x * vec_x + y * vec_y + z * vec_z return return_coord.tolist() pos = dict([(index, indextocoord_3d(index, size, angle=pi / 4)) for index in range(np.prod(size))]) cubic_lattice.draw(style=LatticeDrawStyle(pos=pos)) rows = 4 cols = 3 boundary_condition = BoundaryCondition.OPEN triangular_lattice = TriangularLattice(rows=rows, cols=cols, boundary_condition=boundary_condition) triangular_lattice.draw() rows = 4 cols = 3 boundary_condition = BoundaryCondition.PERIODIC triangular_lattice = TriangularLattice(rows=rows, cols=cols, boundary_condition=boundary_condition) triangular_lattice.draw() graph = rx.PyGraph(multigraph=False) # multigraph shoud be False graph.add_nodes_from(range(6)) weighted_edge_list = [ (0, 1, 1.0 + 1.0j), (0, 2, -1.0), (2, 3, 2.0), (4, 2, -1.0 + 2.0j), (4, 4, 3.0), (2, 5, -1.0), ] graph.add_edges_from(weighted_edge_list) # make a lattice general_lattice = Lattice(graph) set(general_lattice.graph.weighted_edge_list()) general_lattice.draw() general_lattice.draw(self_loop=True) general_lattice.draw(self_loop=True, style=LatticeDrawStyle(with_labels=True)) square_lattice = SquareLattice(rows=5, cols=4, boundary_condition=BoundaryCondition.PERIODIC) t = -1.0 # the interaction parameter v = 0.0 # the onsite potential u = 5.0 # the interaction parameter U fhm = FermiHubbardModel( square_lattice.uniform_parameters( uniform_interaction=t, uniform_onsite_potential=v, ), onsite_interaction=u, ) ham = fhm.second_q_op().simplify() print(ham) graph = rx.PyGraph(multigraph=False) # multiigraph shoud be False graph.add_nodes_from(range(6)) weighted_edge_list = [ (0, 1, 1.0 + 1.0j), (0, 2, -1.0), (2, 3, 2.0), (4, 2, -1.0 + 2.0j), (4, 4, 3.0), (2, 5, -1.0), ] graph.add_edges_from(weighted_edge_list) general_lattice = Lattice(graph) # the lattice whose weights are seen as the interaction matrix. u = 5.0 # the interaction parameter U fhm = FermiHubbardModel(lattice=general_lattice, onsite_interaction=u) ham = fhm.second_q_op().simplify() print(ham) from qiskit_nature.second_q.problems import LatticeModelProblem num_nodes = 4 boundary_condition = BoundaryCondition.OPEN line_lattice = LineLattice(num_nodes=num_nodes, boundary_condition=boundary_condition) fhm = FermiHubbardModel( line_lattice.uniform_parameters( uniform_interaction=t, uniform_onsite_potential=v, ), onsite_interaction=u, ) lmp = LatticeModelProblem(fhm) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.algorithms import GroundStateEigensolver from qiskit_nature.second_q.mappers import JordanWignerMapper numpy_solver = NumPyMinimumEigensolver() qubit_mapper = JordanWignerMapper() calc = GroundStateEigensolver(qubit_mapper, numpy_solver) res = calc.solve(lmp) print(res) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 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 VF2Layout pass""" import io import pickle import unittest from math import pi import ddt import numpy import rustworkx from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit.circuit import ControlFlowOp from qiskit.transpiler import CouplingMap, Target, TranspilerError from qiskit.transpiler.passes.layout.vf2_layout import VF2Layout, VF2LayoutStopReason from qiskit._accelerate.error_map import ErrorMap from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import ( FakeTenerife, FakeVigoV2, FakeRueschlikon, FakeManhattan, FakeYorktown, FakeGuadalupeV2, ) from qiskit.circuit import Measure from qiskit.circuit.library import GraphState, CXGate, XGate, HGate from qiskit.transpiler import PassManager, AnalysisPass from qiskit.transpiler.target import InstructionProperties from qiskit.transpiler.preset_passmanagers.common import generate_embed_passmanager class LayoutTestCase(QiskitTestCase): """VF2Layout assertions""" seed = 42 def assertLayout(self, dag, coupling_map, property_set, strict_direction=False): """Checks if the circuit in dag was a perfect layout in property_set for the given coupling_map""" self.assertEqual(property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.SOLUTION_FOUND) layout = property_set["layout"] edges = coupling_map.graph.edge_list() def run(dag, wire_map): for gate in dag.two_qubit_ops(): if dag.has_calibration_for(gate) or isinstance(gate.op, ControlFlowOp): continue physical_q0 = wire_map[gate.qargs[0]] physical_q1 = wire_map[gate.qargs[1]] if strict_direction: result = (physical_q0, physical_q1) in edges else: result = (physical_q0, physical_q1) in edges or ( physical_q1, physical_q0, ) in edges self.assertTrue(result) for node in dag.op_nodes(ControlFlowOp): for block in node.op.blocks: inner_wire_map = { inner: wire_map[outer] for outer, inner in zip(node.qargs, block.qubits) } run(circuit_to_dag(block), inner_wire_map) run(dag, {bit: layout[bit] for bit in dag.qubits}) @ddt.ddt class TestVF2LayoutSimple(LayoutTestCase): """Tests the VF2Layout pass""" def test_1q_component_influence(self): """Assert that the 1q component of a connected interaction graph is scored correctly.""" target = Target() target.add_instruction( CXGate(), { (0, 1): InstructionProperties(error=0.0), (1, 2): InstructionProperties(error=0.0), (2, 3): InstructionProperties(error=0.0), }, ) target.add_instruction( HGate(), { (0,): InstructionProperties(error=0.0), (1,): InstructionProperties(error=0.0), (2,): InstructionProperties(error=0.0), }, ) target.add_instruction( Measure(), { (0,): InstructionProperties(error=0.1), (1,): InstructionProperties(error=0.1), (2,): InstructionProperties(error=0.9), }, ) qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.cx(1, 0) qc.measure(0, 0) qc.measure(1, 1) vf2_pass = VF2Layout(target=target, seed=self.seed) vf2_pass(qc) layout = vf2_pass.property_set["layout"] self.assertEqual([1, 0], list(layout._p2v.keys())) def test_2q_circuit_2q_coupling(self): """A simple example, without considering the direction 0 - 1 qr1 - qr0 """ cmap = CouplingMap([[0, 1]]) qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 dag = circuit_to_dag(circuit) pass_ = VF2Layout(cmap, strict_direction=False, seed=self.seed, max_trials=1) pass_.run(dag) self.assertLayout(dag, cmap, pass_.property_set) def test_2q_circuit_2q_coupling_sd(self): """A simple example, considering the direction 0 -> 1 qr1 -> qr0 """ cmap = CouplingMap([[0, 1]]) qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 dag = circuit_to_dag(circuit) pass_ = VF2Layout(cmap, strict_direction=True, seed=self.seed, max_trials=1) pass_.run(dag) self.assertLayout(dag, cmap, pass_.property_set, strict_direction=True) @ddt.data(True, False) def test_2q_circuit_simple_control_flow(self, strict_direction): """Test that simple control-flow can be routed on a 2q coupling map.""" cmap = CouplingMap([(0, 1)]) circuit = QuantumCircuit(2) with circuit.for_loop((1,)): circuit.cx(1, 0) dag = circuit_to_dag(circuit) pass_ = VF2Layout(cmap, strict_direction=strict_direction, seed=self.seed, max_trials=1) pass_.run(dag) self.assertLayout(dag, cmap, pass_.property_set, strict_direction=strict_direction) @ddt.data(True, False) def test_2q_circuit_nested_control_flow(self, strict_direction): """Test that simple control-flow can be routed on a 2q coupling map.""" cmap = CouplingMap([(0, 1)]) circuit = QuantumCircuit(2, 1) with circuit.while_loop((circuit.clbits[0], True)): with circuit.if_test((circuit.clbits[0], True)) as else_: circuit.cx(1, 0) with else_: circuit.cx(1, 0) dag = circuit_to_dag(circuit) pass_ = VF2Layout(cmap, strict_direction=strict_direction, seed=self.seed, max_trials=1) pass_.run(dag) self.assertLayout(dag, cmap, pass_.property_set, strict_direction=strict_direction) def test_3q_circuit_3q_coupling_non_induced(self): """A simple example, check for non-induced subgraph 1 qr0 -> qr1 -> qr2 / \ 0 - 2 """ cmap = CouplingMap([[0, 1], [1, 2], [2, 0]]) qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) # qr0-> qr1 circuit.cx(qr[1], qr[2]) # qr1-> qr2 dag = circuit_to_dag(circuit) pass_ = VF2Layout(cmap, seed=-1, max_trials=1) pass_.run(dag) self.assertLayout(dag, cmap, pass_.property_set) def test_3q_circuit_3q_coupling_non_induced_control_flow(self): r"""A simple example, check for non-induced subgraph 1 qr0 -> qr1 -> qr2 / \ 0 - 2 """ cmap = CouplingMap([[0, 1], [1, 2], [2, 0]]) circuit = QuantumCircuit(3, 1) with circuit.for_loop((1,)): circuit.cx(0, 1) # qr0-> qr1 with circuit.if_test((circuit.clbits[0], True)) as else_: pass with else_: with circuit.while_loop((circuit.clbits[0], True)): circuit.cx(1, 2) # qr1-> qr2 dag = circuit_to_dag(circuit) pass_ = VF2Layout(cmap, seed=-1, max_trials=1) pass_.run(dag) self.assertLayout(dag, cmap, pass_.property_set) def test_call_limit(self): """Test that call limit is enforce.""" cmap = CouplingMap([[0, 1], [1, 2], [2, 0]]) qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) # qr0-> qr1 circuit.cx(qr[1], qr[2]) # qr1-> qr2 dag = circuit_to_dag(circuit) pass_ = VF2Layout(cmap, seed=-1, call_limit=1) pass_.run(dag) self.assertEqual( pass_.property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.NO_SOLUTION_FOUND ) def test_coupling_map_and_target(self): """Test that a Target is used instead of a CouplingMap if both are specified.""" cmap = CouplingMap([[0, 1], [1, 2]]) target = Target() target.add_instruction(CXGate(), {(0, 1): None, (1, 2): None, (1, 0): None}) qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) # qr0-> qr1 circuit.cx(qr[1], qr[2]) # qr1-> qr2 circuit.cx(qr[1], qr[0]) # qr1-> qr0 dag = circuit_to_dag(circuit) pass_ = VF2Layout(cmap, seed=-1, max_trials=1, target=target) pass_.run(dag) self.assertLayout(dag, target.build_coupling_map(), pass_.property_set) def test_neither_coupling_map_or_target(self): """Test that we raise if neither a target or coupling map is specified.""" vf2_pass = VF2Layout(seed=123, call_limit=1000, time_limit=20, max_trials=7) circuit = QuantumCircuit(2) dag = circuit_to_dag(circuit) with self.assertRaises(TranspilerError): vf2_pass.run(dag) def test_target_no_error(self): """Test that running vf2layout on a pass against a target with no error rates works.""" n_qubits = 15 target = Target() target.add_instruction(CXGate(), {(i, i + 1): None for i in range(n_qubits - 1)}) vf2_pass = VF2Layout(target=target) circuit = QuantumCircuit(2) circuit.cx(0, 1) dag = circuit_to_dag(circuit) vf2_pass.run(dag) self.assertLayout(dag, target.build_coupling_map(), vf2_pass.property_set) def test_target_some_error(self): """Test that running vf2layout on a pass against a target with some error rates works.""" n_qubits = 15 target = Target() target.add_instruction( XGate(), {(i,): InstructionProperties(error=0.00123) for i in range(n_qubits)} ) target.add_instruction(CXGate(), {(i, i + 1): None for i in range(n_qubits - 1)}) vf2_pass = VF2Layout(target=target) circuit = QuantumCircuit(2) circuit.h(0) circuit.cx(0, 1) dag = circuit_to_dag(circuit) vf2_pass.run(dag) self.assertLayout(dag, target.build_coupling_map(), vf2_pass.property_set) class TestVF2LayoutLattice(LayoutTestCase): """Fit in 25x25 hexagonal lattice coupling map""" cmap25 = CouplingMap.from_hexagonal_lattice(25, 25, bidirectional=False) def graph_state_from_pygraph(self, graph): """Creates a GraphState circuit from a PyGraph""" adjacency_matrix = rustworkx.adjacency_matrix(graph) return GraphState(adjacency_matrix).decompose() def test_hexagonal_lattice_graph_20_in_25(self): """A 20x20 interaction map in 25x25 coupling map""" graph_20_20 = rustworkx.generators.hexagonal_lattice_graph(20, 20) circuit = self.graph_state_from_pygraph(graph_20_20) dag = circuit_to_dag(circuit) pass_ = VF2Layout(self.cmap25, seed=self.seed, max_trials=1) pass_.run(dag) self.assertLayout(dag, self.cmap25, pass_.property_set) def test_hexagonal_lattice_graph_9_in_25(self): """A 9x9 interaction map in 25x25 coupling map""" graph_9_9 = rustworkx.generators.hexagonal_lattice_graph(9, 9) circuit = self.graph_state_from_pygraph(graph_9_9) dag = circuit_to_dag(circuit) pass_ = VF2Layout(self.cmap25, seed=self.seed, max_trials=1) pass_.run(dag) self.assertLayout(dag, self.cmap25, pass_.property_set) class TestVF2LayoutBackend(LayoutTestCase): """Tests VF2Layout against backends""" def test_5q_circuit_Rueschlikon_no_solution(self): """5 qubits in Rueschlikon, no solution q0[1] ↖ ↗ q0[2] q0[0] q0[3] ↙ ↘ q0[4] """ cmap16 = FakeRueschlikon().configuration().coupling_map qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[2]) circuit.cx(qr[0], qr[3]) circuit.cx(qr[0], qr[4]) dag = circuit_to_dag(circuit) pass_ = VF2Layout(CouplingMap(cmap16), seed=self.seed, max_trials=1) pass_.run(dag) layout = pass_.property_set["layout"] self.assertIsNone(layout) self.assertEqual( pass_.property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.NO_SOLUTION_FOUND ) def test_9q_circuit_Rueschlikon_sd(self): """9 qubits in Rueschlikon, considering the direction 1 → 2 → 3 → 4 ← 5 ← 6 → 7 ← 8 ↓ ↑ ↓ ↓ ↑ ↓ ↓ ↑ 0 ← 15 → 14 ← 13 ← 12 → 11 → 10 ← 9 """ cmap16 = CouplingMap(FakeRueschlikon().configuration().coupling_map) qr0 = QuantumRegister(4, "q0") qr1 = QuantumRegister(5, "q1") circuit = QuantumCircuit(qr0, qr1) circuit.cx(qr0[1], qr0[2]) # q0[1] -> q0[2] circuit.cx(qr0[0], qr1[3]) # q0[0] -> q1[3] circuit.cx(qr1[4], qr0[2]) # q1[4] -> q0[2] dag = circuit_to_dag(circuit) pass_ = VF2Layout(cmap16, strict_direction=True, seed=self.seed, max_trials=1) pass_.run(dag) self.assertLayout(dag, cmap16, pass_.property_set) def test_4q_circuit_Tenerife_loose_nodes(self): """4 qubits in Tenerife, with loose nodes 1 ↙ ↑ 0 ← 2 ← 3 ↑ ↙ 4 """ cmap5 = CouplingMap(FakeTenerife().configuration().coupling_map) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 circuit.cx(qr[0], qr[2]) # qr0 -> qr2 dag = circuit_to_dag(circuit) pass_ = VF2Layout(cmap5, seed=self.seed, max_trials=1) pass_.run(dag) self.assertLayout(dag, cmap5, pass_.property_set) def test_3q_circuit_Tenerife_sd(self): """3 qubits in Tenerife, considering the direction 1 1 ↙ ↑ ↙ ↑ 0 ← 2 ← 3 0 ← qr2 ← qr1 ↑ ↙ ↑ ↙ 4 qr0 """ cmap5 = CouplingMap(FakeTenerife().configuration().coupling_map) qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 circuit.cx(qr[0], qr[2]) # qr0 -> qr2 circuit.cx(qr[1], qr[2]) # qr1 -> qr2 dag = circuit_to_dag(circuit) pass_ = VF2Layout(cmap5, strict_direction=True, seed=self.seed, max_trials=1) pass_.run(dag) self.assertLayout(dag, cmap5, pass_.property_set, strict_direction=True) def test_9q_circuit_Rueschlikon(self): """9 qubits in Rueschlikon, without considering the direction 1 → 2 → 3 → 4 ← 5 ← 6 → 7 ← 8 ↓ ↑ ↓ ↓ ↑ ↓ ↓ ↑ 0 ← 15 → 14 ← 13 ← 12 → 11 → 10 ← 9 1 -- q1_0 - q1_1 - 4 --- 5 -- 6 - 7 --- q0_1 | | | | | | | | q1_2 - q1_3 - q0_0 - 13 - q0_3 - 11 - q1_4 - q0_2 """ cmap16 = CouplingMap(FakeRueschlikon().configuration().coupling_map) qr0 = QuantumRegister(4, "q0") qr1 = QuantumRegister(5, "q1") circuit = QuantumCircuit(qr0, qr1) circuit.cx(qr0[1], qr0[2]) # q0[1] -> q0[2] circuit.cx(qr0[0], qr1[3]) # q0[0] -> q1[3] circuit.cx(qr1[4], qr0[2]) # q1[4] -> q0[2] dag = circuit_to_dag(circuit) pass_ = VF2Layout(cmap16, strict_direction=False, seed=self.seed, max_trials=1) pass_.run(dag) self.assertLayout(dag, cmap16, pass_.property_set) def test_3q_circuit_Tenerife(self): """3 qubits in Tenerife, without considering the direction 1 1 ↙ ↑ / | 0 ← 2 ← 3 0 - qr1 - qr2 ↑ ↙ | / 4 qr0 """ cmap5 = CouplingMap(FakeTenerife().configuration().coupling_map) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 circuit.cx(qr[0], qr[2]) # qr0 -> qr2 circuit.cx(qr[1], qr[2]) # qr1 -> qr2 dag = circuit_to_dag(circuit) pass_ = VF2Layout(cmap5, strict_direction=False, seed=self.seed, max_trials=1) pass_.run(dag) self.assertLayout(dag, cmap5, pass_.property_set) def test_3q_circuit_vigo_with_custom_scores(self): """Test custom ErrorMap from analysis pass are used for scoring.""" backend = FakeVigoV2() target = backend.target class FakeScore(AnalysisPass): """Fake analysis pass with custom scoring.""" def run(self, dag): error_map = ErrorMap(9) error_map.add_error((0, 0), 0.1) error_map.add_error((0, 1), 0.5) error_map.add_error((1, 1), 0.2) error_map.add_error((1, 2), 0.8) error_map.add_error((1, 3), 0.75) error_map.add_error((2, 2), 0.123) error_map.add_error((3, 3), 0.333) error_map.add_error((3, 4), 0.12345423) error_map.add_error((4, 4), 0.2222) self.property_set["vf2_avg_error_map"] = error_map qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 circuit.cx(qr[0], qr[2]) # qr0 -> qr2 vf2_pass = VF2Layout(target=target, seed=1234568942) property_set = {} vf2_pass(circuit, property_set) pm = PassManager([FakeScore(), VF2Layout(target=target, seed=1234568942)]) pm.run(circuit) # Assert layout is different from backend properties self.assertNotEqual(property_set["layout"], pm.property_set["layout"]) self.assertLayout(circuit_to_dag(circuit), backend.coupling_map, pm.property_set) def test_error_map_pickle(self): """Test that the `ErrorMap` Rust structure correctly pickles and depickles.""" errors = {(0, 1): 0.2, (1, 0): 0.2, (0, 0): 0.05, (1, 1): 0.02} error_map = ErrorMap.from_dict(errors) with io.BytesIO() as fptr: pickle.dump(error_map, fptr) fptr.seek(0) loaded = pickle.load(fptr) self.assertEqual(len(loaded), len(errors)) self.assertEqual({k: loaded[k] for k in errors}, errors) def test_perfect_fit_Manhattan(self): """A circuit that fits perfectly in Manhattan (65 qubits) See https://github.com/Qiskit/qiskit-terra/issues/5694""" manhattan_cm = FakeManhattan().configuration().coupling_map cmap65 = CouplingMap(manhattan_cm) rows = [x[0] for x in manhattan_cm] cols = [x[1] for x in manhattan_cm] adj_matrix = numpy.zeros((65, 65)) adj_matrix[rows, cols] = 1 circuit = GraphState(adj_matrix).decompose() circuit.measure_all() dag = circuit_to_dag(circuit) pass_ = VF2Layout(cmap65, seed=self.seed, max_trials=1) pass_.run(dag) self.assertLayout(dag, cmap65, pass_.property_set) class TestVF2LayoutOther(LayoutTestCase): """Other VF2Layout tests""" def test_seed(self): """Different seeds yield different results""" seed_1 = 42 seed_2 = 45 cmap5 = FakeTenerife().configuration().coupling_map qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 circuit.cx(qr[0], qr[2]) # qr0 -> qr2 circuit.cx(qr[1], qr[2]) # qr1 -> qr2 dag = circuit_to_dag(circuit) pass_1 = VF2Layout(CouplingMap(cmap5), seed=seed_1, max_trials=1) pass_1.run(dag) layout_1 = pass_1.property_set["layout"] self.assertEqual( pass_1.property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.SOLUTION_FOUND ) pass_2 = VF2Layout(CouplingMap(cmap5), seed=seed_2, max_trials=1) pass_2.run(dag) layout_2 = pass_2.property_set["layout"] self.assertEqual( pass_2.property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.SOLUTION_FOUND ) self.assertNotEqual(layout_1, layout_2) def test_3_q_gate(self): """The pass does not handle gates with more than 2 qubits""" seed_1 = 42 cmap5 = FakeTenerife().configuration().coupling_map qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.ccx(qr[1], qr[0], qr[2]) dag = circuit_to_dag(circuit) pass_1 = VF2Layout(CouplingMap(cmap5), seed=seed_1, max_trials=1) pass_1.run(dag) self.assertEqual( pass_1.property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.MORE_THAN_2Q ) class TestMultipleTrials(QiskitTestCase): """Test the passes behavior with >1 trial.""" def test_no_properties(self): """Test it finds the lowest degree perfect layout with no properties.""" vf2_pass = VF2Layout( CouplingMap( [ (0, 1), (0, 2), (0, 3), (1, 0), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3), (3, 0), (3, 1), (3, 2), (4, 0), (0, 4), (5, 1), (1, 5), ] ) ) qr = QuantumRegister(2) qc = QuantumCircuit(qr) qc.x(qr) qc.measure_all() property_set = {} vf2_pass(qc, property_set) self.assertEqual(set(property_set["layout"].get_physical_bits()), {4, 5}) def test_with_properties(self): """Test it finds the least noise perfect layout with no properties.""" backend = FakeYorktown() qr = QuantumRegister(2) qc = QuantumCircuit(qr) qc.x(qr) qc.measure_all() cmap = CouplingMap(backend.configuration().coupling_map) properties = backend.properties() vf2_pass = VF2Layout(cmap, properties=properties) property_set = {} vf2_pass(qc, property_set) self.assertEqual(set(property_set["layout"].get_physical_bits()), {1, 3}) def test_max_trials_exceeded(self): """Test it exits when max_trials is reached.""" backend = FakeYorktown() qr = QuantumRegister(2) qc = QuantumCircuit(qr) qc.x(qr) qc.cx(0, 1) qc.measure_all() cmap = CouplingMap(backend.configuration().coupling_map) properties = backend.properties() vf2_pass = VF2Layout(cmap, properties=properties, seed=-1, max_trials=1) property_set = {} with self.assertLogs("qiskit.transpiler.passes.layout.vf2_layout", level="DEBUG") as cm: vf2_pass(qc, property_set) self.assertIn( "DEBUG:qiskit.transpiler.passes.layout.vf2_layout:Trial 1 is >= configured max trials 1", cm.output, ) self.assertEqual(set(property_set["layout"].get_physical_bits()), {2, 0}) def test_time_limit_exceeded(self): """Test the pass stops after time_limit is reached.""" backend = FakeYorktown() qr = QuantumRegister(2) qc = QuantumCircuit(qr) qc.x(qr) qc.cx(0, 1) qc.measure_all() cmap = CouplingMap(backend.configuration().coupling_map) properties = backend.properties() vf2_pass = VF2Layout(cmap, properties=properties, seed=-1, time_limit=0.0) property_set = {} with self.assertLogs("qiskit.transpiler.passes.layout.vf2_layout", level="DEBUG") as cm: vf2_pass(qc, property_set) for output in cm.output: if output.startswith( "DEBUG:qiskit.transpiler.passes.layout.vf2_layout:VF2Layout has taken" ) and output.endswith("which exceeds configured max time: 0.0"): break else: self.fail("No failure debug log message found") self.assertEqual(set(property_set["layout"].get_physical_bits()), {2, 0}) def test_reasonable_limits_for_simple_layouts(self): """Test that the default trials is set to a reasonable number.""" backend = FakeManhattan() qc = QuantumCircuit(5) qc.cx(2, 3) qc.cx(0, 1) cmap = CouplingMap(backend.configuration().coupling_map) properties = backend.properties() # Run without any limits set vf2_pass = VF2Layout(cmap, properties=properties, seed=42) property_set = {} with self.assertLogs("qiskit.transpiler.passes.layout.vf2_layout", level="DEBUG") as cm: vf2_pass(qc, property_set) self.assertIn( "DEBUG:qiskit.transpiler.passes.layout.vf2_layout:Trial 159 is >= configured max trials 159", cm.output, ) self.assertEqual(set(property_set["layout"].get_physical_bits()), {49, 40, 33, 0, 34}) def test_no_limits_with_negative(self): """Test that we're not enforcing a trial limit if set to negative.""" backend = FakeYorktown() qc = QuantumCircuit(3) qc.h(0) cmap = CouplingMap(backend.configuration().coupling_map) properties = backend.properties() # Run without any limits set vf2_pass = VF2Layout( cmap, properties=properties, seed=42, max_trials=0, ) property_set = {} with self.assertLogs("qiskit.transpiler.passes.layout.vf2_layout", level="DEBUG") as cm: vf2_pass(qc, property_set) for output in cm.output: self.assertNotIn("is >= configured max trials", output) self.assertEqual(set(property_set["layout"].get_physical_bits()), {3, 1, 0}) def test_qregs_valid_layout_output(self): """Test that vf2 layout doesn't add extra qubits. Reproduce from https://github.com/Qiskit/qiskit-terra/issues/8667 """ backend = FakeGuadalupeV2() qr = QuantumRegister(16, name="qr") cr = ClassicalRegister(5) qc = QuantumCircuit(qr, cr) qc.rz(pi / 2, qr[0]) qc.sx(qr[0]) qc.sx(qr[1]) qc.rz(-pi / 4, qr[1]) qc.sx(qr[1]) qc.rz(pi / 2, qr[1]) qc.rz(2.8272143, qr[0]) qc.rz(0.43324854, qr[1]) qc.sx(qr[1]) qc.rz(-0.95531662, qr[7]) qc.sx(qr[7]) qc.rz(3 * pi / 4, qr[7]) qc.barrier([qr[1], qr[10], qr[4], qr[0], qr[7]]) vf2_pass = VF2Layout( seed=12345, target=backend.target, ) vf2_pass(qc) self.assertEqual(len(vf2_pass.property_set["layout"].get_physical_bits()), 16) self.assertEqual(len(vf2_pass.property_set["layout"].get_virtual_bits()), 16) pm = PassManager( [ VF2Layout( seed=12345, target=backend.target, ) ] ) pm += generate_embed_passmanager(backend.coupling_map) res = pm.run(qc) self.assertEqual(res.num_qubits, 16) if __name__ == "__main__": unittest.main()
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. """Transpiler pulse gate pass testing.""" import ddt from qiskit import pulse, circuit, transpile from qiskit.providers.fake_provider import FakeAthens, FakeAthensV2 from qiskit.quantum_info.random import random_unitary from qiskit.test import QiskitTestCase @ddt.ddt class TestPulseGate(QiskitTestCase): """Integration test of pulse gate pass with custom backend.""" def setUp(self): super().setUp() self.sched_param = circuit.Parameter("P0") with pulse.build(name="sx_q0") as custom_sx_q0: pulse.play(pulse.Constant(100, 0.1), pulse.DriveChannel(0)) self.custom_sx_q0 = custom_sx_q0 with pulse.build(name="sx_q1") as custom_sx_q1: pulse.play(pulse.Constant(100, 0.2), pulse.DriveChannel(1)) self.custom_sx_q1 = custom_sx_q1 with pulse.build(name="cx_q01") as custom_cx_q01: pulse.play(pulse.Constant(100, 0.4), pulse.ControlChannel(0)) self.custom_cx_q01 = custom_cx_q01 with pulse.build(name="my_gate_q0") as my_gate_q0: pulse.shift_phase(self.sched_param, pulse.DriveChannel(0)) pulse.play(pulse.Constant(120, 0.1), pulse.DriveChannel(0)) self.my_gate_q0 = my_gate_q0 with pulse.build(name="my_gate_q1") as my_gate_q1: pulse.shift_phase(self.sched_param, pulse.DriveChannel(1)) pulse.play(pulse.Constant(120, 0.2), pulse.DriveChannel(1)) self.my_gate_q1 = my_gate_q1 def test_transpile_with_bare_backend(self): """Test transpile without custom calibrations.""" backend = FakeAthens() qc = circuit.QuantumCircuit(2) qc.sx(0) qc.x(0) qc.rz(0, 0) qc.sx(1) qc.measure_all() transpiled_qc = transpile(qc, backend, initial_layout=[0, 1]) ref_calibration = {} self.assertDictEqual(transpiled_qc.calibrations, ref_calibration) def test_transpile_with_backend_target(self): """Test transpile without custom calibrations from target.""" backend = FakeAthensV2() target = backend.target qc = circuit.QuantumCircuit(2) qc.sx(0) qc.x(0) qc.rz(0, 0) qc.sx(1) qc.measure_all() transpiled_qc = transpile(qc, initial_layout=[0, 1], target=target) ref_calibration = {} self.assertDictEqual(transpiled_qc.calibrations, ref_calibration) def test_transpile_with_custom_basis_gate(self): """Test transpile with custom calibrations.""" backend = FakeAthens() backend.defaults().instruction_schedule_map.add("sx", (0,), self.custom_sx_q0) backend.defaults().instruction_schedule_map.add("sx", (1,), self.custom_sx_q1) qc = circuit.QuantumCircuit(2) qc.sx(0) qc.x(0) qc.rz(0, 0) qc.sx(1) qc.measure_all() transpiled_qc = transpile(qc, backend, initial_layout=[0, 1]) ref_calibration = { "sx": { ((0,), ()): self.custom_sx_q0, ((1,), ()): self.custom_sx_q1, } } self.assertDictEqual(transpiled_qc.calibrations, ref_calibration) def test_transpile_with_custom_basis_gate_in_target(self): """Test transpile with custom calibrations.""" backend = FakeAthensV2() target = backend.target target["sx"][(0,)].calibration = self.custom_sx_q0 target["sx"][(1,)].calibration = self.custom_sx_q1 qc = circuit.QuantumCircuit(2) qc.sx(0) qc.x(0) qc.rz(0, 0) qc.sx(1) qc.measure_all() transpiled_qc = transpile(qc, initial_layout=[0, 1], target=target) ref_calibration = { "sx": { ((0,), ()): self.custom_sx_q0, ((1,), ()): self.custom_sx_q1, } } self.assertDictEqual(transpiled_qc.calibrations, ref_calibration) def test_transpile_with_instmap(self): """Test providing instruction schedule map.""" instmap = FakeAthens().defaults().instruction_schedule_map instmap.add("sx", (0,), self.custom_sx_q0) instmap.add("sx", (1,), self.custom_sx_q1) # Inst map is renewed backend = FakeAthens() qc = circuit.QuantumCircuit(2) qc.sx(0) qc.x(0) qc.rz(0, 0) qc.sx(1) qc.measure_all() transpiled_qc = transpile(qc, backend, inst_map=instmap, initial_layout=[0, 1]) ref_calibration = { "sx": { ((0,), ()): self.custom_sx_q0, ((1,), ()): self.custom_sx_q1, } } self.assertDictEqual(transpiled_qc.calibrations, ref_calibration) def test_transpile_with_custom_gate(self): """Test providing non-basis gate.""" backend = FakeAthens() backend.defaults().instruction_schedule_map.add( "my_gate", (0,), self.my_gate_q0, arguments=["P0"] ) backend.defaults().instruction_schedule_map.add( "my_gate", (1,), self.my_gate_q1, arguments=["P0"] ) qc = circuit.QuantumCircuit(2) qc.append(circuit.Gate("my_gate", 1, [1.0]), [0]) qc.append(circuit.Gate("my_gate", 1, [2.0]), [1]) transpiled_qc = transpile(qc, backend, basis_gates=["my_gate"], initial_layout=[0, 1]) my_gate_q0_1_0 = self.my_gate_q0.assign_parameters({self.sched_param: 1.0}, inplace=False) my_gate_q1_2_0 = self.my_gate_q1.assign_parameters({self.sched_param: 2.0}, inplace=False) ref_calibration = { "my_gate": { ((0,), (1.0,)): my_gate_q0_1_0, ((1,), (2.0,)): my_gate_q1_2_0, } } self.assertDictEqual(transpiled_qc.calibrations, ref_calibration) def test_transpile_with_parameterized_custom_gate(self): """Test providing non-basis gate, which is kept parameterized throughout transpile.""" backend = FakeAthens() backend.defaults().instruction_schedule_map.add( "my_gate", (0,), self.my_gate_q0, arguments=["P0"] ) param = circuit.Parameter("new_P0") qc = circuit.QuantumCircuit(1) qc.append(circuit.Gate("my_gate", 1, [param]), [0]) transpiled_qc = transpile(qc, backend, basis_gates=["my_gate"], initial_layout=[0]) my_gate_q0_p = self.my_gate_q0.assign_parameters({self.sched_param: param}, inplace=False) ref_calibration = { "my_gate": { ((0,), (param,)): my_gate_q0_p, } } self.assertDictEqual(transpiled_qc.calibrations, ref_calibration) def test_transpile_with_multiple_circuits(self): """Test transpile with multiple circuits with custom gate.""" backend = FakeAthens() backend.defaults().instruction_schedule_map.add( "my_gate", (0,), self.my_gate_q0, arguments=["P0"] ) params = [0.0, 1.0, 2.0, 3.0] circs = [] for param in params: qc = circuit.QuantumCircuit(1) qc.append(circuit.Gate("my_gate", 1, [param]), [0]) circs.append(qc) transpiled_qcs = transpile(circs, backend, basis_gates=["my_gate"], initial_layout=[0]) for param, transpiled_qc in zip(params, transpiled_qcs): my_gate_q0_x = self.my_gate_q0.assign_parameters( {self.sched_param: param}, inplace=False ) ref_calibration = {"my_gate": {((0,), (param,)): my_gate_q0_x}} self.assertDictEqual(transpiled_qc.calibrations, ref_calibration) def test_multiple_instructions_with_different_parameters(self): """Test adding many instruction with different parameter binding.""" backend = FakeAthens() backend.defaults().instruction_schedule_map.add( "my_gate", (0,), self.my_gate_q0, arguments=["P0"] ) qc = circuit.QuantumCircuit(1) qc.append(circuit.Gate("my_gate", 1, [1.0]), [0]) qc.append(circuit.Gate("my_gate", 1, [2.0]), [0]) qc.append(circuit.Gate("my_gate", 1, [3.0]), [0]) transpiled_qc = transpile(qc, backend, basis_gates=["my_gate"], initial_layout=[0]) my_gate_q0_1_0 = self.my_gate_q0.assign_parameters({self.sched_param: 1.0}, inplace=False) my_gate_q0_2_0 = self.my_gate_q0.assign_parameters({self.sched_param: 2.0}, inplace=False) my_gate_q0_3_0 = self.my_gate_q0.assign_parameters({self.sched_param: 3.0}, inplace=False) ref_calibration = { "my_gate": { ((0,), (1.0,)): my_gate_q0_1_0, ((0,), (2.0,)): my_gate_q0_2_0, ((0,), (3.0,)): my_gate_q0_3_0, } } self.assertDictEqual(transpiled_qc.calibrations, ref_calibration) def test_transpile_with_different_qubit(self): """Test transpile with qubit without custom gate.""" backend = FakeAthens() backend.defaults().instruction_schedule_map.add("sx", (0,), self.custom_sx_q0) qc = circuit.QuantumCircuit(1) qc.sx(0) qc.measure_all() transpiled_qc = transpile(qc, backend, initial_layout=[3]) self.assertDictEqual(transpiled_qc.calibrations, {}) @ddt.data(0, 1, 2, 3) def test_transpile_with_both_instmap_and_empty_target(self, opt_level): """Test when instmap and target are both provided and only instmap contains custom schedules. Test case from Qiskit/qiskit-terra/#9489 """ instmap = FakeAthens().defaults().instruction_schedule_map instmap.add("sx", (0,), self.custom_sx_q0) instmap.add("sx", (1,), self.custom_sx_q1) instmap.add("cx", (0, 1), self.custom_cx_q01) # This doesn't have custom schedule definition target = FakeAthensV2().target qc = circuit.QuantumCircuit(2) qc.append(random_unitary(4, seed=123), [0, 1]) qc.measure_all() transpiled_qc = transpile( qc, optimization_level=opt_level, basis_gates=["sx", "rz", "x", "cx"], inst_map=instmap, target=target, initial_layout=[0, 1], ) ref_calibration = { "sx": { ((0,), ()): self.custom_sx_q0, ((1,), ()): self.custom_sx_q1, }, "cx": { ((0, 1), ()): self.custom_cx_q01, }, } self.assertDictEqual(transpiled_qc.calibrations, ref_calibration) @ddt.data(0, 1, 2, 3) def test_transpile_with_instmap_with_v2backend(self, opt_level): """Test when instmap is provided with V2 backend. Test case from Qiskit/qiskit-terra/#9489 """ instmap = FakeAthens().defaults().instruction_schedule_map instmap.add("sx", (0,), self.custom_sx_q0) instmap.add("sx", (1,), self.custom_sx_q1) instmap.add("cx", (0, 1), self.custom_cx_q01) qc = circuit.QuantumCircuit(2) qc.append(random_unitary(4, seed=123), [0, 1]) qc.measure_all() transpiled_qc = transpile( qc, FakeAthensV2(), optimization_level=opt_level, inst_map=instmap, initial_layout=[0, 1], ) ref_calibration = { "sx": { ((0,), ()): self.custom_sx_q0, ((1,), ()): self.custom_sx_q1, }, "cx": { ((0, 1), ()): self.custom_cx_q01, }, } self.assertDictEqual(transpiled_qc.calibrations, ref_calibration) @ddt.data(0, 1, 2, 3) def test_transpile_with_instmap_with_v2backend_with_custom_gate(self, opt_level): """Test when instmap is provided with V2 backend. In this test case, instmap contains a custom gate which doesn't belong to Qiskit standard gate. Target must define a custom gete on the fly to reflect user-provided instmap. Test case from Qiskit/qiskit-terra/#9489 """ with pulse.build(name="custom") as rabi12: pulse.play(pulse.Constant(100, 0.4), pulse.DriveChannel(0)) instmap = FakeAthens().defaults().instruction_schedule_map instmap.add("rabi12", (0,), rabi12) gate = circuit.Gate("rabi12", 1, []) qc = circuit.QuantumCircuit(1) qc.append(gate, [0]) qc.measure_all() transpiled_qc = transpile( qc, FakeAthensV2(), optimization_level=opt_level, inst_map=instmap, initial_layout=[0], ) ref_calibration = { "rabi12": { ((0,), ()): rabi12, } } self.assertDictEqual(transpiled_qc.calibrations, ref_calibration) def test_transpile_with_instmap_not_mutate_backend(self): """Do not override default backend target when transpile with inst map. Providing an instmap for the transpile arguments may override target, which might be pulled from the provided backend instance. This should not override the source object since the same backend may be used for future transpile without intention of instruction overriding. """ backend = FakeAthensV2() original_sx0 = backend.target["sx"][(0,)].calibration instmap = FakeAthens().defaults().instruction_schedule_map instmap.add("sx", (0,), self.custom_sx_q0) qc = circuit.QuantumCircuit(1) qc.sx(0) qc.measure_all() transpiled_qc = transpile( qc, FakeAthensV2(), inst_map=instmap, initial_layout=[0], ) self.assertTrue(transpiled_qc.has_calibration_for(transpiled_qc.data[0])) self.assertEqual( backend.target["sx"][(0,)].calibration, original_sx0, )
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(3, 'q') anc = QuantumRegister(1, 'ancilla') cr = ClassicalRegister(3, 'c') qc = QuantumCircuit(qr, anc, cr) qc.x(anc[0]) qc.h(anc[0]) qc.h(qr[0:3]) qc.cx(qr[0:3], anc[0]) qc.h(qr[0:3]) qc.barrier(qr) qc.measure(qr, cr) qc.draw('mpl')
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 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. from qiskit import QuantumCircuit from qiskit.transpiler import PassManager from qiskit.transpiler.passes import CommutationAnalysis, CommutativeCancellation circuit = QuantumCircuit(5) # Quantum Instantaneous Polynomial Time example circuit.cx(0, 1) circuit.cx(2, 1) circuit.cx(4, 3) circuit.cx(2, 3) circuit.z(0) circuit.z(4) circuit.cx(0, 1) circuit.cx(2, 1) circuit.cx(4, 3) circuit.cx(2, 3) circuit.cx(3, 2) print(circuit) pm = PassManager() pm.append([CommutationAnalysis(), CommutativeCancellation()]) new_circuit = pm.run(circuit) print(new_circuit)
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
PabloMartinezAngerosa
from tsp_qaoa import test_solution from qiskit.visualization import plot_histogram import networkx as nx import numpy as np import json import csv # Array of JSON Objects header = ['instance','p','distance', 'mean'] length_p = 3 length_instances = 2 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 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["mean"]) convergence_min = UNIFORM_CONVERGENCE_SAMPLE[0] UNIFORM_CONVERGENCE_P.append({ "mean":convergence_min["mean"], "probabilities": convergence_min["probabilities"] }) 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(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])
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.second_q.drivers import GaussianForcesDriver # if you ran Gaussian elsewhere and already have the output file driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") # if you want to run the Gaussian job from Qiskit # driver = GaussianForcesDriver( # ['#p B3LYP/6-31g Freq=(Anharm) Int=Ultrafine SCF=VeryTight', # '', # 'CO2 geometry optimization B3LYP/6-31g', # '', # '0 1', # 'C -0.848629 2.067624 0.160992', # 'O 0.098816 2.655801 -0.159738', # 'O -1.796073 1.479446 0.481721', # '', # '' from qiskit_nature.second_q.problems import HarmonicBasis basis = HarmonicBasis([2, 2, 2, 2]) from qiskit_nature.second_q.problems import VibrationalStructureProblem from qiskit_nature.second_q.mappers import DirectMapper vibrational_problem = driver.run(basis=basis) vibrational_problem.hamiltonian.truncation_order = 2 main_op, aux_ops = vibrational_problem.second_q_ops() print(main_op) qubit_mapper = DirectMapper() qubit_op = qubit_mapper.map(main_op) print(qubit_op) basis = HarmonicBasis([3, 3, 3, 3]) vibrational_problem = driver.run(basis=basis) vibrational_problem.hamiltonian.truncation_order = 2 main_op, aux_ops = vibrational_problem.second_q_ops() qubit_mapper = DirectMapper() qubit_op = qubit_mapper.map(main_op) print(qubit_op) # for simplicity, we will use the smaller basis again vibrational_problem = driver.run(basis=HarmonicBasis([2, 2, 2, 2])) vibrational_problem.hamiltonian.truncation_order = 2 from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.algorithms import GroundStateEigensolver solver = GroundStateEigensolver( qubit_mapper, NumPyMinimumEigensolver(filter_criterion=vibrational_problem.get_default_filter_criterion()), ) result = solver.solve(vibrational_problem) print(result) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Qiskit/feedback
Qiskit
# a T1 circuit from qiskit.circuit import QuantumCircuit qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(10, 0, unit="us") qc.measure(0, 0) qc.draw(output="mpl") from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main') device_backend = provider.get_backend('ibmq_armonk') device_backend from qiskit import transpile from qiskit.providers.aer import AerSimulator from qiskit.providers.aer.noise import NoiseModel from qiskit_experiments.library import T1 as T1Experiment print(f"(Backend: {device_backend.name()}, Qubit: 0)") print(f"Reported T1={device_backend.properties().t1(0) * 1e+3:.3f}[ms]") t1exp = T1Experiment(0, delays=list(range(1, 400, 10)), unit="us") t1exp.circuits()[0].draw(output="mpl") # the first T1 circuit t1exp.circuits()[1].draw(output="mpl") # the second T1 circuit t1exp.circuits()[-1].draw(output="mpl") # the last T1 circuit old_noise_model = NoiseModel.from_backend(device_backend) old_noise_model._custom_noise_passes = [] old_sim = AerSimulator.from_backend(device_backend, noise_model=old_noise_model) t1exp.set_transpile_options(scheduling_method="alap") exp_data = t1exp.run(old_sim, seed_simulator=123).block_for_results() result = exp_data.analysis_results()[0] print(f"Ref: Simulated T1 with old noise model={result.value}") display(exp_data.figure(0)) new_sim = AerSimulator.from_backend(device_backend) # call NoiseModel.from_backend() behind the scene t1exp.set_transpile_options(scheduling_method="alap") exp_data = t1exp.run(new_sim, seed_simulator=123).block_for_results() result = exp_data.analysis_results()[0] print(f"Simulated T1={result.value}") print(f"Ref: Reported T1={device_backend.properties().t1(0) * 1e+3:.3f}[ms]") display(exp_data.figure(0)) # original circuit circ = t1exp.circuits()[1] circ.draw(output="mpl") # transpiled circuit (scheduled circuit) transpiled_circ = transpile(circ, device_backend, scheduling_method="alap") transpiled_circ.draw(output="mpl") # noisy circuit noise_model = NoiseModel.from_backend(device_backend) noisy_circ = noise_model._pass_manager().run(transpiled_circ) # within assembler noisy_circ.draw(output="mpl") noise_model = NoiseModel.from_backend(device_backend) nmp = noise_model._pass_manager() print(nmp.passes())
https://github.com/quantum-tokyo/qiskit-handson
quantum-tokyo
# Qiskitライブラリーを導入 from qiskit import * # 描画のためのライブラリーを導入 import matplotlib.pyplot as plt %matplotlib inline # Qiskitバージョンの確認 qiskit.__qiskit_version__ # 2量子ビット回路を用意 q1 = QuantumCircuit(2) # 回路を描画 q1.draw(output="mpl") # q0=0, q1=1の場合 q1.x(1) # q1を1にします。 q1.cx(0,1) # CNOTゲートの制御ゲートをq0、目標ゲートをq1にセットします。 # 回路を描画 q1.draw(output="mpl") ## First, simulate the circuit ## 状態ベクトルシミュレーターの実行 vector_sim = Aer.get_backend('statevector_simulator') job = execute(q1, vector_sim ) result = job.result().get_statevector(q1, decimals=3) print(result) # 2量子ビット回路を用意 q2 = QuantumCircuit(2) # q0=1, q1=1の場合 q2.x(0) # q0を1にします。 q2.x(1) # q1を1にします。 q2.cx(0,1) # CNOTゲートの制御ゲートをq0、目標ゲートをq1にセットします。 # 回路を描画 q2.draw(output="mpl") ## First, simulate the circuit ## 状態ベクトルシミュレーターの実行 vector_sim = Aer.get_backend('statevector_simulator') job = execute(q2, vector_sim ) result = job.result().get_statevector(q2, decimals=3) print(result)
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. """ Example showing how to draw a quantum circuit using Qiskit. """ from qiskit import QuantumCircuit def build_bell_circuit(): """Returns a circuit putting 2 qubits in the Bell state.""" qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) return qc # Create the circuit bell_circuit = build_bell_circuit() # Use the internal .draw() to print the circuit print(bell_circuit)
https://github.com/KathrinKoenig/QuantumTopologicalDataAnalysis
KathrinKoenig
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 24 11:04:02 2021 @author: Eric Brunner, Kathrin König, Andreas Woitzik """ import itertools as it import numpy as np import gudhi as gd from scipy.sparse import csr_matrix from scipy.linalg import expm from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import Aer from qiskit import execute from qiskit.extensions import UnitaryGate def vec_to_state(vec): '''converts vec to state''' n_vertices = int(np.log2(len(vec))) basis_list = list(it.product(range(2), repeat=n_vertices)) indices = np.nonzero(vec)[0] return {basis_list[i]: vec[i] for i in indices} def state_to_vec(state): '''state is a list of state''' n_vertices = len(state[0]) basis_list = list(it.product(range(2), repeat=n_vertices)) basis_dict = {basis_list[i]: i for i in range(2**n_vertices)} vec = np.zeros(2**n_vertices) for stat in state: vec[basis_dict[stat]] = 1 return vec def boundary_operator(x_tuple): '''calculates the boundary of a simplex desribed by x_tuple''' x_np = np.array(x_tuple) indices = np.nonzero(x_np)[0] dictionary = {} k = len(indices) for i in range(k): helper = x_np.copy() helper[indices[k-1-i]] = 0.0 dictionary[tuple(helper)] = (-1.)**(i) return dictionary def boundary_operator_dict(n_vertices): ''' returns the boundary operator on n vertices as a dictionary ''' dictionary = {} dictionary[ ( tuple([0]*n_vertices), tuple([0]*n_vertices) ) ] = 0 for bound in it.product(range(2), repeat=n_vertices): helper = boundary_operator(bound) for key in helper: dictionary[(tuple(bound), key)] = helper[key] return dictionary def boundary_operator_dict_k(n_vertices, k): ''' returns the boundary operator of order k on n vertices as a dictionary ''' dictionary = {} dictionary[ ( tuple([0]*n_vertices), tuple([0]*n_vertices) ) ] = 0 for bound in it.product(range(2), repeat=n_vertices): if np.sum(bound) == k+1: helper = boundary_operator(bound) for key in helper: dictionary[(tuple(bound), key)] = helper[key] return dictionary def boundary_operator_crsmat(n_vertices): ''' returns boundary operator on n vertices as sparse crs matrix ''' dictionary = boundary_operator_dict(n_vertices) basis_list = list(it.product(range(2), repeat=n_vertices)) basis_dict = {basis_list[i]: i for i in range(2**n_vertices)} col = np.array([basis_dict[index[0]] for index in dictionary]) row = np.array([basis_dict[index[1]] for index in dictionary]) data = np.array(list(dictionary.values())) return csr_matrix((data, (row, col)), shape=(2**n_vertices, 2**n_vertices)) def boundary_operator_crsmat_k(n_vertices, k): ''' returns boundary operator of order k on n vertices as sparse crs matrix ''' dictionary = boundary_operator_dict_k(n_vertices, k) basis_list = list(it.product(range(2), repeat=n_vertices)) basis_dict = {basis_list[i]: i for i in range(2**n_vertices)} col = np.array([basis_dict[index[0]] for index in dictionary]) row = np.array([basis_dict[index[1]] for index in dictionary]) data = np.array(list(dictionary.values())) return csr_matrix((data, (row, col)), shape=(2**n_vertices, 2**n_vertices)) def combinatorial_laplacian(n_vertices, k): ''' returns combinatorial Laplacian of order k on n vertices as sparse crs matrix ''' delta_k = boundary_operator_crsmat_k(n_vertices, k) delta_kplus1 = boundary_operator_crsmat_k(n_vertices, k+1) return delta_k.conj().T @ delta_k + delta_kplus1 @ delta_kplus1.conj().T def projector_onto_state(n_vertices, state): '''projector onto simplex state''' basis_list = list(it.product(range(2), repeat=n_vertices)) basis_dict = {basis_list[i]: i for i in range(2**n_vertices)} indices = [basis_dict[s] for s in state] return csr_matrix( (np.ones(len(indices)), (indices, indices)), shape=(2**n_vertices, 2**n_vertices) ) def projected_combinatorial_laplacian(n_vertices, k, state_dict): ''' returns the projected combinatorial Laplacian of order k on n vertices as sparse crs matrix ''' p_k = projector_onto_state(n_vertices, state_dict[k]) p_kp1 = projector_onto_state(n_vertices, state_dict[k+1]) delta_k = boundary_operator_crsmat_k(n_vertices, k) @ p_k delta_kplus1 = boundary_operator_crsmat_k(n_vertices, k+1) @ p_kp1 return delta_k.conj().T @ delta_k + delta_kplus1 @ delta_kplus1.conj().T def initialize_projector( state, circuit=None, initialization_qubits=None, circuit_name=None ): ''' initializes projector onto subspace spanned by list of states input circuit has to have classical register ''' if circuit is None: n_vertices = len(state[0]) qr1 = QuantumRegister(n_vertices, name="state_reg") copy_reg = QuantumRegister(n_vertices, name="copy_reg") quantum_circuit = QuantumCircuit(qr1, copy_reg) state_vec = state_to_vec(state) state_vec = state_vec/np.linalg.norm(state_vec) quantum_circuit.initialize(state_vec, qr1) # quantum_circuit.barrier() for k in range(n_vertices): quantum_circuit.cx(qr1[k], copy_reg[k]) # quantum_circuit.barrier() else: n_vertices = len(state[0]) qr1 = QuantumRegister(n_vertices, name="state_reg") copy_reg = QuantumRegister(n_vertices, name="copy_reg") if circuit.num_qubits - n_vertices > 0: anr = QuantumRegister( circuit.num_qubits - n_vertices, name="an_reg" ) quantum_circuit = QuantumCircuit(anr, qr1, copy_reg) else: quantum_circuit = QuantumCircuit(qr1, copy_reg) state_vec = state_to_vec(state) state_vec = state_vec/np.linalg.norm(state_vec) quantum_circuit.initialize(state_vec, qr1) # quantum_circuit.barrier() for k in range(n_vertices): quantum_circuit.cx(qr1[k], copy_reg[k]) # quantum_circuit.barrier() if initialization_qubits is None: init = list(range(n_vertices)) else: init = initialization_qubits rest = list(set(range(circuit.num_qubits)) - set(init)) sub_inst = circuit.to_instruction() if circuit_name is not None: sub_inst.name = circuit_name quantum_circuit.append(sub_inst, rest + init) return quantum_circuit def simplices_to_states(test_list, n_vertices): ''' converts the simplices to a matrix ''' n_states = len(test_list) arr = np.zeros((n_states, n_vertices)) for k in range(n_states): arr[k, test_list[k]] = 1 return arr class DataFiltration: ''' data: point data given by (number_data_points x dim_points)-numpy-array distance_matrix: (n x n)-numpy-array describing the pair-wise distances of n data points Either one of them has to be given! ''' def __init__( self, data=None, distance_matrix=None, max_dimension=None, max_edge_length=None ): if data is not None: self.skeleton = gd.RipsComplex( points=data, max_edge_length=max_edge_length ) elif distance_matrix is not None: self.skeleton = gd.RipsComplex( distance_matrix=distance_matrix, max_edge_length=max_edge_length ) else: print('Either point data or distance matrix has to be provided!') self.Rips_simplex_tree = self.skeleton.create_simplex_tree( max_dimension=max_dimension ) self.num_vertices = self.Rips_simplex_tree.num_vertices() self.num_simplices = self.Rips_simplex_tree.num_simplices() self.filtration = list(self.Rips_simplex_tree.get_filtration()) def get_filtration_states(self, epsilons=None): ''' epsilons: different radia for the filtration returns a dictionary of the filtration ''' if epsilons is None: epsilons = set([x[1] for x in self.filtration]) filt_dict = {} for eps in epsilons: helper_list = [x[0] for x in self.filtration if x[1] <= eps] filt_dict[eps] = simplices_to_states( helper_list, self.num_vertices ) return filt_dict def plot_persistence_diagram(self): ''' plots a diagram for the persistent topologial features ''' bar_codes = self.Rips_simplex_tree.persistence() gd.plot_persistence_diagram(bar_codes, legend=True) def controled_u(unitary, quantum_circuit, num_eval_qubits, n_vertices): # , k, state_dict): ''' returns a quantum circuit with the controled unitary for the quantum phase estimation routine. ''' unit = unitary gate = UnitaryGate(unit) for counting_qubit in range(num_eval_qubits): quantum_circuit.append( gate.control(1), [counting_qubit] + list( range(num_eval_qubits, num_eval_qubits+n_vertices) ) ) unit = unit@unit gate = UnitaryGate(unit) return quantum_circuit def qft_dagger(quantum_circuit, num): """n-qubit QFTdagger the first n qubits in circ""" # Don't forget the Swaps! for qubit in range(num//2): quantum_circuit.swap(qubit, num-qubit-1) for j in range(num): for k in range(j): quantum_circuit.cp(-np.pi/float(2**(j-k)), k, j) quantum_circuit.h(j) def qpe_total(num_eval_qubits, n_vertices, unitary): # , k, state_dict): ''' returns the full circuit of the quantum phase estimation ''' quantum_circuit = QuantumCircuit(num_eval_qubits + n_vertices) for qubit in range(num_eval_qubits): quantum_circuit.h(qubit) controled_u(unitary, quantum_circuit, num_eval_qubits, n_vertices) # , k, state_dict) # Apply inverse QFT qft_dagger(quantum_circuit, num_eval_qubits) return quantum_circuit class QTDAalgorithm(QuantumCircuit): ''' Class that contains the QTDA algorithm. num_eval_qubits: number of qubits for the evaluation in the quantum phase estimation top_order: the topological order state_dict: the dictionary of states ''' def __init__(self, num_eval_qubits, top_order, state_dict, name='QTDA'): n_vertices = len(state_dict[0][0]) qr_eval = QuantumRegister(num_eval_qubits, 'eval') qr_state = QuantumRegister(n_vertices, 'state') qr_copy = QuantumRegister(n_vertices, 'copy') super().__init__(qr_eval, qr_state, qr_copy, name=name) unitary = expm( 1j*projected_combinatorial_laplacian( n_vertices, top_order, state_dict ).toarray() ) ''' we can also directly use the PhaseEstimation routine from Qiskit, which, however, leads to a larger circuit depth than our designed qpe_total implementation ''' # gate = UnitaryGate(unitary) # qpe = qiskit.circuit.library.PhaseEstimation( # num_eval_qubits, unitary=gate, iqft=None, name='QPE' # ) qpe = qpe_total(num_eval_qubits, n_vertices, unitary) sub_inst = qpe.to_instruction() sub_inst.name = ' QPE ' state_vec = state_to_vec(state_dict[top_order]) state_vec = state_vec/np.linalg.norm(state_vec) self.initialize(state_vec, qr_state) # for a better visualisation one can imput barriers, but they slow # down the computation. # self.barrier() for k in range(n_vertices): self.cx(qr_state[k], qr_copy[k]) # self.barrier() self.append(sub_inst, list(range(num_eval_qubits + n_vertices))) self.eval_qubits = list(range(num_eval_qubits)) class Q_top_spectra: ''' data: point data given by (number_data_points x dim_points)-numpy-array distance_matrix: (n x n)-numpy-array describing the pair-wise distances of n data points Either one of them has to be given! ''' def __init__(self, state_dict, num_eval_qubits=6, shots=1000): self.shots = shots self.state_dict = state_dict self.counts = {} for top_order in self.state_dict: print('Topological order: ', top_order) if len(self.state_dict[top_order]) == 0: print( "calculation terminated because no simplex of dimension %s" % (top_order) ) break quantum_circuit = QTDAalgorithm(num_eval_qubits, top_order, self.state_dict) quantum_circuit.add_register(ClassicalRegister(num_eval_qubits, name="phase")) for qubit in quantum_circuit.eval_qubits: quantum_circuit.measure(qubit, qubit) backend = Aer.get_backend('qasm_simulator') job = execute(quantum_circuit, backend, shots=self.shots) self.counts[top_order] = job.result().get_counts(quantum_circuit) def get_counts(self): ''' returns the number of counts ''' return self.counts def get_spectra(self, chop=None): ''' defaul chop: eigenvalues with less then 2% of all shots are regarded as noise (can be adjusted) exception: the eigenspace of eigenvalue 0 is important, even if it is 0-dimensional; hence, this is always included ''' if chop is None: chop = self.shots/50 eigenvalue_dict = {} for top_order in self.counts: eigenvalue_dict[top_order] = {} eigenvalue_dict[top_order][0.0] = 0 vals = np.fromiter(self.counts[top_order].values(), dtype=float) keys = list(self.counts[top_order].keys()) indices = np.where(vals >= chop) new_vals = vals[indices] new_keys = [keys[i] for i in indices[0]] for i in range(len(new_keys)): eigenvalue_dict[top_order][ 2*np.pi*int(new_keys[i], 2)/int(len(new_keys[i])*'1', 2) ] = ( new_vals[i] * len(self.state_dict[top_order]) / self.shots ) return eigenvalue_dict class Q_persistent_top_spectra: ''' data: point data given by (number_data_points x dim_points)-numpy-array distance_matrix: (n x n)-numpy-array describing the pair-wise distances of n data points Either one of them has to be given! ''' def __init__( self, data=None, distance_matrix=None, max_dimension=None, max_edge_length=None, num_eval_qubits=6, shots=1000, epsilons=None ): self.shots = shots self.filt_dict = DataFiltration( data=data, distance_matrix=distance_matrix, max_dimension=max_dimension, max_edge_length=max_edge_length ).get_filtration_states(epsilons=epsilons) self.state_dict = {} for key in sorted(self.filt_dict.keys()): self.state_dict[key] = {} for k in range(1, max_dimension+1): mask = np.sum(self.filt_dict[key], axis=1) == k self.state_dict[key][k-1] = [ tuple(s) for s in self.filt_dict[key][mask, :] ] self.state_dict[key][max_dimension] = [] # an empty state has to be included # on order max_dimension for consistency self.counts = {} for eps in self.state_dict: print() print('Filtration scale: ', eps) print() self.counts[eps] = {} for top_order in self.state_dict[eps]: print('Topological order: ', top_order) if len(self.state_dict[eps][top_order]) == 0: print( "calculation terminated because no simplex of dimension %s" % (top_order) ) break quantum_circuit = QTDAalgorithm( num_eval_qubits, top_order, self.state_dict[eps] ) quantum_circuit.add_register( ClassicalRegister(num_eval_qubits, name="phase") ) for qubit in quantum_circuit.eval_qubits: quantum_circuit.measure(qubit, qubit) backend = Aer.get_backend('qasm_simulator') job = execute(quantum_circuit, backend, shots=self.shots) self.counts[eps][top_order] = job.result().get_counts(quantum_circuit) def get_counts(self): ''' returns the number of counts ''' return self.counts def get_eigenvalues(self, chop=None): ''' defaul chop: eigenvalues with less then 2% of all shots are regarded as noise (can be adjusted) exception: the eigenspace of eigenvalue 0 is important, even if it is 0-dimensional; hence, this is always included ''' if chop is None: chop = self.shots/50 eigenvalue_dict = {} for eps in self.counts: eigenvalue_dict[eps] = {} for top_order in self.counts[eps]: eigenvalue_dict[eps][top_order] = {} eigenvalue_dict[eps][top_order][0.0] = 0 vals = np.fromiter( self.counts[eps][top_order].values(), dtype=float ) keys = list(self.counts[eps][top_order].keys()) indices = np.where(vals >= chop) new_vals = vals[indices] new_keys = [keys[i] for i in indices[0]] for i, key in enumerate(new_keys): eigenvalue_dict[eps][top_order][ 2*np.pi*int(key, 2)/int(len(new_keys[i])*'1', 2) ] = ( new_vals[i] * len(self.state_dict[eps][top_order]) / self.shots ) return eigenvalue_dict
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_optimization import QuadraticProgram from qiskit_optimization.translators import from_docplex_mp # Make a Docplex model from docplex.mp.model import Model mdl = Model("docplex model") x = mdl.binary_var("x") y = mdl.integer_var(lb=-1, ub=5, name="y") mdl.minimize(x + 2 * y) mdl.add_constraint(x - y == 3) mdl.add_constraint((x + y) * (x - y) <= 1) print(mdl.export_as_lp_string()) # load from a Docplex model mod = from_docplex_mp(mdl) print(type(mod)) print() print(mod.prettyprint()) # make an empty problem mod = QuadraticProgram("my problem") print(mod.prettyprint()) # Add variables mod.binary_var(name="x") mod.integer_var(name="y", lowerbound=-1, upperbound=5) mod.continuous_var(name="z", lowerbound=-1, upperbound=5) print(mod.prettyprint()) # Add objective function using dictionaries mod.minimize(constant=3, linear={"x": 1}, quadratic={("x", "y"): 2, ("z", "z"): -1}) print(mod.prettyprint()) # Add objective function using lists/arrays mod.minimize(constant=3, linear=[1, 0, 0], quadratic=[[0, 1, 0], [1, 0, 0], [0, 0, -1]]) print(mod.prettyprint()) print("constant:\t\t\t", mod.objective.constant) print("linear dict:\t\t\t", mod.objective.linear.to_dict()) print("linear array:\t\t\t", mod.objective.linear.to_array()) print("linear array as sparse matrix:\n", mod.objective.linear.coefficients, "\n") print("quadratic dict w/ index:\t", mod.objective.quadratic.to_dict()) print("quadratic dict w/ name:\t\t", mod.objective.quadratic.to_dict(use_name=True)) print( "symmetric quadratic dict w/ name:\t", mod.objective.quadratic.to_dict(use_name=True, symmetric=True), ) print("quadratic matrix:\n", mod.objective.quadratic.to_array(), "\n") print("symmetric quadratic matrix:\n", mod.objective.quadratic.to_array(symmetric=True), "\n") print("quadratic matrix as sparse matrix:\n", mod.objective.quadratic.coefficients) # Add linear constraints mod.linear_constraint(linear={"x": 1, "y": 2}, sense="==", rhs=3, name="lin_eq") mod.linear_constraint(linear={"x": 1, "y": 2}, sense="<=", rhs=3, name="lin_leq") mod.linear_constraint(linear={"x": 1, "y": 2}, sense=">=", rhs=3, name="lin_geq") print(mod.prettyprint()) # Add quadratic constraints mod.quadratic_constraint( linear={"x": 1, "y": 1}, quadratic={("x", "x"): 1, ("y", "z"): -1}, sense="==", rhs=1, name="quad_eq", ) mod.quadratic_constraint( linear={"x": 1, "y": 1}, quadratic={("x", "x"): 1, ("y", "z"): -1}, sense="<=", rhs=1, name="quad_leq", ) mod.quadratic_constraint( linear={"x": 1, "y": 1}, quadratic={("x", "x"): 1, ("y", "z"): -1}, sense=">=", rhs=1, name="quad_geq", ) print(mod.prettyprint()) lin_geq = mod.get_linear_constraint("lin_geq") print("lin_geq:", lin_geq.linear.to_dict(use_name=True), lin_geq.sense, lin_geq.rhs) quad_geq = mod.get_quadratic_constraint("quad_geq") print( "quad_geq:", quad_geq.linear.to_dict(use_name=True), quad_geq.quadratic.to_dict(use_name=True), quad_geq.sense, lin_geq.rhs, ) # Remove constraints mod.remove_linear_constraint("lin_eq") mod.remove_quadratic_constraint("quad_leq") print(mod.prettyprint()) sub = mod.substitute_variables(constants={"x": 0}, variables={"y": ("z", -1)}) print(sub.prettyprint()) sub = mod.substitute_variables(constants={"x": -1}) print(sub.status) from qiskit_optimization import QiskitOptimizationError try: sub = mod.substitute_variables(constants={"x": -1}, variables={"y": ("x", 1)}) except QiskitOptimizationError as e: print("Error: {}".format(e)) mod = QuadraticProgram() mod.binary_var(name="e") mod.binary_var(name="f") mod.continuous_var(name="g") mod.minimize(linear=[1, 2, 3]) print(mod.export_as_lp_string()) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 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. """ Arbitrary unitary circuit instruction. """ import numpy from qiskit.circuit import Gate, ControlledGate from qiskit.circuit import QuantumCircuit from qiskit.circuit import QuantumRegister, Qubit from qiskit.circuit.exceptions import CircuitError from qiskit.circuit._utils import _compute_control_matrix from qiskit.circuit.library.standard_gates import UGate from qiskit.extensions.quantum_initializer import isometry from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.quantum_info.operators.predicates import is_unitary_matrix from qiskit.quantum_info.synthesis.one_qubit_decompose import OneQubitEulerDecomposer from qiskit.quantum_info.synthesis.two_qubit_decompose import two_qubit_cnot_decompose from qiskit.extensions.exceptions import ExtensionError _DECOMPOSER1Q = OneQubitEulerDecomposer("U") class UnitaryGate(Gate): """Class quantum gates specified by a unitary matrix. Example: We can create a unitary gate from a unitary matrix then add it to a quantum circuit. The matrix can also be directly applied to the quantum circuit, see :meth:`.QuantumCircuit.unitary`. .. code-block:: python from qiskit import QuantumCircuit from qiskit.extensions import UnitaryGate matrix = [[0, 0, 0, 1], [0, 0, 1, 0], [1, 0, 0, 0], [0, 1, 0, 0]] gate = UnitaryGate(matrix) circuit = QuantumCircuit(2) circuit.append(gate, [0, 1]) """ def __init__(self, data, label=None): """Create a gate from a numeric unitary matrix. Args: data (matrix or Operator): unitary operator. label (str): unitary name for backend [Default: None]. Raises: ExtensionError: if input data is not an N-qubit unitary operator. """ if hasattr(data, "to_matrix"): # If input is Gate subclass or some other class object that has # a to_matrix method this will call that method. data = data.to_matrix() elif hasattr(data, "to_operator"): # If input is a BaseOperator subclass this attempts to convert # the object to an Operator so that we can extract the underlying # numpy matrix from `Operator.data`. data = data.to_operator().data # Convert to numpy array in case not already an array data = numpy.array(data, dtype=complex) # Check input is unitary if not is_unitary_matrix(data): raise ExtensionError("Input matrix is not unitary.") # Check input is N-qubit matrix input_dim, output_dim = data.shape num_qubits = int(numpy.log2(input_dim)) if input_dim != output_dim or 2**num_qubits != input_dim: raise ExtensionError("Input matrix is not an N-qubit operator.") # Store instruction params super().__init__("unitary", num_qubits, [data], label=label) def __eq__(self, other): if not isinstance(other, UnitaryGate): return False if self.label != other.label: return False # Should we match unitaries as equal if they are equal # up to global phase? return matrix_equal(self.params[0], other.params[0], ignore_phase=True) def __array__(self, dtype=None): """Return matrix for the unitary.""" # pylint: disable=unused-argument return self.params[0] def inverse(self): """Return the adjoint of the unitary.""" return self.adjoint() def conjugate(self): """Return the conjugate of the unitary.""" return UnitaryGate(numpy.conj(self.to_matrix())) def adjoint(self): """Return the adjoint of the unitary.""" return self.transpose().conjugate() def transpose(self): """Return the transpose of the unitary.""" return UnitaryGate(numpy.transpose(self.to_matrix())) def _define(self): """Calculate a subcircuit that implements this unitary.""" if self.num_qubits == 1: q = QuantumRegister(1, "q") qc = QuantumCircuit(q, name=self.name) theta, phi, lam, global_phase = _DECOMPOSER1Q.angles_and_phase(self.to_matrix()) qc._append(UGate(theta, phi, lam), [q[0]], []) qc.global_phase = global_phase self.definition = qc elif self.num_qubits == 2: self.definition = two_qubit_cnot_decompose(self.to_matrix()) else: from qiskit.quantum_info.synthesis.qsd import ( # pylint: disable=cyclic-import qs_decomposition, ) self.definition = qs_decomposition(self.to_matrix()) def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Return controlled version of gate Args: num_ctrl_qubits (int): number of controls to add to gate (default=1) label (str): optional gate label ctrl_state (int or str or None): The control state in decimal or as a bit string (e.g. '1011'). If None, use 2**num_ctrl_qubits-1. Returns: UnitaryGate: controlled version of gate. Raises: QiskitError: Invalid ctrl_state. ExtensionError: Non-unitary controlled unitary. """ mat = self.to_matrix() cmat = _compute_control_matrix(mat, num_ctrl_qubits, ctrl_state=None) iso = isometry.Isometry(cmat, 0, 0) return ControlledGate( "c-unitary", num_qubits=self.num_qubits + num_ctrl_qubits, params=[mat], label=label, num_ctrl_qubits=num_ctrl_qubits, definition=iso.definition, ctrl_state=ctrl_state, base_gate=self.copy(), ) def _qasm2_decomposition(self): """Return an unparameterized version of ourselves, so the OQ2 exporter doesn't choke on the non-standard things in our `params` field.""" out = self.definition.to_gate() out.name = self.name return out def validate_parameter(self, parameter): """Unitary gate parameter has to be an ndarray.""" if isinstance(parameter, numpy.ndarray): return parameter else: raise CircuitError(f"invalid param type {type(parameter)} in gate {self.name}") def unitary(self, obj, qubits, label=None): """Apply unitary gate specified by ``obj`` to ``qubits``. Args: obj (matrix or Operator): unitary operator. qubits (Union[int, Tuple[int]]): The circuit qubits to apply the transformation to. label (str): unitary name for backend [Default: None]. Returns: QuantumCircuit: The quantum circuit. Raises: ExtensionError: if input data is not an N-qubit unitary operator. Example: Apply a gate specified by a unitary matrix to a quantum circuit .. code-block:: python from qiskit import QuantumCircuit matrix = [[0, 0, 0, 1], [0, 0, 1, 0], [1, 0, 0, 0], [0, 1, 0, 0]] circuit = QuantumCircuit(2) circuit.unitary(matrix, [0, 1]) """ gate = UnitaryGate(obj, label=label) if isinstance(qubits, QuantumRegister): qubits = qubits[:] # for single qubit unitary gate, allow an 'int' or a 'list of ints' as qubits. if gate.num_qubits == 1: if isinstance(qubits, (int, Qubit)) or len(qubits) > 1: qubits = [qubits] return self.append(gate, qubits, []) QuantumCircuit.unitary = unitary
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
min_qubits=2 max_qubits=8 skip_qubits=1 max_circuits=3 num_shots=1000 backend_id="dm_simulator" #backend_id="statevector_simulator" #hub="ibm-q"; group="open"; project="main" provider_backend = None exec_options = {} # # ========================== # # *** If using IBMQ hardware, run this once to authenticate # from qiskit import IBMQ # IBMQ.save_account('YOUR_API_TOKEN_HERE') # # *** If you are part of an IBMQ group, set hub, group, and project name here # hub="YOUR_HUB_NAME"; group="YOUR_GROUP_NAME"; project="YOUR_PROJECT_NAME" # # *** This example shows how to specify an IBMQ backend using a known "backend_id" # exec_options = { "optimization_level":3, "use_sessions":True, "resilience_level":1} # backend_id="ibmq_belem" # # ========================== # # *** If using Azure Quantum, use this hub identifier and specify the desired backend_id # # Identify your resources with env variables AZURE_QUANTUM_RESOURCE_ID and AZURE_QUANTUM_LOCATION # hub="azure-quantum"; group="open"; project="QED-C App-Oriented Benchmarks - Qiskit Version" # backend_id="<YOUR_BACKEND_NAME_HERE>" # # ========================== # The remaining examples illustrate other backend execution options # # An example using IonQ provider # from qiskit_ionq import IonQProvider # provider = IonQProvider() # Be sure to set the QISKIT_IONQ_API_TOKEN environment variable # provider_backend = provider.get_backend("ionq_qpu") # backend_id="ionq_qpu" # # An example using BlueQubit provider # import os, bluequbit, _common.executors.bluequbit_executor as bluequbit_executor # provider_backend = bluequbit.init() # backend_id="BlueQubit-CPU" # # An example using a typical custom provider backend (e.g. AQT simulator) # import os # from qiskit_aqt_provider import AQTProvider # provider = AQTProvider(os.environ.get('AQT_ACCESS_KEY')) # get your key from environment # provider_backend = provider.backends.aqt_qasm_simulator_noise_1 # backend_id="aqt_qasm_simulator_noise_1" # # Fire Opal can be used to manage executions on other backends, as illustrated here # import _common.executors.fire_opal_executor as fire_opal_executor # from _common.executors.fire_opal_executor import FireOpalBackend # ibm_backend_id = "ibmq_jakarta" # backend_id = f"fire_opal_{ibm_backend_id}" # provider_backend = FireOpalBackend(ibm_backend_id=ibm_backend_id, hub=hub, group=group, project=project, token=token) # exec_options = {"executor": fire_opal_executor.run} import sys sys.path[1:1] = [ "_common", "_common/qsim" ] import execute as ex # noise parameters for dm-simulator (introduce noise by changing the values) options_noise = { 'plot': False, "thermal_factor": 0.9, 'show_partition': False, "decoherence_factor": 1.0, "depolarization_factor": 0.9, "bell_depolarization_factor": 1.0, "decay_factor": 1.0, "rotation_error": {'rx': [1.0, 0.0], 'ry': [1.0, 0.0], 'rz': [1.0, 0.0]}, # Default values [1.0, 0.0] "tsp_model_error": [1.0, 0.0], } ex.options_noise = options_noise # Custom optimization options can be specified in this cell (below is an example) # # Example of pytket Transformer # import _common.transformers.tket_optimiser as tket_optimiser # exec_options.update({ "optimization_level": 0, "layout_method":'sabre', "routing_method":'sabre', "transformer": tket_optimiser.high_optimisation }) # # Define a custom noise model to be used during execution # import _common.custom.custom_qiskit_noise_model as custom_qiskit_noise_model # exec_options.update({ "noise_model": custom_qiskit_noise_model.my_noise_model() }) # # Example of mthree error mitigation # import _common.postprocessors.mthree.mthree_em as mthree_em # exec_options.update({ "postprocessor": mthree_em.get_mthree_handlers(backend_id, provider_backend) }) # pip uninstall qiskit-aer -y # pip install qiskit-aer import sys sys.path.insert(1, "deutsch-jozsa/qsim") import dj_benchmark dj_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "bernstein-vazirani/qsim") import bv_benchmark bv_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, method=1, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "bernstein-vazirani/qsim") import bv_benchmark bv_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, method=2, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "hidden-shift/qsim") import hs_benchmark hs_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, max_circuits=max_circuits, num_shots=num_shots, backend_id=backend_id, provider_backend=provider_backend, #hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "quantum-fourier-transform/qsim") import qft_benchmark qft_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, method=1, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "quantum-fourier-transform/qsim") import qft_benchmark qft_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, method=2, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "grovers/qsim") import grovers_benchmark grovers_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "phase-estimation/qsim") import pe_benchmark pe_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "hhl/qsim") import hhl_benchmark hhl_benchmark.verbose=False hhl_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, method=1, use_best_widths=True, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "amplitude-estimation/qsim") import ae_benchmark ae_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "monte-carlo/qsim") import mc_benchmark mc_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "hamiltonian-simulation/qsim") import hamiltonian_simulation_benchmark hamiltonian_simulation_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "vqe/qsim") import vqe_benchmark vqe_num_shots=4098 vqe_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, max_circuits=max_circuits, num_shots=vqe_num_shots, method=1, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "shors/qsim") import shors_benchmark shors_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, max_circuits=1, num_shots=num_shots, method=1, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "shors/qsim") import shors_benchmark shors_benchmark.run(min_qubits=min_qubits, max_qubits=max_qubits, max_circuits=1, num_shots=num_shots, method=2, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options) import sys sys.path.insert(1, "_common") import metrics # metrics.depth_base = 2 # metrics.QV = 0 # apps = [ "Hidden Shift", "Grover's Search", "Quantum Fourier Transform (1)", "Hamiltonian Simulation" ] # backend_id='qasm_simulator' metrics.plot_all_app_metrics(backend_id, do_all_plots=False, include_apps=None)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse dc = pulse.DriveChannel d0, d1, d2, d3, d4 = dc(0), dc(1), dc(2), dc(3), dc(4) with pulse.build(name='pulse_programming_in') as pulse_prog: pulse.play([1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], d0) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d1) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], d2) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d3) pulse.play([1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0], d4) pulse_prog.draw()
https://github.com/usamisaori/quantum-expressibility-entangling-capability
usamisaori
import numpy as np from qiskit.quantum_info import state_fidelity, Statevector def getStatevector(circuit): return Statevector(circuit).data import warnings warnings.filterwarnings('ignore') def P_haar(N, F): if F == 1: return 0 else: return (N - 1) * ((1 - F) ** (N - 2)) def KL(P, Q): epsilon = 1e-8 kl_divergence = 0.0 for p, q in zip(P, Q): kl_divergence += p * np.log( (p + epsilon) / (q + epsilon) ) return abs(kl_divergence) def expressibility(qubits, sampler, *, bins=100, epoch=3000, layer=1, encode=False, return_detail=False): unit = 1 / bins limits = [] probabilities = np.array([0] * bins) for i in range(1, bins + 1): limits.append(unit * i) for i in range(epoch): circuit_1 = sampler(layer=layer, qubits=qubits) circuit_2 = sampler(layer=layer, qubits=qubits) f = state_fidelity( getStatevector(circuit_1), getStatevector(circuit_2) ) for j in range(bins): if f <= limits[j]: probabilities[j] += 1 break pHaar_vqc = [ P_haar(2 ** qubits, f - (unit/2)) / bins for f in limits] probabilities = [ p / epoch for p in probabilities ] if return_detail: return pHaar_vqc, probabilities else: return KL(probabilities, pHaar_vqc)
https://github.com/anpaschool/quantum-computing
anpaschool
# Useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np from math import pi from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit import Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.visualization import * from qiskit.providers.aer import UnitarySimulator from qiskit.tools.visualization import circuit_drawer from qiskit.quantum_info import state_fidelity from qiskit import BasicAer backend = BasicAer.get_backend('unitary_simulator') qr = QuantumRegister(2) cr = ClassicalRegister(2) groverCircuit = QuantumCircuit(qr,cr) groverCircuit.h(qr) groverCircuit.draw(output="mpl") job = execute(groverCircuit, backend) job.result().get_unitary(groverCircuit, decimals=3) groverCircuit.measure(qr,cr) groverCircuit.draw(output="mpl") simulator = Aer.get_backend('qasm_simulator') result = execute(groverCircuit, simulator).result() counts = result.get_counts(groverCircuit) plot_histogram(counts, title='Grover Intermediate measurement') qr = QuantumRegister(2) cr = ClassicalRegister(2) groverCircuit = QuantumCircuit(qr,cr) groverCircuit.h(qr) '''oracle w = |00>''' groverCircuit.x(qr) groverCircuit.cz(qr[0],qr[1]) groverCircuit.x(qr) groverCircuit.draw(output="mpl") job = execute(groverCircuit, backend) job.result().get_unitary(groverCircuit, decimals=3) INIT = 0.5*np.array([[1,1,1,1],[1,-1,1,-1],[1,1,-1,-1],[1,-1,-1,1]]) CZ = np.array([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,-1]]) XX = np.array([[0,0,0,1],[0,0,1,0],[0,1,0,0],[1,0,0,0]]) '''Oracle''' ORCL = np.dot(XX,np.dot(CZ,XX)) print(ORCL) '''FUll circuit matrix so far''' np.dot(ORCL,INIT) groverCircuit.measure(qr,cr) groverCircuit.draw(output="mpl") simulator = Aer.get_backend('qasm_simulator') result = execute(groverCircuit, simulator).result() counts = result.get_counts(groverCircuit) plot_histogram(counts, title='Grover Intermediate measurement') qr = QuantumRegister(2) cr = ClassicalRegister(2) groverCircuit = QuantumCircuit(qr,cr) groverCircuit.h(qr) '''oracle w = |00>''' groverCircuit.x(qr) groverCircuit.cz(qr[0],qr[1]) groverCircuit.x(qr) '''Grover Transform''' groverCircuit.h(qr) '''Reflection''' groverCircuit.z(qr) groverCircuit.cz(qr[0],qr[1]) '''end of Reflection''' groverCircuit.h(qr) '''end of Grover Transform''' groverCircuit.draw(output="mpl") job = execute(groverCircuit, backend) job.result().get_unitary(groverCircuit, decimals=3) HH = 0.5*np.array([[1,1,1,1],[1,-1,1,-1],[1,1,-1,-1],[1,-1,-1,1]]) ZZ = np.array([[1,0,0,0],[0,-1,0,0],[0,0,-1,0],[0,0,0,1]]) '''Grover Transform''' GT = np.dot(HH,np.dot(CZ,np.dot(ZZ,HH))) print(GT) '''FUll circut matrix''' np.dot(INIT,np.dot(ORCL,GT)) simulator = Aer.get_backend('qasm_simulator') result = execute(groverCircuit, simulator).result() counts = result.get_counts(groverCircuit) plot_histogram(counts, title='Grover Intermediate measurement')
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
PabloMartinezAngerosa
import numpy as np import networkx as nx import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble from qiskit.quantum_info import Statevector from qiskit.aqua.algorithms import NumPyEigensolver from qiskit.quantum_info import Pauli from qiskit.aqua.operators import op_converter from qiskit.aqua.operators import WeightedPauliOperator from qiskit.visualization import plot_histogram from qiskit.providers.aer.extensions.snapshot_statevector import * from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost from utils import mapeo_grafo from collections import defaultdict from operator import itemgetter from scipy.optimize import minimize import matplotlib.pyplot as plt LAMBDA = 10 SEED = 10 SHOTS = 10000 # returns the bit index for an alpha and j def bit(i_city, l_time, num_cities): return i_city * num_cities + l_time # e^(cZZ) def append_zz_term(qc, q_i, q_j, gamma, constant_term): qc.cx(q_i, q_j) qc.rz(2*gamma*constant_term,q_j) qc.cx(q_i, q_j) # e^(cZ) def append_z_term(qc, q_i, gamma, constant_term): qc.rz(2*gamma*constant_term, q_i) # e^(cX) def append_x_term(qc,qi,beta): qc.rx(-2*beta, qi) def get_not_edge_in(G): N = G.number_of_nodes() not_edge = [] for i in range(N): for j in range(N): if i != j: buffer_tupla = (i,j) in_edges = False for edge_i, edge_j in G.edges(): if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)): in_edges = True if in_edges == False: not_edge.append((i, j)) return not_edge def get_classical_simplified_z_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # z term # z_classic_term = [0] * N**2 # first term for l in range(N): for i in range(N): z_il_index = bit(i, l, N) z_classic_term[z_il_index] += -1 * _lambda # second term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_jl z_jl_index = bit(j, l, N) z_classic_term[z_jl_index] += _lambda / 2 # third term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_ij z_ij_index = bit(i, j, N) z_classic_term[z_ij_index] += _lambda / 2 # fourth term not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 4 # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) z_classic_term[z_jlplus_index] += _lambda / 4 # fifthy term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) z_classic_term[z_il_index] += weight_ij / 4 # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) z_classic_term[z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) z_classic_term[z_il_index] += weight_ji / 4 # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) z_classic_term[z_jlplus_index] += weight_ji / 4 return z_classic_term def tsp_obj_2(x, G,_lambda): # obtenemos el valor evaluado en f(x_1, x_2,... x_n) not_edge = get_not_edge_in(G) N = G.number_of_nodes() tsp_cost=0 #Distancia weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # x_il x_il_index = bit(edge_i, l, N) # x_jlplus l_plus = (l+1) % N x_jlplus_index = bit(edge_j, l_plus, N) tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij # add order term because G.edges() do not include order tuples # # x_i'l x_il_index = bit(edge_j, l, N) # x_j'lplus x_jlplus_index = bit(edge_i, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji #Constraint 1 for l in range(N): penal1 = 1 for i in range(N): x_il_index = bit(i, l, N) penal1 -= int(x[x_il_index]) tsp_cost += _lambda * penal1**2 #Contstraint 2 for i in range(N): penal2 = 1 for l in range(N): x_il_index = bit(i, l, N) penal2 -= int(x[x_il_index]) tsp_cost += _lambda*penal2**2 #Constraint 3 for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # x_il x_il_index = bit(i, l, N) # x_j(l+1) l_plus = (l+1) % N x_jlplus_index = bit(j, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda return tsp_cost def get_classical_simplified_zz_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # zz term # zz_classic_term = [[0] * N**2 for i in range(N**2) ] # first term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) # z_jl z_jl_index = bit(j, l, N) zz_classic_term[z_il_index][z_jl_index] += _lambda / 2 # second term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) # z_ij z_ij_index = bit(i, j, N) zz_classic_term[z_il_index][z_ij_index] += _lambda / 2 # third term not_edge = get_not_edge_in(G) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4 # fourth term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4 return zz_classic_term def get_classical_simplified_hamiltonian(G, _lambda): # z term # z_classic_term = get_classical_simplified_z_term(G, _lambda) # zz term # zz_classic_term = get_classical_simplified_zz_term(G, _lambda) return z_classic_term, zz_classic_term def get_cost_circuit(G, gamma, _lambda): N = G.number_of_nodes() N_square = N**2 qc = QuantumCircuit(N_square,N_square) z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda) # z term for i in range(N_square): if z_classic_term[i] != 0: append_z_term(qc, i, gamma, z_classic_term[i]) # zz term for i in range(N_square): for j in range(N_square): if zz_classic_term[i][j] != 0: append_zz_term(qc, i, j, gamma, zz_classic_term[i][j]) return qc def get_mixer_operator(G,beta): N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) for n in range(N**2): append_x_term(qc, n, beta) return qc def get_QAOA_circuit(G, beta, gamma, _lambda): assert(len(beta)==len(gamma)) N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) # init min mix state qc.h(range(N**2)) p = len(beta) for i in range(p): qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda)) qc = qc.compose(get_mixer_operator(G, beta[i])) qc.barrier(range(N**2)) qc.snapshot_statevector("final_state") qc.measure(range(N**2),range(N**2)) return qc def invert_counts(counts): return {k[::-1] :v for k,v in counts.items()} # Sample expectation value def compute_tsp_energy_2(counts, G): energy = 0 get_counts = 0 total_counts = 0 for meas, meas_count in counts.items(): obj_for_meas = tsp_obj_2(meas, G, LAMBDA) energy += obj_for_meas*meas_count total_counts += meas_count mean = energy/total_counts return mean def get_black_box_objective_2(G,p): backend = Aer.get_backend('qasm_simulator') sim = Aer.get_backend('aer_simulator') # function f costo def f(theta): beta = theta[:p] gamma = theta[p:] # Anzats qc = get_QAOA_circuit(G, beta, gamma, LAMBDA) result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result() final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0] state_vector = Statevector(final_state_vector) probabilities = state_vector.probabilities() probabilities_states = invert_counts(state_vector.probabilities_dict()) expected_value = 0 for state,probability in probabilities_states.items(): cost = tsp_obj_2(state, G, LAMBDA) expected_value += cost*probability counts = result.get_counts() mean = compute_tsp_energy_2(invert_counts(counts),G) return mean return f def crear_grafo(cantidad_ciudades): pesos, conexiones = None, None mejor_camino = None while not mejor_camino: pesos, conexiones = rand_graph(cantidad_ciudades) mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False) G = mapeo_grafo(conexiones, pesos) return G, mejor_costo, mejor_camino def run_QAOA(p,ciudades, grafo): if grafo == None: G, mejor_costo, mejor_camino = crear_grafo(ciudades) print("Mejor Costo") print(mejor_costo) print("Mejor Camino") print(mejor_camino) print("Bordes del grafo") print(G.edges()) print("Nodos") print(G.nodes()) print("Pesos") labels = nx.get_edge_attributes(G,'weight') print(labels) else: G = grafo intial_random = [] # beta, mixer Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,np.pi)) # gamma, cost Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,2*np.pi)) init_point = np.array(intial_random) obj = get_black_box_objective_2(G,p) res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True}) print(res_sample) if __name__ == '__main__': # Run QAOA parametros: profundidad p, numero d ciudades, run_QAOA(5, 3, None)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
%matplotlib inline import matplotlib.pyplot as plt from qiskit import QuantumCircuit, execute, Aer from qiskit.circuit.random import random_circuit n_circs = 10000 n_qubits = 4 n_layers = 30 freq = [] backend_m = Aer.get_backend("qasm_simulator") backend_s = Aer.get_backend("statevector_simulator") for _ in range(n_circs): #Generate a random circuit circ = random_circuit(n_qubits, n_layers, measure = False) #Sample one string from its output meas = QuantumCircuit(n_qubits,n_qubits) meas.measure(range(n_qubits),range(n_qubits)) circ_m = circ + meas job = execute(circ_m,backend = backend_m, shots = 1, memory = True) string = job.result().get_memory()[0] #Compute the exact probability of the string job = execute(circ, backend = backend_s) state = job.result().get_statevector() freq.append(abs(state[int(string,2)])**2) import numpy as np xs = np.linspace(0.0, 1.0, 100) dim = 2**n_qubits ys = xs*(dim**2)*np.exp(-dim*xs) plt.hist(freq, bins = 100, density = True) plt.plot(xs, ys, label='Theoretical') plt.show()
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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/ardieb/QiskitPlayground
ardieb
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute from qiskit.quantum_info import Statevector, random_statevector from qiskit.visualization import plot_bloch_multivector, plot_histogram, plot_state_qsphere, plot_state_city from qiskit.circuit.library import iSwapGate import numpy as np import matplotlib.pyplot as plt import itertools %matplotlib inline sim = Aer.get_backend('statevector_simulator') toffoli = QuantumCircuit(3) toffoli.h([2]) toffoli.cx([1], [2]) toffoli.tdg([2]) toffoli.cx([0], [2]) toffoli.t([2]) toffoli.cx([1], [2]) toffoli.tdg([2]) toffoli.cx([0], [2]) toffoli.tdg([1]) toffoli.t([2]) toffoli.cx([0], [1]) toffoli.h([2]) toffoli.tdg([1]) toffoli.cx([0], [1]) toffoli.t([0]) toffoli.s([1]) results = [] circuits = [] basis_states = [''.join(s) for s in itertools.product('01', repeat=3)] for state in basis_states: circ = QuantumCircuit(3) circ.initialize(Statevector.from_label(state).data, [0,1,2]) circ = circ + toffoli circuits.append(circ) results.append(execute(circ, sim).result()) toffoli.draw('mpl') for state, res in zip(basis_states, results): print(f'Input state: {state}') display(plot_histogram(res.get_counts())) toffoli2 = QuantumCircuit(3) toffoli2.ry(np.pi/4, [2]) toffoli2.cx([1], [2]) toffoli2.ry(np.pi/4, [2]) toffoli2.cx([0], [2]) toffoli2.ry(-np.pi/4, [2]) toffoli2.cx([1], [2]) toffoli2.ry(-np.pi/4, [2]) results2 = [] circuits2 = [] for state in basis_states: circ = QuantumCircuit(3) circ.initialize(Statevector.from_label(state).data, [0,1,2]) circ = circ + toffoli2 circuits2.append(circ) results2.append(execute(circ, sim).result()) toffoli2.draw('mpl') for state, res in zip(basis_states, results2): print(f'Input state: {state}') display(plot_histogram(res.get_counts())) # Compare the results for state, res1, circ1, res2, circ2 in zip(basis_states, results, circuits, results2, circuits2): print(f'Input state: {state}') s1, s2 = res1.get_statevector(circ1, decimals=3), res2.get_statevector(circ2, decimals=3) print(f'Output of toffoli is: {s1}') print(f'Output of phase offset toffoli is: {s2}') print('\n') circ1 = QuantumCircuit(2) circ1.reset([0]) circ1.reset([1]) circ1.ry(np.pi/2, [1]) circ1.ry(np.pi/2, [0]) circ1.x([1]) circ1.cz([0], [1]) circ1.x([1]) circ1.ry(np.pi/2,[0]) circ2 = QuantumCircuit(2) circ2.reset([0]) circ2.reset([1]) circ2.h([0]) circ2.cx([0],[1]) res1, res2 = execute(circ1, sim).result(), execute(circ2, sim).result() display(circ1.draw('mpl')) display(circ2.draw('mpl')) # They both Produce the bell state sv1 = res1.get_statevector(circ1, decimals=3) sv2 = res2.get_statevector(circ2, decimals=3) display(plot_histogram(res1.get_counts())) display(plot_state_city(sv1)) display(plot_histogram(res2.get_counts())) display(plot_state_city(sv2)) # But they don't evalaute the same on the entire basis... circ1 = QuantumCircuit(2) circ1.initialize(Statevector.from_label('01').data, [0, 1]) circ1.ry(np.pi/2, [1]) circ1.ry(np.pi/2, [0]) circ1.x([1]) circ1.cz([0], [1]) circ1.x([1]) circ1.ry(np.pi/2,[0]) circ2 = QuantumCircuit(2) circ2.initialize(Statevector.from_label('01').data, [0, 1]) circ2.h([0]) circ2.cx([0],[1]) res1, res2 = execute(circ1, sim).result(), execute(circ2, sim).result() sv1 = res1.get_statevector(circ1, decimals=3) sv2 = res2.get_statevector(circ2, decimals=3) display(plot_histogram(res1.get_counts())) display(plot_state_city(sv1)) display(plot_histogram(res2.get_counts())) display(plot_state_city(sv2)) circ1 = QuantumCircuit(3) circ1.ry(np.pi/2, [0]) circ1.ry(np.pi/2, [1]) circ1.ry(np.pi/2, [2]) circ1.x([1]) circ1.cz([0], [1]) circ1.x([1]) circ1.x([1]) circ1.cz([2], [1]) circ1.x([1]) circ1.ry(np.pi/2, [0]) circ1.ry(np.pi/2, [2]) circ2 = QuantumCircuit(3) circ2.ry(np.pi/2, [0]) circ2.ry(np.pi/2, [1]) circ2.ry(np.pi/2, [2]) # we defined the iSwapGate in class to be the inverse of what qiskit defined it as circ2.append(iSwapGate().inverse(), [[0], [1]], []) circ2.append(iSwapGate().inverse(), [[1], [2]], []) circ2.rx(-np.pi/2, [0]) circ2.rx(-np.pi/2, [1]) circ3 = QuantumCircuit(3) circ3.h([0]) circ3.cx([0], [1]) circ3.cx([1], [2]) # On the state 000 results = [] circuits = [] for c in (circ1, circ2, circ3): circ = QuantumCircuit(3) circ.reset([0]) circ.reset([1]) circ.reset([2]) circ = circ + c display(circ.draw('mpl')) circuits.append(circ) results.append(execute(circ, sim).result()) sv1, sv2, sv3 = (results[i].get_statevector(circuits[i], decimals=3) for i in range(3)) res1, res2, res3 = results display(plot_histogram(res1.get_counts())) display(plot_state_city(sv1)) display(plot_histogram(res2.get_counts())) display(plot_state_city(sv2)) display(plot_histogram(res3.get_counts())) display(plot_state_city(sv3)) # but they're not the same on all basis states results = [] circuits = [] for c in (circ1, circ2, circ3): circ = QuantumCircuit(3) circ.initialize(Statevector.from_label('010').data, [0,1,2]) circ = circ + c circuits.append(circ) results.append(execute(circ, sim).result()) sv1, sv2, sv3 = (results[i].get_statevector(circuits[i], decimals=3) for i in range(3)) res1, res2, res3 = results display(plot_histogram(res1.get_counts())) display(plot_state_city(sv1)) display(plot_histogram(res2.get_counts())) display(plot_state_city(sv2)) display(plot_histogram(res3.get_counts())) display(plot_state_city(sv3)) # First need to make the exponential matrix operator from scipy.linalg import expm from qiskit.extensions import UnitaryGate sx = np.array([[0, 1],[1, 0]]) sy = np.array([[0, -1j],[1j, 0]]) sz = np.array([[1, 0],[0, -1]]) S = .5 * (np.kron(np.eye(2), np.kron(sx, sx)) + np.kron(sx, np.kron(np.eye(2), sx)) + np.kron(sx, np.kron(sx, np.eye(2))) + np.kron(np.eye(2), np.kron(sy, sy)) + np.kron(sy, np.kron(np.eye(2), sy)) + np.kron(sy, np.kron(sy, np.eye(2)))) G = UnitaryGate(expm(-1j * np.pi/2 * 4/9 * S), label = 'Exp') wcircuit = QuantumCircuit(3) wcircuit.reset([0]) wcircuit.reset([1]) wcircuit.reset([2]) wcircuit.x([1]) wcircuit.append(G, [[0], [1], [2]]) wcircuit.rz(4 * np.pi/3, [1]) wcircuit.draw('mpl') res = execute(wcircuit, sim).result() sv = res.get_statevector(wcircuit, decimals=3) display(plot_histogram(res.get_counts())) display(plot_state_city(sv)) a = '11' initphi = QuantumCircuit(3, 2) initphi.reset([0]) initphi.reset([1]) initphi.reset([2]) initphi.x([2]) initphi.h([0, 1, 2]) uf = QuantumCircuit(3, 2) uf.ccx([0], [1], [2]) grover = QuantumCircuit(3, 2) grover.h([0, 1]) grover.x([0, 1]) grover.cz([0], [1]) grover.x([0, 1]) grover.h([0, 1]) display(initphi.draw('mpl')) display(uf.draw('mpl')) display(grover.draw('mpl')) iterations = int((np.pi/4) * 2**2/2) circ = initphi for _ in range(iterations): circ = circ + uf + grover circ.measure([0, 1], [0, 1]) # on a qasm simulator qasm_sim = Aer.get_backend('qasm_simulator') shots = 1024 res = execute(circ, backend=qasm_sim, shots=shots).result() plot_histogram(res.get_counts()) # random state for testing rng_state = random_statevector(4) plot_state_qsphere(rng_state.data) circ1 = QuantumCircuit(4, 2) circ1.reset([0]) circ1.reset([1]) circ1.initialize(rng_state.data, [2, 3]) circ1.h([0, 1]) circ1.cx([0], [2]) circ1.cx([0], [3]) circ1.cz([1], [2]) circ1.cz([1], [3]) circ1.h([0, 1]) circ1.measure([0, 1], [0, 1]) circ2 = QuantumCircuit(4, 2) circ2.reset([0]) circ2.reset([1]) circ2.initialize(rng_state.data, [2, 3]) circ2.h([0]) circ2.cx([0], [2]) circ2.cx([0], [3]) circ2.h([0]) circ2.cx([2], [1]) circ2.cx([3], [1]) circ2.measure([0, 1], [0, 1]) display(circ1.draw('mpl')) display(circ2.draw('mpl')) # check that these circuits produce the same measurements shots = 1024 res = execute(circ1, backend=qasm_sim, shots=shots).result() plot_histogram(res.get_counts()) shots = 1024 res = execute(circ2, backend=qasm_sim, shots=shots).result() plot_histogram(res.get_counts()) psi = random_statevector(2) qr = QuantumRegister(4, 'q') cr = [ClassicalRegister(1, 'a'), ClassicalRegister(1, 'b')] circ = QuantumCircuit(qr) circ.add_register(cr[0]) circ.add_register(cr[1]) circ.reset(qr[0]) circ.reset(qr[2]) circ.reset(qr[3]) circ.initialize(psi.data, qr[1]) circ.t(qr[2]) circ.h(qr[0]) circ.cz(qr[0], qr[1]) circ.cz(qr[0], qr[2]) circ.h(qr[0]) circ.measure(qr[0], cr[0]) # This was my answer on the hw #circ.x(qr[1]).c_if(cr[0], 1) #circ.z(qr[1]).c_if(cr[0], 1) #circ.x(qr[1]).c_if(cr[0], 1) circ.unitary(UnitaryGate(expm(2 * 1j * np.pi/4 * sz)), [qr[1]],).c_if(cr[0], 1) circ.h(qr[3]) circ.cx(qr[3], qr[2]) circ.h(qr[3]) circ.measure(qr[3], cr[1]) #circ.x(qr[1]).c_if(cr[1], 1) #circ.z(qr[1]).c_if(cr[1], 1) #circ.x(qr[1]).c_if(cr[1], 1) circ.z(qr[1]).c_if(cr[1], 1) display(circ.draw('mpl')) result = execute(circ, sim).result() plot_histogram(result.get_counts()) sv = result.get_statevector(circ, decimals=3) print(sv) display(plot_state_qsphere(sv)) display(plot_bloch_multivector(sv)) # compare to just T gate circ2 = QuantumCircuit(1) circ2.initialize(psi.data, [0]) circ2.t([0]) result2 = execute(circ2, sim).result() sv2 = result2.get_statevector(circ2, decimals=3) plot_bloch_multivector(sv2) plot_histogram(result2.get_counts()) from qiskit.circuit.library import TGate, ZGate, RZGate circ1 = QuantumCircuit(3) circ1.cx([2], [1]) circ1.cx([1], [0]) circ1.t([0]) circ1.tdg([1]) circ1.t([2]) circ1.cx([2], [1]) circ1.cx([1], [0]) circ1.tdg([0]) circ1.cx([2], [0]) circ2 = QuantumCircuit(3) circ2.append(TGate().inverse().power(2).control(1, label='$S^\dagger$'), [0, 1]) circ2.append(ZGate().control(2), [0, 1, 2]) circ3 = QuantumCircuit(3) circ3.append(RZGate(np.pi).control(2), [0, 1, 2]) # equiv to -iZ display(circ1.draw('mpl')) display(circ2.draw('mpl')) display(circ3.draw('mpl')) # eval on random state psi = random_statevector(8) circuits = [] results = [] for c in (circ1, circ2, circ3): circ = QuantumCircuit(3) circ.initialize(psi.data, [0, 1, 2]) circ = circ + c circuits.append(circ) results.append(execute(circ, sim).result()) sv1, sv2, sv3 = [res.get_statevector(circ, decimals=3) for circ, res in zip(circuits, results)] res1, res2, res3 = results plot_histogram(res1.get_counts()) plot_histogram(res2.get_counts()) plot_histogram(res3.get_counts()) # I'll use a 7 bit circuit ==> P operates on 4 qubits, operators chosen at random from qiskit.circuit.library import XGate, YGate, ZGate import random from time import time random.seed(time()) # random composition of gates P = [[None, XGate(), YGate(), ZGate()][random.randint(0, 3)] for _ in range(4)] qr = QuantumRegister(7, 'q') cr = [ClassicalRegister(1, 'a'), ClassicalRegister(1, 'b')] circ = QuantumCircuit(qr) circ.add_register(cr[0]) circ.add_register(cr[1]) # initial states for i in range(7): circ.reset(qr[i]) # theta = pi/4 circ.t(qr[5]) # arbitrary input state to apply Ptheta to circ.x(qr[1]) circ.h(qr[2]) circ.x(qr[3]) circ.y(qr[4]) circ.h(qr[0]) for i, u in enumerate(P): if u is not None: circ.append(u.control(1), [qr[0],qr[i+1]]) circ.cz(qr[0], qr[5]) circ.h(qr[0]) circ.measure(qr[0], cr[0]) circ.h(qr[6]) circ.cx(qr[6], qr[5]) circ.h(qr[6]) circ.measure(qr[6], cr[1]) # O1 for i, u in enumerate(P): if u is not None: circ.append(UnitaryGate(expm(2 * 1j * np.pi/4 * u.to_matrix())).c_if(cr[0], 1), [qr[i + 1]]) # O2 for i, u in enumerate(P): if u is not None: circ.append(u.c_if(cr[1], 1), [qr[i+1]]) circ.draw('mpl') result = execute(circ, sim).result() sv = result.get_statevector(circ, decimals=3) print(sv) plot_histogram(result.get_counts()) plot_bloch_multivector(sv)
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """User-space constructor functions for the expression tree, which do some of the inference and lifting boilerplate work.""" # pylint: disable=redefined-builtin,redefined-outer-name from __future__ import annotations __all__ = [ "lift", "bit_not", "logic_not", "bit_and", "bit_or", "bit_xor", "logic_and", "logic_or", "equal", "not_equal", "less", "less_equal", "greater", "greater_equal", "lift_legacy_condition", ] import enum import typing from .expr import Expr, Var, Value, Unary, Binary, Cast from .. import types if typing.TYPE_CHECKING: import qiskit class _CastKind(enum.Enum): EQUAL = enum.auto() """The two types are equal; no cast node is required at all.""" IMPLICIT = enum.auto() """The 'from' type can be cast to the 'to' type implicitly. A ``Cast(implicit=True)`` node is the minimum required to specify this.""" LOSSLESS = enum.auto() """The 'from' type can be cast to the 'to' type explicitly, and the cast will be lossless. This requires a ``Cast(implicit=False)`` node, but there's no danger from inserting one.""" DANGEROUS = enum.auto() """The 'from' type has a defined cast to the 'to' type, but depending on the value, it may lose data. A user would need to manually specify casts.""" NONE = enum.auto() """There is no casting permitted from the 'from' type to the 'to' type.""" def _uint_cast(from_: types.Uint, to_: types.Uint, /) -> _CastKind: if from_.width == to_.width: return _CastKind.EQUAL if from_.width < to_.width: return _CastKind.LOSSLESS return _CastKind.DANGEROUS _ALLOWED_CASTS = { (types.Bool, types.Bool): lambda _a, _b, /: _CastKind.EQUAL, (types.Bool, types.Uint): lambda _a, _b, /: _CastKind.LOSSLESS, (types.Uint, types.Bool): lambda _a, _b, /: _CastKind.IMPLICIT, (types.Uint, types.Uint): _uint_cast, } def _cast_kind(from_: types.Type, to_: types.Type, /) -> _CastKind: if (coercer := _ALLOWED_CASTS.get((from_.kind, to_.kind))) is None: return _CastKind.NONE return coercer(from_, to_) def _coerce_lossless(expr: Expr, type: types.Type) -> Expr: """Coerce ``expr`` to ``type`` by inserting a suitable :class:`Cast` node, if the cast is lossless. Otherwise, raise a ``TypeError``.""" kind = _cast_kind(expr.type, type) if kind is _CastKind.EQUAL: return expr if kind is _CastKind.IMPLICIT: return Cast(expr, type, implicit=True) if kind is _CastKind.LOSSLESS: return Cast(expr, type, implicit=False) if kind is _CastKind.DANGEROUS: raise TypeError(f"cannot cast '{expr}' to '{type}' without loss of precision") raise TypeError(f"no cast is defined to take '{expr}' to '{type}'") def lift_legacy_condition( condition: tuple[qiskit.circuit.Clbit | qiskit.circuit.ClassicalRegister, int], / ) -> Expr: """Lift a legacy two-tuple equality condition into a new-style :class:`Expr`. Examples: Taking an old-style conditional instruction and getting an :class:`Expr` from its condition:: from qiskit.circuit import ClassicalRegister from qiskit.circuit.library import HGate from qiskit.circuit.classical import expr cr = ClassicalRegister(2) instr = HGate().c_if(cr, 3) lifted = expr.lift_legacy_condition(instr.condition) """ from qiskit.circuit import Clbit # pylint: disable=cyclic-import target, value = condition if isinstance(target, Clbit): bool_ = types.Bool() return Var(target, bool_) if value else Unary(Unary.Op.LOGIC_NOT, Var(target, bool_), bool_) left = Var(target, types.Uint(width=target.size)) if value.bit_length() > target.size: left = Cast(left, types.Uint(width=value.bit_length()), implicit=True) right = Value(value, left.type) return Binary(Binary.Op.EQUAL, left, right, types.Bool()) def lift(value: typing.Any, /, type: types.Type | None = None) -> Expr: """Lift the given Python ``value`` to a :class:`~.expr.Value` or :class:`~.expr.Var`. If an explicit ``type`` is given, the typing in the output will reflect that. Examples: Lifting simple circuit objects to be :class:`~.expr.Var` instances:: >>> from qiskit.circuit import Clbit, ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.lift(Clbit()) Var(<clbit>, Bool()) >>> expr.lift(ClassicalRegister(3, "c")) Var(ClassicalRegister(3, "c"), Uint(3)) The type of the return value can be influenced, if the given value could be interpreted losslessly as the given type (use :func:`cast` to perform a full set of casting operations, include lossy ones):: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr, types >>> expr.lift(ClassicalRegister(3, "c"), types.Uint(5)) Var(ClassicalRegister(3, "c"), Uint(5)) >>> expr.lift(5, types.Uint(4)) Value(5, Uint(4)) """ if isinstance(value, Expr): if type is not None: raise ValueError("use 'cast' to cast existing expressions, not 'lift'") return value from qiskit.circuit import Clbit, ClassicalRegister # pylint: disable=cyclic-import inferred: types.Type if value is True or value is False or isinstance(value, Clbit): inferred = types.Bool() constructor = Value if value is True or value is False else Var elif isinstance(value, ClassicalRegister): inferred = types.Uint(width=value.size) constructor = Var elif isinstance(value, int): if value < 0: raise ValueError("cannot represent a negative value") inferred = types.Uint(width=value.bit_length() or 1) constructor = Value else: raise TypeError(f"failed to infer a type for '{value}'") if type is None: type = inferred if types.is_supertype(type, inferred): return constructor(value, type) raise TypeError( f"the explicit type '{type}' is not suitable for representing '{value}';" f" it must be non-strict supertype of '{inferred}'" ) def cast(operand: typing.Any, type: types.Type, /) -> Expr: """Create an explicit cast from the given value to the given type. Examples: Add an explicit cast node that explicitly casts a higher precision type to a lower precision one:: >>> from qiskit.circuit.classical import expr, types >>> value = expr.value(5, types.Uint(32)) >>> expr.cast(value, types.Uint(8)) Cast(Value(5, types.Uint(32)), types.Uint(8), implicit=False) """ operand = lift(operand) if _cast_kind(operand.type, type) is _CastKind.NONE: raise TypeError(f"cannot cast '{operand}' to '{type}'") return Cast(operand, type) def bit_not(operand: typing.Any, /) -> Expr: """Create a bitwise 'not' expression node from the given value, resolving any implicit casts and lifting the value into a :class:`Value` node if required. Examples: Bitwise negation of a :class:`.ClassicalRegister`:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.bit_not(ClassicalRegister(3, "c")) Unary(Unary.Op.BIT_NOT, Var(ClassicalRegister(3, 'c'), Uint(3)), Uint(3)) """ operand = lift(operand) if operand.type.kind not in (types.Bool, types.Uint): raise TypeError(f"cannot apply '{Unary.Op.BIT_NOT}' to type '{operand.type}'") return Unary(Unary.Op.BIT_NOT, operand, operand.type) def logic_not(operand: typing.Any, /) -> Expr: """Create a logical 'not' expression node from the given value, resolving any implicit casts and lifting the value into a :class:`Value` node if required. Examples: Logical negation of a :class:`.ClassicalRegister`:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.logic_not(ClassicalRegister(3, "c")) Unary(\ Unary.Op.LOGIC_NOT, \ Cast(Var(ClassicalRegister(3, 'c'), Uint(3)), Bool(), implicit=True), \ Bool()) """ operand = _coerce_lossless(lift(operand), types.Bool()) return Unary(Unary.Op.LOGIC_NOT, operand, operand.type) def _lift_binary_operands(left: typing.Any, right: typing.Any) -> tuple[Expr, Expr]: """Lift two binary operands simultaneously, inferring the widths of integer literals in either position to match the other operand.""" left_int = isinstance(left, int) and not isinstance(left, bool) right_int = isinstance(right, int) and not isinstance(right, bool) if not (left_int or right_int): left = lift(left) right = lift(right) elif not right_int: right = lift(right) if right.type.kind is types.Uint: if left.bit_length() > right.type.width: raise TypeError( f"integer literal '{left}' is wider than the other operand '{right}'" ) left = Value(left, right.type) else: left = lift(left) elif not left_int: left = lift(left) if left.type.kind is types.Uint: if right.bit_length() > left.type.width: raise TypeError( f"integer literal '{right}' is wider than the other operand '{left}'" ) right = Value(right, left.type) else: right = lift(right) else: # Both are `int`, so we take our best case to make things work. uint = types.Uint(max(left.bit_length(), right.bit_length(), 1)) left = Value(left, uint) right = Value(right, uint) return left, right def _binary_bitwise(op: Binary.Op, left: typing.Any, right: typing.Any) -> Expr: left, right = _lift_binary_operands(left, right) type: types.Type if left.type.kind is right.type.kind is types.Bool: type = types.Bool() elif left.type.kind is types.Uint and right.type.kind is types.Uint: if left.type != right.type: raise TypeError( "binary bitwise operations are defined between unsigned integers of the same width," f" but got {left.type.width} and {right.type.width}." ) type = left.type else: raise TypeError(f"invalid types for '{op}': '{left.type}' and '{right.type}'") return Binary(op, left, right, type) def bit_and(left: typing.Any, right: typing.Any, /) -> Expr: """Create a bitwise 'and' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Bitwise 'and' of a classical register and an integer literal:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.bit_and(ClassicalRegister(3, "c"), 0b111) Binary(\ Binary.Op.BIT_AND, \ Var(ClassicalRegister(3, 'c'), Uint(3)), \ Value(7, Uint(3)), \ Uint(3)) """ return _binary_bitwise(Binary.Op.BIT_AND, left, right) def bit_or(left: typing.Any, right: typing.Any, /) -> Expr: """Create a bitwise 'or' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Bitwise 'or' of a classical register and an integer literal:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.bit_or(ClassicalRegister(3, "c"), 0b101) Binary(\ Binary.Op.BIT_OR, \ Var(ClassicalRegister(3, 'c'), Uint(3)), \ Value(5, Uint(3)), \ Uint(3)) """ return _binary_bitwise(Binary.Op.BIT_OR, left, right) def bit_xor(left: typing.Any, right: typing.Any, /) -> Expr: """Create a bitwise 'exclusive or' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Bitwise 'exclusive or' of a classical register and an integer literal:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.bit_xor(ClassicalRegister(3, "c"), 0b101) Binary(\ Binary.Op.BIT_XOR, \ Var(ClassicalRegister(3, 'c'), Uint(3)), \ Value(5, Uint(3)), \ Uint(3)) """ return _binary_bitwise(Binary.Op.BIT_XOR, left, right) def _binary_logical(op: Binary.Op, left: typing.Any, right: typing.Any) -> Expr: bool_ = types.Bool() left = _coerce_lossless(lift(left), bool_) right = _coerce_lossless(lift(right), bool_) return Binary(op, left, right, bool_) def logic_and(left: typing.Any, right: typing.Any, /) -> Expr: """Create a logical 'and' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Logical 'and' of two classical bits:: >>> from qiskit.circuit import Clbit >>> from qiskit.circuit.classical import expr >>> expr.logical_and(Clbit(), Clbit()) Binary(Binary.Op.LOGIC_AND, Var(<clbit 0>, Bool()), Var(<clbit 1>, Bool()), Bool()) """ return _binary_logical(Binary.Op.LOGIC_AND, left, right) def logic_or(left: typing.Any, right: typing.Any, /) -> Expr: """Create a logical 'or' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Logical 'or' of two classical bits >>> from qiskit.circuit import Clbit >>> from qiskit.circuit.classical import expr >>> expr.logical_and(Clbit(), Clbit()) Binary(Binary.Op.LOGIC_OR, Var(<clbit 0>, Bool()), Var(<clbit 1>, Bool()), Bool()) """ return _binary_logical(Binary.Op.LOGIC_OR, left, right) def _equal_like(op: Binary.Op, left: typing.Any, right: typing.Any) -> Expr: left, right = _lift_binary_operands(left, right) if left.type.kind is not right.type.kind: raise TypeError(f"invalid types for '{op}': '{left.type}' and '{right.type}'") type = types.greater(left.type, right.type) return Binary(op, _coerce_lossless(left, type), _coerce_lossless(right, type), types.Bool()) def equal(left: typing.Any, right: typing.Any, /) -> Expr: """Create an 'equal' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Equality between a classical register and an integer:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.equal(ClassicalRegister(3, "c"), 7) Binary(Binary.Op.EQUAL, \ Var(ClassicalRegister(3, "c"), Uint(3)), \ Value(7, Uint(3)), \ Uint(3)) """ return _equal_like(Binary.Op.EQUAL, left, right) def not_equal(left: typing.Any, right: typing.Any, /) -> Expr: """Create a 'not equal' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Inequality between a classical register and an integer:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.not_equal(ClassicalRegister(3, "c"), 7) Binary(Binary.Op.NOT_EQUAL, \ Var(ClassicalRegister(3, "c"), Uint(3)), \ Value(7, Uint(3)), \ Uint(3)) """ return _equal_like(Binary.Op.NOT_EQUAL, left, right) def _binary_relation(op: Binary.Op, left: typing.Any, right: typing.Any) -> Expr: left, right = _lift_binary_operands(left, right) if left.type.kind is not right.type.kind or left.type.kind is types.Bool: raise TypeError(f"invalid types for '{op}': '{left.type}' and '{right.type}'") type = types.greater(left.type, right.type) return Binary(op, _coerce_lossless(left, type), _coerce_lossless(right, type), types.Bool()) def less(left: typing.Any, right: typing.Any, /) -> Expr: """Create a 'less than' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Query if a classical register is less than an integer:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.less(ClassicalRegister(3, "c"), 5) Binary(Binary.Op.LESS, \ Var(ClassicalRegister(3, "c"), Uint(3)), \ Value(5, Uint(3)), \ Uint(3)) """ return _binary_relation(Binary.Op.LESS, left, right) def less_equal(left: typing.Any, right: typing.Any, /) -> Expr: """Create a 'less than or equal to' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Query if a classical register is less than or equal to another:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.less(ClassicalRegister(3, "a"), ClassicalRegister(3, "b")) Binary(Binary.Op.LESS_EQUAL, \ Var(ClassicalRegister(3, "a"), Uint(3)), \ Var(ClassicalRegister(3, "b"), Uint(3)), \ Uint(3)) """ return _binary_relation(Binary.Op.LESS_EQUAL, left, right) def greater(left: typing.Any, right: typing.Any, /) -> Expr: """Create a 'greater than' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Query if a classical register is greater than an integer:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.less(ClassicalRegister(3, "c"), 5) Binary(Binary.Op.GREATER, \ Var(ClassicalRegister(3, "c"), Uint(3)), \ Value(5, Uint(3)), \ Uint(3)) """ return _binary_relation(Binary.Op.GREATER, left, right) def greater_equal(left: typing.Any, right: typing.Any, /) -> Expr: """Create a 'greater than or equal to' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Query if a classical register is greater than or equal to another:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.less(ClassicalRegister(3, "a"), ClassicalRegister(3, "b")) Binary(Binary.Op.GREATER_EQUAL, \ Var(ClassicalRegister(3, "a"), Uint(3)), \ Var(ClassicalRegister(3, "b"), Uint(3)), \ Uint(3)) """ return _binary_relation(Binary.Op.GREATER_EQUAL, left, right)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit.library import QFT def create_qpe_circuit(theta, num_qubits): '''Creates a QPE circuit given theta and num_qubits.''' # Step 1: Create a circuit with two quantum registers and one classical register. first = QuantumRegister(size=num_qubits, name='first') # the first register for phase estimation second = QuantumRegister(size=1, name='second') # the second register for storing eigenvector |psi> classical = ClassicalRegister(size=num_qubits, name='readout') # classical register for readout qpe_circuit = QuantumCircuit(first, second, classical) # Step 2: Initialize the qubits. # All qubits are initialized in |0> by default, no extra code is needed to initialize the first register. qpe_circuit.x(second) # Initialize the second register with state |psi>, which is |1> in this example. # Step 3: Create superposition in the first register. qpe_circuit.barrier() # Add barriers to separate each step of the algorithm for better visualization. qpe_circuit.h(first) # Step 4: Apply a controlled-U^(2^j) black box. qpe_circuit.barrier() for j in range(num_qubits): qpe_circuit.cp(theta*2*np.pi*(2**j), j, num_qubits) # Theta doesn't contain the 2 pi factor. # Step 5: Apply an inverse QFT to the first register. qpe_circuit.barrier() qpe_circuit.compose(QFT(num_qubits, inverse=True), inplace=True) # Step 6: Measure the first register. qpe_circuit.barrier() qpe_circuit.measure(first, classical) return qpe_circuit num_qubits = 4 qpe_circuit_fixed_phase = create_qpe_circuit(1/2, num_qubits) # Create a QPE circuit with fixed theta=1/2. qpe_circuit_fixed_phase.draw('mpl') from qiskit.circuit import Parameter theta = Parameter('theta') # Create a parameter `theta` whose values can be assigned later. qpe_circuit_parameterized = create_qpe_circuit(theta, num_qubits) qpe_circuit_parameterized.draw('mpl') number_of_phases = 21 phases = np.linspace(0, 2, number_of_phases) individual_phases = [[ph] for ph in phases] # Phases need to be expressed as a list of lists. from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService() backend = "ibmq_qasm_simulator" # use the simulator from qiskit_ibm_runtime import Sampler, Session with Session(service=service, backend=backend): results = Sampler().run( [qpe_circuit_parameterized]*len(individual_phases), parameter_values=individual_phases ).result() from qiskit.tools.visualization import plot_histogram idx = 6 plot_histogram(results.quasi_dists[idx].binary_probabilities(), legend=[f'$\\theta$={phases[idx]:.3f}']) def most_likely_bitstring(results_dict): '''Finds the most likely outcome bit string from a result dictionary.''' return max(results_dict, key=results_dict.get) def find_neighbors(bitstring): '''Finds the neighbors of a bit string. Example: For bit string '1010', this function returns ('1001', '1011') ''' if bitstring == len(bitstring)*'0': neighbor_left = len(bitstring)*'1' else: neighbor_left = format((int(bitstring,2)-1), '0%sb'%len(bitstring)) if bitstring == len(bitstring)*'1': neighbor_right = len(bitstring)*'0' else: neighbor_right = format((int(bitstring,2)+1), '0%sb'%len(bitstring)) return (neighbor_left, neighbor_right) def estimate_phase(results_dict): '''Estimates the phase from a result dictionary of a QPE circuit.''' # Find the most likely outcome bit string N1 and its neighbors. num_1_key = most_likely_bitstring(results_dict) neighbor_left, neighbor_right = find_neighbors(num_1_key) # Get probabilities of N1 and its neighbors. num_1_prob = results_dict.get(num_1_key) neighbor_left_prob = results_dict.get(neighbor_left) neighbor_right_prob = results_dict.get(neighbor_right) # Find the second most likely outcome N2 and its probability P2 among the neighbors. if neighbor_left_prob is None: # neighbor_left doesn't exist if neighbor_right_prob is None: # both neighbors don't exist, N2 is N1 num_2_key = num_1_key num_2_prob = num_1_prob else: # If only neighbor_left doesn't exist, N2 is neighbor_right. num_2_key = neighbor_right num_2_prob = neighbor_right_prob elif neighbor_right_prob is None: # If only neighbor_right doesn't exist, N2 is neighbor_left. num_2_key = neighbor_left num_2_prob = neighbor_left_prob elif neighbor_left_prob > neighbor_right_prob: # Both neighbors exist and neighbor_left has higher probability, so N2 is neighbor_left. num_2_key = neighbor_left num_2_prob = neighbor_left_prob else: # Both neighbors exist and neighbor_right has higher probability, so N2 is neighor_right. num_2_key = neighbor_right num_2_prob = neighbor_right_prob # Calculate the estimated phases for N1 and N2. num_qubits = len(num_1_key) num_1_phase = (int(num_1_key, 2) / 2**num_qubits) num_2_phase = (int(num_2_key, 2) / 2**num_qubits) # Calculate the weighted average phase from N1 and N2. phase_estimated = (num_1_phase * num_1_prob + num_2_phase * num_2_prob) / (num_1_prob + num_2_prob) return phase_estimated qpe_solutions = [] for idx, result_dict in enumerate(results.quasi_dists): qpe_solutions.append(estimate_phase(result_dict.binary_probabilities())) ideal_solutions = np.append( phases[:(number_of_phases-1)//2], # first period np.subtract(phases[(number_of_phases-1)//2:-1], 1) # second period ) ideal_solutions = np.append(ideal_solutions, np.subtract(phases[-1], 2)) # starting point of the third period import matplotlib.pyplot as plt fig = plt.figure(figsize=(10, 6)) plt.plot(phases, ideal_solutions, '--', label='Ideal solutions') plt.plot(phases, qpe_solutions, 'o', label='QPE solutions') plt.title('Quantum Phase Estimation Algorithm') plt.xlabel('Input Phase') plt.ylabel('Output Phase') plt.legend() import qiskit_ibm_runtime qiskit_ibm_runtime.version.get_version_info() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": ### replaced z gate ### qc.x(qubit) return qc def decode_message(qc): qc.cx(1, 0) qc.h(1) return qc
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector qc = QuantumCircuit(2) qc.h(0) qc.x(1) # You can reverse the order of the qubits. from qiskit.quantum_info import DensityMatrix qc = QuantumCircuit(2) qc.h([0, 1]) qc.t(1) qc.s(0) qc.cx(0,1) matrix = DensityMatrix(qc) plot_bloch_multivector(matrix, title='My Bloch Spheres', reverse_bits=True)
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() # 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 # the same spect pulse used in every schedule drive_amp = 0.9 drive_sigma = 16 drive_duration = 128 spec_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp, sigma=drive_sigma, name=f"Spec drive amplitude = {drive_amp}") # Construct an np array of the frequencies for our experiment spec_freqs_GHz = np.arange(5.0, 5.2, 0.005) # Create the base schedule # Start with drive pulse acting on the drive channel spec_schedules = [] for freq in spec_freqs_GHz: sb_spec_pulse = helper.apply_sideband(spec_pulse, qubit_lo_freq[0]-freq*GHz, dt) spec_schedule = pulse.Schedule(name='SB Frequency = {}'.format(freq)) spec_schedule += Play(sb_spec_pulse, drive_chan) # The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration spec_schedule += measure << spec_schedule.duration spec_schedules.append(spec_schedule) spec_schedules[0].draw() from qiskit import assemble # assemble the schedules into a Qobj spec01_qobj = assemble(**helper.get_params('spec01', globals())) # run the simulation spec01_result = backend_sim.run(spec01_qobj, duffing_model).result() # retrieve the data from the experiment spec01_values = helper.get_values_from_result(spec01_result, qubit) fit_params, y_fit = helper.fit_lorentzian(spec_freqs_GHz, spec01_values, [5, 5, 1, 0]) f01 = fit_params[1] plt.scatter(spec_freqs_GHz, np.real(spec01_values), color='white') # plot real part of sweep values plt.plot(spec_freqs_GHz, y_fit, color='red') plt.xlim([min(spec_freqs_GHz), max(spec_freqs_GHz)]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured Signal [a.u.]") plt.show() print("01 Spectroscopy yields %f GHz"%f01) x180_amp = 0.629070 #from lab 6 Rabi experiment x_pulse = pulse_lib.gaussian(duration=drive_duration, amp=x180_amp, sigma=drive_sigma, name='x_pulse') anharmonicity_guess_GHz = -0.3 def build_spec12_pulse_schedule(freq): sb12_spec_pulse = helper.apply_sideband(spec_pulse, (freq + anharmonicity_guess_GHz)*GHz, dt) ### create a 12 spectroscopy pulse schedule spec12_schedule (already done) ### play an x pulse on the drive channel ### play sidebanded spec pulse on the drive channel ### add measurement pulse to schedule spec12_schedule = pulse.Schedule() ### WRITE YOUR CODE BETWEEN THESE LINES - START spec12_schedule += Play(x_pulse, drive_chan) spec12_schedule += Play(sb12_spec_pulse, drive_chan) spec12_schedule += measure << spec12_schedule.duration ### WRITE YOUR CODE BETWEEN THESE LINES - STOP return spec12_schedule sb_freqs_GHz = np.arange(-.1, .1, 0.005) # sweep +/- 100 MHz around guess # now vary the sideband frequency for each spec pulse spec_schedules = [] for freq in sb_freqs_GHz: spec_schedules.append(build_spec12_pulse_schedule(freq)) spec_schedules[0].draw() # assemble the schedules into a Qobj spec12_qobj = assemble(**helper.get_params('spec12', globals())) answer1 = spec12_qobj # run the simulation spec12_result = backend_sim.run(spec12_qobj, duffing_model).result() # retrieve the data from the experiment spec12_values = helper.get_values_from_result(spec12_result, qubit) anharm_offset = qubit_lo_freq[0]/GHz + anharmonicity_guess_GHz fit_params, y_fit = helper.fit_lorentzian(anharm_offset + sb_freqs_GHz, spec12_values, [5, 4.5, .1, 3]) f12 = fit_params[1] plt.scatter(anharm_offset + sb_freqs_GHz, np.real(spec12_values), color='white') # plot real part of sweep values plt.plot(anharm_offset + sb_freqs_GHz, y_fit, color='red') plt.xlim([anharm_offset + min(sb_freqs_GHz), anharm_offset + max(sb_freqs_GHz)]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured Signal [a.u.]") plt.show() print("12 Spectroscopy yields %f GHz"%f12) print("Measured transmon anharmonicity is %f MHz"%((f12-f01)*GHz/MHz)) 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/Pitt-JonesLab/mirror-gates
Pitt-JonesLab
from qiskit.transpiler.coupling import CouplingMap from mirror_gates.pass_managers import Mirage, QiskitLevel3 from qiskit.transpiler import PassManager from mirror_gates.logging import transpile_benchy_logger from mirror_gates.sqiswap_decomposer import SiSwapDecomposePass from qiskit.transpiler.passmanager import PassManager from qiskit.transpiler.passes import Optimize1qGatesDecomposition N = 3 # coupling_map = FakeQuitoV2().target.build_coupling_map() # coupling_map = CouplingMap.from_heavy_hex(5) coupling_map = CouplingMap.from_line(N) # coupling_map = CouplingMap.from_heavy_hex(5) # coupling_map = CouplingMap.from_grid(3, 3) # coupling_map.draw() cx_basis = False from transpile_benchy.library import CircuitLibrary lib = CircuitLibrary(circuit_list=[]) qc = lib.get_circuit("fredkin_n3") qc = qc.decompose() # display(qc.draw("mpl", fold=-1)) runner = Mirage( coupling_map, cx_basis=cx_basis, logger=transpile_benchy_logger, ) routed = runner.run(qc) if not cx_basis: decomposer = PassManager() decomposer.append(SiSwapDecomposePass()) decomposer.append(Optimize1qGatesDecomposition()) mirage_output = decomposer.run(routed) else: mirage_output = routed # mirage_output.draw("mpl", fold=-1) runner = QiskitLevel3(coupling_map, cx_basis=cx_basis) routed = runner.run(qc) if not cx_basis: decomposer = PassManager() decomposer.append(SiSwapDecomposePass()) decomposer.append(Optimize1qGatesDecomposition()) qiskit_output = decomposer.run(routed) else: qiskit_output = routed # qiskit_output.draw("mpl", fold=-1) from mirror_gates.noisy_fidelity import get_noisy_fidelity a, b, c, d = get_noisy_fidelity(qiskit_output, coupling_map) print(f"Fidelity: {a:.3f}, Duration: {b:.3f}") # display(c.draw("mpl", fold=-1)) a, b, c, d = get_noisy_fidelity(mirage_output, coupling_map) print(f"Fidelity: {a:.3f}, Duration: {b:.3f}") # display(c.draw("mpl", fold=-1))
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. """ Special data types. """ from enum import Enum from typing import NamedTuple, List, Union, NewType, Tuple, Dict from qiskit import circuit ScheduledGate = NamedTuple( "ScheduledGate", [ ("t0", int), ("operand", circuit.Gate), ("duration", int), ("bits", List[Union[circuit.Qubit, circuit.Clbit]]), ("bit_position", int), ], ) ScheduledGate.__doc__ = "A gate instruction with embedded time." ScheduledGate.t0.__doc__ = "Time when the instruction is issued." ScheduledGate.operand.__doc__ = "Gate object associated with the gate." ScheduledGate.duration.__doc__ = "Time duration of the instruction." ScheduledGate.bits.__doc__ = "List of bit associated with the gate." ScheduledGate.bit_position.__doc__ = "Position of bit associated with this drawing source." GateLink = NamedTuple( "GateLink", [("t0", int), ("opname", str), ("bits", List[Union[circuit.Qubit, circuit.Clbit]])] ) GateLink.__doc__ = "Dedicated object to represent a relationship between instructions." GateLink.t0.__doc__ = "A position where the link is placed." GateLink.opname.__doc__ = "Name of gate associated with this link." GateLink.bits.__doc__ = "List of bit associated with the instruction." Barrier = NamedTuple( "Barrier", [("t0", int), ("bits", List[Union[circuit.Qubit, circuit.Clbit]]), ("bit_position", int)], ) Barrier.__doc__ = "Dedicated object to represent a barrier instruction." Barrier.t0.__doc__ = "A position where the barrier is placed." Barrier.bits.__doc__ = "List of bit associated with the instruction." Barrier.bit_position.__doc__ = "Position of bit associated with this drawing source." HorizontalAxis = NamedTuple( "HorizontalAxis", [("window", Tuple[int, int]), ("axis_map", Dict[int, int]), ("label", str)] ) HorizontalAxis.__doc__ = "Data to represent configuration of horizontal axis." HorizontalAxis.window.__doc__ = "Left and right edge of graph." HorizontalAxis.axis_map.__doc__ = "Mapping of apparent coordinate system and actual location." HorizontalAxis.label.__doc__ = "Label of horizontal axis." class BoxType(str, Enum): """Box type. SCHED_GATE: Box that represents occupation time by gate. DELAY: Box associated with delay. TIMELINE: Box that represents time slot of a bit. """ SCHED_GATE = "Box.ScheduledGate" DELAY = "Box.Delay" TIMELINE = "Box.Timeline" class LineType(str, Enum): """Line type. BARRIER: Line that represents barrier instruction. GATE_LINK: Line that represents a link among gates. """ BARRIER = "Line.Barrier" GATE_LINK = "Line.GateLink" class SymbolType(str, Enum): """Symbol type. FRAME: Symbol that represents zero time frame change (Rz) instruction. """ FRAME = "Symbol.Frame" class LabelType(str, Enum): """Label type. GATE_NAME: Label that represents name of gate. DELAY: Label associated with delay. GATE_PARAM: Label that represents parameter of gate. BIT_NAME: Label that represents name of bit. """ GATE_NAME = "Label.Gate.Name" DELAY = "Label.Delay" GATE_PARAM = "Label.Gate.Param" BIT_NAME = "Label.Bit.Name" class AbstractCoordinate(Enum): """Abstract coordinate that the exact value depends on the user preference. RIGHT: The horizontal coordinate at t0 shifted by the left margin. LEFT: The horizontal coordinate at tf shifted by the right margin. TOP: The vertical coordinate at the top of the canvas. BOTTOM: The vertical coordinate at the bottom of the canvas. """ RIGHT = "RIGHT" LEFT = "LEFT" TOP = "TOP" BOTTOM = "BOTTOM" class Plotter(str, Enum): """Name of timeline plotter APIs. MPL: Matplotlib plotter interface. Show timeline in 2D canvas. """ MPL = "mpl" # convenient type to represent union of drawing data DataTypes = NewType("DataType", Union[BoxType, LabelType, LineType, SymbolType]) # convenient type to represent union of values to represent a coordinate Coordinate = NewType("Coordinate", Union[float, AbstractCoordinate]) # Valid bit objects Bits = NewType("Bits", Union[circuit.Qubit, circuit.Clbit])
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test pulse builder context utilities.""" from math import pi import numpy as np from qiskit import circuit, compiler, pulse from qiskit.pulse import builder, exceptions, macros from qiskit.pulse.instructions import directives from qiskit.pulse.transforms import target_qobj_transform from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeOpenPulse2Q from qiskit.providers.fake_provider.utils.configurable_backend import ( ConfigurableFakeBackend as ConfigurableBackend, ) from qiskit.pulse import library, instructions class TestBuilder(QiskitTestCase): """Test the pulse builder context.""" def setUp(self): super().setUp() self.backend = FakeOpenPulse2Q() self.configuration = self.backend.configuration() self.defaults = self.backend.defaults() self.inst_map = self.defaults.instruction_schedule_map def assertScheduleEqual(self, program, target): """Assert an error when two pulse programs are not equal. .. note:: Two programs are converted into standard execution format then compared. """ self.assertEqual(target_qobj_transform(program), target_qobj_transform(target)) class TestBuilderBase(TestBuilder): """Test builder base.""" def test_schedule_supplied(self): """Test that schedule is used if it is supplied to the builder.""" d0 = pulse.DriveChannel(0) with pulse.build(name="reference") as reference: with pulse.align_sequential(): pulse.delay(10, d0) with pulse.build(schedule=reference) as schedule: pass self.assertScheduleEqual(schedule, reference) self.assertEqual(schedule.name, "reference") def test_default_alignment_left(self): """Test default left alignment setting.""" d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(0) with pulse.build(default_alignment="left") as schedule: pulse.delay(10, d0) pulse.delay(20, d1) with pulse.build(self.backend) as reference: with pulse.align_left(): pulse.delay(10, d0) pulse.delay(20, d1) self.assertScheduleEqual(schedule, reference) def test_default_alignment_right(self): """Test default right alignment setting.""" d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(0) with pulse.build(default_alignment="right") as schedule: pulse.delay(10, d0) pulse.delay(20, d1) with pulse.build() as reference: with pulse.align_right(): pulse.delay(10, d0) pulse.delay(20, d1) self.assertScheduleEqual(schedule, reference) def test_default_alignment_sequential(self): """Test default sequential alignment setting.""" d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(0) with pulse.build(default_alignment="sequential") as schedule: pulse.delay(10, d0) pulse.delay(20, d1) with pulse.build() as reference: with pulse.align_sequential(): pulse.delay(10, d0) pulse.delay(20, d1) self.assertScheduleEqual(schedule, reference) class TestContexts(TestBuilder): """Test builder contexts.""" def test_align_sequential(self): """Test the sequential alignment context.""" d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as schedule: with pulse.align_sequential(): pulse.delay(3, d0) pulse.delay(5, d1) pulse.delay(7, d0) reference = pulse.Schedule() # d0 reference.insert(0, instructions.Delay(3, d0), inplace=True) reference.insert(8, instructions.Delay(7, d0), inplace=True) # d1 reference.insert(3, instructions.Delay(5, d1), inplace=True) self.assertScheduleEqual(schedule, reference) def test_align_left(self): """Test the left alignment context.""" d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) d2 = pulse.DriveChannel(2) with pulse.build() as schedule: with pulse.align_left(): pulse.delay(11, d2) pulse.delay(3, d0) with pulse.align_left(): pulse.delay(5, d1) pulse.delay(7, d0) reference = pulse.Schedule() # d0 reference.insert(0, instructions.Delay(3, d0), inplace=True) reference.insert(3, instructions.Delay(7, d0), inplace=True) # d1 reference.insert(3, instructions.Delay(5, d1), inplace=True) # d2 reference.insert(0, instructions.Delay(11, d2), inplace=True) self.assertScheduleEqual(schedule, reference) def test_align_right(self): """Test the right alignment context.""" d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) d2 = pulse.DriveChannel(2) with pulse.build() as schedule: with pulse.align_right(): with pulse.align_right(): pulse.delay(11, d2) pulse.delay(3, d0) pulse.delay(13, d0) pulse.delay(5, d1) reference = pulse.Schedule() # d0 reference.insert(8, instructions.Delay(3, d0), inplace=True) reference.insert(11, instructions.Delay(13, d0), inplace=True) # d1 reference.insert(19, instructions.Delay(5, d1), inplace=True) # d2 reference.insert(0, instructions.Delay(11, d2), inplace=True) self.assertScheduleEqual(schedule, reference) def test_transpiler_settings(self): """Test the transpiler settings context. Tests that two cx gates are optimized away with higher optimization level. """ twice_cx_qc = circuit.QuantumCircuit(2) twice_cx_qc.cx(0, 1) twice_cx_qc.cx(0, 1) with pulse.build(self.backend) as schedule: with pulse.transpiler_settings(optimization_level=0): builder.call(twice_cx_qc) self.assertNotEqual(len(schedule.instructions), 0) with pulse.build(self.backend) as schedule: with pulse.transpiler_settings(optimization_level=3): builder.call(twice_cx_qc) self.assertEqual(len(schedule.instructions), 0) def test_scheduler_settings(self): """Test the circuit scheduler settings context.""" inst_map = pulse.InstructionScheduleMap() d0 = pulse.DriveChannel(0) test_x_sched = pulse.Schedule() test_x_sched += instructions.Delay(10, d0) inst_map.add("x", (0,), test_x_sched) ref_sched = pulse.Schedule() with self.assertWarns(DeprecationWarning): ref_sched += pulse.instructions.Call(test_x_sched) x_qc = circuit.QuantumCircuit(2) x_qc.x(0) with pulse.build(backend=self.backend) as schedule: with pulse.transpiler_settings(basis_gates=["x"]): with pulse.circuit_scheduler_settings(inst_map=inst_map): builder.call(x_qc) self.assertScheduleEqual(schedule, ref_sched) def test_phase_offset(self): """Test the phase offset context.""" d0 = pulse.DriveChannel(0) with pulse.build() as schedule: with pulse.phase_offset(3.14, d0): pulse.delay(10, d0) reference = pulse.Schedule() reference += instructions.ShiftPhase(3.14, d0) reference += instructions.Delay(10, d0) reference += instructions.ShiftPhase(-3.14, d0) self.assertScheduleEqual(schedule, reference) def test_frequency_offset(self): """Test the frequency offset context.""" d0 = pulse.DriveChannel(0) with pulse.build() as schedule: with pulse.frequency_offset(1e9, d0): pulse.delay(10, d0) reference = pulse.Schedule() reference += instructions.ShiftFrequency(1e9, d0) reference += instructions.Delay(10, d0) reference += instructions.ShiftFrequency(-1e9, d0) self.assertScheduleEqual(schedule, reference) def test_phase_compensated_frequency_offset(self): """Test that the phase offset context properly compensates for phase accumulation.""" d0 = pulse.DriveChannel(0) with pulse.build(self.backend) as schedule: with pulse.frequency_offset(1e9, d0, compensate_phase=True): pulse.delay(10, d0) reference = pulse.Schedule() reference += instructions.ShiftFrequency(1e9, d0) reference += instructions.Delay(10, d0) reference += instructions.ShiftPhase( -2 * np.pi * ((1e9 * 10 * self.configuration.dt) % 1), d0 ) reference += instructions.ShiftFrequency(-1e9, d0) self.assertScheduleEqual(schedule, reference) class TestChannels(TestBuilder): """Test builder channels.""" def test_drive_channel(self): """Text context builder drive channel.""" with pulse.build(self.backend): self.assertEqual(pulse.drive_channel(0), pulse.DriveChannel(0)) def test_measure_channel(self): """Text context builder measure channel.""" with pulse.build(self.backend): self.assertEqual(pulse.measure_channel(0), pulse.MeasureChannel(0)) def test_acquire_channel(self): """Text context builder acquire channel.""" with pulse.build(self.backend): self.assertEqual(pulse.acquire_channel(0), pulse.AcquireChannel(0)) def test_control_channel(self): """Text context builder control channel.""" with pulse.build(self.backend): self.assertEqual(pulse.control_channels(0, 1)[0], pulse.ControlChannel(0)) class TestInstructions(TestBuilder): """Test builder instructions.""" def test_delay(self): """Test delay instruction.""" d0 = pulse.DriveChannel(0) with pulse.build() as schedule: pulse.delay(10, d0) reference = pulse.Schedule() reference += instructions.Delay(10, d0) self.assertScheduleEqual(schedule, reference) def test_play_parametric_pulse(self): """Test play instruction with parametric pulse.""" d0 = pulse.DriveChannel(0) test_pulse = library.Constant(10, 1.0) with pulse.build() as schedule: pulse.play(test_pulse, d0) reference = pulse.Schedule() reference += instructions.Play(test_pulse, d0) self.assertScheduleEqual(schedule, reference) def test_play_sample_pulse(self): """Test play instruction with sample pulse.""" d0 = pulse.DriveChannel(0) test_pulse = library.Waveform([0.0, 0.0]) with pulse.build() as schedule: pulse.play(test_pulse, d0) reference = pulse.Schedule() reference += instructions.Play(test_pulse, d0) self.assertScheduleEqual(schedule, reference) def test_play_array_pulse(self): """Test play instruction on an array directly.""" d0 = pulse.DriveChannel(0) test_array = np.array([0.0, 0.0], dtype=np.complex_) with pulse.build() as schedule: pulse.play(test_array, d0) reference = pulse.Schedule() test_pulse = pulse.Waveform(test_array) reference += instructions.Play(test_pulse, d0) self.assertScheduleEqual(schedule, reference) def test_play_name_argument(self): """Test name argument for play instruction.""" d0 = pulse.DriveChannel(0) test_pulse = library.Constant(10, 1.0) with pulse.build() as schedule: pulse.play(test_pulse, channel=d0, name="new_name") self.assertEqual(schedule.instructions[0][1].name, "new_name") def test_acquire_memory_slot(self): """Test acquire instruction into memory slot.""" acquire0 = pulse.AcquireChannel(0) mem0 = pulse.MemorySlot(0) with pulse.build() as schedule: pulse.acquire(10, acquire0, mem0) reference = pulse.Schedule() reference += pulse.Acquire(10, acquire0, mem_slot=mem0) self.assertScheduleEqual(schedule, reference) def test_acquire_register_slot(self): """Test acquire instruction into register slot.""" acquire0 = pulse.AcquireChannel(0) reg0 = pulse.RegisterSlot(0) with pulse.build() as schedule: pulse.acquire(10, acquire0, reg0) reference = pulse.Schedule() reference += pulse.Acquire(10, acquire0, reg_slot=reg0) self.assertScheduleEqual(schedule, reference) def test_acquire_qubit(self): """Test acquire instruction on qubit.""" acquire0 = pulse.AcquireChannel(0) mem0 = pulse.MemorySlot(0) with pulse.build() as schedule: pulse.acquire(10, 0, mem0) reference = pulse.Schedule() reference += pulse.Acquire(10, acquire0, mem_slot=mem0) self.assertScheduleEqual(schedule, reference) def test_instruction_name_argument(self): """Test setting the name of an instruction.""" d0 = pulse.DriveChannel(0) for instruction_method in [ pulse.delay, pulse.set_frequency, pulse.set_phase, pulse.shift_frequency, pulse.shift_phase, ]: with pulse.build() as schedule: instruction_method(0, d0, name="instruction_name") self.assertEqual(schedule.instructions[0][1].name, "instruction_name") def test_set_frequency(self): """Test set frequency instruction.""" d0 = pulse.DriveChannel(0) with pulse.build() as schedule: pulse.set_frequency(1e9, d0) reference = pulse.Schedule() reference += instructions.SetFrequency(1e9, d0) self.assertScheduleEqual(schedule, reference) def test_shift_frequency(self): """Test shift frequency instruction.""" d0 = pulse.DriveChannel(0) with pulse.build() as schedule: pulse.shift_frequency(0.1e9, d0) reference = pulse.Schedule() reference += instructions.ShiftFrequency(0.1e9, d0) self.assertScheduleEqual(schedule, reference) def test_set_phase(self): """Test set phase instruction.""" d0 = pulse.DriveChannel(0) with pulse.build() as schedule: pulse.set_phase(3.14, d0) reference = pulse.Schedule() reference += instructions.SetPhase(3.14, d0) self.assertScheduleEqual(schedule, reference) def test_shift_phase(self): """Test shift phase instruction.""" d0 = pulse.DriveChannel(0) with pulse.build() as schedule: pulse.shift_phase(3.14, d0) reference = pulse.Schedule() reference += instructions.ShiftPhase(3.14, d0) self.assertScheduleEqual(schedule, reference) def test_snapshot(self): """Test snapshot instruction.""" with pulse.build() as schedule: pulse.snapshot("test", "state") reference = pulse.Schedule() reference += instructions.Snapshot("test", "state") self.assertScheduleEqual(schedule, reference) class TestDirectives(TestBuilder): """Test builder directives.""" def test_barrier_with_align_right(self): """Test barrier directive with right alignment context.""" d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) d2 = pulse.DriveChannel(2) with pulse.build() as schedule: with pulse.align_right(): pulse.delay(3, d0) pulse.barrier(d0, d1, d2) pulse.delay(11, d2) with pulse.align_right(): pulse.delay(5, d1) pulse.delay(7, d0) reference = pulse.Schedule() # d0 reference.insert(0, instructions.Delay(3, d0), inplace=True) reference.insert(7, instructions.Delay(7, d0), inplace=True) # d1 reference.insert(9, instructions.Delay(5, d1), inplace=True) # d2 reference.insert(3, instructions.Delay(11, d2), inplace=True) self.assertScheduleEqual(schedule, reference) def test_barrier_with_align_left(self): """Test barrier directive with left alignment context.""" d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) d2 = pulse.DriveChannel(2) with pulse.build() as schedule: with pulse.align_left(): pulse.delay(3, d0) pulse.barrier(d0, d1, d2) pulse.delay(11, d2) with pulse.align_left(): pulse.delay(5, d1) pulse.delay(7, d0) reference = pulse.Schedule() # d0 reference.insert(0, instructions.Delay(3, d0), inplace=True) reference.insert(3, instructions.Delay(7, d0), inplace=True) # d1 reference.insert(3, instructions.Delay(5, d1), inplace=True) # d2 reference.insert(3, instructions.Delay(11, d2), inplace=True) self.assertScheduleEqual(schedule, reference) def test_barrier_on_qubits(self): """Test barrier directive on qubits.""" with pulse.build(self.backend) as schedule: pulse.barrier(0, 1) reference = pulse.ScheduleBlock() reference += directives.RelativeBarrier( pulse.DriveChannel(0), pulse.DriveChannel(1), pulse.MeasureChannel(0), pulse.MeasureChannel(1), pulse.ControlChannel(0), pulse.ControlChannel(1), pulse.AcquireChannel(0), pulse.AcquireChannel(1), ) self.assertEqual(schedule, reference) def test_trivial_barrier(self): """Test that trivial barrier is not added.""" with pulse.build() as schedule: pulse.barrier(pulse.DriveChannel(0)) self.assertEqual(schedule, pulse.ScheduleBlock()) class TestUtilities(TestBuilder): """Test builder utilities.""" def test_active_backend(self): """Test getting active builder backend.""" with pulse.build(self.backend): self.assertEqual(pulse.active_backend(), self.backend) def test_append_schedule(self): """Test appending a schedule to the active builder.""" d0 = pulse.DriveChannel(0) reference = pulse.Schedule() reference += instructions.Delay(10, d0) with pulse.build() as schedule: builder.call(reference) self.assertScheduleEqual(schedule, reference) def test_append_instruction(self): """Test appending an instruction to the active builder.""" d0 = pulse.DriveChannel(0) instruction = instructions.Delay(10, d0) with pulse.build() as schedule: builder.append_instruction(instruction) self.assertScheduleEqual(schedule, (0, instruction)) def test_qubit_channels(self): """Test getting the qubit channels of the active builder's backend.""" with pulse.build(self.backend): qubit_channels = pulse.qubit_channels(0) self.assertEqual( qubit_channels, { pulse.DriveChannel(0), pulse.MeasureChannel(0), pulse.AcquireChannel(0), pulse.ControlChannel(0), pulse.ControlChannel(1), }, ) def test_active_transpiler_settings(self): """Test setting settings of active builder's transpiler.""" with pulse.build(self.backend): self.assertFalse(pulse.active_transpiler_settings()) with pulse.transpiler_settings(test_setting=1): self.assertEqual(pulse.active_transpiler_settings()["test_setting"], 1) def test_active_circuit_scheduler_settings(self): """Test setting settings of active builder's circuit scheduler.""" with pulse.build(self.backend): self.assertFalse(pulse.active_circuit_scheduler_settings()) with pulse.circuit_scheduler_settings(test_setting=1): self.assertEqual(pulse.active_circuit_scheduler_settings()["test_setting"], 1) def test_num_qubits(self): """Test builder utility to get number of qubits.""" with pulse.build(self.backend): self.assertEqual(pulse.num_qubits(), 2) def test_samples_to_seconds(self): """Test samples to time""" config = self.backend.configuration() config.dt = 0.1 with pulse.build(self.backend): time = pulse.samples_to_seconds(100) self.assertTrue(isinstance(time, float)) self.assertEqual(pulse.samples_to_seconds(100), 10) def test_samples_to_seconds_array(self): """Test samples to time (array format).""" config = self.backend.configuration() config.dt = 0.1 with pulse.build(self.backend): samples = np.array([100, 200, 300]) times = pulse.samples_to_seconds(samples) self.assertTrue(np.issubdtype(times.dtype, np.floating)) np.testing.assert_allclose(times, np.array([10, 20, 30])) def test_seconds_to_samples(self): """Test time to samples""" config = self.backend.configuration() config.dt = 0.1 with pulse.build(self.backend): samples = pulse.seconds_to_samples(10) self.assertTrue(isinstance(samples, int)) self.assertEqual(pulse.seconds_to_samples(10), 100) def test_seconds_to_samples_array(self): """Test time to samples (array format).""" config = self.backend.configuration() config.dt = 0.1 with pulse.build(self.backend): times = np.array([10, 20, 30]) samples = pulse.seconds_to_samples(times) self.assertTrue(np.issubdtype(samples.dtype, np.integer)) np.testing.assert_allclose(pulse.seconds_to_samples(times), np.array([100, 200, 300])) class TestMacros(TestBuilder): """Test builder macros.""" def test_macro(self): """Test builder macro decorator.""" @pulse.macro def nested(a): pulse.play(pulse.Gaussian(100, a, 20), pulse.drive_channel(0)) return a * 2 @pulse.macro def test(): pulse.play(pulse.Constant(100, 1.0), pulse.drive_channel(0)) output = nested(0.5) return output with pulse.build(self.backend) as schedule: output = test() self.assertEqual(output, 0.5 * 2) reference = pulse.Schedule() reference += pulse.Play(pulse.Constant(100, 1.0), pulse.DriveChannel(0)) reference += pulse.Play(pulse.Gaussian(100, 0.5, 20), pulse.DriveChannel(0)) self.assertScheduleEqual(schedule, reference) def test_measure(self): """Test utility function - measure.""" with pulse.build(self.backend) as schedule: reg = pulse.measure(0) self.assertEqual(reg, pulse.MemorySlot(0)) reference = macros.measure( qubits=[0], inst_map=self.inst_map, meas_map=self.configuration.meas_map ) self.assertScheduleEqual(schedule, reference) def test_measure_multi_qubits(self): """Test utility function - measure with multi qubits.""" with pulse.build(self.backend) as schedule: regs = pulse.measure([0, 1]) self.assertListEqual(regs, [pulse.MemorySlot(0), pulse.MemorySlot(1)]) reference = macros.measure( qubits=[0, 1], inst_map=self.inst_map, meas_map=self.configuration.meas_map ) self.assertScheduleEqual(schedule, reference) def test_measure_all(self): """Test utility function - measure.""" with pulse.build(self.backend) as schedule: regs = pulse.measure_all() self.assertEqual(regs, [pulse.MemorySlot(0), pulse.MemorySlot(1)]) reference = macros.measure_all(self.backend) self.assertScheduleEqual(schedule, reference) backend_100q = ConfigurableBackend("100q", 100) with pulse.build(backend_100q) as schedule: regs = pulse.measure_all() reference = backend_100q.defaults().instruction_schedule_map.get( "measure", list(range(100)) ) self.assertScheduleEqual(schedule, reference) def test_delay_qubit(self): """Test delaying on a qubit macro.""" with pulse.build(self.backend) as schedule: pulse.delay_qubits(10, 0) d0 = pulse.DriveChannel(0) m0 = pulse.MeasureChannel(0) a0 = pulse.AcquireChannel(0) u0 = pulse.ControlChannel(0) u1 = pulse.ControlChannel(1) reference = pulse.Schedule() reference += instructions.Delay(10, d0) reference += instructions.Delay(10, m0) reference += instructions.Delay(10, a0) reference += instructions.Delay(10, u0) reference += instructions.Delay(10, u1) self.assertScheduleEqual(schedule, reference) def test_delay_qubits(self): """Test delaying on multiple qubits to make sure we don't insert delays twice.""" with pulse.build(self.backend) as schedule: pulse.delay_qubits(10, 0, 1) d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) m0 = pulse.MeasureChannel(0) m1 = pulse.MeasureChannel(1) a0 = pulse.AcquireChannel(0) a1 = pulse.AcquireChannel(1) u0 = pulse.ControlChannel(0) u1 = pulse.ControlChannel(1) reference = pulse.Schedule() reference += instructions.Delay(10, d0) reference += instructions.Delay(10, d1) reference += instructions.Delay(10, m0) reference += instructions.Delay(10, m1) reference += instructions.Delay(10, a0) reference += instructions.Delay(10, a1) reference += instructions.Delay(10, u0) reference += instructions.Delay(10, u1) self.assertScheduleEqual(schedule, reference) class TestGates(TestBuilder): """Test builder gates.""" def test_cx(self): """Test cx gate.""" with pulse.build(self.backend) as schedule: pulse.cx(0, 1) reference_qc = circuit.QuantumCircuit(2) reference_qc.cx(0, 1) reference = compiler.schedule(reference_qc, self.backend) self.assertScheduleEqual(schedule, reference) def test_u1(self): """Test u1 gate.""" with pulse.build(self.backend) as schedule: with pulse.transpiler_settings(layout_method="trivial"): pulse.u1(np.pi / 2, 0) reference_qc = circuit.QuantumCircuit(1) reference_qc.append(circuit.library.U1Gate(np.pi / 2), [0]) reference = compiler.schedule(reference_qc, self.backend) self.assertScheduleEqual(schedule, reference) def test_u2(self): """Test u2 gate.""" with pulse.build(self.backend) as schedule: pulse.u2(np.pi / 2, 0, 0) reference_qc = circuit.QuantumCircuit(1) reference_qc.append(circuit.library.U2Gate(np.pi / 2, 0), [0]) reference = compiler.schedule(reference_qc, self.backend) self.assertScheduleEqual(schedule, reference) def test_u3(self): """Test u3 gate.""" with pulse.build(self.backend) as schedule: pulse.u3(np.pi / 8, np.pi / 16, np.pi / 4, 0) reference_qc = circuit.QuantumCircuit(1) reference_qc.append(circuit.library.U3Gate(np.pi / 8, np.pi / 16, np.pi / 4), [0]) reference = compiler.schedule(reference_qc, self.backend) self.assertScheduleEqual(schedule, reference) def test_x(self): """Test x gate.""" with pulse.build(self.backend) as schedule: pulse.x(0) reference_qc = circuit.QuantumCircuit(1) reference_qc.x(0) reference_qc = compiler.transpile(reference_qc, self.backend) reference = compiler.schedule(reference_qc, self.backend) self.assertScheduleEqual(schedule, reference) def test_lazy_evaluation_with_transpiler(self): """Test that the two cx gates are optimizied away by the transpiler.""" with pulse.build(self.backend) as schedule: pulse.cx(0, 1) pulse.cx(0, 1) reference_qc = circuit.QuantumCircuit(2) reference = compiler.schedule(reference_qc, self.backend) self.assertScheduleEqual(schedule, reference) def test_measure(self): """Test pulse measurement macro against circuit measurement and ensure agreement.""" with pulse.build(self.backend) as schedule: with pulse.align_sequential(): pulse.x(0) pulse.measure(0) reference_qc = circuit.QuantumCircuit(1, 1) reference_qc.x(0) reference_qc.measure(0, 0) reference_qc = compiler.transpile(reference_qc, self.backend) reference = compiler.schedule(reference_qc, self.backend) self.assertScheduleEqual(schedule, reference) def test_backend_require(self): """Test that a backend is required to use a gate.""" with self.assertRaises(exceptions.BackendNotSet): with pulse.build(): pulse.x(0) class TestBuilderComposition(TestBuilder): """Test more sophisticated composite builder examples.""" def test_complex_build(self): """Test a general program build with nested contexts, circuits and macros.""" d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) d2 = pulse.DriveChannel(2) delay_dur = 30 short_dur = 20 long_dur = 49 with pulse.build(self.backend) as schedule: with pulse.align_sequential(): pulse.delay(delay_dur, d0) pulse.u2(0, pi / 2, 1) with pulse.align_right(): pulse.play(library.Constant(short_dur, 0.1), d1) pulse.play(library.Constant(long_dur, 0.1), d2) pulse.u2(0, pi / 2, 1) with pulse.align_left(): pulse.u2(0, pi / 2, 0) pulse.u2(0, pi / 2, 1) pulse.u2(0, pi / 2, 0) pulse.measure(0) # prepare and schedule circuits that will be used. single_u2_qc = circuit.QuantumCircuit(2) single_u2_qc.append(circuit.library.U2Gate(0, pi / 2), [1]) single_u2_qc = compiler.transpile(single_u2_qc, self.backend) single_u2_sched = compiler.schedule(single_u2_qc, self.backend) # sequential context sequential_reference = pulse.Schedule() sequential_reference += instructions.Delay(delay_dur, d0) sequential_reference.insert(delay_dur, single_u2_sched, inplace=True) # align right align_right_reference = pulse.Schedule() align_right_reference += pulse.Play(library.Constant(long_dur, 0.1), d2) align_right_reference.insert( long_dur - single_u2_sched.duration, single_u2_sched, inplace=True ) align_right_reference.insert( long_dur - single_u2_sched.duration - short_dur, pulse.Play(library.Constant(short_dur, 0.1), d1), inplace=True, ) # align left triple_u2_qc = circuit.QuantumCircuit(2) triple_u2_qc.append(circuit.library.U2Gate(0, pi / 2), [0]) triple_u2_qc.append(circuit.library.U2Gate(0, pi / 2), [1]) triple_u2_qc.append(circuit.library.U2Gate(0, pi / 2), [0]) triple_u2_qc = compiler.transpile(triple_u2_qc, self.backend) align_left_reference = compiler.schedule(triple_u2_qc, self.backend, method="alap") # measurement measure_reference = macros.measure( qubits=[0], inst_map=self.inst_map, meas_map=self.configuration.meas_map ) reference = pulse.Schedule() reference += sequential_reference # Insert so that the long pulse on d2 occurs as early as possible # without an overval on d1. insert_time = reference.ch_stop_time(d1) - align_right_reference.ch_start_time(d1) reference.insert(insert_time, align_right_reference, inplace=True) reference.insert(reference.ch_stop_time(d0, d1), align_left_reference, inplace=True) reference += measure_reference self.assertScheduleEqual(schedule, reference) class TestSubroutineCall(TestBuilder): """Test for calling subroutine.""" def test_call(self): """Test calling schedule instruction.""" d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) reference = pulse.Schedule() reference = reference.insert(10, instructions.Delay(10, d0)) reference += instructions.Delay(20, d1) ref_sched = pulse.Schedule() with self.assertWarns(DeprecationWarning): ref_sched += pulse.instructions.Call(reference) with pulse.build() as schedule: with pulse.align_right(): builder.call(reference) self.assertScheduleEqual(schedule, ref_sched) with pulse.build() as schedule: with pulse.align_right(): pulse.call(reference) self.assertScheduleEqual(schedule, ref_sched) def test_call_circuit(self): """Test calling circuit instruction.""" inst_map = self.inst_map reference = inst_map.get("u1", (0,), 0.0) ref_sched = pulse.Schedule() with self.assertWarns(DeprecationWarning): ref_sched += pulse.instructions.Call(reference) u1_qc = circuit.QuantumCircuit(2) u1_qc.append(circuit.library.U1Gate(0.0), [0]) transpiler_settings = {"optimization_level": 0} with pulse.build(self.backend, default_transpiler_settings=transpiler_settings) as schedule: with pulse.align_right(): builder.call(u1_qc) self.assertScheduleEqual(schedule, ref_sched) def test_call_circuit_with_cregs(self): """Test calling of circuit wiht classical registers.""" qc = circuit.QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) with pulse.build(self.backend) as schedule: pulse.call(qc) reference_qc = compiler.transpile(qc, self.backend) reference = compiler.schedule(reference_qc, self.backend) ref_sched = pulse.Schedule() with self.assertWarns(DeprecationWarning): ref_sched += pulse.instructions.Call(reference) self.assertScheduleEqual(schedule, ref_sched) def test_call_gate_and_circuit(self): """Test calling circuit with gates.""" h_control = circuit.QuantumCircuit(2) h_control.h(0) with pulse.build(self.backend) as schedule: with pulse.align_sequential(): # this is circuit, a subroutine stored as Call instruction pulse.call(h_control) # this is instruction, not subroutine pulse.cx(0, 1) # this is macro, not subroutine pulse.measure([0, 1]) # subroutine h_reference = compiler.schedule(compiler.transpile(h_control, self.backend), self.backend) # gate cx_circ = circuit.QuantumCircuit(2) cx_circ.cx(0, 1) cx_reference = compiler.schedule(compiler.transpile(cx_circ, self.backend), self.backend) # measurement measure_reference = macros.measure( qubits=[0, 1], inst_map=self.inst_map, meas_map=self.configuration.meas_map ) reference = pulse.Schedule() with self.assertWarns(DeprecationWarning): reference += pulse.instructions.Call(h_reference) reference += cx_reference reference += measure_reference << reference.duration self.assertScheduleEqual(schedule, reference) def test_subroutine_not_transpiled(self): """Test called circuit is frozen as a subroutine.""" subprogram = circuit.QuantumCircuit(1) subprogram.x(0) transpiler_settings = {"optimization_level": 2} with pulse.build(self.backend, default_transpiler_settings=transpiler_settings) as schedule: pulse.call(subprogram) pulse.call(subprogram) self.assertNotEqual(len(target_qobj_transform(schedule).instructions), 0) def test_subroutine_not_transformed(self): """Test called schedule is not transformed.""" d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) subprogram = pulse.Schedule() subprogram.insert(0, pulse.Delay(30, d0), inplace=True) subprogram.insert(10, pulse.Delay(10, d1), inplace=True) with pulse.build() as target: with pulse.align_right(): pulse.delay(10, d1) pulse.call(subprogram) reference = pulse.Schedule() reference.insert(0, pulse.Delay(10, d1), inplace=True) reference.insert(10, pulse.Delay(30, d0), inplace=True) reference.insert(20, pulse.Delay(10, d1), inplace=True) self.assertScheduleEqual(target, reference) def test_deepcopying_subroutine(self): """Test if deepcopying the schedule can copy inline subroutine.""" from copy import deepcopy with pulse.build() as subroutine: pulse.delay(10, pulse.DriveChannel(0)) with pulse.build() as main_prog: pulse.call(subroutine) copied_prog = deepcopy(main_prog) main_call = main_prog.instructions[0] copy_call = copied_prog.instructions[0] self.assertNotEqual(id(main_call), id(copy_call)) def test_call_with_parameters(self): """Test call subroutine with parameters.""" amp = circuit.Parameter("amp") with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0)) with pulse.build() as main_prog: pulse.call(subroutine, amp=0.1) pulse.call(subroutine, amp=0.3) self.assertEqual(main_prog.is_parameterized(), False) assigned_sched = target_qobj_transform(main_prog) play_0 = assigned_sched.instructions[0][1] play_1 = assigned_sched.instructions[1][1] self.assertEqual(play_0.pulse.amp, 0.1) self.assertEqual(play_1.pulse.amp, 0.3) def test_call_partly_with_parameters(self): """Test multiple calls partly with parameters then assign.""" amp = circuit.Parameter("amp") with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0)) with pulse.build() as main_prog: pulse.call(subroutine, amp=0.1) pulse.call(subroutine) self.assertEqual(main_prog.is_parameterized(), True) main_prog.assign_parameters({amp: 0.5}) self.assertEqual(main_prog.is_parameterized(), False) assigned_sched = target_qobj_transform(main_prog) play_0 = assigned_sched.instructions[0][1] play_1 = assigned_sched.instructions[1][1] self.assertEqual(play_0.pulse.amp, 0.1) self.assertEqual(play_1.pulse.amp, 0.5) def test_call_with_not_existing_parameter(self): """Test call subroutine with parameter not defined.""" amp = circuit.Parameter("amp1") with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0)) with self.assertRaises(exceptions.PulseError): with pulse.build(): pulse.call(subroutine, amp=0.1) def test_call_with_common_parameter(self): """Test call subroutine with parameter that is defined multiple times.""" amp = circuit.Parameter("amp") with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(320, amp, 80), pulse.DriveChannel(0)) with pulse.build() as main_prog: pulse.call(subroutine, amp=0.1) assigned_sched = target_qobj_transform(main_prog) play_0 = assigned_sched.instructions[0][1] play_1 = assigned_sched.instructions[1][1] self.assertEqual(play_0.pulse.amp, 0.1) self.assertEqual(play_1.pulse.amp, 0.1) def test_call_with_parameter_name_collision(self): """Test call subroutine with duplicated parameter names.""" amp1 = circuit.Parameter("amp") amp2 = circuit.Parameter("amp") sigma = circuit.Parameter("sigma") with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, amp1, sigma), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, amp2, sigma), pulse.DriveChannel(0)) with pulse.build() as main_prog: pulse.call(subroutine, value_dict={amp1: 0.1, amp2: 0.2}, sigma=40) assigned_sched = target_qobj_transform(main_prog) play_0 = assigned_sched.instructions[0][1] play_1 = assigned_sched.instructions[1][1] self.assertEqual(play_0.pulse.amp, 0.1) self.assertEqual(play_0.pulse.sigma, 40) self.assertEqual(play_1.pulse.amp, 0.2) self.assertEqual(play_1.pulse.sigma, 40) def test_call_subroutine_with_parametrized_duration(self): """Test call subroutine containing a parametrized duration.""" dur = circuit.Parameter("dur") with pulse.build() as subroutine: pulse.play(pulse.Constant(dur, 0.1), pulse.DriveChannel(0)) pulse.play(pulse.Constant(dur, 0.2), pulse.DriveChannel(0)) with pulse.build() as main: pulse.call(subroutine) self.assertEqual(len(main.blocks), 1)
https://github.com/sahar-saoudi/Bernstein-Vazirani-Circuit
sahar-saoudi
from qiskit import QuantumCircuit import matplotlib.pyplot as plt from qiskit.circuit import Gate from qiskit.visualization import plot_histogram def oracle_function(qubits_number: int, secret_number: int) -> Gate: """ This function returns a gate corresponding to the question asked to know the secret number """ assert 0 < secret_number < (2**qubits_number-1) assert qubits_number>0 oracle_circuit = QuantumCircuit(qubits_number+ 1, name="oracle") for qubit, bit in enumerate(reversed(f"{secret_number:0{qubits_number}b}")): if bit == '1': oracle_circuit.cx(qubit, qubits_number) oracle=oracle_circuit.to_gate() return oracle def circuit_function(oracle: Gate) -> QuantumCircuit: """ This function returns the quantum circuit that represents the algorithm of Bernstein Vazirani """ qubits_number = oracle.num_qubits circuit = QuantumCircuit(qubits_number, qubits_number-1) circuit.x(qubits_number-1) circuit.h(range(qubits_number)) circuit.barrier() circuit.append(oracle, range(qubits_number)) circuit.barrier() circuit.h(range(qubits_number-1)) circuit.barrier() circuit.measure(range(qubits_number-1), range(qubits_number-1)) circuit.barrier() return circuit #example: oracle = oracle_function(6, 33) circuit = circuit_function(oracle) print(circuit) circuit.draw(output="mpl", style="clifford") plt.show()
https://github.com/tomtuamnuq/compare-qiskit-ocean
tomtuamnuq
import itertools import matplotlib.pyplot as plt import networkx as nx from dwave.system import DWaveSampler, FixedEmbeddingComposite import dwave_networkx as dnx import dimod from minorminer import find_embedding from random_lp.lp_random_gen import RandomLP var = 3 cstr = 3 multiple = 1 penalty = 1 lp_bin = RandomLP.create_random_binary_prog("test_" + str(0), cstr, var, multiple=multiple, penalty=penalty) qp = lp_bin.qubo lp_bin.complexity() bqm = dimod.AdjVectorBQM(qp.objective.linear.to_array(), qp.objective.quadratic.to_dict(), qp.objective.constant, vartype=dimod.BINARY) G = bqm.to_networkx_graph() labels = {} variables, constraints = [], [] for key, value in qp.variables_index.items(): if 'slack' in key: label = '' constraints.append(value) else: label = key[1:] variables.append(value) labels[value] = label var_edges, cstr_edges = G.subgraph(variables).edges, G.subgraph(constraints).edges options = {"node_size": 600, "alpha": 0.9} plt.figure(1, figsize=(12,12)) #pos = nx.circular_layout(G) pos = nx.spring_layout(G, k=0.2, iterations=15, seed=1) # k controls the distance between the nodes and varies between 0 and 1 # iterations is the number of times simulated annealing is run # default k =0.1 and iterations=50 # draw each component individually ? nx.draw_networkx_nodes(G, pos, nodelist=variables, node_color="r", **options) nx.draw_networkx_nodes(G, pos, nodelist=constraints, node_color="b", **options) nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5) nx.draw_networkx_edges( G, pos, edgelist=var_edges, width=3, alpha=0.5, edge_color="r", ) nx.draw_networkx_edges( G, pos, edgelist=cstr_edges, width=2, alpha=0.5, edge_color="b", ) nx.draw_networkx_labels(G, pos, labels, font_size=10) plt.axis("off") plt.show() P_16 = dnx.pegasus_graph(16) embedding = find_embedding(G, P_16, timeout=60, tries=50) P_16_sub = P_16.subgraph(list(itertools.chain(*embedding.values()))) P_16_labels = {} P_16_constraints = [] P_16_variables = [] P_16_chains = [] for key, value in embedding.items(): for node in value: if key in constraints: P_16_constraints.append(node) else: P_16_variables.append(node) P_16_labels[node] = labels[key] if len(value) > 1: P_16_chains.append(value) P_16_var_edges, P_16_cstr_edges = P_16_sub.subgraph(P_16_variables).edges, P_16_sub.subgraph(P_16_constraints).edges options = {"node_size": 300, "alpha": 0.9} plt.figure(2, figsize=(12,12)) pos = dnx.pegasus_layout(P_16_sub) nx.draw_networkx_nodes(P_16_sub, pos, nodelist=P_16_variables, node_color="r", **options) nx.draw_networkx_nodes(P_16_sub, pos, nodelist=P_16_constraints, node_color="b", **options) nx.draw_networkx_edges(P_16_sub, pos, width=1.0, alpha=0.5) nx.draw_networkx_edges( P_16_sub, pos, edgelist=P_16_var_edges, width=3, alpha=0.5, edge_color="r", ) nx.draw_networkx_edges( P_16_sub, pos, edgelist=P_16_cstr_edges, width=2, alpha=0.5, edge_color="b", ) nx.draw_networkx_edges( P_16_sub, pos, edgelist=P_16_chains, width=4, alpha=0.5, edge_color="g", ) nx.draw_networkx_labels(P_16_sub, pos, P_16_labels, font_size=10) plt.axis("off") plt.show() structured_sampler = dimod.StructureComposite(DWaveSampler(), P_16.nodes, P_16.edges) sampler = FixedEmbeddingComposite(structured_sampler, embedding=embedding) res = sampler.sample(bqm, label="embedding_of_random_lp", num_reads=100) res.to_pandas_dataframe() solution = res.first.sample solution qp.get_feasibility_info(solution.values()) from qiskit.optimization.algorithms import CplexOptimizer cplex = CplexOptimizer() cplex.solve(qp)