repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Variational Quantum Real Time Evolution algorithm.""" from __future__ import annotations from collections.abc import Mapping, Sequence from typing import Type, Callable import numpy as np from scipy.integrate import OdeSolver from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.primitives import BaseEstimator from .solvers.ode.forward_euler_solver import ForwardEulerSolver from .variational_principles import RealVariationalPrinciple, RealMcLachlanPrinciple from .var_qte import VarQTE from ..real_time_evolver import RealTimeEvolver class VarQRTE(VarQTE, RealTimeEvolver): """Variational Quantum Real Time Evolution algorithm. .. code-block::python import numpy as np from qiskit_algorithms import TimeEvolutionProblem, VarQRTE from qiskit.circuit.library import EfficientSU2 from qiskit_algorithms.time_evolvers.variational import RealMcLachlanPrinciple from qiskit.quantum_info import SparsePauliOp from qiskit.quantum_info import SparsePauliOp, Pauli from qiskit.primitives import Estimator observable = SparsePauliOp.from_list( [ ("II", 0.2252), ("ZZ", 0.5716), ("IZ", 0.3435), ("ZI", -0.4347), ("YY", 0.091), ("XX", 0.091), ] ) ansatz = EfficientSU2(observable.num_qubits, reps=1) init_param_values = np.ones(len(ansatz.parameters)) * np.pi/2 var_principle = RealMcLachlanPrinciple() time = 1 # without evaluating auxiliary operators evolution_problem = TimeEvolutionProblem(observable, time) var_qrte = VarQRTE(ansatz, init_param_values, var_principle) evolution_result = var_qrte.evolve(evolution_problem) # evaluating auxiliary operators aux_ops = [Pauli("XX"), Pauli("YZ")] evolution_problem = TimeEvolutionProblem(observable, time, aux_operators=aux_ops) var_qrte = VarQRTE(ansatz, init_param_values, var_principle, Estimator()) evolution_result = var_qrte.evolve(evolution_problem) """ def __init__( self, ansatz: QuantumCircuit, initial_parameters: Mapping[Parameter, float] | Sequence[float], variational_principle: RealVariationalPrinciple | None = None, estimator: BaseEstimator | None = None, ode_solver: Type[OdeSolver] | str = ForwardEulerSolver, lse_solver: Callable[[np.ndarray, np.ndarray], np.ndarray] | None = None, num_timesteps: int | None = None, imag_part_tol: float = 1e-7, num_instability_tol: float = 1e-7, ) -> None: r""" Args: ansatz: Ansatz to be used for variational time evolution. initial_parameters: Initial parameter values for an ansatz. variational_principle: Variational Principle to be used. Defaults to ``RealMcLachlanPrinciple``. estimator: An estimator primitive used for calculating expectation values of TimeEvolutionProblem.aux_operators. ode_solver: ODE solver callable that implements a SciPy ``OdeSolver`` interface or a string indicating a valid method offered by SciPy. lse_solver: Linear system of equations solver callable. It accepts ``A`` and ``b`` to solve ``Ax=b`` and returns ``x``. If ``None``, the default ``np.linalg.lstsq`` solver is used. num_timesteps: The number of timesteps to take. If ``None``, it is automatically selected to achieve a timestep of approximately 0.01. Only relevant in case of the ``ForwardEulerSolver``. imag_part_tol: Allowed value of an imaginary part that can be neglected if no imaginary part is expected. num_instability_tol: The amount of negative value that is allowed to be rounded up to 0 for quantities that are expected to be non-negative. """ if variational_principle is None: variational_principle = RealMcLachlanPrinciple() super().__init__( ansatz, initial_parameters, variational_principle, estimator, ode_solver, lse_solver=lse_solver, num_timesteps=num_timesteps, imag_part_tol=imag_part_tol, num_instability_tol=num_instability_tol, )
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# vector |v> print("vector |v>") values = [-0.1, -0.3, 0.4, 0.5] total = 0 # summation of squares for i in range(len(values)): total += values[i]**2; # add the square of each value print("total is ",total) print("the missing part is",1-total) print("so, the value of 'a' can be",(1-total)**0.5,"or",-(1-total)**0.5) # square root of the missing part print() print("vector |u>") values = [1/(2**0.5), -1/(3**0.5)] total = 0 # summation of squares for i in range(len(values)): total += values[i]**2; # add the square of each value print("total is ",total) print("the missing part is",1-total) # the missing part is 1/b, square of 1/sqrt(b) # thus, b is 1/missing_part print("so, the value of 'b' should be",1/(1-total)) #%%writefile randqstate.py from random import randrange # randomly creating a 2-dimensional quantum state def random_quantum_state(): first_entry = randrange(100) first_entry = first_entry/100 first_entry = first_entry**0.5 # we found the first value before determining its sign if randrange(2) == 0: # determine the sign first_entry = -1 * first_entry second_entry = 1 - (first_entry**2) second_entry = second_entry**0.5 if randrange(2) == 0: # determine the sign second_entry = -1 * second_entry return [first_entry,second_entry] # testing whether a given quantum state is valid def is_quantum_state(quantum_state): length_square = 0 for i in range(len(quantum_state)): length_square += quantum_state[i]**2 print("summation of entry squares is",length_square) # there might be precision problem # the length may be very close to 1 but not exactly 1 # so we use the following trick if (length_square - 1)**2 < 0.00000001: return True return False # else # defining a function for Hadamard multiplication def hadamard(quantum_state): result_quantum_state = [0,0] # define with zero entries result_quantum_state[0] = (1/(2**0.5)) * quantum_state[0] + (1/(2**0.5)) * quantum_state[1] result_quantum_state[1] = (1/(2**0.5)) * quantum_state[0] - (1/(2**0.5)) * quantum_state[1] return result_quantum_state # we are ready for i in range(10): picked_quantum_state=random_quantum_state() print(picked_quantum_state,"this is randomly picked quantum state") new_quantum_state = hadamard(picked_quantum_state) print(new_quantum_state,"this is new quantum state") print("Is it valid?",is_quantum_state(new_quantum_state)) print() # print an empty line
https://github.com/calebclothier/GoogleDTC
calebclothier
import numpy as np import matplotlib.pyplot as plt from matplotlib import colors from qiskit import IBMQ, assemble, transpile from qiskit import QuantumCircuit N_QUBITS = 20 # Number of qubits used in Google paper # Link to IBMQ account with API token #IBMQ.save_account(API_TOKEN) # Load IBMQ cloud-based QASM simulator provider = IBMQ.load_account() backend = provider.backend.ibmq_qasm_simulator def random_bitstring_circuit(n_qubits: int) -> QuantumCircuit: """ Args: n_qubits: desired number of qubits in the bitstring Returns: QuantumCircuit: creates a random bitstring from the ground state """ qc = QuantumCircuit(n_qubits) # Generate random bitstring random_bitstring = np.random.randint(2, size=n_qubits) # Apply X gate to nonzero qubits in bitstring for i in range(n_qubits): if random_bitstring[i]: qc.x(i) return qc def floquet_circuit(n_qubits: int, g: float) -> QuantumCircuit: """ Args: n_qubits: number of qubits g: parameter controlling amount of x-rotation Returns: QuantumCircuit: circuit implementation of the unitary operator U_f as detailed in https://arxiv.org/pdf/2107.13571.pdf """ qc = QuantumCircuit(n_qubits) # X rotation by g*pi on all qubits (simulates the periodic driving pulse) for i in range(n_qubits): qc.rx(g*np.pi, i) qc.barrier() # Ising interaction (only couples adjacent spins with random coupling strengths) for i in range(0, n_qubits-1, 2): phi = np.random.uniform(low=0.5, high=1.5) theta = -phi * np.pi / 2 qc.rzz(theta, i, i+1) for i in range(1, n_qubits-1, 2): phi = np.random.uniform(low=0.5, high=1.5) theta = -phi * np.pi / 2 qc.rzz(theta, i, i+1) qc.barrier() # Longitudinal fields for disorder for i in range(n_qubits): h = np.random.uniform(low=-1, high=1) qc.rz(h * np.pi, i) return qc def calculate_mean_polarization(n_qubits: int, counts: dict, q_index: int) -> float: """ Args: n_qubits: total number of qubits counts: dictionary of bitstring measurement outcomes and their respective total counts q_index: index of qubit whose expected polarization we want to calculate Returns: float: the mean Z-polarization <Z>, in [-1, 1], of the qubit at q_index """ run, num_shots = 0, 0 for bitstring in counts.keys(): val = 1 if (int(bitstring[n_qubits-q_index-1]) == 0) else -1 run += val * counts[bitstring] num_shots += counts[bitstring] return run / num_shots def calculate_two_point_correlations(series: list) -> list: """ Args: series: time-ordered list of expectation values for some random variable Returns: list: two point correlations <f(0)f(t)> of the random variable evaluated at all t>0 """ n = len(series) data = np.asarray(series) mean = np.mean(data) c0 = np.sum((data - mean) ** 2) / float(n) def r(h): acf_lag = ((data[:n - h] - mean) * (data[h:] - mean)).sum() / float(n) / c0 return round(acf_lag, 3) x = np.arange(n) # Avoiding lag 0 calculation acf_coeffs = list(map(r, x)) return acf_coeffs def simulate(n_qubits: int, initial_state: QuantumCircuit, max_time_steps: int, g: float) -> None: mean_polarizations = np.zeros((n_qubits, max_time_steps+1)) floq_qc = floquet_circuit(n_qubits, g) for t in range(0, max_time_steps+1): if ((t % 5) == 0): print('Time t=%d' % t) qc = QuantumCircuit(n_qubits) qc = qc.compose(initial_state) for i in range(t): qc = qc.compose(floq_qc) qc.measure_all() transpiled = transpile(qc, backend) job = backend.run(transpiled) retrieved_job = backend.retrieve_job(job.job_id()) counts = retrieved_job.result().get_counts() for qubit in range(n_qubits): mean_polarizations[qubit,t] = calculate_mean_polarization(n_qubits, counts, q_index=qubit) return mean_polarizations polarized_state = QuantumCircuit(N_QUBITS) # All qubits in |0> state thermal_z = simulate(n_qubits=N_QUBITS, initial_state=polarized_state, max_time_steps=50, g=0.6) fig, ax = plt.subplots(figsize=(10,10)) im = ax.matshow(thermal_z, cmap='viridis') plt.rcParams.update({'font.size': 15}) plt.rcParams['text.usetex'] = True ax.set_xlabel('Floquet cycles (t)') ax.xaxis.labelpad = 10 ax.set_ylabel('Qubit') ax.set_xticks(np.arange(0, 51, 10)) ax.set_yticks(np.arange(0, N_QUBITS, 5)) ax.xaxis.set_label_position('top') im.set_clim(-1, 1) cbar = plt.colorbar(im, fraction=0.018, pad=0.04) cbar.set_label(r'$\langle Z(t) \rangle$') plt.show() plt.plot(thermal_z[10,:], 'bs-') plt.xlabel('Floquet cycles (t)') plt.tick_params(axis="x", bottom=True, top=False, labelbottom=True, labeltop=False) plt.ylabel(r'$\langle Z(t) \rangle$') dtc_z = simulate(n_qubits=N_QUBITS, initial_state=polarized_state, max_time_steps=50, g=0.97) fig, ax = plt.subplots(figsize=(10,10)) im = ax.matshow(dtc_z, cmap='viridis') plt.rcParams.update({'font.size': 15}) plt.rcParams['text.usetex'] = True ax.set_xlabel('Floquet cycles (t)') ax.xaxis.labelpad = 10 ax.set_ylabel('Qubit') ax.set_xticks(np.arange(0, 51, 10)) ax.set_yticks(np.arange(0, N_QUBITS, 5)) ax.xaxis.set_label_position('top') im.set_clim(-1, 1) cbar = plt.colorbar(im, fraction=0.018, pad=0.04) cbar.set_label(r'$\langle Z(t) \rangle$') plt.show() plt.plot(dtc_z[10,:], 'bs-') plt.xlabel('Floquet cycles (t)') plt.tick_params(axis="x", bottom=True, top=False, labelbottom=True, labeltop=False) plt.ylabel(r'$\langle Z(t) \rangle$')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.units import DistanceUnit from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.mappers import ParityMapper from qiskit_nature.second_q.properties import ParticleNumber from qiskit_nature.second_q.transformers import ActiveSpaceTransformer bond_distance = 2.5 # in Angstrom # specify driver driver = PySCFDriver( atom=f"Li 0 0 0; H 0 0 {bond_distance}", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) problem = driver.run() # specify active space transformation active_space_trafo = ActiveSpaceTransformer( num_electrons=problem.num_particles, num_spatial_orbitals=3 ) # transform the electronic structure problem problem = active_space_trafo.transform(problem) # construct the parity mapper with 2-qubit reduction qubit_mapper = ParityMapper(num_particles=problem.num_particles) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.algorithms.ground_state_solvers import GroundStateEigensolver np_solver = NumPyMinimumEigensolver() np_groundstate_solver = GroundStateEigensolver(qubit_mapper, np_solver) np_result = np_groundstate_solver.solve(problem) target_energy = np_result.total_energies[0] print(np_result) from qiskit.circuit.library import EfficientSU2 ansatz = EfficientSU2(num_qubits=4, reps=1, entanglement="linear", insert_barriers=True) ansatz.decompose().draw("mpl", style="iqx") import numpy as np from qiskit.utils import algorithm_globals # fix random seeds for reproducibility np.random.seed(5) algorithm_globals.random_seed = 5 from qiskit.algorithms.optimizers import SPSA optimizer = SPSA(maxiter=100) initial_point = np.random.random(ansatz.num_parameters) from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.primitives import Estimator estimator = Estimator() local_vqe = VQE( estimator, ansatz, optimizer, initial_point=initial_point, ) local_vqe_groundstate_solver = GroundStateEigensolver(qubit_mapper, local_vqe) local_vqe_result = local_vqe_groundstate_solver.solve(problem) print(local_vqe_result) from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(group="open") # replace by your runtime provider backend = provider.get_backend("ibmq_qasm_simulator") # select a backend that supports the runtime from qiskit_nature.runtime import VQEClient runtime_vqe = VQEClient( ansatz=ansatz, optimizer=optimizer, initial_point=initial_point, provider=provider, backend=backend, shots=1024, measurement_error_mitigation=True, ) # use a complete measurement fitter for error mitigation runtime_vqe_groundstate_solver = GroundStateEigensolver(qubit_mapper, runtime_vqe) runtime_vqe_result = runtime_vqe_groundstate_solver.solve(problem) print(runtime_vqe_result) runtime_result = runtime_vqe_result.raw_result history = runtime_result.optimizer_history loss = history["energy"] import matplotlib.pyplot as plt plt.rcParams["font.size"] = 14 # plot loss and reference value plt.figure(figsize=(12, 6)) plt.plot(loss + runtime_vqe_result.nuclear_repulsion_energy, label="Runtime VQE") plt.axhline(y=target_energy + 0.2, color="tab:red", ls=":", label="Target + 200mH") plt.axhline(y=target_energy, color="tab:red", ls="--", label="Target") plt.legend(loc="best") plt.xlabel("Iteration") plt.ylabel("Energy [H]") plt.title("VQE energy"); import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/carstenblank/qiskit-aws-braket-provider
carstenblank
# This code is part of Qiskit. # # (C) Alpine Quantum Technologies GmbH 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. from math import pi from typing import Union import pytest from hypothesis import assume, given from hypothesis import strategies as st from qiskit import QuantumCircuit, transpile from qiskit.circuit.library import RXGate, RYGate from qiskit_aqt_provider.aqt_resource import AQTResource from qiskit_aqt_provider.test.circuits import ( assert_circuits_equal, assert_circuits_equivalent, qft_circuit, ) from qiskit_aqt_provider.test.fixtures import MockSimulator from qiskit_aqt_provider.transpiler_plugin import rewrite_rx_as_r, wrap_rxx_angle @pytest.mark.parametrize( ("input_theta", "output_theta", "output_phi"), [ (pi / 3, pi / 3, 0.0), (-pi / 3, pi / 3, pi), (7 * pi / 5, 3 * pi / 5, pi), (25 * pi, pi, pi), (22 * pi / 3, 2 * pi / 3, pi), ], ) def test_rx_rewrite_example( input_theta: float, output_theta: float, output_phi: float, ) -> None: """Snapshot test for the Rx(θ) → R(θ, φ) rule.""" result = QuantumCircuit(1) result.append(rewrite_rx_as_r(input_theta), (0,)) expected = QuantumCircuit(1) expected.r(output_theta, output_phi, 0) reference = QuantumCircuit(1) reference.rx(input_theta, 0) assert_circuits_equal(result, expected) assert_circuits_equivalent(result, reference) @given(theta=st.floats(allow_nan=False, min_value=-1000 * pi, max_value=1000 * pi)) @pytest.mark.parametrize("optimization_level", [1, 2, 3]) @pytest.mark.parametrize("test_gate", [RXGate, RYGate]) def test_rx_ry_rewrite_transpile( theta: float, optimization_level: int, test_gate: Union[RXGate, RYGate], ) -> None: """Test the rewrite rule: Rx(θ), Ry(θ) → R(θ, φ), θ ∈ [0, π], φ ∈ [0, 2π].""" assume(abs(theta) > pi / 200) # we only need the backend's transpiler target for this test backend = MockSimulator(noisy=False) qc = QuantumCircuit(1) qc.append(test_gate(theta), (0,)) trans_qc = transpile(qc, backend, optimization_level=optimization_level) assert isinstance(trans_qc, QuantumCircuit) assert_circuits_equivalent(trans_qc, qc) assert set(trans_qc.count_ops()) <= set(backend.configuration().basis_gates) num_r = trans_qc.count_ops().get("r") assume(num_r is not None) assert num_r == 1 for operation in trans_qc.data: instruction = operation[0] if instruction.name == "r": theta, phi = instruction.params assert 0 <= float(theta) <= pi assert 0 <= float(phi) <= 2 * pi break else: # pragma: no cover pytest.fail("No R gates in transpiled circuit.") def test_decompose_1q_rotations_example(offline_simulator_no_noise: AQTResource) -> None: """Snapshot test for the efficient rewrite of single-qubit rotation runs as ZXZ.""" qc = QuantumCircuit(1) qc.rx(pi / 2, 0) qc.ry(pi / 2, 0) expected = QuantumCircuit(1) expected.rz(-pi / 2, 0) expected.r(pi / 2, 0, 0) result = transpile(qc, offline_simulator_no_noise, optimization_level=3) assert isinstance(result, QuantumCircuit) # only got one circuit back assert_circuits_equal(result, expected) assert_circuits_equivalent(result, expected) def test_rxx_wrap_angle_case0() -> None: """Snapshot test for Rxx(θ) rewrite with 0 <= θ <= π/2.""" result = QuantumCircuit(2) result.append(wrap_rxx_angle(pi / 2), (0, 1)) expected = QuantumCircuit(2) expected.rxx(pi / 2, 0, 1) assert_circuits_equal(result.decompose(), expected) assert_circuits_equivalent(result.decompose(), expected) def test_rxx_wrap_angle_case0_negative() -> None: """Snapshot test for Rxx(θ) rewrite with -π/2 <= θ < 0.""" result = QuantumCircuit(2) result.append(wrap_rxx_angle(-pi / 2), (0, 1)) expected = QuantumCircuit(2) expected.rz(pi, 0) expected.rxx(pi / 2, 0, 1) expected.rz(pi, 0) assert_circuits_equal(result.decompose(), expected) assert_circuits_equivalent(result.decompose(), expected) def test_rxx_wrap_angle_case1() -> None: """Snapshot test for Rxx(θ) rewrite with π/2 < θ <= 3π/2.""" result = QuantumCircuit(2) result.append(wrap_rxx_angle(3 * pi / 2), (0, 1)) expected = QuantumCircuit(2) expected.rx(pi, 0) expected.rx(pi, 1) expected.rxx(pi / 2, 0, 1) assert_circuits_equal(result.decompose(), expected) assert_circuits_equivalent(result.decompose(), expected) def test_rxx_wrap_angle_case1_negative() -> None: """Snapshot test for Rxx(θ) rewrite with -3π/2 <= θ < -π/2.""" result = QuantumCircuit(2) result.append(wrap_rxx_angle(-3 * pi / 2), (0, 1)) expected = QuantumCircuit(2) expected.rxx(pi / 2, 0, 1) assert_circuits_equal(result.decompose(), expected) assert_circuits_equivalent(result.decompose(), expected) def test_rxx_wrap_angle_case2() -> None: """Snapshot test for Rxx(θ) rewrite with θ > 3*π/2.""" result = QuantumCircuit(2) result.append(wrap_rxx_angle(18 * pi / 10), (0, 1)) # mod 2π = 9π/5 → -π/5 expected = QuantumCircuit(2) expected.rz(pi, 0) expected.rxx(pi / 5, 0, 1) expected.rz(pi, 0) assert_circuits_equal(result.decompose(), expected) assert_circuits_equivalent(result.decompose(), expected) def test_rxx_wrap_angle_case2_negative() -> None: """Snapshot test for Rxx(θ) rewrite with θ < -3π/2.""" result = QuantumCircuit(2) result.append(wrap_rxx_angle(-18 * pi / 10), (0, 1)) # mod 2π = π/5 expected = QuantumCircuit(2) expected.rxx(pi / 5, 0, 1) assert_circuits_equal(result.decompose(), expected) assert_circuits_equivalent(result.decompose(), expected) @given( angle=st.floats( allow_nan=False, allow_infinity=False, min_value=-1000 * pi, max_value=1000 * pi, ) ) @pytest.mark.parametrize("qubits", [3]) @pytest.mark.parametrize("optimization_level", [1, 2, 3]) def test_rxx_wrap_angle_transpile(angle: float, qubits: int, optimization_level: int) -> None: """Check that Rxx angles are wrapped by the transpiler.""" assume(abs(angle) > pi / 200) qc = QuantumCircuit(qubits) qc.rxx(angle, 0, 1) # we only need the backend's transpilation target for this test backend = MockSimulator(noisy=False) trans_qc = transpile(qc, backend, optimization_level=optimization_level) assert isinstance(trans_qc, QuantumCircuit) assert_circuits_equivalent(trans_qc, qc) assert set(trans_qc.count_ops()) <= set(backend.configuration().basis_gates) num_rxx = trans_qc.count_ops().get("rxx") # in high optimization levels, the gate might be dropped assume(num_rxx is not None) assert num_rxx == 1 # check that all Rxx have angles in [0, π/2] for operation in trans_qc.data: instruction = operation[0] if instruction.name == "rxx": (theta,) = instruction.params assert 0 <= float(theta) <= pi / 2 break # there's only one Rxx gate in the circuit else: # pragma: no cover pytest.fail("Transpiled circuit contains no Rxx gate.") @pytest.mark.parametrize("qubits", [1, 5, 10]) @pytest.mark.parametrize("optimization_level", [1, 2, 3]) def test_qft_circuit_transpilation( qubits: int, optimization_level: int, offline_simulator_no_noise: AQTResource ) -> None: """Transpile a N-qubit QFT circuit for an AQT backend. Check that the angles are properly wrapped. """ qc = qft_circuit(qubits) trans_qc = transpile(qc, offline_simulator_no_noise, optimization_level=optimization_level) assert isinstance(trans_qc, QuantumCircuit) assert set(trans_qc.count_ops()) <= set(offline_simulator_no_noise.configuration().basis_gates) for operation in trans_qc.data: instruction = operation[0] if instruction.name == "rxx": (theta,) = instruction.params assert 0 <= float(theta) <= pi / 2 if instruction.name == "r": (theta, _) = instruction.params assert abs(theta) <= pi if optimization_level < 3 and qubits < 6: assert_circuits_equivalent(qc, trans_qc)
https://github.com/acfilok96/Quantum-Computation
acfilok96
import qiskit print(qiskit.__version__) from qiskit_machine_learning.datasets import ad_hoc_data adhoc_dimension = 2 train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(training_size = 20, test_size = 5, n = adhoc_dimension, gap=0.3, plot_data =False, one_hot=False, include_sample_total=True) import numpy print(numpy.array(adhoc_total).shape) print("train data shape: ", train_features.shape,"\ttrain labels shape: ", train_labels.shape) print("test data shape: ", test_features.shape,"\ttest labels shape: ", test_labels.shape) print('train data:\n',train_features[:5]) print('\ntrain label:\n',train_labels[:5]) # plot_adhoc_dataset(train_features, train_labels, test_features, test_labels, adhoc_total) from qiskit import Aer from qiskit.utils import QuantumInstance seed=20 quantum_instance = QuantumInstance(Aer.get_backend("qasm_simulator"), shots=1024, seed_simulator=seed, seed_transpiler=seed) from qiskit.circuit.library import ZFeatureMap from qiskit_machine_learning.kernels import QuantumKernel z_feature_map = ZFeatureMap(feature_dimension=adhoc_dimension, reps=2) z_kernel = QuantumKernel(feature_map = z_feature_map, quantum_instance=quantum_instance) # z_feature_map.draw(output='mpl', scale=2) z_feature_map.decompose().draw(output='mpl', scale=2) from sklearn.svm import SVC svc = SVC(kernel=z_kernel.evaluate) svc.fit(train_features, train_labels) score = svc.score(test_features, test_labels) print('Callable kernel with ZFeatureMap classification test score: ', score) prediction = svc.predict(test_features) print(prediction) from qiskit.circuit.library import ZZFeatureMap zz_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement='linear') zz_kernel = QuantumKernel(feature_map = zz_feature_map, quantum_instance=quantum_instance) zz_feature_map.decompose().draw(output='mpl', scale=2) from sklearn.svm import SVC svc = SVC(kernel=zz_kernel.evaluate) svc.fit(train_features, train_labels) score = svc.score(test_features, test_labels) print('Callable kernel with ZZFeatureMap classification test score: ', score) prediction = svc.predict(test_features) print(prediction) from qiskit_machine_learning.algorithms import QSVC qsvc = QSVC() qsvc.quantum_kernel.quantum_instance = quantum_instance qsvc.fit(train_features, train_labels) score = qsvc.score(test_features, test_labels) print('QSVC classification test score: ', score) prediction = qsvc.predict(test_features) print(prediction) from qiskit.circuit.library import ZFeatureMap from qiskit_machine_learning.kernels import QuantumKernel # here feature_dimension = 2 and reps = 1 adhoc_dimension = 2 z_feature_map = ZFeatureMap(feature_dimension=adhoc_dimension, reps=1) z_kernel = QuantumKernel(feature_map = z_feature_map, quantum_instance=quantum_instance) z_feature_map.decompose().draw(output='mpl', scale=2) from qiskit.circuit.library import ZFeatureMap from qiskit_machine_learning.kernels import QuantumKernel # here feature_dimension = 2 and reps = 2 adhoc_dimension = 2 z_feature_map = ZFeatureMap(feature_dimension=adhoc_dimension, reps=2) z_kernel = QuantumKernel(feature_map = z_feature_map, quantum_instance=quantum_instance) z_feature_map.decompose().draw(output='mpl', scale=2) from qiskit.circuit.library import ZFeatureMap from qiskit_machine_learning.kernels import QuantumKernel # here feature_dimension = 3 and reps = 4 adhoc_dimension = 3 z_feature_map = ZFeatureMap(feature_dimension=adhoc_dimension, reps=4) z_kernel = QuantumKernel(feature_map = z_feature_map, quantum_instance=quantum_instance) z_feature_map.decompose().draw(output='mpl', scale=2) # same happens for ZZFeatureMap from qiskit.circuit.library import ZZFeatureMap adhoc_dimension=2 zz_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=1, entanglement='linear') zz_kernel = QuantumKernel(feature_map = zz_feature_map, quantum_instance=quantum_instance) zz_feature_map.decompose().draw(output='mpl', scale=2) # same happens for ZZFeatureMap from qiskit.circuit.library import ZZFeatureMap adhoc_dimension=2 zz_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement='linear') zz_kernel = QuantumKernel(feature_map = zz_feature_map, quantum_instance=quantum_instance) zz_feature_map.decompose().draw(output='mpl', scale=2) # same happens for ZZFeatureMap from qiskit.circuit.library import ZZFeatureMap adhoc_dimension=3 zz_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=1, entanglement='linear') zz_kernel = QuantumKernel(feature_map = zz_feature_map, quantum_instance=quantum_instance) zz_feature_map.decompose().draw(output='mpl', scale=2) # same happens for ZZFeatureMap from qiskit.circuit.library import ZZFeatureMap adhoc_dimension=3 zz_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement='linear') zz_kernel = QuantumKernel(feature_map = zz_feature_map, quantum_instance=quantum_instance) zz_feature_map.decompose().draw(output='mpl', scale=2)
https://github.com/Innanov/Qiskit-Global-Summer-School-2022
Innanov
import networkx as nx import numpy as np import plotly.graph_objects as go import matplotlib as mpl import pandas as pd from IPython.display import clear_output from plotly.subplots import make_subplots from matplotlib import pyplot as plt from qiskit import Aer from qiskit import QuantumCircuit from qiskit.visualization import plot_state_city from qiskit.algorithms.optimizers import COBYLA, SLSQP, ADAM from time import time from copy import copy from typing import List from qc_grader.graph_util import display_maxcut_widget, QAOA_widget, graphs mpl.rcParams['figure.dpi'] = 300 from qiskit.circuit import Parameter, ParameterVector #Parameters are initialized with a simple string identifier parameter_0 = Parameter('θ[0]') parameter_1 = Parameter('θ[1]') circuit = QuantumCircuit(1) #We can then pass the initialized parameters as the rotation angle argument to the Rx and Ry gates circuit.ry(theta = parameter_0, qubit = 0) circuit.rx(theta = parameter_1, qubit = 0) circuit.draw('mpl') parameter = Parameter('θ') circuit = QuantumCircuit(1) circuit.ry(theta = parameter, qubit = 0) circuit.rx(theta = parameter, qubit = 0) circuit.draw('mpl') #Set the number of layers and qubits n=3 num_layers = 2 #ParameterVectors are initialized with a string identifier and an integer specifying the vector length parameters = ParameterVector('θ', n*(num_layers+1)) circuit = QuantumCircuit(n, n) for layer in range(num_layers): #Appending the parameterized Ry gates using parameters from the vector constructed above for i in range(n): circuit.ry(parameters[n*layer+i], i) circuit.barrier() #Appending the entangling CNOT gates for i in range(n): for j in range(i): circuit.cx(j,i) circuit.barrier() #Appending one additional layer of parameterized Ry gates for i in range(n): circuit.ry(parameters[n*num_layers+i], i) circuit.barrier() circuit.draw('mpl') print(circuit.parameters) #Create parameter dictionary with random values to bind param_dict = {parameter: np.random.random() for parameter in parameters} print(param_dict) #Assign parameters using the assign_parameters method bound_circuit = circuit.assign_parameters(parameters = param_dict) bound_circuit.draw('mpl') new_parameters = ParameterVector('Ψ',9) new_circuit = circuit.assign_parameters(parameters = [k*new_parameters[i] for k in range(9)]) new_circuit.draw('mpl') #Run the circuit with assigned parameters on Aer's statevector simulator simulator = Aer.get_backend('statevector_simulator') result = simulator.run(bound_circuit).result() statevector = result.get_statevector(bound_circuit) plot_state_city(statevector) #The following line produces an error when run because 'circuit' still contains non-assigned parameters #result = simulator.run(circuit).result() for key in graphs.keys(): print(key) graph = nx.Graph() #Add nodes and edges graph.add_nodes_from(np.arange(0,6,1)) edges = [(0,1,2.0),(0,2,3.0),(0,3,2.0),(0,4,4.0),(0,5,1.0),(1,2,4.0),(1,3,1.0),(1,4,1.0),(1,5,3.0),(2,4,2.0),(2,5,3.0),(3,4,5.0),(3,5,1.0)] graph.add_weighted_edges_from(edges) graphs['custom'] = graph #Display widget display_maxcut_widget(graphs['custom']) def maxcut_cost_fn(graph: nx.Graph, bitstring: List[int]) -> float: """ Computes the maxcut cost function value for a given graph and cut represented by some bitstring Args: graph: The graph to compute cut values for bitstring: A list of integer values '0' or '1' specifying a cut of the graph Returns: The value of the cut """ #Get the weight matrix of the graph weight_matrix = nx.adjacency_matrix(graph).toarray() size = weight_matrix.shape[0] value = 0. #INSERT YOUR CODE TO COMPUTE THE CUT VALUE HERE for i in range(size): for j in range(size): value+= weight_matrix[i,j]*bitstring[i]*(1-bitstring[j]) return value def plot_maxcut_histogram(graph: nx.Graph) -> None: """ Plots a bar diagram with the values for all possible cuts of a given graph. Args: graph: The graph to compute cut values for """ num_vars = graph.number_of_nodes() #Create list of bitstrings and corresponding cut values bitstrings = ['{:b}'.format(i).rjust(num_vars, '0')[::-1] for i in range(2**num_vars)] values = [maxcut_cost_fn(graph = graph, bitstring = [int(x) for x in bitstring]) for bitstring in bitstrings] #Sort both lists by largest cut value values, bitstrings = zip(*sorted(zip(values, bitstrings))) #Plot bar diagram bar_plot = go.Bar(x = bitstrings, y = values, marker=dict(color=values, colorscale = 'plasma', colorbar=dict(title='Cut Value'))) fig = go.Figure(data=bar_plot, layout = dict(xaxis=dict(type = 'category'), width = 1500, height = 600)) fig.show() plot_maxcut_histogram(graph = graphs['custom']) from qc_grader import grade_lab2_ex1 bitstring = [1, 0, 1, 1, 0, 0] #DEFINE THE CORRECT MAXCUT BITSTRING HERE # Note that the grading function is expecting a list of integers '0' and '1' grade_lab2_ex1(bitstring) from qiskit_optimization import QuadraticProgram quadratic_program = QuadraticProgram('sample_problem') print(quadratic_program.export_as_lp_string()) quadratic_program.binary_var(name = 'x_0') quadratic_program.integer_var(name = 'x_1') quadratic_program.continuous_var(name = 'x_2', lowerbound = -2.5, upperbound = 1.8) quadratic = [[0,1,2],[3,4,5],[0,1,2]] linear = [10,20,30] quadratic_program.minimize(quadratic = quadratic, linear = linear, constant = -5) print(quadratic_program.export_as_lp_string()) def quadratic_program_from_graph(graph: nx.Graph) -> QuadraticProgram: """Constructs a quadratic program from a given graph for a MaxCut problem instance. Args: graph: Underlying graph of the problem. Returns: QuadraticProgram """ #Get weight matrix of graph weight_matrix = nx.adjacency_matrix(graph) shape = weight_matrix.shape size = shape[0] #Build qubo matrix Q from weight matrix W qubo_matrix = np.zeros((size, size)) qubo_vector = np.zeros(size) for i in range(size): for j in range(size): qubo_matrix[i, j] -= weight_matrix[i, j] for i in range(size): for j in range(size): qubo_vector[i] += weight_matrix[i,j] #INSERT YOUR CODE HERE quadratic_program=QuadraticProgram('sample_problem') for i in range(size): quadratic_program.binary_var(name='x_{}'.format(i)) quadratic_program.maximize(quadratic =qubo_matrix, linear = qubo_vector) return quadratic_program quadratic_program = quadratic_program_from_graph(graphs['custom']) print(quadratic_program.export_as_lp_string()) from qc_grader import grade_lab2_ex2 # Note that the grading function is expecting a quadratic program grade_lab2_ex2(quadratic_program) def qaoa_circuit(qubo: QuadraticProgram, p: int = 1): """ Given a QUBO instance and the number of layers p, constructs the corresponding parameterized QAOA circuit with p layers. Args: qubo: The quadratic program instance p: The number of layers in the QAOA circuit Returns: The parameterized QAOA circuit """ size = len(qubo.variables) qubo_matrix = qubo.objective.quadratic.to_array(symmetric=True) qubo_linearity = qubo.objective.linear.to_array() #Prepare the quantum and classical registers qaoa_circuit = QuantumCircuit(size,size) #Apply the initial layer of Hadamard gates to all qubits qaoa_circuit.h(range(size)) #Create the parameters to be used in the circuit gammas = ParameterVector('gamma', p) betas = ParameterVector('beta', p) #Outer loop to create each layer for i in range(p): #Apply R_Z rotational gates from cost layer #INSERT YOUR CODE HERE for j in range(size): qubo_matrix_sum_of_col = 0 for k in range(size): qubo_matrix_sum_of_col+= qubo_matrix[j][k] qaoa_circuit.rz(gammas[i]*(qubo_linearity[j]+qubo_matrix_sum_of_col),j) #Apply R_ZZ rotational gates for entangled qubit rotations from cost layer #INSERT YOUR CODE HERE for j in range(size): for k in range(size): if j!=k: qaoa_circuit.rzz(gammas[i]*qubo_matrix[j][k]*0.5,j,k) # Apply single qubit X - rotations with angle 2*beta_i to all qubits #INSERT YOUR CODE HERE for j in range(size): qaoa_circuit.rx(2*betas[i],j) return qaoa_circuit quadratic_program = quadratic_program_from_graph(graphs['custom']) custom_circuit = qaoa_circuit(qubo = quadratic_program) test = custom_circuit.assign_parameters(parameters=[1.0]*len(custom_circuit.parameters)) from qc_grader import grade_lab2_ex3 # Note that the grading function is expecting a quantum circuit grade_lab2_ex3(test) from qiskit.algorithms import QAOA from qiskit_optimization.algorithms import MinimumEigenOptimizer backend = Aer.get_backend('statevector_simulator') qaoa = QAOA(optimizer = ADAM(), quantum_instance = backend, reps=1, initial_point = [0.1,0.1]) eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa) quadratic_program = quadratic_program_from_graph(graphs['custom']) result = eigen_optimizer.solve(quadratic_program) print(result) def plot_samples(samples): """ Plots a bar diagram for the samples of a quantum algorithm Args: samples """ #Sort samples by probability samples = sorted(samples, key = lambda x: x.probability) #Get list of probabilities, function values and bitstrings probabilities = [sample.probability for sample in samples] values = [sample.fval for sample in samples] bitstrings = [''.join([str(int(i)) for i in sample.x]) for sample in samples] #Plot bar diagram sample_plot = go.Bar(x = bitstrings, y = probabilities, marker=dict(color=values, colorscale = 'plasma',colorbar=dict(title='Function Value'))) fig = go.Figure( data=sample_plot, layout = dict( xaxis=dict( type = 'category' ) ) ) fig.show() plot_samples(result.samples) graph_name = 'custom' quadratic_program = quadratic_program_from_graph(graph=graphs[graph_name]) trajectory={'beta_0':[], 'gamma_0':[], 'energy':[]} offset = 1/4*quadratic_program.objective.quadratic.to_array(symmetric = True).sum() + 1/2*quadratic_program.objective.linear.to_array().sum() def callback(eval_count, params, mean, std_dev): trajectory['beta_0'].append(params[1]) trajectory['gamma_0'].append(params[0]) trajectory['energy'].append(-mean + offset) optimizers = { 'cobyla': COBYLA(), 'slsqp': SLSQP(), 'adam': ADAM() } qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=1, initial_point = [6.2,1.8],callback = callback) eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa) result = eigen_optimizer.solve(quadratic_program) fig = QAOA_widget(landscape_file=f'./resources/energy_landscapes/{graph_name}.csv', trajectory = trajectory, samples = result.samples) fig.show() graph_name = 'custom' quadratic_program = quadratic_program_from_graph(graphs[graph_name]) #Create callback to record total number of evaluations max_evals = 0 def callback(eval_count, params, mean, std_dev): global max_evals max_evals = eval_count #Create empty lists to track values energies = [] runtimes = [] num_evals=[] #Run QAOA for different values of p for p in range(1,10): print(f'Evaluating for p = {p}...') qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=p, callback=callback) eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa) start = time() result = eigen_optimizer.solve(quadratic_program) runtimes.append(time()-start) num_evals.append(max_evals) #Calculate energy of final state from samples avg_value = 0. for sample in result.samples: avg_value += sample.probability*sample.fval energies.append(avg_value) #Create and display plots energy_plot = go.Scatter(x = list(range(1,10)), y =energies, marker=dict(color=energies, colorscale = 'plasma')) runtime_plot = go.Scatter(x = list(range(1,10)), y =runtimes, marker=dict(color=runtimes, colorscale = 'plasma')) num_evals_plot = go.Scatter(x = list(range(1,10)), y =num_evals, marker=dict(color=num_evals, colorscale = 'plasma')) fig = make_subplots(rows = 1, cols = 3, subplot_titles = ['Energy value', 'Runtime', 'Number of evaluations']) fig.update_layout(width=1800,height=600, showlegend=False) fig.add_trace(energy_plot, row=1, col=1) fig.add_trace(runtime_plot, row=1, col=2) fig.add_trace(num_evals_plot, row=1, col=3) clear_output() fig.show() def plot_qaoa_energy_landscape(graph: nx.Graph, cvar: float = None): num_shots = 1000 seed = 42 simulator = Aer.get_backend('qasm_simulator') simulator.set_options(seed_simulator = 42) #Generate circuit circuit = qaoa_circuit(qubo = quadratic_program_from_graph(graph), p=1) circuit.measure(range(graph.number_of_nodes()),range(graph.number_of_nodes())) #Create dictionary with precomputed cut values for all bitstrings cut_values = {} size = graph.number_of_nodes() for i in range(2**size): bitstr = '{:b}'.format(i).rjust(size, '0')[::-1] x = [int(bit) for bit in bitstr] cut_values[bitstr] = maxcut_cost_fn(graph, x) #Perform grid search over all parameters data_points = [] max_energy = None for beta in np.linspace(0,np.pi, 50): for gamma in np.linspace(0, 4*np.pi, 50): bound_circuit = circuit.assign_parameters([beta, gamma]) result = simulator.run(bound_circuit, shots = num_shots).result() statevector = result.get_counts(bound_circuit) energy = 0 measured_cuts = [] for bitstring, count in statevector.items(): measured_cuts = measured_cuts + [cut_values[bitstring]]*count if cvar is None: #Calculate the mean of all cut values energy = sum(measured_cuts)/num_shots else: #raise NotImplementedError() #INSERT YOUR CODE HERE measured_cuts = sorted(measured_cuts, reverse = True) for w in range(int(cvar*num_shots)): energy += measured_cuts[w]/int((cvar*num_shots)) #Update optimal parameters if max_energy is None or energy > max_energy: max_energy = energy optimum = {'beta': beta, 'gamma': gamma, 'energy': energy} #Update data data_points.append({'beta': beta, 'gamma': gamma, 'energy': energy}) #Create and display surface plot from data_points df = pd.DataFrame(data_points) df = df.pivot(index='beta', columns='gamma', values='energy') matrix = df.to_numpy() beta_values = df.index.tolist() gamma_values = df.columns.tolist() surface_plot = go.Surface( x=gamma_values, y=beta_values, z=matrix, coloraxis = 'coloraxis' ) fig = go.Figure(data = surface_plot) fig.show() #Return optimum return optimum graph = graphs['custom'] optimal_parameters = plot_qaoa_energy_landscape(graph = graph) print('Optimal parameters:') print(optimal_parameters) optimal_parameters = plot_qaoa_energy_landscape(graph = graph, cvar = 0.2) print(optimal_parameters) from qc_grader import grade_lab2_ex4 # Note that the grading function is expecting a python dictionary # with the entries 'beta', 'gamma' and 'energy' grade_lab2_ex4(optimal_parameters)
https://github.com/dkp-quantum/Tutorials
dkp-quantum
# If you already have saved IBM credentials with previous version, # update your credentials that is stored in disk IBMQ.update_account() # import from qiskit import * import numpy as np from qiskit.visualization import plot_histogram, plot_state_city, plot_state_paulivec from qiskit.quantum_info import Pauli, state_fidelity, basis_state, process_fidelity from qiskit.tools.monitor import backend_overview, backend_monitor, job_monitor # Create a quantum register with 3 qubits q = QuantumRegister(3,'q') # Form a quantum circuit # Note that the circuit name is optional qc = QuantumCircuit(q,name="first_qc") # Display the quantum circuit qc.draw() # Create a classical register with 3 bits c = ClassicalRegister(3,'c') meas = QuantumCircuit(q,c,name="first_m") meas.barrier(q) meas.measure(q[0], c[0]) meas.measure(q[1], c[1]) meas.measure(q[2], c[2]) #meas.measure(q[3], c[3]) #meas.measure(q[4], c[4]) meas.draw() # Add a x gate on qubit 0. qc.x(0) # Add a Hadamard gate on qubit 1, putting this in superposition. qc.h(1) # Add a CX (CNOT) gate on control qubit 1 # and target qubit 2 to create an entangled state. qc.cx(1, 2) qc.draw() # Quantum circuits can be added with + operations # Add two pre-defined circuits qc_comp=qc+meas qc_comp.draw() # Draw the quantum circuit in a different (slightly better) format qc_comp.draw(output='mpl') # Use Aer's qasm_simulator backend_q = Aer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator. # We've set the number of repeats of the circuit # to be 1024, which is default. job_sim1 = execute(qc_comp, backend_q, shots=1024) job_sim1.status() # Grab the results from the job. result_sim1 = job_sim1.result() result_sim1 result_sim1.get_counts(qc_comp) plot_histogram(result_sim1.get_counts(qc_comp)) # Use Aer's statevector_simulator backend_sv = Aer.get_backend('statevector_simulator') # Execute the circuit on the statevector simulator. job_sim2 = execute(qc, backend_sv) # Grab the results from the job. result_sim2 = job_sim2.result() # Output the entire result job_sim2.result() # See output state as a vector outputstate = result_sim2.get_statevector(qc, decimals=5) print(outputstate) # Visualize density matrix plot_state_city(outputstate) # Examine state fidelity, compare with a basis state |111> sf1=state_fidelity(basis_state('111', 3), outputstate) # Examine state fidelity w.r.t the desired state desired_state=[0,1,0,0,0,0,0,1]/np.sqrt(2) sf2=state_fidelity(desired_state, outputstate) print(sf1) print(sf2) # Create a simple quantum register with 2 qubit # to examine unitary simulator qu2 = QuantumRegister(2,'qu') # Form a quantum circuit # Note that the circuit name is optional qu = QuantumCircuit(qu2,name="unitary_qc") # Add a single qubit rotation qu.z(0) qu.z(1) # Display the quantum circuit qu.draw(output='mpl') # Use Aer's unitary_simulator backend_u = Aer.get_backend('unitary_simulator') # Execute the circuit on the unitary simulator. job_usim = execute(qu, backend_u) # Grab the results from the job. result_usim = job_usim.result() result_usim # Output the unitary matrix unitary = result_usim.get_unitary(qu) print('%s\n' % unitary) # Check process fidelity pf1=process_fidelity(Pauli(label='IX').to_matrix(), unitary) pf2=process_fidelity(Pauli(label='ZZ').to_matrix(), unitary) print('%s\n' % pf1) print('%s\n' % pf2) # Measure an expectation value of a Pauli observable Z = np.array([[1, 0], [0, -1]]) X = np.array([[0, 1], [1, 0]]) Y = np.array([[0, -1j], [1j, 0]]) ZZ=np.kron(Z,Z) XX=np.kron(X,X) # Or use qiskit's built-in function to define Pauli matrices ZI = Pauli(label='ZI').to_matrix() XI = Pauli(label='XI').to_matrix() YI = Pauli(label='YI').to_matrix() # Create some functions for measuring expectation values # For pure states def expectation_state(state, Operator): return np.dot(state.conj(), np.dot(Operator, state)) # For density matrices def expectation_density(density, Operator): return np.trace(Operator @ density) IBMQ.enable_account('YOUR_TOKERN') print(IBMQ.stored_account()) print(IBMQ.active_account()) my_provider=IBMQ.get_provider() my_provider.backends() # Retrieve IBM Quantum device information backend_overview() # Retrieve a specific IBM Quantum device information # ibmq_16_melbourne as an example backend_mel = my_provider.get_backend('ibmq_16_melbourne') backend_monitor(backend_mel) # Create a 3-qubit GHZ state ghz3 = QuantumRegister(3,'q') qc= QuantumCircuit(ghz3) qc.h(0) qc.cx(0,1) qc.cx(0,2) qghz3=qc+meas qghz3.draw(output='mpl') # Define backend as one of the real devices (5-qubit systems for now) backend_qx2 = my_provider.get_backend('ibmqx2') backend_qx4 = my_provider.get_backend('ibmqx4') # There is a new 5-qubit backend backend_ou = my_provider.get_backend('ibmq_ourense') # Run 3-qubit GHZ experiment on a 5-qubit device (try ourense) job_exp = execute(qghz3, backend=backend_ou) job_monitor(job_exp) # Grab experimental results result_ou = job_exp.result() counts_ou = result_exp.get_counts(qghz3) plot_histogram(counts_ou) # Run the same experiment on the other 5-qubit device as well. job_exp2 = execute(qghz3, backend=backend_qx4) job_monitor(job_exp2) # Grab experimental results result_exp2 = job_exp2.result() counts_exp2 = result_exp2.get_counts(qghz3) # Finally, run the same experiment on the 14-qubit device. job_exp3 = execute(qghz3, backend=backend_mel) job_monitor(job_exp3) # Grab experimental results result_mel = job_exp3.result() counts_mel = result_mel.get_counts(qghz3) plot_histogram(counts_mel) # Now, compare to theory by running it on qasm_simulator job_qasm = execute(qghz3,backend=backend_q) result_qasm = job_qasm.result() counts_qasm = result_qasm.get_counts(qghz3) # Plot both experimental and ideal results plot_histogram([counts_qasm,counts_ou,counts_mel], color=['black','green','blue'], legend=['QASM','Ourense','Melbourne']) # Create a quantum register with 3 qubits q = QuantumRegister(3,'q') # Form a quantum circuit qent = QuantumCircuit(q) qent.initialize([1, 0, 0, 0, 0, 0, 0, 1] / np.sqrt(2), [q[0], q[1], q[2]]) # Display the quantum circuit qent.draw(output='mpl') # Use Aer's state vector simulator backend_sv = Aer.get_backend('statevector_simulator') # Execute and plot output state output_ent = execute(qent, backend_sv).result().get_statevector(0, decimals=3) plot_state_city(output_ent) # Build a sub-circuit # sub_ghz(n,c,t) creates a quantum circuit for creating an n-qubit GHZ state. # n is the total number of qubits, c is an index for a control qubit, t is a vector of indices for target qubits. def sub_ghz(n,c,t): sub_q = QuantumRegister(n) sub_circ = QuantumCircuit(sub_q, name='sub_ghz') sub_circ.h(c) for i in t: sub_circ.cx(c,i) return sub_circ # Create a sub-circuit for 3-qubit GHZ state prep. sub_ghz3 = sub_ghz(3,0,[1,2]) sub_inst3 = sub_ghz3.to_instruction() # Create a sub-circuit consisting of T gate and cnot. sub_tcnot = QuantumCircuit(QuantumRegister(2),name='t+cnot') sub_tcnot.t(0) sub_tcnot.cx(0,1) q = QuantumRegister(5, 'q') circ = QuantumCircuit(q) # Now create a quantum circuit using sub-circuits. # Apply Hadamard on all gates. for i in range(5): circ.h(i) # circ.barrier() # Appy 2-qubit GHZ preparation on qubits 0 and 1, and on qubits 3 and 4. circ.append(sub_tcnot, [q[0],q[1]]) circ.append(sub_tcnot, [q[3], q[4]]) # circ.barrier() # Apply 3-qubit GHZ preparation on all 3 neighbouring qubits. for i in range(3): circ.append(sub_inst3, [q[i], q[i+1],q[i+2]]) circ.draw(output='mpl') # We can also decompose the circuit that is constructed using sub-circuits. circ.decompose().draw(output='mpl') from qiskit.circuit import Parameter # Define two parameters, t1 and t2 theta1 = Parameter('t1') theta2 = Parameter('t2') # Build a 5-qubit circuit qc = QuantumCircuit(5, 1) # First parameter, t1, is used for a single qubit rotation of a controlled qubit qc.ry(theta1,0) for i in range(5-1): qc.cx(i, i+1) qc.barrier() # Second parameter, t2, is used here qc.rz(theta2,range(5)) qc.barrier() for i in reversed(range(5-1)): qc.cx(i, i+1) qc.ry(theta1,0) qc.measure(0, 0) qc.draw(output='mpl') theta1_range = np.linspace(0, np.pi/2, 2) theta2_range = np.linspace(0, 2 * np.pi, 64) circuits = [qc.bind_parameters({theta1: theta_val1, theta2: theta_val2}) for theta_val1 in theta1_range for theta_val2 in theta2_range ] # Visualize several circuits to check that correct circuits are generated correctly. circuits[0].draw(output='mpl') # circuits[1].draw(output='mpl') # circuits[64].draw(output='mpl') # theta1_range = np.linspace(0, np.pi/2, 2) # theta2_range = np.linspace(0, 2 * np.pi, 64) # circuits = [qc.bind_parameters({theta1: theta_val1, theta2: theta_val2}) # for theta_val1 in theta1_range for theta_val2 in theta2_range ] # Visualize several circuits to check that correct circuits are generated correctly. # circuits[0].draw(output='mpl') circuits[1].draw(output='mpl') # circuits[64].draw(output='mpl') # theta1_range = np.linspace(0, np.pi/2, 2) # theta2_range = np.linspace(0, 2 * np.pi, 64) # circuits = [qc.bind_parameters({theta1: theta_val1, theta2: theta_val2}) # for theta_val1 in theta1_range for theta_val2 in theta2_range ] # Visualize several circuits to check that correct circuits are generated correctly. # circuits[0].draw(output='mpl') # circuits[1].draw(output='mpl') circuits[64].draw(output='mpl') # Execute multiple circuits job = execute(qc, backend=Aer.get_backend('qasm_simulator'), parameter_binds=[{theta1: theta_val1, theta2: theta_val2} for theta_val1 in theta1_range for theta_val2 in theta2_range]) # Store all counts counts = [job.result().get_counts(i) for i in range(len(job.result().results))] # Plot to visualize the result import matplotlib.pyplot as plt plt.figure(figsize=(12,6)) plt.plot(range(len(theta1_range)*len(theta2_range)), list(map(lambda counts: (counts.get('0',0)-counts.get('1',1))/1024,counts))) plt.show() # Reset operation forces the target qubit to go to |0> q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.reset(q[0]) # qc.x(q) qc.measure(q, c) qc.draw(output='mpl') # Test the result job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots=1024) job.result().get_counts(qc) # Controlled qubit operation, controlled by classical bits # This could be useful for designing a post-selection scheme of a quantum algorithm q2 = QuantumRegister(2,'q') cont = ClassicalRegister(1,'cont') qc = QuantumCircuit(q2,cont) qc.x(0) qc.swap(q2[0],q2[1]).c_if(cont, 1) qc.measure(q2[0],cont) qc.draw(output='mpl') job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots=1024) job.result().get_counts(qc) import random as r qr = QuantumRegister(3) cr1 = ClassicalRegister(1) # Define a separate classical register for classically-controlled gate cr2 = ClassicalRegister(1) qtel = QuantumCircuit(qr,cr1,cr2) # Make a reference circuit to compare qref = QuantumCircuit(1,1) # Prepare a 2-qubit bell state qtel.h(1) qtel.cx(1,2) qtel.barrier() # Prepare a random 1-qubit state a1 = r.random()*np.pi a2 = r.random()*np.pi a3= r.random()*np.pi qtel.u3(a1,a2,a3,0) # Design a reference circuit for comparing to teleportation result qref.u3(a1,a2,a3,0) qref.measure(0,0) print('Reference circuit:') display(qref.draw(output='mpl')) # Apply bell measurement on qubit 0 and 1 qtel.cx(0,1) qtel.h(0) qtel.barrier() qtel.measure([0, 1],[0, 1]) qtel.z(2).c_if(cr1,1) qtel.x(2).c_if(cr2,1) qtel.measure(2,1) print('Quantum teleportation circuit:') display(qtel.draw(output='mpl')) # n is the number of shots n=10000 job_qtel = execute(qtel, backend_q, shots=n) job_ref = execute(qref, backend_q, shots=n) display(plot_histogram(job_ref.result().get_counts(qref))) qtel_c = job_qtel.result().get_counts(qtel) # Need some post-processing print(qtel_c) p1 = (qtel_c['1 0']+qtel_c['1 1'])/n p0 = (qtel_c['0 0']+qtel_c['0 1'])/n print('Prob. 1 from QT = %s' % p1) print('Prob. 0 from QT = %s' % p0) from qiskit.compiler import transpile from qiskit.transpiler import PassManager, Layout from qiskit.tools.visualization import plot_gate_map # Let's take a look at the layout of physical devices with the gate directions display(plot_gate_map(backend_qx4,plot_directed=True)) display(plot_gate_map(backend_ou,plot_directed=True)) display(plot_gate_map(backend_mel,plot_directed=True)) # Create a dummy circuit for default transpiler demonstration qr = QuantumRegister(3) cr = ClassicalRegister(3) qc = QuantumCircuit(qr,cr) qc.h(0) qc.swap(0,1) qc.cx(1,0) qc.s(2) qc.x(2) qc.h(2) qc.measure(qr[2],cr[2]) qc.h(0) qc.cx(0,1) qc.cx(0,1) qc.h(0) qc.measure(qr[0],cr[0]) qc.measure(qr[1],cr[1]) print('Original circuit') display(qc.draw(output='mpl')) # Transpile the circuit to run on ibmqx4 qt_qx4 = transpile(qc,backend_qx4) print('Transpiled circuit for ibmqx4') display(qt_qx4.draw(output='mpl')) # Transpile the circuit to run on ibmq_Ourense qt_ou = transpile(qc,backend_ou) print('Transpiled circuit for ibmqx_Oursense') display(qt_ou.draw(output='mpl')) qr = QuantumRegister(3,'q') qc = QuantumCircuit(qr) qc.h(0) qc.cx(0,1) qc.cx(0,2) qc.draw(output='mpl') qc_t = transpile(qc, basis_gates=['u1','u2','u3','cx']) # Display transpiled circuit display(qc_t.draw(output='mpl')) # Print out some circuit properties # Total nunmber of operations print("Number of operations = %s" % qc_t.size()) # Circuit depth print("Circuit depth = %s" % qc_t.depth()) # Number of qubits print("Number of qubits = %s" % qc_t.width()) # Breakdown of operations by type print("Operations: %s" % qc_t.count_ops()) # Number of unentangled subcircuits in this circuit. # In principle, each subcircuit can be executed on a different quantum device. print("Number of unentangled subcircuits = %s" % qc_t.num_tensor_factors()) # Map it onto 5 qubit backend ibmqx2 qc_qx2 = transpile(qc, backend_qx2, basis_gates=['u1','u2','u3','cx']) display(qc_qx2.draw(output='mpl')) display(plot_gate_map(backend_qx2,plot_directed=True)) # Print out some circuit properties # Total nunmber of operations print("Number of operations = %s" % qc_qx2.size()) # Circuit depth print("Circuit depth = %s" % qc_qx2.depth()) # Map it onto 5 qubit backend ibmqx4 qc_qx4 = transpile(qc, backend_qx4,basis_gates=['u1','u2','u3','cx']) display(qc_qx4.draw(output='mpl')) display(plot_gate_map(backend_qx4,plot_directed=True)) # Print out some circuit properties # Total nunmber of operations print("Number of operations = %s" % qc_qx4.size()) # Circuit depth print("Circuit depth = %s" % qc_qx4.depth()) # Customize the layout layout = Layout({qr[0]: 3, qr[1]: 4, qr[2]: 2}) # Map it onto 5 qubit backend ibmqx4 qc_qx4_new = transpile(qc, backend_qx4,initial_layout=layout,basis_gates=['u1','u2','u3','cx']) display(qc_qx4_new.draw(output='mpl')) # Print out some circuit properties # Total nunmber of operations print("Number of operations = %s" % qc_qx4_new.size()) # Circuit depth print("Circuit depth = %s" % qc_qx4_new.depth()) # Test transpilation with Toffoli gate qr = QuantumRegister(3,'q') qccx = QuantumCircuit(qr) qccx.ccx(0,1,2) qccx.draw(output='mpl') qccx_t = transpile(qccx, basis_gates=['u3','cx']) # Display transpiled circuit display(qccx_t.draw(output='mpl')) # Print out some circuit properties # Total nunmber of operations print("Number of operations = %s" % qccx_t.size()) # Circuit depth print("Circuit depth = %s" % qccx_t.depth()) # Number of qubits print("Number of qubits = %s" % qccx_t.width()) # Breakdown of operations by type print("Operations: %s" % qccx_t.count_ops()) # Number of unentangled subcircuits in this circuit. # In principle, each subcircuit can be executed on a different quantum device. print("Number of unentangled subcircuits = %s" % qccx_t.num_tensor_factors()) # Map it onto 5 qubit backend ibmqx2 qccx_qx2 = transpile(qccx, backend_qx2) display(qccx_qx2.draw(output='mpl')) display(plot_gate_map(backend_qx2,plot_directed=True)) # Print out some circuit properties # Total nunmber of operations print("Number of operations = %s" % qccx_qx2.size()) # Circuit depth print("Circuit depth = %s" % qccx_qx2.depth()) # Number of cx gates print("Number of cx operations = %s" % qccx_qx2.count_ops()['cx']) # Map it onto 5 qubit backend ibmqx4 qccx_qx4 = transpile(qccx, backend_qx4) display(qccx_qx4.draw(output='mpl')) display(plot_gate_map(backend_qx4,plot_directed=True)) # Print out some circuit properties # Total nunmber of operations print("Number of operations = %s" % qccx_qx4.size()) # Circuit depth print("Circuit depth = %s" % qccx_qx4.depth()) # Number of cx gates print("Number of cx operations = %s" % qccx_qx4.count_ops()['cx']) # Customize the layout layout = Layout({qr[0]: 3, qr[1]: 4, qr[2]: 2}) # Map it onto 5 qubit backend ibmqx4 qccx_qx4_new = transpile(qccx, backend_qx4,initial_layout=layout) display(qccx_qx4_new.draw(output='mpl')) display(plot_gate_map(backend_qx4,plot_directed=True)) # Print out some circuit properties # Total nunmber of operations print("Number of operations = %s" % qccx_qx4_new.size()) # Circuit depth print("Circuit depth = %s" % qccx_qx4_new.depth()) # Number of cx gates print("Number of cx operations = %s" % qccx_qx4.count_ops()['cx']) # The device information such as gate error and T1 and T2 also should be considered # when customizing the layout. backend_monitor(backend_qx2) display(plot_gate_map(backend_ou,plot_directed=True)) # Customize the layout IBMQ Ourense layout_ou = Layout({qr[0]: 2, qr[1]: 3, qr[2]: 1}) # Map it onto 5 qubit backend ibmqx4 qccx_ou = transpile(qccx, backend_ou,initial_layout=layout_ou) display(qccx_ou.draw(output='mpl')) # Print out some circuit properties # Total nunmber of operations print("Number of operations = %s" % qccx_ou.size()) # Circuit depth print("Circuit depth = %s" % qccx_ou.depth()) # Number of cx gates print("Number of cx operations = %s" % qccx_ou.count_ops()['cx']) # Apply Toffoli among 5 qubits qr = QuantumRegister(5,'q') toff = QuantumCircuit(qr) for i in range(5): toff.h(i) toff.ccx(0,1,2) toff.ccx(1,2,3) toff.ccx(2,3,4) display(toff.draw(output='mpl')) # Print out some circuit properties # Total nunmber of operations print("Number of operations = %s" % toff.size()) # Count different types of operations print("Operation counts = %s" % toff.count_ops()) # Circuit depth print("Circuit depth = %s" % toff.depth()) toff_t = transpile(toff, backend_mel) display(toff_t.draw(output='latex')) # Print out some circuit properties # Total nunmber of operations print("Number of operations = %s" % toff_t.size()) # Count different types of operations print("Operation counts = %s" % toff_t.count_ops()) # Circuit depth print("Circuit depth = %s" % toff_t.depth()) # Transpile many times (100 times in this example) and pick the best one tcircs0 = transpile([toff]*100, backend_mel,optimization_level=0) tcircs1 = transpile([toff]*100, backend_mel,optimization_level=1) tcircs2 = transpile([toff]*100, backend_mel,optimization_level=2) tcircs3 = transpile([toff]*100, backend_mel,optimization_level=3) num_cx0 = [c.count_ops()['cx'] for c in tcircs0] num_cx1 = [c.count_ops()['cx'] for c in tcircs1] num_cx2 = [c.count_ops()['cx'] for c in tcircs2] num_cx3 = [c.count_ops()['cx'] for c in tcircs3] num_tot0 = [c.size() for c in tcircs0] num_tot1 = [c.size() for c in tcircs1] num_tot2 = [c.size() for c in tcircs2] num_tot3 = [c.size() for c in tcircs3] num_depth0 = [c.depth() for c in tcircs0] num_depth1 = [c.depth() for c in tcircs1] num_depth2 = [c.depth() for c in tcircs2] num_depth3 = [c.depth() for c in tcircs3] plt.rcParams.update({'font.size': 16}) # Plot the number of CNOT gates plt.figure(figsize=(12,6)) plt.plot(range(len(num_cx0)),num_cx0,'r',label='level 0') plt.plot(range(len(num_cx1)),num_cx1,'b',label='level 1') plt.plot(range(len(num_cx2)),num_cx2,'g',label='level 2') plt.plot(range(len(num_cx3)),num_cx3,'k',label='level 3') plt.legend(loc='upper left') plt.xlabel('Random trial') plt.ylabel('# of cx gates') plt.show() # Plot total number of gates plt.figure(figsize=(12,6)) plt.plot(range(len(num_cx0)),num_tot0,'r',label='level 0') plt.plot(range(len(num_cx1)),num_tot1,'b',label='level 1') plt.plot(range(len(num_cx2)),num_tot2,'g',label='level 2') plt.plot(range(len(num_cx3)),num_tot3,'k',label='level 3') plt.legend(loc='upper left') plt.xlabel('Random trial') plt.ylabel('# of total gates') plt.show() # Plot the number of CNOT gates plt.figure(figsize=(12,6)) plt.plot(range(len(num_cx0)),num_depth0,'r',label='level 0') plt.plot(range(len(num_cx1)),num_depth1,'b',label='level 1') plt.plot(range(len(num_cx2)),num_depth2,'g',label='level 2') plt.plot(range(len(num_cx3)),num_depth3,'k',label='level 3') plt.legend(loc='upper left') plt.xlabel('Random trial') plt.ylabel('Circuit depth') plt.show() print('Opt0: Minimum # of cx gates = %s' % min(num_cx0)) print('Opt0: The best circuit is the circut %s' % num_cx0.index(min(num_cx0))) print('Opt1: Minimum # of cx gates = %s' % min(num_cx1)) print('Opt1: The best circuit is the circut %s' % num_cx1.index(min(num_cx1))) print('Opt2: Minimum # of cx gates = %s' % min(num_cx2)) print('Opt2: The best circuit is the circut %s' % num_cx2.index(min(num_cx2))) print('Opt3: Minimum # of cx gates = %s' % min(num_cx3)) print('Opt3: The best circuit is the circut %s' % num_cx3.index(min(num_cx3))) # Create a 10-qubit GHZ state qr = QuantumRegister(10,'q') ghz = QuantumCircuit(qr) ghz.h(0) for i in range(9): ghz.cx(i,i+1) display(ghz.draw(output='mpl')) # Print out some circuit properties # Total nunmber of operations print("Number of operations = %s" % ghz.size()) # Count different types of operations print("Operation counts = %s" % ghz.count_ops()) # Circuit depth print("Circuit depth = %s" % ghz.depth()) ghz_t = transpile(ghz, backend_mel) ghz_t.draw(output='latex') # Print out some circuit properties # Total nunmber of operations print("Number of operations = %s" % ghz_t.size()) # Count different types of operations print("Operation counts = %s" % ghz_t.count_ops()) # Circuit depth print("Circuit depth = %s" % ghz_t.depth()) # Transpile 100 times and pick the best one circs = transpile([ghz]*100, backend_mel) num_cx = [c.count_ops()['cx'] for c in circs] # Plot the number of CNOT gates plt.figure(figsize=(12,6)) plt.plot(range(len(num_cx)),num_cx) plt.show() print('Minimum # of cx gates = %s' % min(num_cx)) print('The best circuit is the circut %s' % num_cx.index(min(num_cx)))
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
mathelatics
from qiskit import * from qiskit.tools.visualization import plot_bloch_multivector, plot_histogram qc = QuantumCircuit(1, 1) qc.x(0) qc.draw(output='mpl') simulator = Aer.get_backend('statevector_simulator') result = execute(qc, backend=simulator).result() statevector = result.get_statevector() print(statevector) plot_bloch_multivector(statevector) qc.measure([0],[0]) simulator = Aer.get_backend('qasm_simulator') result = execute(qc, backend=simulator, shots=1024).result() counts = result.get_counts() print(counts) plot_histogram(counts) qc = QuantumCircuit(1, 1) qc.x(0) simulator = Aer.get_backend('unitary_simulator') result = execute(qc, backend=simulator).result() unitary = result.get_unitary() print(unitary)
https://github.com/Tojarieh97/VQE
Tojarieh97
from qiskit.circuit.library.standard_gates import RXGate, RZGate, CXGate, CZGate from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister import numpy as np def anzats_circ(thetas, D1, D2, in_state): qr = QuantumRegister(4, name="q") qc = QuantumCircuit(qr) qc.initialize(in_state) for d in range(D1): qc.append(RXGate(thetas[8]), [qr[2]]) qc.append(RXGate(thetas[9]), [qr[3]]) qc.append(RZGate(thetas[10]), [qr[2]]) qc.append(RZGate(thetas[11]), [qr[3]]) qc.append(CZGate(), [qr[2], qr[3]]) qc.barrier(qr) for d in range(D2): qc.append(RXGate(thetas[0]), [qr[0]]) qc.append(RXGate(thetas[1]), [qr[1]]) qc.append(RXGate(thetas[2]), [qr[2]]) qc.append(RXGate(thetas[3]), [qr[3]]) qc.append(RZGate(thetas[4]), [qr[0]]) qc.append(RZGate(thetas[5]), [qr[1]]) qc.append(RZGate(thetas[6]), [qr[2]]) qc.append(RZGate(thetas[7]), [qr[3]]) qc.append(CZGate(), [qr[0], qr[1]]) qc.append(CZGate(), [qr[1], qr[2]]) qc.append(CZGate(), [qr[2], qr[3]]) qc.barrier(qr) qc.append(RXGate(thetas[0]), [qr[0]]) qc.append(RXGate(thetas[1]), [qr[1]]) qc.append(RXGate(thetas[2]), [qr[2]]) qc.append(RXGate(thetas[3]), [qr[3]]) qc.append(RZGate(thetas[4]), [qr[0]]) qc.append(RZGate(thetas[5]), [qr[1]]) qc.append(RZGate(thetas[6]), [qr[2]]) qc.append(RZGate(thetas[7]), [qr[3]]) qc.measure_all() return qc def get_k_basis(k, n): full_basis = np.identity(n) return full_basis[:k]
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. """These tests are the examples given in the arXiv paper describing OpenQASM 2. Specifically, there is a test for each subsection (except the description of 'qelib1.inc') in section 3 of https://arxiv.org/abs/1707.03429v2. The examples are copy/pasted from the source files there.""" # pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring import math import os import tempfile import ddt from qiskit import qasm2 from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister, Qubit from qiskit.circuit.library import U1Gate, U3Gate, CU1Gate from qiskit.test import QiskitTestCase from . import gate_builder def load(string, *args, **kwargs): # We're deliberately not using the context-manager form here because we need to use it in a # slightly odd pattern. # pylint: disable=consider-using-with temp = tempfile.NamedTemporaryFile(mode="w", delete=False) try: temp.write(string) # NamedTemporaryFile claims not to be openable a second time on Windows, so close it # (without deletion) so Rust can open it again. temp.close() return qasm2.load(temp.name, *args, **kwargs) finally: # Now actually clean up after ourselves. os.unlink(temp.name) @ddt.ddt class TestArxivExamples(QiskitTestCase): @ddt.data(qasm2.loads, load) def test_teleportation(self, parser): example = """\ // quantum teleportation example OPENQASM 2.0; include "qelib1.inc"; qreg q[3]; creg c0[1]; creg c1[1]; creg c2[1]; // optional post-rotation for state tomography gate post q { } u3(0.3,0.2,0.1) q[0]; h q[1]; cx q[1],q[2]; barrier q; cx q[0],q[1]; h q[0]; measure q[0] -> c0[0]; measure q[1] -> c1[0]; if(c0==1) z q[2]; if(c1==1) x q[2]; post q[2]; measure q[2] -> c2[0];""" parsed = parser(example) post = gate_builder("post", [], QuantumCircuit([Qubit()])) q = QuantumRegister(3, "q") c0 = ClassicalRegister(1, "c0") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(1, "c2") qc = QuantumCircuit(q, c0, c1, c2) qc.append(U3Gate(0.3, 0.2, 0.1), [q[0]], []) qc.h(q[1]) qc.cx(q[1], q[2]) qc.barrier(q) qc.cx(q[0], q[1]) qc.h(q[0]) qc.measure(q[0], c0[0]) qc.measure(q[1], c1[0]) qc.z(q[2]).c_if(c0, 1) qc.x(q[2]).c_if(c1, 1) qc.append(post(), [q[2]], []) qc.measure(q[2], c2[0]) self.assertEqual(parsed, qc) @ddt.data(qasm2.loads, load) def test_qft(self, parser): example = """\ // quantum Fourier transform OPENQASM 2.0; include "qelib1.inc"; qreg q[4]; creg c[4]; x q[0]; x q[2]; barrier q; h q[0]; cu1(pi/2) q[1],q[0]; h q[1]; cu1(pi/4) q[2],q[0]; cu1(pi/2) q[2],q[1]; h q[2]; cu1(pi/8) q[3],q[0]; cu1(pi/4) q[3],q[1]; cu1(pi/2) q[3],q[2]; h q[3]; measure q -> c;""" parsed = parser(example) qc = QuantumCircuit(QuantumRegister(4, "q"), ClassicalRegister(4, "c")) qc.x(0) qc.x(2) qc.barrier(range(4)) qc.h(0) qc.append(CU1Gate(math.pi / 2), [1, 0]) qc.h(1) qc.append(CU1Gate(math.pi / 4), [2, 0]) qc.append(CU1Gate(math.pi / 2), [2, 1]) qc.h(2) qc.append(CU1Gate(math.pi / 8), [3, 0]) qc.append(CU1Gate(math.pi / 4), [3, 1]) qc.append(CU1Gate(math.pi / 2), [3, 2]) qc.h(3) qc.measure(range(4), range(4)) self.assertEqual(parsed, qc) @ddt.data(qasm2.loads, load) def test_inverse_qft_1(self, parser): example = """\ // QFT and measure, version 1 OPENQASM 2.0; include "qelib1.inc"; qreg q[4]; creg c[4]; h q; barrier q; h q[0]; measure q[0] -> c[0]; if(c==1) u1(pi/2) q[1]; h q[1]; measure q[1] -> c[1]; if(c==1) u1(pi/4) q[2]; if(c==2) u1(pi/2) q[2]; if(c==3) u1(pi/2+pi/4) q[2]; h q[2]; measure q[2] -> c[2]; if(c==1) u1(pi/8) q[3]; if(c==2) u1(pi/4) q[3]; if(c==3) u1(pi/4+pi/8) q[3]; if(c==4) u1(pi/2) q[3]; if(c==5) u1(pi/2+pi/8) q[3]; if(c==6) u1(pi/2+pi/4) q[3]; if(c==7) u1(pi/2+pi/4+pi/8) q[3]; h q[3]; measure q[3] -> c[3];""" parsed = parser(example) q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c) qc.h(q) qc.barrier(q) qc.h(q[0]) qc.measure(q[0], c[0]) qc.append(U1Gate(math.pi / 2).c_if(c, 1), [q[1]]) qc.h(q[1]) qc.measure(q[1], c[1]) qc.append(U1Gate(math.pi / 4).c_if(c, 1), [q[2]]) qc.append(U1Gate(math.pi / 2).c_if(c, 2), [q[2]]) qc.append(U1Gate(math.pi / 4 + math.pi / 2).c_if(c, 3), [q[2]]) qc.h(q[2]) qc.measure(q[2], c[2]) qc.append(U1Gate(math.pi / 8).c_if(c, 1), [q[3]]) qc.append(U1Gate(math.pi / 4).c_if(c, 2), [q[3]]) qc.append(U1Gate(math.pi / 8 + math.pi / 4).c_if(c, 3), [q[3]]) qc.append(U1Gate(math.pi / 2).c_if(c, 4), [q[3]]) qc.append(U1Gate(math.pi / 8 + math.pi / 2).c_if(c, 5), [q[3]]) qc.append(U1Gate(math.pi / 4 + math.pi / 2).c_if(c, 6), [q[3]]) qc.append(U1Gate(math.pi / 8 + math.pi / 4 + math.pi / 2).c_if(c, 7), [q[3]]) qc.h(q[3]) qc.measure(q[3], c[3]) self.assertEqual(parsed, qc) @ddt.data(qasm2.loads, load) def test_inverse_qft_2(self, parser): example = """\ // QFT and measure, version 2 OPENQASM 2.0; include "qelib1.inc"; qreg q[4]; creg c0[1]; creg c1[1]; creg c2[1]; creg c3[1]; h q; barrier q; h q[0]; measure q[0] -> c0[0]; if(c0==1) u1(pi/2) q[1]; h q[1]; measure q[1] -> c1[0]; if(c0==1) u1(pi/4) q[2]; if(c1==1) u1(pi/2) q[2]; h q[2]; measure q[2] -> c2[0]; if(c0==1) u1(pi/8) q[3]; if(c1==1) u1(pi/4) q[3]; if(c2==1) u1(pi/2) q[3]; h q[3]; measure q[3] -> c3[0];""" parsed = parser(example) q = QuantumRegister(4, "q") c0 = ClassicalRegister(1, "c0") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(1, "c2") c3 = ClassicalRegister(1, "c3") qc = QuantumCircuit(q, c0, c1, c2, c3) qc.h(q) qc.barrier(q) qc.h(q[0]) qc.measure(q[0], c0[0]) qc.append(U1Gate(math.pi / 2).c_if(c0, 1), [q[1]]) qc.h(q[1]) qc.measure(q[1], c1[0]) qc.append(U1Gate(math.pi / 4).c_if(c0, 1), [q[2]]) qc.append(U1Gate(math.pi / 2).c_if(c1, 1), [q[2]]) qc.h(q[2]) qc.measure(q[2], c2[0]) qc.append(U1Gate(math.pi / 8).c_if(c0, 1), [q[3]]) qc.append(U1Gate(math.pi / 4).c_if(c1, 1), [q[3]]) qc.append(U1Gate(math.pi / 2).c_if(c2, 1), [q[3]]) qc.h(q[3]) qc.measure(q[3], c3[0]) self.assertEqual(parsed, qc) @ddt.data(qasm2.loads, load) def test_ripple_carry_adder(self, parser): example = """\ // quantum ripple-carry adder from Cuccaro et al, quant-ph/0410184 OPENQASM 2.0; include "qelib1.inc"; gate majority a,b,c { cx c,b; cx c,a; ccx a,b,c; } gate unmaj a,b,c { ccx a,b,c; cx c,a; cx a,b; } qreg cin[1]; qreg a[4]; qreg b[4]; qreg cout[1]; creg ans[5]; // set input states x a[0]; // a = 0001 x b; // b = 1111 // add a to b, storing result in b majority cin[0],b[0],a[0]; majority a[0],b[1],a[1]; majority a[1],b[2],a[2]; majority a[2],b[3],a[3]; cx a[3],cout[0]; unmaj a[2],b[3],a[3]; unmaj a[1],b[2],a[2]; unmaj a[0],b[1],a[1]; unmaj cin[0],b[0],a[0]; measure b[0] -> ans[0]; measure b[1] -> ans[1]; measure b[2] -> ans[2]; measure b[3] -> ans[3]; measure cout[0] -> ans[4];""" parsed = parser(example) majority_definition = QuantumCircuit([Qubit(), Qubit(), Qubit()]) majority_definition.cx(2, 1) majority_definition.cx(2, 0) majority_definition.ccx(0, 1, 2) majority = gate_builder("majority", [], majority_definition) unmaj_definition = QuantumCircuit([Qubit(), Qubit(), Qubit()]) unmaj_definition.ccx(0, 1, 2) unmaj_definition.cx(2, 0) unmaj_definition.cx(0, 1) unmaj = gate_builder("unmaj", [], unmaj_definition) cin = QuantumRegister(1, "cin") a = QuantumRegister(4, "a") b = QuantumRegister(4, "b") cout = QuantumRegister(1, "cout") ans = ClassicalRegister(5, "ans") qc = QuantumCircuit(cin, a, b, cout, ans) qc.x(a[0]) qc.x(b) qc.append(majority(), [cin[0], b[0], a[0]]) qc.append(majority(), [a[0], b[1], a[1]]) qc.append(majority(), [a[1], b[2], a[2]]) qc.append(majority(), [a[2], b[3], a[3]]) qc.cx(a[3], cout[0]) qc.append(unmaj(), [a[2], b[3], a[3]]) qc.append(unmaj(), [a[1], b[2], a[2]]) qc.append(unmaj(), [a[0], b[1], a[1]]) qc.append(unmaj(), [cin[0], b[0], a[0]]) qc.measure(b, ans[:4]) qc.measure(cout[0], ans[4]) self.assertEqual(parsed, qc) @ddt.data(qasm2.loads, load) def test_randomised_benchmarking(self, parser): example = """\ // One randomized benchmarking sequence OPENQASM 2.0; include "qelib1.inc"; qreg q[2]; creg c[2]; h q[0]; barrier q; cz q[0],q[1]; barrier q; s q[0]; cz q[0],q[1]; barrier q; s q[0]; z q[0]; h q[0]; barrier q; measure q -> c; """ parsed = parser(example) q = QuantumRegister(2, "q") c = ClassicalRegister(2, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.barrier(q) qc.cz(q[0], q[1]) qc.barrier(q) qc.s(q[0]) qc.cz(q[0], q[1]) qc.barrier(q) qc.s(q[0]) qc.z(q[0]) qc.h(q[0]) qc.barrier(q) qc.measure(q, c) self.assertEqual(parsed, qc) @ddt.data(qasm2.loads, load) def test_process_tomography(self, parser): example = """\ OPENQASM 2.0; include "qelib1.inc"; gate pre q { } // pre-rotation gate post q { } // post-rotation qreg q[1]; creg c[1]; pre q[0]; barrier q; h q[0]; barrier q; post q[0]; measure q[0] -> c[0];""" parsed = parser(example) pre = gate_builder("pre", [], QuantumCircuit([Qubit()])) post = gate_builder("post", [], QuantumCircuit([Qubit()])) qc = QuantumCircuit(QuantumRegister(1, "q"), ClassicalRegister(1, "c")) qc.append(pre(), [0]) qc.barrier(qc.qubits) qc.h(0) qc.barrier(qc.qubits) qc.append(post(), [0]) qc.measure(0, 0) self.assertEqual(parsed, qc) @ddt.data(qasm2.loads, load) def test_error_correction(self, parser): example = """\ // Repetition code syndrome measurement OPENQASM 2.0; include "qelib1.inc"; qreg q[3]; qreg a[2]; creg c[3]; creg syn[2]; gate syndrome d1,d2,d3,a1,a2 { cx d1,a1; cx d2,a1; cx d2,a2; cx d3,a2; } x q[0]; // error barrier q; syndrome q[0],q[1],q[2],a[0],a[1]; measure a -> syn; if(syn==1) x q[0]; if(syn==2) x q[2]; if(syn==3) x q[1]; measure q -> c;""" parsed = parser(example) syndrome_definition = QuantumCircuit([Qubit() for _ in [None] * 5]) syndrome_definition.cx(0, 3) syndrome_definition.cx(1, 3) syndrome_definition.cx(1, 4) syndrome_definition.cx(2, 4) syndrome = gate_builder("syndrome", [], syndrome_definition) q = QuantumRegister(3, "q") a = QuantumRegister(2, "a") c = ClassicalRegister(3, "c") syn = ClassicalRegister(2, "syn") qc = QuantumCircuit(q, a, c, syn) qc.x(q[0]) qc.barrier(q) qc.append(syndrome(), [q[0], q[1], q[2], a[0], a[1]]) qc.measure(a, syn) qc.x(q[0]).c_if(syn, 1) qc.x(q[2]).c_if(syn, 2) qc.x(q[1]).c_if(syn, 3) qc.measure(q, c) self.assertEqual(parsed, qc)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit.library import IntegerComparator from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler # set problem parameters n_z = 2 z_max = 2 z_values = np.linspace(-z_max, z_max, 2**n_z) p_zeros = [0.15, 0.25] rhos = [0.1, 0.05] lgd = [1, 2] K = len(p_zeros) alpha = 0.05 from qiskit_finance.circuit.library import GaussianConditionalIndependenceModel as GCI u = GCI(n_z, z_max, p_zeros, rhos) u.draw() u_measure = u.measure_all(inplace=False) sampler = Sampler() job = sampler.run(u_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # analyze uncertainty circuit and determine exact solutions p_z = np.zeros(2**n_z) p_default = np.zeros(K) values = [] probabilities = [] num_qubits = u.num_qubits for i, prob in binary_probabilities.items(): # extract value of Z and corresponding probability i_normal = int(i[-n_z:], 2) p_z[i_normal] += prob # determine overall default probability for k loss = 0 for k in range(K): if i[K - k - 1] == "1": p_default[k] += prob loss += lgd[k] values += [loss] probabilities += [prob] values = np.array(values) probabilities = np.array(probabilities) expected_loss = np.dot(values, probabilities) losses = np.sort(np.unique(values)) pdf = np.zeros(len(losses)) for i, v in enumerate(losses): pdf[i] += sum(probabilities[values == v]) cdf = np.cumsum(pdf) i_var = np.argmax(cdf >= 1 - alpha) exact_var = losses[i_var] exact_cvar = np.dot(pdf[(i_var + 1) :], losses[(i_var + 1) :]) / sum(pdf[(i_var + 1) :]) print("Expected Loss E[L]: %.4f" % expected_loss) print("Value at Risk VaR[L]: %.4f" % exact_var) print("P[L <= VaR[L]]: %.4f" % cdf[exact_var]) print("Conditional Value at Risk CVaR[L]: %.4f" % exact_cvar) # plot loss PDF, expected loss, var, and cvar plt.bar(losses, pdf) plt.axvline(expected_loss, color="green", linestyle="--", label="E[L]") plt.axvline(exact_var, color="orange", linestyle="--", label="VaR(L)") plt.axvline(exact_cvar, color="red", linestyle="--", label="CVaR(L)") plt.legend(fontsize=15) plt.xlabel("Loss L ($)", size=15) plt.ylabel("probability (%)", size=15) plt.title("Loss Distribution", size=20) plt.xticks(size=15) plt.yticks(size=15) plt.show() # plot results for Z plt.plot(z_values, p_z, "o-", linewidth=3, markersize=8) plt.grid() plt.xlabel("Z value", size=15) plt.ylabel("probability (%)", size=15) plt.title("Z Distribution", size=20) plt.xticks(size=15) plt.yticks(size=15) plt.show() # plot results for default probabilities plt.bar(range(K), p_default) plt.xlabel("Asset", size=15) plt.ylabel("probability (%)", size=15) plt.title("Individual Default Probabilities", size=20) plt.xticks(range(K), size=15) plt.yticks(size=15) plt.grid() plt.show() # add Z qubits with weight/loss 0 from qiskit.circuit.library import WeightedAdder agg = WeightedAdder(n_z + K, [0] * n_z + lgd) from qiskit.circuit.library import LinearAmplitudeFunction # define linear objective function breakpoints = [0] slopes = [1] offsets = [0] f_min = 0 f_max = sum(lgd) c_approx = 0.25 objective = LinearAmplitudeFunction( agg.num_sum_qubits, slope=slopes, offset=offsets, # max value that can be reached by the qubit register (will not always be reached) domain=(0, 2**agg.num_sum_qubits - 1), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A") # load the random variable state_preparation.append(u.to_gate(), qr_state) # aggregate state_preparation.append(agg.to_gate(), qr_state[:] + qr_sum[:] + qr_carry[:]) # linear objective function state_preparation.append(objective.to_gate(), qr_sum[:] + qr_obj[:]) # uncompute aggregation state_preparation.append(agg.to_gate().inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) # draw the circuit state_preparation.draw() state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result value = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1": value += prob print("Exact Expected Loss: %.4f" % expected_loss) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % objective.post_processing(value)) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)], post_processing=objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) # print results conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % expected_loss) print("Estimated value:\t%.4f" % result.estimation_processed) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) # set x value to estimate the CDF x_eval = 2 comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False) comparator.draw() def get_cdf_circuit(x_eval): # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") qr_compare = QuantumRegister(1, "compare") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A") # load the random variable state_preparation.append(u, qr_state) # aggregate state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:]) # comparator objective function comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False) state_preparation.append(comparator, qr_sum[:] + qr_obj[:] + qr_carry[:]) # uncompute aggregation state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) return state_preparation state_preparation = get_cdf_circuit(x_eval) state_preparation.draw() state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result var_prob = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1": var_prob += prob print("Operator CDF(%s)" % x_eval + " = %.4f" % var_prob) print("Exact CDF(%s)" % x_eval + " = %.4f" % cdf[x_eval]) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem(state_preparation=state_preparation, objective_qubits=[len(qr_state)]) # construct amplitude estimation ae_cdf = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_cdf = ae_cdf.estimate(problem) # print results conf_int = np.array(result_cdf.confidence_interval) print("Exact value: \t%.4f" % cdf[x_eval]) print("Estimated value:\t%.4f" % result_cdf.estimation) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) def run_ae_for_cdf(x_eval, epsilon=0.01, alpha=0.05, simulator="aer_simulator"): # construct amplitude estimation state_preparation = get_cdf_circuit(x_eval) problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)] ) ae_var = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_var = ae_var.estimate(problem) return result_var.estimation def bisection_search( objective, target_value, low_level, high_level, low_value=None, high_value=None ): """ Determines the smallest level such that the objective value is still larger than the target :param objective: objective function :param target: target value :param low_level: lowest level to be considered :param high_level: highest level to be considered :param low_value: value of lowest level (will be evaluated if set to None) :param high_value: value of highest level (will be evaluated if set to None) :return: dictionary with level, value, num_eval """ # check whether low and high values are given and evaluated them otherwise print("--------------------------------------------------------------------") print("start bisection search for target value %.3f" % target_value) print("--------------------------------------------------------------------") num_eval = 0 if low_value is None: low_value = objective(low_level) num_eval += 1 if high_value is None: high_value = objective(high_level) num_eval += 1 # check if low_value already satisfies the condition if low_value > target_value: return { "level": low_level, "value": low_value, "num_eval": num_eval, "comment": "returned low value", } elif low_value == target_value: return {"level": low_level, "value": low_value, "num_eval": num_eval, "comment": "success"} # check if high_value is above target if high_value < target_value: return { "level": high_level, "value": high_value, "num_eval": num_eval, "comment": "returned low value", } elif high_value == target_value: return { "level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success", } # perform bisection search until print("low_level low_value level value high_level high_value") print("--------------------------------------------------------------------") while high_level - low_level > 1: level = int(np.round((high_level + low_level) / 2.0)) num_eval += 1 value = objective(level) print( "%2d %.3f %2d %.3f %2d %.3f" % (low_level, low_value, level, value, high_level, high_value) ) if value >= target_value: high_level = level high_value = value else: low_level = level low_value = value # return high value after bisection search print("--------------------------------------------------------------------") print("finished bisection search") print("--------------------------------------------------------------------") return {"level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success"} # run bisection search to determine VaR objective = lambda x: run_ae_for_cdf(x) bisection_result = bisection_search( objective, 1 - alpha, min(losses) - 1, max(losses), low_value=0, high_value=1 ) var = bisection_result["level"] print("Estimated Value at Risk: %2d" % var) print("Exact Value at Risk: %2d" % exact_var) print("Estimated Probability: %.3f" % bisection_result["value"]) print("Exact Probability: %.3f" % cdf[exact_var]) # define linear objective breakpoints = [0, var] slopes = [0, 1] offsets = [0, 0] # subtract VaR and add it later to the estimate f_min = 0 f_max = 3 - var c_approx = 0.25 cvar_objective = LinearAmplitudeFunction( agg.num_sum_qubits, slopes, offsets, domain=(0, 2**agg.num_sum_qubits - 1), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) cvar_objective.draw() # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") qr_work = QuantumRegister(cvar_objective.num_ancillas - len(qr_carry), "work") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, qr_work, name="A") # load the random variable state_preparation.append(u, qr_state) # aggregate state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:]) # linear objective function state_preparation.append(cvar_objective, qr_sum[:] + qr_obj[:] + qr_carry[:] + qr_work[:]) # uncompute aggregation state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result value = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1)] == "1": value += prob # normalize and add VaR to estimate value = cvar_objective.post_processing(value) d = 1.0 - bisection_result["value"] v = value / d if d != 0 else 0 normalized_value = v + var print("Estimated CVaR: %.4f" % normalized_value) print("Exact CVaR: %.4f" % exact_cvar) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)], post_processing=cvar_objective.post_processing, ) # construct amplitude estimation ae_cvar = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_cvar = ae_cvar.estimate(problem) # print results d = 1.0 - bisection_result["value"] v = result_cvar.estimation_processed / d if d != 0 else 0 print("Exact CVaR: \t%.4f" % exact_cvar) print("Estimated CVaR:\t%.4f" % (v + var)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit.visualization import plot_circuit_layout from qiskit.providers.fake_provider import FakeVigo backend = FakeVigo() ghz = QuantumCircuit(3, 3) ghz.h(0) ghz.cx(0,range(1,3)) ghz.barrier() ghz.measure(range(3), range(3)) new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3) plot_circuit_layout(new_circ_lv3, backend)
https://github.com/FilipeChagasDev/register-by-constant-qft-adder
FilipeChagasDev
# By Filipe Chagas # 2022 import qiskit from numeric_systems import * from typing import * def result_string_to_list(result: str) -> List[bool]: """Convert a string result to a list of bits. :param result: String result from Qiskit. :type result: str :return: List of bits. Most significant bit last. :rtype: List[bool] """ return [(True if c == '1' else False) for c in result[::-1]] def extract_register_from_result(result: List[bool], register: List[int]) -> List[bool]: """Extract a register from a list of bits. :param result: List of bits from Qiskit result. Most significant bit last. :type result: List[bool] :param register: List of register's qubits indexes. Most significant bit last. :type register: List[int] :return: List of bits. Most significant bit last. :rtype: List[bool] """ return [result[i] for i in register] def one_shot_simulation(circuit: qiskit.QuantumCircuit) -> List[bool]: """Do a one-shot simulation with Qiskit and return it's result as a list of bits. :param circuit: Qiskit quantum circuit. :type circuit: qiskit.QuantumCircuit :return: List of bits. Most significant bit last. :rtype: List[bool] """ backend = qiskit.BasicAer.get_backend('qasm_simulator') job = qiskit.execute(circuit, backend, shots=1) counts = job.result().get_counts() result_string = list(counts.keys())[0] return result_string_to_list(result_string)
https://github.com/xtophe388/QISKIT
xtophe388
import sys, time, getpass try: sys.path.append("../../") # go to parent dir import Qconfig qx_config = { "APItoken": Qconfig.APItoken, "url": Qconfig.config['url']} print('Qconfig loaded from %s.' % Qconfig.__file__) except: APItoken = getpass.getpass('Please input your token and hit enter: ') qx_config = { "APItoken": APItoken, "url":"https://quantumexperience.ng.bluemix.net/api"} print('Qconfig.py not found in qiskit-tutorial directory; Qconfig loaded using user input.') from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, QISKitError from qiskit import available_backends, execute, register, least_busy # Create a Quantum Register called "q" with 3 qubits qr = QuantumRegister(3) # Create a Classical Register called "c" with 3 bits cr = ClassicalRegister(3) # Create a Quantum Circuit called involving "qr" and "cr" circuit = QuantumCircuit(qr, cr) # Not gate on qubit 0 circuit.x(qr[0]) # Not gate on qubit 1 circuit.x(qr[1]) # Barrier to seperator the input from the circuit circuit.barrier(qr[0]) circuit.barrier(qr[1]) circuit.barrier(qr[2]) # Toffoli gate from qubit 0,1 to qubit 2 circuit.ccx(qr[0], qr[1], qr[2]) # CNOT (Controlled-NOT) gate from qubit 0 to qubit 1 circuit.cx(qr[0], qr[1]) # measure gate from qr to cr circuit.measure(qr, cr) # QASM from a program QASM_source = circuit.qasm() print(QASM_source) from qiskit.tools.visualization import circuit_drawer circuit_drawer(circuit) backend = 'local_qasm_simulator' # Create a Quantum Program for execution job = execute(circuit, backend) job.status result = job.result() result.get_counts(circuit) register(qx_config['APItoken'], qx_config['url']) large_enough_devices = available_backends(lambda x: x.configuration['n_qubits'] > 3 and not x.configuration['simulator']) backend = least_busy(large_enough_devices) print("the best backend is " + backend) shots = 1024 # Number of shots to run the program (experiment); maximum is 8192 shots. max_credits = 3 # Maximum number of credits to spend on executions. job_exp = execute(circuit, backend=backend, shots=shots, max_credits=max_credits) lapse = 0 interval = 30 while not job_exp.done: print('Status @ {} seconds'.format(interval * lapse)) print(job_exp.status) time.sleep(interval) lapse += 1 print(job_exp.status) result_real = job_exp.result() result_real.get_counts(circuit) jobID = job_exp.id print('JOB ID: {}'.format(jobID))
https://github.com/ahkatlio/QHSO_Basics_of_Qiskit
ahkatlio
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer from qiskit.visualization import plot_state_qsphere, plot_histogram # We create a Quantum Register with 3 qubits. q = QuantumRegister(3, 'qubit') # We create a Classical Register with 3 bits. c = ClassicalRegister(3, 'Classical bit') # We create a Quantum Circuit qc = QuantumCircuit(q, c) # We add x gate to the first qubit qc.x(q[0]) qc.barrier() qc.draw(output='mpl') qc.h(q[1]) qc.cx(q[1], q[2]) qc.barrier() qc.draw(output='mpl') qc.cx(q[0], q[1]) qc.h(0) qc.barrier() qc.measure(0,0) qc.measure(1,1) qc.barrier() qc.draw(output='mpl') from math import pi qc.crx(pi, q[1], q[2]).c_if(c, 1) qc.crz(pi, q[0], q[2]).c_if(c, 1) qc.draw(output='mpl') # We execute the quantum circuit on a statevector simulator backend backend = Aer.get_backend('statevector_simulator') result = execute(qc, backend).result() statevector = result.get_statevector(qc) plot_state_qsphere(statevector, show_state_phases = True, use_degrees = True) from qiskit import IBMQ from qiskit.providers.ibmq import least_busy # Replace 'MY_API_TOKEN' with your actual API token IBMQ.save_account('API_TOKEN', overwrite=True) # We get the least busy IBM Quantum device provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) # We print the name of the least busy backend print("Least busy backend:", backend.name()) import time from qiskit.tools.monitor import job_monitor # We execute the circuit on the least busy backend. Monitor the execution of the job in the queue backend = provider.get_backend('ibmq_belem') # We execute the circuit on the backend start_time = time.time() job_exp = execute(qc, backend=backend, shots=1024) job_monitor(job_exp, interval=2) result_exp = job_exp.result() counts_exp = result_exp.get_counts(qc) end_time = time.time() # We calculate the time taken in minutes and seconds time_taken = end_time - start_time minutes, seconds = divmod(time_taken, 60) # We print the results and the time it took to run the code print("Counts:", counts_exp) print("Time taken: {} minutes and {:.2f} seconds".format(int(minutes), seconds)) plot_histogram(counts_exp)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from __future__ import annotations import numpy as np import networkx as nx num_nodes = 4 w = np.array([[0., 1., 1., 0.], [1., 0., 1., 1.], [1., 1., 0., 1.], [0., 1., 1., 0.]]) G = nx.from_numpy_array(w) layout = nx.random_layout(G, seed=10) colors = ['r', 'g', 'b', 'y'] nx.draw(G, layout, node_color=colors) labels = nx.get_edge_attributes(G, 'weight') nx.draw_networkx_edge_labels(G, pos=layout, edge_labels=labels); def objective_value(x: np.ndarray, w: np.ndarray) -> float: """Compute the value of a cut. Args: x: Binary string as numpy array. w: Adjacency matrix. Returns: Value of the cut. """ X = np.outer(x, (1 - x)) w_01 = np.where(w != 0, 1, 0) return np.sum(w_01 * X) def bitfield(n: int, L: int) -> list[int]: result = np.binary_repr(n, L) return [int(digit) for digit in result] # [2:] to chop off the "0b" part # use the brute-force way to generate the oracle L = num_nodes max = 2**L sol = np.inf for i in range(max): cur = bitfield(i, L) how_many_nonzero = np.count_nonzero(cur) if how_many_nonzero * 2 != L: # not balanced continue cur_v = objective_value(np.array(cur), w) if cur_v < sol: sol = cur_v print(f'Objective value computed by the brute-force method is {sol}') from qiskit.quantum_info import Pauli, SparsePauliOp def get_operator(weight_matrix: np.ndarray) -> tuple[SparsePauliOp, float]: r"""Generate Hamiltonian for the graph partitioning Notes: Goals: 1 Separate the vertices into two set of the same size. 2 Make sure the number of edges between the two set is minimized. Hamiltonian: H = H_A + H_B H_A = sum\_{(i,j)\in E}{(1-ZiZj)/2} H_B = (sum_{i}{Zi})^2 = sum_{i}{Zi^2}+sum_{i!=j}{ZiZj} H_A is for achieving goal 2 and H_B is for achieving goal 1. Args: weight_matrix: Adjacency matrix. Returns: Operator for the Hamiltonian A constant shift for the obj function. """ num_nodes = len(weight_matrix) pauli_list = [] coeffs = [] shift = 0 for i in range(num_nodes): for j in range(i): if weight_matrix[i, j] != 0: x_p = np.zeros(num_nodes, dtype=bool) z_p = np.zeros(num_nodes, dtype=bool) z_p[i] = True z_p[j] = True pauli_list.append(Pauli((z_p, x_p))) coeffs.append(-0.5) shift += 0.5 for i in range(num_nodes): for j in range(num_nodes): if i != j: x_p = np.zeros(num_nodes, dtype=bool) z_p = np.zeros(num_nodes, dtype=bool) z_p[i] = True z_p[j] = True pauli_list.append(Pauli((z_p, x_p))) coeffs.append(1.0) else: shift += 1 return SparsePauliOp(pauli_list, coeffs=coeffs), shift qubit_op, offset = get_operator(w) from qiskit.algorithms.minimum_eigensolvers import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit.primitives import Sampler from qiskit.quantum_info import Pauli, Statevector from qiskit.result import QuasiDistribution from qiskit.utils import algorithm_globals sampler = Sampler() def sample_most_likely(state_vector: QuasiDistribution | Statevector) -> np.ndarray: """Compute the most likely binary string from state vector. Args: state_vector: State vector or quasi-distribution. Returns: Binary string as an array of ints. """ if isinstance(state_vector, QuasiDistribution): values = list(state_vector.values()) else: values = state_vector n = int(np.log2(len(values))) k = np.argmax(np.abs(values)) x = bitfield(k, n) x.reverse() return np.asarray(x) algorithm_globals.random_seed = 10598 optimizer = COBYLA() qaoa = QAOA(sampler, optimizer, reps=2) result = qaoa.compute_minimum_eigenvalue(qubit_op) x = sample_most_likely(result.eigenstate) print(x) print(f'Objective value computed by QAOA is {objective_value(x, w)}') from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit.quantum_info import Operator npme = NumPyMinimumEigensolver() result = npme.compute_minimum_eigenvalue(Operator(qubit_op)) x = sample_most_likely(result.eigenstate) print(x) print(f'Objective value computed by the NumPyMinimumEigensolver is {objective_value(x, w)}') from qiskit.algorithms.minimum_eigensolvers import SamplingVQE from qiskit.circuit.library import TwoLocal from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 10598 optimizer = COBYLA() ansatz = TwoLocal(qubit_op.num_qubits, "ry", "cz", reps=2, entanglement="linear") sampling_vqe = SamplingVQE(sampler, ansatz, optimizer) result = sampling_vqe.compute_minimum_eigenvalue(qubit_op) x = sample_most_likely(result.eigenstate) print(x) print(f"Objective value computed by VQE is {objective_value(x, w)}") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import BasicAer, transpile, QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.h(0) qc.measure(0, 0) qc.draw('mpl')
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-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. r""" Channel event manager for pulse schedules. This module provides a `ChannelEvents` class that manages a series of instructions for a pulse channel. Channel-wise filtering of the pulse program makes the arrangement of channels easier in the core drawer function. The `ChannelEvents` class is expected to be called by other programs (not by end-users). The `ChannelEvents` class instance is created with the class method ``load_program``: .. code-block:: python event = ChannelEvents.load_program(sched, DriveChannel(0)) The `ChannelEvents` is created for a specific pulse channel and loosely assorts pulse instructions within the channel with different visualization purposes. Phase and frequency related instructions are loosely grouped as frame changes. The instantaneous value of those operands are combined and provided as ``PhaseFreqTuple``. Instructions that have finite duration are grouped as waveforms. The grouped instructions are returned as an iterator by the corresponding method call: .. code-block:: python for t0, frame, instruction in event.get_waveforms(): ... for t0, frame_change, instructions in event.get_frame_changes(): ... The class method ``get_waveforms`` returns the iterator of waveform type instructions with the ``PhaseFreqTuple`` (frame) at the time when instruction is issued. This is because a pulse envelope of ``Waveform`` may be modulated with a phase factor $exp(-i \omega t - \phi)$ with frequency $\omega$ and phase $\phi$ and appear on the canvas. Thus, it is better to tell users in which phase and frequency the pulse envelope is modulated from a viewpoint of program debugging. On the other hand, the class method ``get_frame_changes`` returns a ``PhaseFreqTuple`` that represents a total amount of change at that time because it is convenient to know the operand value itself when we debug a program. Because frame change type instructions are usually zero duration, multiple instructions can be issued at the same time and those operand values should be appropriately combined. In Qiskit Pulse we have set and shift type instructions for the frame control, the set type instruction will be converted into the relevant shift amount for visualization. Note that these instructions are not interchangeable and the order should be kept. For example: .. code-block:: python sched1 = Schedule() sched1 = sched1.insert(0, ShiftPhase(-1.57, DriveChannel(0)) sched1 = sched1.insert(0, SetPhase(3.14, DriveChannel(0)) sched2 = Schedule() sched2 = sched2.insert(0, SetPhase(3.14, DriveChannel(0)) sched2 = sched2.insert(0, ShiftPhase(-1.57, DriveChannel(0)) In this example, ``sched1`` and ``sched2`` will have different frames. On the drawer canvas, the total frame change amount of +3.14 should be shown for ``sched1``, while ``sched2`` is +1.57. Since the `SetPhase` and the `ShiftPhase` instruction behave differently, we cannot simply sum up the operand values in visualization output. It should be also noted that zero duration instructions issued at the same time will be overlapped on the canvas. Thus it is convenient to plot a total frame change amount rather than plotting each operand value bound to the instruction. """ from __future__ import annotations from collections import defaultdict from collections.abc import Iterator from qiskit import pulse, circuit from qiskit.visualization.pulse_v2.types import PhaseFreqTuple, PulseInstruction class ChannelEvents: """Channel event manager.""" _waveform_group = ( pulse.instructions.Play, pulse.instructions.Delay, pulse.instructions.Acquire, ) _frame_group = ( pulse.instructions.SetFrequency, pulse.instructions.ShiftFrequency, pulse.instructions.SetPhase, pulse.instructions.ShiftPhase, ) def __init__( self, waveforms: dict[int, pulse.Instruction], frames: dict[int, list[pulse.Instruction]], channel: pulse.channels.Channel, ): """Create new event manager. Args: waveforms: List of waveforms shown in this channel. frames: List of frame change type instructions shown in this channel. channel: Channel object associated with this manager. """ self._waveforms = waveforms self._frames = frames self.channel = channel # initial frame self._init_phase = 0.0 self._init_frequency = 0.0 # time resolution self._dt = 0.0 @classmethod def load_program(cls, program: pulse.Schedule, channel: pulse.channels.Channel): """Load a pulse program represented by ``Schedule``. Args: program: Target ``Schedule`` to visualize. channel: The channel managed by this instance. Returns: ChannelEvents: The channel event manager for the specified channel. """ waveforms = {} frames = defaultdict(list) # parse instructions for t0, inst in program.filter(channels=[channel]).instructions: if isinstance(inst, cls._waveform_group): if inst.duration == 0: # special case, duration of delay can be zero continue waveforms[t0] = inst elif isinstance(inst, cls._frame_group): frames[t0].append(inst) return ChannelEvents(waveforms, frames, channel) def set_config(self, dt: float, init_frequency: float, init_phase: float): """Setup system status. Args: dt: Time resolution in sec. init_frequency: Modulation frequency in Hz. init_phase: Initial phase in rad. """ self._dt = dt or 1.0 self._init_frequency = init_frequency or 0.0 self._init_phase = init_phase or 0.0 def get_waveforms(self) -> Iterator[PulseInstruction]: """Return waveform type instructions with frame.""" sorted_frame_changes = sorted(self._frames.items(), key=lambda x: x[0], reverse=True) sorted_waveforms = sorted(self._waveforms.items(), key=lambda x: x[0]) # bind phase and frequency with instruction phase = self._init_phase frequency = self._init_frequency for t0, inst in sorted_waveforms: is_opaque = False while len(sorted_frame_changes) > 0 and sorted_frame_changes[-1][0] <= t0: _, frame_changes = sorted_frame_changes.pop() phase, frequency = ChannelEvents._calculate_current_frame( frame_changes=frame_changes, phase=phase, frequency=frequency ) # Convert parameter expression into float if isinstance(phase, circuit.ParameterExpression): phase = float(phase.bind({param: 0 for param in phase.parameters})) if isinstance(frequency, circuit.ParameterExpression): frequency = float(frequency.bind({param: 0 for param in frequency.parameters})) frame = PhaseFreqTuple(phase, frequency) # Check if pulse has unbound parameters if isinstance(inst, pulse.Play): is_opaque = inst.pulse.is_parameterized() yield PulseInstruction(t0, self._dt, frame, inst, is_opaque) def get_frame_changes(self) -> Iterator[PulseInstruction]: """Return frame change type instructions with total frame change amount.""" # TODO parse parametrised FCs correctly sorted_frame_changes = sorted(self._frames.items(), key=lambda x: x[0]) phase = self._init_phase frequency = self._init_frequency for t0, frame_changes in sorted_frame_changes: is_opaque = False pre_phase = phase pre_frequency = frequency phase, frequency = ChannelEvents._calculate_current_frame( frame_changes=frame_changes, phase=phase, frequency=frequency ) # keep parameter expression to check either phase or frequency is parameterized frame = PhaseFreqTuple(phase - pre_phase, frequency - pre_frequency) # remove parameter expressions to find if next frame is parameterized if isinstance(phase, circuit.ParameterExpression): phase = float(phase.bind({param: 0 for param in phase.parameters})) is_opaque = True if isinstance(frequency, circuit.ParameterExpression): frequency = float(frequency.bind({param: 0 for param in frequency.parameters})) is_opaque = True yield PulseInstruction(t0, self._dt, frame, frame_changes, is_opaque) @classmethod def _calculate_current_frame( cls, frame_changes: list[pulse.instructions.Instruction], phase: float, frequency: float ) -> tuple[float, float]: """Calculate the current frame from the previous frame. If parameter is unbound phase or frequency accumulation with this instruction is skipped. Args: frame_changes: List of frame change instructions at a specific time. phase: Phase of previous frame. frequency: Frequency of previous frame. Returns: Phase and frequency of new frame. """ for frame_change in frame_changes: if isinstance(frame_change, pulse.instructions.SetFrequency): frequency = frame_change.frequency elif isinstance(frame_change, pulse.instructions.ShiftFrequency): frequency += frame_change.frequency elif isinstance(frame_change, pulse.instructions.SetPhase): phase = frame_change.phase elif isinstance(frame_change, pulse.instructions.ShiftPhase): phase += frame_change.phase return phase, frequency
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) ### removed cx gate ### return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) qc.h(1) return qc
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute from qiskit.circuit import Gate from qiskit.visualization import plot_histogram, plot_bloch_multivector # Define no. of input qubits n = 4 circ = QuantumCircuit(n+1, n) circ.reset(range(n+1)) circ.x(0) circ.barrier() circ.h(range(n+1)) circ.barrier() circ.append(Gate(name="$U_f$", num_qubits=n+1, params=[]), range(n+1)) circ.barrier() circ.h(range(1, n+1)) circ.barrier() circ.measure(range(1, n+1), range(n)) circ.draw('mpl', reverse_bits=True) # Constant Function constant = QuantumCircuit(n+1, name='Constant') constant.x(0) constant.draw('mpl', reverse_bits=True) # Balanced Function balanced = QuantumCircuit(n+1, name='Balanced') for i in range(1, n+1): balanced.cx(i, 0) balanced.draw('mpl', reverse_bits=True) circ = QuantumCircuit(n+1) circ.x(0) circ.barrier() circ.h(range(n+1)) circ.append(constant.to_instruction(), range(n+1)) circ.h(range(1, n+1)) circ.draw(reverse_bits=True, plot_barriers=False) simulator = Aer.get_backend('statevector_simulator') result = execute(circ, simulator).result() state = result.get_statevector(circ) plot_bloch_multivector(state) circ = QuantumCircuit(n+1) circ.x(0) circ.barrier() circ.h(range(n+1)) circ.append(balanced.to_instruction(), range(n+1)) circ.h(range(1, n+1)) circ.draw(reverse_bits=True, plot_barriers=False) simulator = Aer.get_backend('statevector_simulator') result = execute(circ, simulator).result() state = result.get_statevector(circ) plot_bloch_multivector(state) circ = QuantumCircuit(n+1, n) circ.x(0) circ.barrier() circ.h(range(n+1)) circ.append(constant.to_instruction(), range(n+1)) circ.h(range(1, n+1)) circ.measure(range(1, n+1), range(n)) circ.draw(reverse_bits=True, plot_barriers=False) simulator = Aer.get_backend('qasm_simulator') result = execute(circ, simulator, shots=1000).result() counts = result.get_counts(circ) plot_histogram(counts)
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/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for visualization tools.""" import unittest import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Qubit, Clbit from qiskit.visualization.circuit import _utils from qiskit.visualization import array_to_latex from qiskit.test import QiskitTestCase from qiskit.utils import optionals class TestVisualizationUtils(QiskitTestCase): """Tests for circuit drawer utilities.""" def setUp(self): super().setUp() self.qr1 = QuantumRegister(2, "qr1") self.qr2 = QuantumRegister(2, "qr2") self.cr1 = ClassicalRegister(2, "cr1") self.cr2 = ClassicalRegister(2, "cr2") self.circuit = QuantumCircuit(self.qr1, self.qr2, self.cr1, self.cr2) self.circuit.cx(self.qr2[0], self.qr2[1]) self.circuit.measure(self.qr2[0], self.cr2[0]) self.circuit.cx(self.qr2[1], self.qr2[0]) self.circuit.measure(self.qr2[1], self.cr2[1]) self.circuit.cx(self.qr1[0], self.qr1[1]) self.circuit.measure(self.qr1[0], self.cr1[0]) self.circuit.cx(self.qr1[1], self.qr1[0]) self.circuit.measure(self.qr1[1], self.cr1[1]) def test_get_layered_instructions(self): """_get_layered_instructions without reverse_bits""" (qregs, cregs, layered_ops) = _utils._get_layered_instructions(self.circuit) exp = [ [("cx", (self.qr2[0], self.qr2[1]), ()), ("cx", (self.qr1[0], self.qr1[1]), ())], [("measure", (self.qr2[0],), (self.cr2[0],))], [("measure", (self.qr1[0],), (self.cr1[0],))], [("cx", (self.qr2[1], self.qr2[0]), ()), ("cx", (self.qr1[1], self.qr1[0]), ())], [("measure", (self.qr2[1],), (self.cr2[1],))], [("measure", (self.qr1[1],), (self.cr1[1],))], ] self.assertEqual([self.qr1[0], self.qr1[1], self.qr2[0], self.qr2[1]], qregs) self.assertEqual([self.cr1[0], self.cr1[1], self.cr2[0], self.cr2[1]], cregs) self.assertEqual( exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_reverse_bits(self): """_get_layered_instructions with reverse_bits=True""" (qregs, cregs, layered_ops) = _utils._get_layered_instructions( self.circuit, reverse_bits=True ) exp = [ [("cx", (self.qr2[0], self.qr2[1]), ()), ("cx", (self.qr1[0], self.qr1[1]), ())], [("measure", (self.qr2[0],), (self.cr2[0],))], [("measure", (self.qr1[0],), (self.cr1[0],)), ("cx", (self.qr2[1], self.qr2[0]), ())], [("cx", (self.qr1[1], self.qr1[0]), ())], [("measure", (self.qr2[1],), (self.cr2[1],))], [("measure", (self.qr1[1],), (self.cr1[1],))], ] self.assertEqual([self.qr2[1], self.qr2[0], self.qr1[1], self.qr1[0]], qregs) self.assertEqual([self.cr2[1], self.cr2[0], self.cr1[1], self.cr1[0]], cregs) self.assertEqual( exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_remove_idle_wires(self): """_get_layered_instructions with idle_wires=False""" qr1 = QuantumRegister(3, "qr1") qr2 = QuantumRegister(3, "qr2") cr1 = ClassicalRegister(3, "cr1") cr2 = ClassicalRegister(3, "cr2") circuit = QuantumCircuit(qr1, qr2, cr1, cr2) circuit.cx(qr2[0], qr2[1]) circuit.measure(qr2[0], cr2[0]) circuit.cx(qr2[1], qr2[0]) circuit.measure(qr2[1], cr2[1]) circuit.cx(qr1[0], qr1[1]) circuit.measure(qr1[0], cr1[0]) circuit.cx(qr1[1], qr1[0]) circuit.measure(qr1[1], cr1[1]) (qregs, cregs, layered_ops) = _utils._get_layered_instructions(circuit, idle_wires=False) exp = [ [("cx", (qr2[0], qr2[1]), ()), ("cx", (qr1[0], qr1[1]), ())], [("measure", (qr2[0],), (cr2[0],))], [("measure", (qr1[0],), (cr1[0],))], [("cx", (qr2[1], qr2[0]), ()), ("cx", (qr1[1], qr1[0]), ())], [("measure", (qr2[1],), (cr2[1],))], [("measure", (qr1[1],), (cr1[1],))], ] self.assertEqual([qr1[0], qr1[1], qr2[0], qr2[1]], qregs) self.assertEqual([cr1[0], cr1[1], cr2[0], cr2[1]], cregs) self.assertEqual( exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_left_justification_simple(self): """Test _get_layered_instructions left justification simple since #2802 q_0: |0>───────■── ┌───┐ │ q_1: |0>┤ H ├──┼── ├───┤ │ q_2: |0>┤ H ├──┼── └───┘┌─┴─┐ q_3: |0>─────┤ X ├ └───┘ """ qc = QuantumCircuit(4) qc.h(1) qc.h(2) qc.cx(0, 3) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="left") l_exp = [ [ ("h", (Qubit(QuantumRegister(4, "q"), 1),), ()), ("h", (Qubit(QuantumRegister(4, "q"), 2),), ()), ], [("cx", (Qubit(QuantumRegister(4, "q"), 0), Qubit(QuantumRegister(4, "q"), 3)), ())], ] self.assertEqual( l_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_right_justification_simple(self): """Test _get_layered_instructions right justification simple since #2802 q_0: |0>──■─────── │ ┌───┐ q_1: |0>──┼──┤ H ├ │ ├───┤ q_2: |0>──┼──┤ H ├ ┌─┴─┐└───┘ q_3: |0>┤ X ├───── └───┘ """ qc = QuantumCircuit(4) qc.h(1) qc.h(2) qc.cx(0, 3) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="right") r_exp = [ [("cx", (Qubit(QuantumRegister(4, "q"), 0), Qubit(QuantumRegister(4, "q"), 3)), ())], [ ("h", (Qubit(QuantumRegister(4, "q"), 1),), ()), ("h", (Qubit(QuantumRegister(4, "q"), 2),), ()), ], ] self.assertEqual( r_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_left_justification_less_simple(self): """Test _get_layered_instructions left justification less simple example since #2802 ┌────────────┐┌───┐┌────────────┐ ┌─┐┌────────────┐┌───┐┌────────────┐ q_0: |0>┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├──────────────┤M├┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├ ├────────────┤└─┬─┘├────────────┤┌────────────┐└╥┘└────────────┘└─┬─┘├────────────┤ q_1: |0>┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├┤ U2(0,pi/1) ├─╫─────────────────■──┤ U2(0,pi/1) ├ └────────────┘ └────────────┘└────────────┘ ║ └────────────┘ q_2: |0>────────────────────────────────────────────────╫────────────────────────────────── ║ q_3: |0>────────────────────────────────────────────────╫────────────────────────────────── ║ q_4: |0>────────────────────────────────────────────────╫────────────────────────────────── ║ c1_0: 0 ════════════════════════════════════════════════╩══════════════════════════════════ """ qasm = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[5]; creg c1[1]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; u2(0,3.14159265358979) q[1]; measure q[0] -> c1[0]; u2(0,3.14159265358979) q[0]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; """ qc = QuantumCircuit.from_qasm_str(qasm) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="left") l_exp = [ [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("u2", (Qubit(QuantumRegister(5, "q"), 1),), ())], [ ( "measure", (Qubit(QuantumRegister(5, "q"), 0),), (Clbit(ClassicalRegister(1, "c1"), 0),), ) ], [("u2", (Qubit(QuantumRegister(5, "q"), 0),), ())], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], ] self.assertEqual( l_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_right_justification_less_simple(self): """Test _get_layered_instructions right justification less simple example since #2802 ┌────────────┐┌───┐┌────────────┐┌─┐┌────────────┐┌───┐┌────────────┐ q_0: |0>┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├┤M├┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├ ├────────────┤└─┬─┘├────────────┤└╥┘├────────────┤└─┬─┘├────────────┤ q_1: |0>┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├─╫─┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├ └────────────┘ └────────────┘ ║ └────────────┘ └────────────┘ q_2: |0>──────────────────────────────────╫────────────────────────────────── ║ q_3: |0>──────────────────────────────────╫────────────────────────────────── ║ q_4: |0>──────────────────────────────────╫────────────────────────────────── ║ c1_0: 0 ══════════════════════════════════╩══════════════════════════════════ """ qasm = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[5]; creg c1[1]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; u2(0,3.14159265358979) q[1]; measure q[0] -> c1[0]; u2(0,3.14159265358979) q[0]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; """ qc = QuantumCircuit.from_qasm_str(qasm) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="right") r_exp = [ [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [ ( "measure", (Qubit(QuantumRegister(5, "q"), 0),), (Clbit(ClassicalRegister(1, "c1"), 0),), ) ], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], ] self.assertEqual( r_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_op_with_cargs(self): """Test _get_layered_instructions op with cargs right of measure ┌───┐┌─┐ q_0: |0>┤ H ├┤M├───────────── └───┘└╥┘┌───────────┐ q_1: |0>──────╫─┤0 ├ ║ │ add_circ │ c_0: 0 ══════╩═╡0 ╞ └───────────┘ c_1: 0 ═════════════════════ """ qc = QuantumCircuit(2, 2) qc.h(0) qc.measure(0, 0) qc_2 = QuantumCircuit(1, 1, name="add_circ") qc_2.h(0).c_if(qc_2.cregs[0], 1) qc_2.measure(0, 0) qc.append(qc_2, [1], [0]) (_, _, layered_ops) = _utils._get_layered_instructions(qc) expected = [ [("h", (Qubit(QuantumRegister(2, "q"), 0),), ())], [ ( "measure", (Qubit(QuantumRegister(2, "q"), 0),), (Clbit(ClassicalRegister(2, "c"), 0),), ) ], [ ( "add_circ", (Qubit(QuantumRegister(2, "q"), 1),), (Clbit(ClassicalRegister(2, "c"), 0),), ) ], ] self.assertEqual( expected, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_nomathmode(self): """Test generate latex label default.""" self.assertEqual("abc", _utils.generate_latex_label("abc")) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_nomathmode_utf8char(self): """Test generate latex label utf8 characters.""" self.assertEqual( "{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label("∭X∀Y"), ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_mathmode_utf8char(self): """Test generate latex label mathtext with utf8.""" self.assertEqual( "abc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label("$abc_$∭X∀Y"), ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_mathmode_underscore_outside(self): """Test generate latex label with underscore outside mathmode.""" self.assertEqual( "abc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label("$abc$_∭X∀Y"), ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_escaped_dollar_signs(self): """Test generate latex label with escaped dollarsign.""" self.assertEqual("${\\ensuremath{\\forall}}$", _utils.generate_latex_label(r"\$∀\$")) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_escaped_dollar_sign_in_mathmode(self): """Test generate latex label with escaped dollar sign in mathmode.""" self.assertEqual( "a$bc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label(r"$a$bc$_∭X∀Y"), ) def test_array_to_latex(self): """Test array_to_latex produces correct latex string""" matrix = [ [np.sqrt(1 / 2), 1 / 16, 1 / np.sqrt(8) + 3j, -0.5 + 0.5j], [1 / 3 - 1 / 3j, np.sqrt(1 / 2) * 1j, 34.3210, -9 / 2], ] matrix = np.array(matrix) exp_str = ( "\\begin{bmatrix}\\frac{\\sqrt{2}}{2}&\\frac{1}{16}&" "\\frac{\\sqrt{2}}{4}+3i&-\\frac{1}{2}+\\frac{i}{2}\\\\" "\\frac{1}{3}+\\frac{i}{3}&\\frac{\\sqrt{2}i}{2}&34.321&-" "\\frac{9}{2}\\\\\\end{bmatrix}" ) result = array_to_latex(matrix, source=True).replace(" ", "").replace("\n", "") self.assertEqual(exp_str, result) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# 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. """Class for a Variational Principle.""" from __future__ import annotations from abc import ABC, abstractmethod from collections.abc import Sequence import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.quantum_info.operators.base_operator import BaseOperator from ....exceptions import AlgorithmError from ....gradients import BaseEstimatorGradient, BaseQGT, DerivativeType class VariationalPrinciple(ABC): """A Variational Principle class. It determines the time propagation of parameters in a quantum state provided as a parametrized quantum circuit (ansatz). Attributes: qgt (BaseQGT): Instance of a class used to compute the GQT. gradient (BaseEstimatorGradient): Instance of a class used to compute the state gradient. """ def __init__( self, qgt: BaseQGT, gradient: BaseEstimatorGradient, ) -> None: """ Args: qgt: Instance of a class used to compute the GQT. gradient: Instance of a class used to compute the state gradient. """ self.qgt = qgt self.gradient = gradient def metric_tensor( self, ansatz: QuantumCircuit, param_values: Sequence[float] ) -> Sequence[float]: """ Calculates a metric tensor according to the rules of this variational principle. Args: ansatz: Quantum state in the form of a parametrized quantum circuit. param_values: Values of parameters to be bound. Returns: Metric tensor. Raises: AlgorithmError: If a QFI job fails. """ self.qgt.derivative_type = DerivativeType.REAL try: metric_tensor = self.qgt.run([ansatz], [param_values], [None]).result().qgts[0] except Exception as exc: raise AlgorithmError("The QFI primitive job failed!") from exc return metric_tensor @abstractmethod def evolution_gradient( self, hamiltonian: BaseOperator, ansatz: QuantumCircuit, param_values: Sequence[float], gradient_params: Sequence[Parameter] | None = None, ) -> np.ndarray: """ Calculates an evolution gradient according to the rules of this variational principle. Args: hamiltonian: Operator used for Variational Quantum Time Evolution. ansatz: Quantum state in the form of a parametrized quantum circuit. param_values: Values of parameters to be bound. gradient_params: List of parameters with respect to which gradients should be computed. If ``None`` given, gradients w.r.t. all parameters will be computed. Returns: An evolution gradient. """ pass
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/InvictusWingsSRL/QiskitTutorials
InvictusWingsSRL
#Libraries needed to implement and simulate quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile, qasm2, qasm3 from qiskit_aer import Aer from qiskit.primitives import BackendSampler from qiskit.providers.basic_provider import BasicProvider # instead of BasicAer from qiskit.visualization import plot_histogram #Custem functions to simplify answers import Our_Qiskit_Functions as oq #a part of the library presented in arXiv:1903.04359v1. import numpy as np import math as m import scipy as sci import random import matplotlib.pyplot as plt #Initialize backends simulators to visualize circuits S_simulator = Aer.backends(name='statevector_simulator')[0] M_simulator = Aer.backends(name='qasm_simulator')[0] alpha = 2*m.pi/3 U = np.array([ [ np.cos(alpha) , np.sin(alpha) ], [ -np.sin(alpha) , np.cos(alpha) ] ]) #--------------------------------------------------- e = 0.5*(-1+m.sqrt(3)*1.0j) v = 1.0/m.sqrt(2)*np.array( [-1.0j,1] ) #--------------------------------------------------- print('____ Unitary Matrix ____\n',U) print( '\n U |u> = ',np.dot(U,v)) print( 'e^{2\u03C0i\u03C6} |u> = ',e * v) q = QuantumRegister(3,name='q' ) qc= QuantumCircuit(q,name='qc') #------------------------------- qc.x( q[1] ) qc.x( q[2] ) print('____ Initial State ____') oq.Wavefunction(qc) qc.swap( q[0], q[2] ) oq.QFT_dgr( qc,q,3 ) print('\n____ After QFT\u2020 ____') oq.Wavefunction(qc) #====================================== print('\n ____ QFT\u2020 Expression ____') for k in np.arange( 8 ): phase = 1.0/(m.sqrt(8)) * np.exp( -1.0j*m.pi*( (3*k)/4 ) ) print( 'state: ',oq.Binary(int(k),8),' phase: ',round(phase.real,4)+round(phase.imag,4)*1.0j ) n = 3 theta = 0.52 print('Theta = ',theta,' n = ',n,'\n---------------------------') #=================== state = [] bstate = [] bdec = [] for i in range(2**n): state.append(0) bstate.append(oq.Binary(i,2**n)) bc = 0 for i2 in range(len(bstate[i])): bc = bc + ( 1.0/(2**(i2+1)))*bstate[i][i2] bdec.append(bc) #------------------------------------------------------------- for y in range(2**n): for x in range(2**n): state[y] = state[y] + 1.0/(2**n) * np.exp( (-2.0j*np.pi*x/(2**n))*(y-2**n*theta) ) #-------------------------------------------------------------- for j in np.arange(2**n): print('Probability: ',round( abs(state[j])**2,4 ),' State: ',bstate[j],' Binary Decimal: ',bdec[j]) x = [] y = [] n = 3 for k in np.arange( 1000 ): if( k != 500 ): phi = -5 + k/100. x.append( phi ) y.append( 1/(2**(2*n)) * abs( (-1 + np.exp(2.0j*m.pi*phi) )/(-1 + np.exp(2.0j*m.pi*phi/(2**n))) )**2 ) else: x.append(phi) y.append(1) plt.plot(x,y) plt.axis([-5,5,0,1]) plt.show() n = 4 theta = 0.52 print('Theta = ',theta,' n = ',n,'\n---------------------------') #=================== state = [] bstate = [] bdec = [] for i in range(2**n): state.append(0) bstate.append(oq.Binary(i,2**n)) bc = 0 for i2 in range(len(bstate[i])): bc = bc + ( 1.0/(2**(i2+1)))*bstate[i][i2] bdec.append(bc) #------------------------------------------------------------- for y in range(2**n): for x in range(2**n): state[y] = state[y] + 1.0/(2**n) * np.exp( (-2.0j*np.pi*x/(2**n))*(y-2**n*theta) ) #-------------------------------------------------------------- for j in np.arange(2**n): print('Probability: ',round( abs(state[j])**2,4 ),' State: ',bstate[j],' Binary Decimal: ',bdec[j]) Prob = [ 0.0028,0.0028,0.0031,0.0037,0.0049,0.0076,0.0144,0.0424,0.7063,0.1571,0.0265,0.011,0.0064,0.0044,0.0035,0.003 ] Measured = np.zeros( len(Prob) ) trials = 10000 n = 4 #======================================== Simulate measurements on the final system for t in range(trials): M = random.random() p = 0 for s in range( len(Prob) ): if( p < M < (p + Prob[s]) ): Measured[s] = Measured[s] + 1 p = p + Prob[s] #--------------------------------------- MD = {} for i in range( len(Prob) ): state = oq.Binary(int(i),2**n) state_str = '' for j in range(len(state)): state_str = state_str+str(state[j]) MD[state_str] = int( Measured[i] ) MP = oq.Most_Probable(MD,2) for mp in range(2): MP[0][mp] = MP[0][mp]/trials #======================================== Compute phi using the most probable state phi,theta = oq.QPE_phi(MP) print('\nMost Probable State: |'+str(MP[1][0])+'> Probability: ',round(MP[0][0],5)) print('\nCorresponding \u03A6: ',phi,'\n\nApproximate \u03B8: ',round(theta,5)) n = 3 q1 = QuantumRegister(n,name='q1') q2 = QuantumRegister(1,name='q2') qc = QuantumCircuit(q1,q2,name='qc') theta = 0.52 phi = 2*m.pi*theta #--------------------------------------------------- for i in np.arange(n): qc.h(q1[int(i)]) qc.x( q2[0] ) for j in np.arange(n): for k in np.arange(2**j): qc.cp( phi, q1[int(n-1-j)], q2[0] ) print('\n___ After Control-U Operations ___') oq.Wavefunction( qc, systems=[n,1] ) #--------------------------------------------------- Phases = [np.exp(4.0j*phi),np.exp(2.0j*phi),np.exp(1.0j*phi)] print(' ') for i in np.arange(8): state = oq.Binary(int(i),8) phase = m.sqrt(1/8) for j in np.arange(3): if(state[j]==1): phase = phase*Phases[j] print('State: ',state,' Phase: ',round(phase.real,5)+round(phase.imag,5)*1.0j) n = 3 q1 = QuantumRegister(n,name='q1') q2 = QuantumRegister(1,name='q2') c = ClassicalRegister(n,name='c') qc = QuantumCircuit(q1,q2,c,name='qc') theta = 0.666 #--------------------------------------------------- for i in np.arange(n): qc.h(q1[int(i)]) qc.x( q2[0] ) phi = 2*m.pi*theta for j in np.arange(n): for k in np.arange(2**j): qc.cp( phi, q1[int(n-1-j)], q2[0] ) print('\n___ After QFT_dgr ___') oq.QFT_dgr( qc,q1,n,swap=True ) oq.Wavefunction( qc, systems=[n,1] ) #--------------------------------------------------- qc.measure(q1,c) #results = oq.execute(qc, BasicProvider().get_backend('qasm_simulator'), shots=10000).result() results = oq.execute(qc, S_simulator, shots=10000).result() plot_histogram({key: value / 10000. for key, value in results.get_counts().items()}) n1 = 3 n2 = 2 phases = [] for p in np.arange( n2 ): phases.append( round( 2*m.pi*random.random(),4 ) ) theta = round( sum(phases)/(2*m.pi),5) if( theta > 1 ): theta = round( theta - m.floor(theta),5) #================================= q = QuantumRegister(n1,name='q') qu = QuantumRegister(n2,name='qu') c = ClassicalRegister(n1,name='c') qc = QuantumCircuit(q,qu,c,name='qc') #---------------------------------- for i in np.arange(n1): qc.h( q[int(i)] ) for i2 in np.arange(n2): qc.x( qu[int(i2)] ) qc.barrier() for j in np.arange(n1): for j2 in np.arange(2**j): for j3 in np.arange(n2): qc.cp( phases[int(j3)], q[int(n1-1-j)], qu[int(j3)] ) qc.barrier() oq.QFT_dgr( qc,q,n1,swap=True ) #--------------------------------------------------- print('Phases: ',phases) print('\nCombined \u03B8: ',theta) qc.measure(q,c) #results = execute(qc, BasicAer.get_backend('qasm_simulator'), shots=10000).result() results = oq.execute(qc, S_simulator, shots=10000).result() plot_histogram({key: value / 10000. for key, value in results.get_counts().items()}) print(qc) n1 = 5 n2 = 3 phases = [] trials = 10000 for p in np.arange( n2 ): phases.append( round( 2*m.pi*random.random(),4 ) ) theta = round( sum(phases)/(2*m.pi),5) if( theta > 1 ): theta = round( theta - m.floor(theta),5) #================================================================== QPE Circuit q = QuantumRegister(n1,name='q') qu = QuantumRegister(n2,name='qu') c = ClassicalRegister(n1,name='c') qc = QuantumCircuit(q,qu,c,name='qc') #------------------------------------- for i in np.arange(n1): qc.h( q[int(i)] ) for i2 in np.arange(n2): qc.x( qu[int(i2)] ) for j in np.arange(n1): for j2 in np.arange(2**j): for j3 in np.arange(n2): qc.cp( phases[int(j3)], q[int(n1-1-j)], qu[int(j3)] ) oq.QFT_dgr( qc,q,n1,swap=True ) #================================================================== print('Phases: ',phases,' Combined \u03B8: ',theta) qc.measure(q,c) M = oq.Measurement( qc,systems=[n1,n2],shots=trials,return_M=True,print_M=False ) MP = oq.Most_Probable(M,2) for mp in np.arange(2): MP[0][mp] = MP[0][mp]/trials phi,theta = oq.QPE_phi(MP) print('\nMost Probable State: |'+str(MP[1][0])+'> Probability: ',round(MP[0][0],5)) print('\nSecond Most Probable: |'+str(MP[1][1])+'> Probability: ',round(MP[0][1],5)) print('\nCorresponding \u03A6: ',phi,'\n\nApproximate \u03B8: ',round(theta,5))
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import Aer, QuantumCircuit, transpile from qiskit.circuit.library import PhaseEstimation qc= QuantumCircuit(3,3) # dummy unitary circuit unitary_circuit = QuantumCircuit(1) unitary_circuit.h(0) # QPE qc.append(PhaseEstimation(2, unitary_circuit), list(range(3))) qc.measure(list(range(3)), list(range(3))) backend = Aer.get_backend('qasm_simulator') qc_transpiled = transpile(qc, backend) result = backend.run(qc, shots = 8192).result()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test for the converter dag dependency to circuit and circuit to dag dependency.""" import unittest from qiskit.converters.dagdependency_to_circuit import dagdependency_to_circuit from qiskit.converters.circuit_to_dagdependency import circuit_to_dagdependency from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.test import QiskitTestCase class TestCircuitToDagCanonical(QiskitTestCase): """Test QuantumCircuit to DAGDependency.""" def test_circuit_and_dag_canonical(self): """Check convert to dag dependency and back""" qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit_in = QuantumCircuit(qr, cr) circuit_in.h(qr[0]) circuit_in.h(qr[1]) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.x(qr[0]).c_if(cr, 0x3) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.measure(qr[2], cr[2]) dag_dependency = circuit_to_dagdependency(circuit_in) circuit_out = dagdependency_to_circuit(dag_dependency) self.assertEqual(circuit_out, circuit_in) def test_circuit_and_dag_canonical2(self): """Check convert to dag dependency and back also when the option ``create_preds_and_succs`` is False.""" qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit_in = QuantumCircuit(qr, cr) circuit_in.h(qr[0]) circuit_in.h(qr[1]) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.x(qr[0]).c_if(cr, 0x3) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.measure(qr[2], cr[2]) dag_dependency = circuit_to_dagdependency(circuit_in, create_preds_and_succs=False) circuit_out = dagdependency_to_circuit(dag_dependency) self.assertEqual(circuit_out, circuit_in) def test_calibrations(self): """Test that calibrations are properly copied over.""" circuit_in = QuantumCircuit(1) circuit_in.add_calibration("h", [0], None) self.assertEqual(len(circuit_in.calibrations), 1) dag_dependency = circuit_to_dagdependency(circuit_in) self.assertEqual(len(dag_dependency.calibrations), 1) circuit_out = dagdependency_to_circuit(dag_dependency) self.assertEqual(len(circuit_out.calibrations), 1) def test_metadata(self): """Test circuit metadata is preservered through conversion.""" meta_dict = {"experiment_id": "1234", "execution_number": 4} qr = QuantumRegister(2) circuit_in = QuantumCircuit(qr, metadata=meta_dict) circuit_in.h(qr[0]) circuit_in.cx(qr[0], qr[1]) circuit_in.measure_all() dag_dependency = circuit_to_dagdependency(circuit_in) self.assertEqual(dag_dependency.metadata, meta_dict) circuit_out = dagdependency_to_circuit(dag_dependency) self.assertEqual(circuit_out.metadata, meta_dict) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/matteoacrossi/oqs-jupyterbook
matteoacrossi
from IPython.display import IFrame IFrame(src='./gen_plots/jaynescummings.html', width=900, height=350) ########################################### # Amplitude damping channel on IBMQ_VIGO # ########################################### from qiskit import QuantumRegister, QuantumCircuit # Quantum register q = QuantumRegister(5, name='q') # Quantum circuit ad = QuantumCircuit(q) # Amplitude damping channel acting on system qubit ## Qubit identification system = 1 environment = 2 # Define rotation angle theta = 0.0 # Construct circuit ad.x(q[system]) ad.cu3(theta, 0.0, 0.0, q[system], q[environment]) ad.cx(q[environment], q[system]) # Draw circuit ad.draw(output='mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit circ = QuantumCircuit(2, 2) circ.h(0) circ.cx(0, 1) circ.measure(0, 0) circ.measure(1, 1) circ.draw('mpl') from qiskit import pulse from qiskit.pulse.library import Gaussian from qiskit.providers.fake_provider import FakeValencia backend = FakeValencia() with pulse.build(backend, name='hadamard') as h_q0: pulse.play(Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0)) h_q0.draw() circ.add_calibration('h', [0], h_q0) from qiskit import transpile from qiskit.providers.fake_provider import FakeHanoi backend = FakeHanoi() circ = transpile(circ, backend) print(backend.configuration().basis_gates) circ.draw('mpl', idle_wires=False) from qiskit import QuantumCircuit from qiskit.circuit import Gate circ = QuantumCircuit(1, 1) custom_gate = Gate('my_custom_gate', 1, [3.14, 1]) # 3.14 is an arbitrary parameter for demonstration circ.append(custom_gate, [0]) circ.measure(0, 0) circ.draw('mpl') with pulse.build(backend, name='custom') as my_schedule: pulse.play(Gaussian(duration=64, amp=0.2, sigma=8), pulse.drive_channel(0)) circ.add_calibration('my_custom_gate', [0], my_schedule, [3.14, 1]) # Alternatively: circ.add_calibration(custom_gate, [0], my_schedule) circ = transpile(circ, backend) circ.draw('mpl', idle_wires=False) circ = QuantumCircuit(2, 2) circ.append(custom_gate, [1]) from qiskit import QiskitError try: circ = transpile(circ, backend) except QiskitError as e: print(e) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Multiple-Control U1 gate. Not using ancillary qubits. """ import logging from numpy import angle from sympy.combinatorics.graycode import GrayCode from qiskit import QuantumCircuit, QuantumRegister from qiskit.aqua.utils.controlled_circuit import apply_cu1 logger = logging.getLogger(__name__) def _apply_mcu1(circuit, theta, ctls, tgt, global_phase=0): """Apply multi-controlled u1 gate from ctls to tgt with angle theta.""" n = len(ctls) gray_code = list(GrayCode(n).generate_gray()) last_pattern = None theta_angle = theta*(1/(2**(n-1))) gp_angle = angle(global_phase)*(1/(2**(n-1))) for pattern in gray_code: if '1' not in pattern: continue if last_pattern is None: last_pattern = pattern #find left most set bit lm_pos = list(pattern).index('1') #find changed bit comp = [i != j for i, j in zip(pattern, last_pattern)] if True in comp: pos = comp.index(True) else: pos = None if pos is not None: if pos != lm_pos: circuit.cx(ctls[pos], ctls[lm_pos]) else: indices = [i for i, x in enumerate(pattern) if x == '1'] for idx in indices[1:]: circuit.cx(ctls[idx], ctls[lm_pos]) #check parity if pattern.count('1') % 2 == 0: #inverse apply_cu1(circuit, -theta_angle, ctls[lm_pos], tgt) if global_phase: circuit.u1(-gp_angle, ctls[lm_pos]) else: apply_cu1(circuit, theta_angle, ctls[lm_pos], tgt) if global_phase: circuit.u1(gp_angle, ctls[lm_pos]) last_pattern = pattern def mcu1(self, theta, control_qubits, target_qubit): """ Apply Multiple-Controlled U1 gate Args: theta: angle theta control_qubits: The list of control qubits target_qubit: The target qubit """ if isinstance(target_qubit, QuantumRegister) and len(target_qubit) == 1: target_qubit = target_qubit[0] temp = [] self._check_qargs(control_qubits) temp += control_qubits self._check_qargs([target_qubit]) temp.append(target_qubit) self._check_dups(temp) n_c = len(control_qubits) if n_c == 1: # cu1 apply_cu1(self, theta, control_qubits[0], target_qubit) else: _apply_mcu1(self, theta, control_qubits, target_qubit) QuantumCircuit.mcu1 = mcu1
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# # We copy and paste the previous code # # initial case # We assume that the probability of getting head is 1 at the beginning, # becasue Asja will start with one euro. prob_head = 1 prob_tail = 0 number_of_iterations = 10 for i in range(number_of_iterations): # if the last result was head new_prob_head_from_head = prob_head * 0.6 new_prob_tail_from_head = prob_head * 0.4 # if the last result was tail # we know that prob_tail is 0 at the begining # but we still keep these two lines to have the same code for each iteration new_prob_head_from_tail = prob_tail * 0.3 new_prob_tail_from_tail = prob_tail * 0.7 # update the probabilities at the end of coin toss prob_head = new_prob_head_from_head + new_prob_head_from_tail prob_tail = new_prob_tail_from_head + new_prob_tail_from_tail # print prob_head and prob_tail print("the probability of getting head",prob_head) print("the probability of getting tail",prob_tail)
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
from qiskit import * nshots = 8192 qiskit.IBMQ.load_account() provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') simulator = Aer.get_backend('qasm_simulator') device = provider.get_backend('ibmq_bogota') from qiskit.tools.monitor import job_monitor from qiskit.tools.visualization import plot_histogram def qc_ent_dist(): qc = QuantumCircuit(2, name = 'E dist') qc.h([1]); qc.cx(1, 0) return qc qc_ent_dist_ = qc_ent_dist() qc_ent_dist_.draw(output = 'mpl') def qc_encoding(cbits): qc = QuantumCircuit(1, name = 'codificação') if cbits == '00': qc.id([0]) elif cbits == '01': qc.z([0]) elif cbits == '10': qc.x([0]) elif cbits == '11': qc.x([0]); qc.z([0]) return qc qc_encoding_ = qc_encoding('11') qc_encoding_.draw(output = 'mpl') def qc_decoding(): qc = QuantumCircuit(2, name = 'decodificação') qc.cx(1, 0); qc.h([1]) return qc qc_decoding_ = qc_decoding(); qc_decoding_.draw(output = 'mpl') cbits = '00' qc = QuantumCircuit(2, 2) qc_ent_dist_ = qc_ent_dist(); qc.append(qc_ent_dist_, [0,1]) qc.barrier() qc_encoding_ = qc_encoding(cbits); qc.append(qc_encoding_, [0]) qc.barrier() qc_decoding_ = qc_decoding(); qc.append(qc_decoding_, [0,1]) qc.measure([0,1],[0,1]) #qc.draw(output = 'mpl') qc.decompose().draw(output = 'mpl') result = execute(qc, backend = simulator, shots = nshots).result() plot_histogram(result.get_counts(qc)) job = execute(qc, backend = device, shots = nshots) job_monitor(job) plot_histogram(job.result().get_counts(qc))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit # Create a circuit with a register of three qubits circ = QuantumCircuit(3) # H gate on qubit 0, putting this qubit in a superposition of |0> + |1>. circ.h(0) # A CX (CNOT) gate on control qubit 0 and target qubit 1 generating a Bell state. circ.cx(0, 1) # CX (CNOT) gate on control qubit 0 and target qubit 2 resulting in a GHZ state. circ.cx(0, 2) # Draw the circuit circ.draw('mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag from qiskit.visualization import dag_drawer q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') circ = QuantumCircuit(q, c) circ.h(q[0]) circ.cx(q[0], q[1]) circ.measure(q[0], c[0]) circ.rz(0.5, q[1]).c_if(c, 2) dag = circuit_to_dag(circ) dag_drawer(dag)
https://github.com/SakshieP/Grovers-algorithm
SakshieP
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute, Aer, IBMQ from qiskit.visualization import plot_histogram IBMQ.save_account("APIKEY") my_list=[1,3,5,6,7,8,23,56] def the_oracle(my_input): winner=7 if my_input is winner: response = True else: response = False return response for index, trial_number in enumerate(my_list): if the_oracle(trial_number) is True: print('Winner found at index %i' %index) print('%i calls to the Oracle used' %(index+1)) break from qiskit import * import matplotlib.pyplot as plt import numpy as np oracle = QuantumCircuit(2,name='oracle') oracle.cz(0,1) oracle.to_gate() oracle.draw() backend = Aer.get_backend('statevector_simulator') grover_circ = QuantumCircuit(2,2) grover_circ.h([0,1]) grover_circ.append(oracle,[0,1]) grover_circ.draw() job = execute(grover_circ,backend) result = job.result() sv = result .get_statevector() np.around(sv,2) reflection = QuantumCircuit(2,name='reflection') reflection.h([0,1]) reflection.z([0,1]) reflection.cz(0,1) reflection.h([0,1]) reflection.to_gate() reflection.draw() backend = Aer.get_backend('qasm_simulator') grover_circ = QuantumCircuit(2,2) grover_circ.h([0,1]) grover_circ.append(oracle,[0,1]) grover_circ.append(reflection,[0,1]) grover_circ.measure([0,1],[0,1]) grover_circ.draw() job=execute(grover_circ,backend,shots=1) result=job.result() result.get_counts()
https://github.com/tomtuamnuq/compare-qiskit-ocean
tomtuamnuq
import os import shutil import time from random_lp.random_qp import RandomQP DIR = 'TEST_DATA' + "/" + time.strftime("%d_%m_%Y") def getPath(filename = "", directory = ""): return DIR + "/" + directory + "/" + filename DIR shutil.rmtree(getPath(directory = "DENSE"), ignore_errors=True) os.makedirs(getPath(directory = "DENSE")) # create dense random binary quadratic Programs # start with 10 variables and 5 constraints max_qubits = 200 var = 10 while True: cstr = int(var / 2) qp_bin = RandomQP.create_random_binary_prog("test_dense_" + str(var), cstr, var) qp_bin.write_to_lp_file(getPath(qp_bin.name, directory = "DENSE")) if qp_bin.complexity() > max_qubits : print(var) break if qp_bin.complexity() > 100 : var = var + 10 else: var = var + 5
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 qiskit_aer import Aer from qiskit.providers.exceptions import QiskitBackendNotFoundError # from qiskit import IBMQ from .emulator_backend import EmulatorBackend class LocalSubProviderManager(): def __init__(self, provider): self._provider = provider self._init_backends() def _init_backends(self): self._backends = [Aer.get_backend('aer_simulator')] self._backends.append(EmulatorBackend(self._provider)) # for sub_provider in self.sub_providers: # self._backends += sub_provider.backends() self._backends_by_name = {} for backend in self._backends: self._backends_by_name[backend.name] = backend def backends(self): return self._backends def get_backend(self, name=None, **kwargs): if name not in self._backends_by_name: raise QiskitBackendNotFoundError("No backend matches criteria.") else: return self._backends_by_name[name]
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) # with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) # with open(filename, "wb") as f: # pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) # with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump(backend.properties(), f) retrieved_jobs = jobs retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/AlphaMiyaL/Qiskit-Quantum-Journey
AlphaMiyaL
# X gate # X|0> = |1> # X|1> = |0> # moving from q0 to q1 from qiskit import * from qiskit.tools.visualization import plot_bloch_multivector circuit = QuantumCircuit(1,1) circuit.x(0) simulator = Aer.get_backend('statevector_simulator') result = execute(circuit, backend=simulator).result() statevector = result.get_statevector() print(statevector) %matplotlib inline circuit.draw(output='mpl') plot_bloch_multivector(statevector) circuit.measure([0], [0]) backend = Aer.get_backend('qasm_simulator') result = execute(circuit,backend=backend, shots = 1024).result() counts = result.get_counts() from qiskit.tools.visualization import plot_histogram plot_histogram(counts) circuit = QuantumCircuit(1,1) circuit.x(0) simulator = Aer.get_backend('unitary_simulator') result = execute(circuit, backend=simulator).result() unitary = result.get_unitary() print(unitary)
https://github.com/Sinestro38/Wine-quantumSupportVectorMachine
Sinestro38
from matplotlib import pyplot as plt import numpy as np from qiskit import Aer, execute from qiskit.tools import job_monitor from qiskit.aqua import QuantumInstance from qiskit.circuit.library import ZZFeatureMap, PauliFeatureMap, ZFeatureMap from qiskit.aqua.algorithms import QSVM from qiskit.aqua.components.multiclass_extensions import OneAgainstRest from qiskit.aqua.utils import split_dataset_to_data_and_labels, map_label_to_class_name from qiskit.aqua import MissingOptionalLibraryError from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler, MinMaxScaler from sklearn.decomposition import PCA import pandas as pd data = datasets.load_wine() target = data.target data = data.data training_dataset_size = 10 testing_dataset_size = 10 class_labels = ["A", "B", "C"] pd.DataFrame(data) dim = 3 training_dataset_size = 20 testing_dataset_size = 10 sample_train, sample_test, label_train, label_test = train_test_split(data, target, random_state=10) # Standardizing the dataset -- gaussian with unit variance and 0 mean std = StandardScaler() std.fit(sample_train) sample_train = std.transform(sample_train) sample_test = std.transform(sample_test) # Using PCA to reduce no. of dimensions to 2 to match number of qubits pca = PCA(dim) pca.fit(sample_train) sample_train = pca.transform(sample_train) sample_test = pca.transform(sample_test) # Scaling data to range from -1 to 1 minmax = MinMaxScaler() minmax = minmax.fit(sample_train) sample_train = minmax.transform(sample_train) sample_test = minmax.transform(sample_test) # Setting dataset size to number of training_dataset_size training_input = {key: (sample_train[label_train == k, :])[:training_dataset_size] for k, key in enumerate(class_labels)} test_input = {key: (sample_test[label_test == k, :])[:testing_dataset_size] for k, key in enumerate(class_labels)} # Plotting data for k in range(0, 3): plt.scatter(sample_train[label_train == k, 0][:training_dataset_size], sample_train[label_train == k, 1][:training_dataset_size]) plt.title("Wine dataset with reduced dimensions") plt.show() datapoints, class_to_label = split_dataset_to_data_and_labels(test_input) backend = Aer.get_backend("qasm_simulator") feature_map = ZZFeatureMap(dim, reps=2) print(feature_map) svm = QSVM(feature_map, training_input, test_input, None, multiclass_extension=OneAgainstRest()) quantum_instance = QuantumInstance(backend, shots=8000) result = svm.run(quantum_instance) predicted_labels = svm.predict(datapoints[0]) predicted_classes = map_label_to_class_name(predicted_labels, svm.label_to_class) print(f"Ground truth: {datapoints[1]}") print(f"Prediction: {predicted_labels}") print(" RESULTS Testing success ratio: ", result['testing_accuracy'])
https://github.com/Harcipan/QAI_GroverSim
Harcipan
# initialization import numpy as np # importing Qiskit from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, transpile # import basic plot tools from qiskit.visualization import plot_histogram # set the length of the n-bit input string. n = 3 # set the length of the n-bit input string. n = 3 const_oracle = QuantumCircuit(n+1) output = np.random.randint(2) if output == 1: const_oracle.x(n) const_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) balanced_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() balanced_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Show oracle balanced_oracle.draw() dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) dj_circuit.draw() dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit = dj_circuit.compose(balanced_oracle) dj_circuit.draw() dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit = dj_circuit.compose(balanced_oracle) # Repeat H-gates for qubit in range(n): dj_circuit.h(qubit) dj_circuit.barrier() # Measure for i in range(n): dj_circuit.measure(i, i) # Display circuit dj_circuit.draw() # use local simulator aer_sim = Aer.get_backend('aer_simulator') results = aer_sim.run(dj_circuit).result() answer = results.get_counts() plot_histogram(answer) # ...we have a 0% chance of measuring 000. assert answer.get('000', 0) == 0 def dj_oracle(case, n): # We need to make a QuantumCircuit object to return # This circuit has n+1 qubits: the size of the input, # plus one output qubit oracle_qc = QuantumCircuit(n+1) # First, let's deal with the case in which oracle is balanced if case == "balanced": # First generate a random number that tells us which CNOTs to # wrap in X-gates: b = np.random.randint(1,2**n) # Next, format 'b' as a binary string of length 'n', padded with zeros: b_str = format(b, '0'+str(n)+'b') # Next, we place the first X-gates. Each digit in our binary string # corresponds to a qubit, if the digit is 0, we do nothing, if it's 1 # we apply an X-gate to that qubit: for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Do the controlled-NOT gates for each qubit, using the output qubit # as the target: for qubit in range(n): oracle_qc.cx(qubit, n) # Next, place the final X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Case in which oracle is constant if case == "constant": # First decide what the fixed output of the oracle will be # (either always 0 or always 1) output = np.random.randint(2) if output == 1: oracle_qc.x(n) oracle_gate = oracle_qc.to_gate() oracle_gate.name = "Oracle" # To show when we display the circuit return oracle_gate def dj_algorithm(oracle, n): dj_circuit = QuantumCircuit(n+1, n) # Set up the output qubit: dj_circuit.x(n) dj_circuit.h(n) # And set up the input register: for qubit in range(n): dj_circuit.h(qubit) # Let's append the oracle gate to our circuit: dj_circuit.append(oracle, range(n+1)) # Finally, perform the H-gates again and measure: for qubit in range(n): dj_circuit.h(qubit) for i in range(n): dj_circuit.measure(i, i) return dj_circuit n = 4 oracle_gate = dj_oracle('balanced', n) dj_circuit = dj_algorithm(oracle_gate, n) dj_circuit.draw() transpiled_dj_circuit = transpile(dj_circuit, aer_sim) results = aer_sim.run(transpiled_dj_circuit).result() answer = results.get_counts() plot_histogram(answer) # Load our saved IBMQ accounts and get the least busy backend device with greater than or equal to (n+1) qubits IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.tools.monitor import job_monitor transpiled_dj_circuit = transpile(dj_circuit, backend, optimization_level=3) job = backend.run(transpiled_dj_circuit) job_monitor(job, interval=2) # Get the results of the computation results = job.result() answer = results.get_counts() plot_histogram(answer) # ...the most likely result is 1111. assert max(answer, key=answer.get) == '1111' from qiskit_textbook.problems import dj_problem_oracle oracle = dj_problem_oracle(1) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/xtophe388/QISKIT
xtophe388
# useful additional packages import matplotlib.pyplot as plt import matplotlib.axes as axes %matplotlib inline import numpy as np import networkx as nx from qiskit.tools.visualization import plot_histogram from qiskit_acqua import Operator, run_algorithm, get_algorithm_instance from qiskit_acqua.input import get_input_instance from qiskit_acqua.ising import maxcut import logging logger = logging.getLogger() # logger.setLevel(logging.DEBUG) # uncomment it to see detailed logging ################# import Qconfig and set APIToken and API url and prepare backends ############ try: import sys sys.path.append("../../") # go to parent dir import Qconfig except Exception as e: print(e) from qiskit import register, available_backends #set api APItoken=getattr(Qconfig, 'APItoken', None) url = Qconfig.config.get('url', None) hub = Qconfig.config.get('hub', None) group = Qconfig.config.get('group', None) project = Qconfig.config.get('project', None) try: register(APItoken, url, hub, group, project) except Exception as e: print(e) print("Backends: {}".format(available_backends())) # 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) default_axes = plt.axes(frameon=True) nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, ax=default_axes, pos=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 'b' for i in range(n)] nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, pos=pos) print('\nBest solution = ' + str(xbest_brute) + ' cost = ' + str(best_cost_brute)) qubitOp, offset = maxcut.get_maxcut_qubitops(w) algo_input = get_input_instance('EnergyInput') algo_input.qubit_op = qubitOp #Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector algorithm_cfg = { 'name': 'ExactEigensolver', } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg } result = run_algorithm(params,algo_input) x = maxcut.sample_most_likely(len(w), np.array(result['eigvecs'])) print('energy:', result['energy']) print('maxcut objective:', result['energy'] + offset) print('solution:', maxcut.get_graph_solution(x)) print('solution objective:', maxcut.maxcut_value(x, w)) colors = ['r' if maxcut.get_graph_solution(x)[i] == 0 else 'b' for i in range(n)] nx.draw_networkx(G, node_color=colors, node_size=600, alpha = .8, pos=pos) algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'matrix' } optimizer_cfg = { 'name': 'SPSA', 'max_trials': 300 } var_form_cfg = { 'name': 'RY', 'depth': 5, 'entanglement': 'linear' } params = { 'problem': {'name': 'ising', 'random_seed': 10598}, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg, 'backend': {'name': 'local_statevector_simulator'} } result = run_algorithm(params, algo_input) x = maxcut.sample_most_likely(len(w), result['eigvecs'][0]) print('energy:', result['energy']) print('time:', result['eval_time']) print('maxcut objective:', result['energy'] + offset) print('solution:', maxcut.get_graph_solution(x)) print('solution objective:', maxcut.maxcut_value(x, w)) colors = ['r' if maxcut.get_graph_solution(x)[i] == 0 else 'b' for i in range(n)] nx.draw_networkx(G, node_color=colors, node_size=600, alpha = .8, pos=pos) # run quantum algorithm with shots params['backend']['name'] = 'local_qasm_simulator' params['backend']['shots'] = 1024 result = run_algorithm(params, algo_input) x = maxcut.sample_most_likely(len(w), result['eigvecs'][0]) print('energy:', result['energy']) print('time:', result['eval_time']) print('maxcut objective:', result['energy'] + offset) print('solution:', maxcut.get_graph_solution(x)) print('solution objective:', maxcut.maxcut_value(x, w)) plot_histogram(result['eigvecs'][0]) colors = ['r' if maxcut.get_graph_solution(x)[i] == 0 else 'b' for i in range(n)] nx.draw_networkx(G, node_color=colors, node_size=600, alpha = .8, pos=pos)
https://github.com/lynnlangit/learning-quantum
lynnlangit
import numpy as np from qiskit.algorithms.linear_solvers.numpy_linear_solver import NumPyLinearSolver from qiskit.algorithms.linear_solvers.hhl import HHL matrix = np.array([[1, -1/3], [-1/3, 1]]) vector = np.array([1, 0]) naive_hhl_solution = HHL().solve(matrix, vector) classical_solution = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector)) from qiskit.algorithms.linear_solvers.matrices.tridiagonal_toeplitz import TridiagonalToeplitz tridi_matrix = TridiagonalToeplitz(1, 1, -1 / 3) tridi_solution = HHL().solve(tridi_matrix, vector) print('classical state:', classical_solution.state) print('naive state:') print(naive_hhl_solution.state) print('tridiagonal state:') print(tridi_solution.state) print('classical Euclidean norm:', classical_solution.euclidean_norm) print('naive Euclidean norm:', naive_hhl_solution.euclidean_norm) print('tridiagonal Euclidean norm:', tridi_solution.euclidean_norm) from qiskit.quantum_info import Statevector naive_sv = Statevector(naive_hhl_solution.state).data tridi_sv = Statevector(tridi_solution.state).data # Extract the right vector components. 1000 corresponds to the index 8 and 1001 corresponds to the index 9 naive_full_vector = np.array([naive_sv[8], naive_sv[9]]) tridi_full_vector = np.array([tridi_sv[8], tridi_sv[9]]) print('naive raw solution vector:', naive_full_vector) print('tridi raw solution vector:', tridi_full_vector) naive_full_vector = np.real(naive_full_vector) tridi_full_vector = np.real(tridi_full_vector) print('full naive solution vector:', naive_hhl_solution.euclidean_norm*naive_full_vector/np.linalg.norm(naive_full_vector)) print('full tridi solution vector:', tridi_solution.euclidean_norm*tridi_full_vector/np.linalg.norm(tridi_full_vector)) print('classical state:', classical_solution.state) from scipy.sparse import diags num_qubits = 2 matrix_size = 2 ** num_qubits # entries of the tridiagonal Toeplitz symmetric matrix a = 1 b = -1/3 matrix = diags([b, a, b], [-1, 0, 1], shape=(matrix_size, matrix_size)).toarray() vector = np.array([1] + [0]*(matrix_size - 1)) # run the algorithms classical_solution = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector)) naive_hhl_solution = HHL().solve(matrix, vector) tridi_matrix = TridiagonalToeplitz(num_qubits, a, b) tridi_solution = HHL().solve(tridi_matrix, vector) print('classical euclidean norm:', classical_solution.euclidean_norm) print('naive euclidean norm:', naive_hhl_solution.euclidean_norm) print('tridiagonal euclidean norm:', tridi_solution.euclidean_norm) from qiskit import transpile num_qubits = list(range(1,5)) a = 1 b = -1/3 i=1 # calculate the circuit depths for different number of qubits to compare the use of resources naive_depths = [] tridi_depths = [] for nb in num_qubits: matrix = diags([b, a, b], [-1, 0, 1], shape=(2**nb, 2**nb)).toarray() vector = np.array([1] + [0]*(2**nb -1)) naive_hhl_solution = HHL().solve(matrix, vector) tridi_matrix = TridiagonalToeplitz(nb, a, b) tridi_solution = HHL().solve(tridi_matrix, vector) naive_qc = transpile(naive_hhl_solution.state,basis_gates=['id', 'rz', 'sx', 'x', 'cx']) tridi_qc = transpile(tridi_solution.state,basis_gates=['id', 'rz', 'sx', 'x', 'cx']) naive_depths.append(naive_qc.depth()) tridi_depths.append(tridi_qc.depth()) i +=1 sizes = [str(2**nb)+"x"+str(2**nb) for nb in num_qubits] columns = ['size of the system', 'quantum_solution depth', 'tridi_solution depth'] data = np.array([sizes, naive_depths, tridi_depths]) row_format ="{:>23}" * (len(columns) + 2) for team, row in zip(columns, data): print(row_format.format(team, *row)) print('excess:', [naive_depths[i] - tridi_depths[i] for i in range(0, len(naive_depths))]) from qiskit.algorithms.linear_solvers.observables import AbsoluteAverage, MatrixFunctional num_qubits = 1 matrix_size = 2 ** num_qubits # entries of the tridiagonal Toeplitz symmetric matrix a = 1 b = -1/3 matrix = diags([b, a, b], [-1, 0, 1], shape=(matrix_size, matrix_size)).toarray() vector = np.array([1] + [0]*(matrix_size - 1)) tridi_matrix = TridiagonalToeplitz(1, a, b) average_solution = HHL().solve(tridi_matrix, vector, AbsoluteAverage()) classical_average = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector), AbsoluteAverage()) print('quantum average:', average_solution.observable) print('classical average:', classical_average.observable) print('quantum circuit results:', average_solution.circuit_results) observable = MatrixFunctional(1, 1 / 2) functional_solution = HHL().solve(tridi_matrix, vector, observable) classical_functional = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector), observable) print('quantum functional:', functional_solution.observable) print('classical functional:', classical_functional.observable) print('quantum circuit results:', functional_solution.circuit_results) from qiskit import BasicAer backend = BasicAer.get_backend('qasm_simulator') hhl = HHL(1e-3, quantum_instance=backend) accurate_solution = hhl.solve(matrix, vector) classical_solution = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector)) print(accurate_solution.euclidean_norm) print(classical_solution.euclidean_norm) from qiskit import QuantumRegister, QuantumCircuit import numpy as np t = 2 # This is not optimal; As an exercise, set this to the # value that will get the best results. See section 8 for solution. nqubits = 4 # Total number of qubits nb = 1 # Number of qubits representing the solution nl = 2 # Number of qubits representing the eigenvalues theta = 0 # Angle defining |b> a = 1 # Matrix diagonal b = -1/3 # Matrix off-diagonal # Initialize the quantum and classical registers qr = QuantumRegister(nqubits) # Create a Quantum Circuit qc = QuantumCircuit(qr) qrb = qr[0:nb] qrl = qr[nb:nb+nl] qra = qr[nb+nl:nb+nl+1] # State preparation. qc.ry(2*theta, qrb[0]) # QPE with e^{iAt} for qu in qrl: qc.h(qu) qc.p(a*t, qrl[0]) qc.p(a*t*2, qrl[1]) qc.u(b*t, -np.pi/2, np.pi/2, qrb[0]) # Controlled e^{iAt} on \lambda_{1}: params=b*t qc.p(np.pi/2,qrb[0]) qc.cx(qrl[0],qrb[0]) qc.ry(params,qrb[0]) qc.cx(qrl[0],qrb[0]) qc.ry(-params,qrb[0]) qc.p(3*np.pi/2,qrb[0]) # Controlled e^{2iAt} on \lambda_{2}: params = b*t*2 qc.p(np.pi/2,qrb[0]) qc.cx(qrl[1],qrb[0]) qc.ry(params,qrb[0]) qc.cx(qrl[1],qrb[0]) qc.ry(-params,qrb[0]) qc.p(3*np.pi/2,qrb[0]) # Inverse QFT qc.h(qrl[1]) qc.rz(-np.pi/4,qrl[1]) qc.cx(qrl[0],qrl[1]) qc.rz(np.pi/4,qrl[1]) qc.cx(qrl[0],qrl[1]) qc.rz(-np.pi/4,qrl[0]) qc.h(qrl[0]) # Eigenvalue rotation t1=(-np.pi +np.pi/3 - 2*np.arcsin(1/3))/4 t2=(-np.pi -np.pi/3 + 2*np.arcsin(1/3))/4 t3=(np.pi -np.pi/3 - 2*np.arcsin(1/3))/4 t4=(np.pi +np.pi/3 + 2*np.arcsin(1/3))/4 qc.cx(qrl[1],qra[0]) qc.ry(t1,qra[0]) qc.cx(qrl[0],qra[0]) qc.ry(t2,qra[0]) qc.cx(qrl[1],qra[0]) qc.ry(t3,qra[0]) qc.cx(qrl[0],qra[0]) qc.ry(t4,qra[0]) qc.measure_all() print("Depth: %i" % qc.depth()) print("CNOTS: %i" % qc.count_ops()['cx']) qc.draw(fold=-1) from qiskit import BasicAer, ClassicalRegister, IBMQ from qiskit.compiler import transpile from qiskit.ignis.mitigation.measurement import (complete_meas_cal, # Measurement error mitigation functions CompleteMeasFitter, MeasurementFilter) provider = IBMQ.load_account() backend = provider.get_backend('ibmqx2') # calibrate using real hardware layout = [2,3,0,4] chip_qubits = 5 # Transpiled circuit for the real hardware qc_qa_cx = transpile(qc, backend=backend, initial_layout=layout) meas_cals, state_labels = complete_meas_cal(qubit_list=layout, qr=QuantumRegister(chip_qubits)) qcs = meas_cals + [qc_qa_cx] job = backend.run(qcs, shots=10)
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
%run init.ipynb from qiskit import * nshots = 8192 IBMQ.load_account() provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main') device = provider.get_backend('ibmq_bogota') simulator = Aer.get_backend('qasm_simulator') from qiskit.visualization import plot_histogram from qiskit.tools.monitor import job_monitor from qiskit.quantum_info import state_fidelity
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeAuckland backend = FakeAuckland() ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) depths = [] gate_counts = [] non_local_gate_counts = [] levels = [str(x) for x in range(4)] for level in range(4): circ = transpile(ghz, backend, optimization_level=level) depths.append(circ.depth()) gate_counts.append(sum(circ.count_ops().values())) non_local_gate_counts.append(circ.num_nonlocal_gates()) fig, (ax1, ax2) = plt.subplots(2, 1) ax1.bar(levels, depths, label='Depth') ax1.set_xlabel("Optimization Level") ax1.set_ylabel("Depth") ax1.set_title("Output Circuit Depth") ax2.bar(levels, gate_counts, label='Number of Circuit Operations') ax2.bar(levels, non_local_gate_counts, label='Number of non-local gates') ax2.set_xlabel("Optimization Level") ax2.set_ylabel("Number of gates") ax2.legend() ax2.set_title("Number of output circuit gates") fig.tight_layout() plt.show()
https://github.com/quantumjim/qreative
quantumjim
import sys sys.path.append('../') import CreativeQiskit b = CreativeQiskit.twobit() b.prepare({'Z':True}) print(" bit value =",b.Z_value() ) b.prepare({'Z':False}) print(" bit value =",b.Z_value() ) b.prepare({'X':True}) print(" bit value =",b.X_value() ) b.prepare({'X':False}) print(" bit value =",b.X_value() ) print(" Here are 10 trials with, each with True encoded in the Z basis. The values read out with X are:\n") for trial in range(1,11): b.prepare({'Z':True}) message = " Try " + str(trial)+": " message += str( b.X_value() ) print( message ) for trial in range(1,11): message = " Try " + str(trial)+": " b.prepare({'Z':True}) for repeat in range(5): message += str( b.X_value() ) + ", " print(message) b = CreativeQiskit.twobit() for trial in range(1,11): message = " Try " + str(trial)+": " b.prepare({'Z':True}) for repeat in range(5): message += str( b.X_value(noisy=0.2,mitigate=False) ) + ", " print(message) b = CreativeQiskit.twobit() for trial in range(1,11): message = " Try " + str(trial)+": " b.prepare({'Z':True}) for repeat in range(5): message += str( b.X_value(noisy=True) ) + ", " print(message) ship = CreativeQiskit.twobit() destroyed = False while not destroyed: basis = input('\n > Choose a torpedo type (Z or X)...\n ') destroyed = ship.value(basis) if destroyed: print('\n *Ship destroyed!*') else: print('\n *Attack failed!*') print('\n **Mission complete!**')
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/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) ### removed cx gate ### return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) qc.h(1) return qc
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np 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.draw(output='mpl')
https://github.com/jenglick/scipy22-qiskit-runtime-tutorial
jenglick
from qiskit_nature.drivers import Molecule from qiskit_nature.drivers.second_quantization import ElectronicStructureDriverType, ElectronicStructureMoleculeDriver dist = 0.72 molecule = Molecule(geometry=[['H', [0., 0., 0.]], ['H', [0., 0., dist]]]) driver = ElectronicStructureMoleculeDriver(molecule, basis='sto3g', \ driver_type=ElectronicStructureDriverType.PYSCF) print(molecule) from qiskit_nature.problems.second_quantization import ElectronicStructureProblem es_problem = ElectronicStructureProblem(driver) second_q_ops = es_problem.second_q_ops() print(second_q_ops[0]) from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.mappers.second_quantization import ParityMapper qubit_converter = QubitConverter(ParityMapper(), two_qubit_reduction=True) hamiltonian = qubit_converter.convert(second_q_ops[0], num_particles=es_problem.num_particles) print(hamiltonian) from qiskit.algorithms import NumPyMinimumEigensolver from qiskit.algorithms import MinimumEigensolverResult # Generate the exact solution sol = MinimumEigensolverResult() sol.eigenvalue = NumPyMinimumEigensolver().compute_minimum_eigenvalue(hamiltonian).eigenvalue exact_solution = es_problem.interpret(sol).total_energies[0] print('exact_solution:\n{}'.format(exact_solution)) from qiskit.opflow import TaperedPauliSumOp import numpy as np ops = [] h = hamiltonian.primitive h.coeffs = np.real(hamiltonian.coeffs) ops.append(TaperedPauliSumOp(h, hamiltonian.z2_symmetries)) from qiskit_ibm_runtime import QiskitRuntimeService, Estimator service = QiskitRuntimeService() options = {"backend" : "ibmq_qasm_simulator"} from qiskit.algorithms.optimizers import NELDER_MEAD from qiskit.circuit.library import RealAmplitudes circuit = RealAmplitudes(num_qubits=hamiltonian.num_qubits, reps=2) circuit.decompose().draw() convergence = [] with Estimator( circuits=circuit, observables=ops, options=options, service=service ) as estimator: def evaluate_expectation(x): x = list(x) results = estimator(circuits=[0], observables=[0], parameter_values=[x]).values[0] return np.real(results) def callback(fx): expval = evaluate_expectation(fx) print('expval: {}'.format(expval)) convergence.append(expval) np.random.seed(1) initial_point = np.random.uniform(-np.pi, np.pi, len(circuit.parameters)) optimizer = NELDER_MEAD(40, callback=callback) result = optimizer.minimize(fun=evaluate_expectation, x0=initial_point) total_energy = [] for i in range(len(convergence)): sol = MinimumEigensolverResult() sol.eigenvalue = convergence[i] sol = es_problem.interpret(sol).total_energies[0] total_energy.append(sol) print(total_energy) import matplotlib.pyplot as plt plt.rcParams["font.size"] = 14 plt.figure(figsize=(12, 6)) plt.plot(total_energy, label="Estimator VQE") plt.axhline(y=exact_solution, color="tab:red", ls="--", label="Target") plt.legend(loc="best") plt.xlabel("Iteration") plt.ylabel("Energy [H]") plt.title("VQE energy") plt.show() import qiskit_ibm_runtime qiskit_ibm_runtime.version.get_version_info() from qiskit.tools.jupyter import * %qiskit_version_table %qiskit_copyright
https://github.com/sayana25/IQCQ-UPES-2023
sayana25
pip install qiskit !pip install pylatexenc pip install qiskit-aer pip install qiskit-ibm-runtime pip install qiskit-ibm-provider import numpy as np from numpy import pi # importing Qiskit from qiskit import QuantumCircuit, transpile, Aer, IBMQ, assemble from qiskit.visualization import plot_histogram, plot_bloch_multivector from math import pi, sqrt sim = Aer.get_backend('aer_simulator') # Let's do an X-gate on a |0> qubit qc = QuantumCircuit(1) qc.x(0) qc.draw('mpl') # Let's see the result qc.save_statevector() qobj = assemble(qc) state = sim.run(qobj).result().get_statevector() plot_bloch_multivector(state) # Let's do an Y-gate on a |0> qubit qc = QuantumCircuit(1) #qc.x(0) qc.y(0) qc.draw('mpl') # Let's see the result qc.save_statevector() qobj = assemble(qc) state = sim.run(qobj).result().get_statevector() plot_bloch_multivector(state) # Let's do an Y-gate on a |1> qubit qc = QuantumCircuit(1) #In qiskit, the qubit is initialised at |0> qc.x(0) #prepares the |1> qubit qc.y(0) #Then y-gate is applied on y qc.draw('mpl') # Let's see the result qc.save_statevector() qobj = assemble(qc) state = sim.run(qobj).result().get_statevector() plot_bloch_multivector(state) # Let's do an Y-gate on a |1> qubit qc = QuantumCircuit(1) #In qiskit, the qubit is initialised at |0> qc.z(0) #z rotation on the |0> qubit, leaves it unchanged as seen below qc.draw('mpl') # Let's see the result qc.save_statevector() qobj = assemble(qc) state = sim.run(qobj).result().get_statevector() plot_bloch_multivector(state) # Let's do an Y-gate on a |1> qubit qc = QuantumCircuit(1) #In qiskit, the qubit is initialised at |0> qc.x(0) qc.z(0) #z rotation on the |1> qubit? qc.draw('mpl') # Let's see the result qc.save_statevector() qobj = assemble(qc) state = sim.run(qobj).result().get_statevector() plot_bloch_multivector(state) # Let's do an H-gate on a |0> qubit qc = QuantumCircuit(1) #In qiskit, the qubit is initialised at |0> qc.h(0) qc.draw('mpl') # Let's see the result qc.save_statevector() qobj = assemble(qc) state = sim.run(qobj).result().get_statevector() plot_bloch_multivector(state) # Let's do an H-gate on a |0> qubit followed by Z qc = QuantumCircuit(1) #In qiskit, the qubit is initialised at |0>, let's convert it to the |1> state qc.h(0) qc.z(0) # Let's see the result qc.save_statevector() qobj = assemble(qc) state = sim.run(qobj).result().get_statevector() plot_bloch_multivector(state) # Let's do an H-gate on a |0> qubit followed by X qc = QuantumCircuit(1) #In qiskit, the qubit is initialised at |0>, let's convert it to the |1> state qc.h(0) qc.x(0) #Does this make any difference? qc.z(0) #This flips # Let's see the result qc.save_statevector() qobj = assemble(qc) state = sim.run(qobj).result().get_statevector() plot_bloch_multivector(state) import numpy as np from numpy import pi # importing Qiskit from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.monitor import job_monitor from qiskit.visualization import plot_histogram, plot_bloch_multivector qc = QuantumCircuit(3) qc.h(2) qc.cp(pi/2, 1, 2) # CROT from qubit 1 to qubit 2 qc.cp(pi/4, 0, 2) # CROT from qubit 2 to qubit 0 qc.h(1) qc.cp(pi/2, 0, 1) # CROT from qubit 0 to qubit 1 qc.h(0) qc.swap(0,2) qc.draw('mpl') def qft_rotations(circuit, n): """Performs qft on the first n qubits in circuit (without swaps)""" if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(pi/2**(n-qubit), qubit, n) # At the end of our function, we call the same function again on # the next qubits (we reduced n by one earlier in the function) qft_rotations(circuit, n) # Let's see how it looks: qc = QuantumCircuit(4) qft_rotations(qc,4) qc.draw('mpl') def swap_registers(circuit, n): for qubit in range(n//2): circuit.swap(qubit, n-qubit-1) return circuit def qft(circuit, n): """QFT on the first n qubits in circuit""" qft_rotations(circuit, n) swap_registers(circuit, n) return circuit # Let's see how it looks: qc = QuantumCircuit(4) qft(qc,4) qc.draw('mpl') bin(5) # Create the circuit qc = QuantumCircuit(3) # Encode the state 5 qc.x(0) qc.x(2) qc.draw('mpl') #Checking qubit states in the bloch vector representation using the Aer simulator sim = Aer.get_backend("aer_simulator") qc_init = qc.copy() qc_init.save_statevector() statevector = sim.run(qc_init).result().get_statevector() plot_bloch_multivector(statevector) qft(qc,3) qc.draw('mpl') qc.save_statevector() statevector = sim.run(qc).result().get_statevector() plot_bloch_multivector(statevector) bin(4) # Create the circuit qc = QuantumCircuit(3) # Encode the state 4 qc.x(2) qc.draw('mpl') sim = Aer.get_backend("aer_simulator") qc_init = qc.copy() qc_init.save_statevector() statevector = sim.run(qc_init).result().get_statevector() plot_bloch_multivector(statevector) qft(qc,3) qc.draw('mpl') qc.save_statevector() statevector = sim.run(qc).result().get_statevector() plot_bloch_multivector(statevector)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.units import DistanceUnit from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.mappers import ParityMapper from qiskit_nature.second_q.properties import ParticleNumber from qiskit_nature.second_q.transformers import ActiveSpaceTransformer bond_distance = 2.5 # in Angstrom # specify driver driver = PySCFDriver( atom=f"Li 0 0 0; H 0 0 {bond_distance}", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) problem = driver.run() # specify active space transformation active_space_trafo = ActiveSpaceTransformer( num_electrons=problem.num_particles, num_spatial_orbitals=3 ) # transform the electronic structure problem problem = active_space_trafo.transform(problem) # construct the parity mapper with 2-qubit reduction qubit_mapper = ParityMapper(num_particles=problem.num_particles) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.algorithms.ground_state_solvers import GroundStateEigensolver np_solver = NumPyMinimumEigensolver() np_groundstate_solver = GroundStateEigensolver(qubit_mapper, np_solver) np_result = np_groundstate_solver.solve(problem) target_energy = np_result.total_energies[0] print(np_result) from qiskit.circuit.library import EfficientSU2 ansatz = EfficientSU2(num_qubits=4, reps=1, entanglement="linear", insert_barriers=True) ansatz.decompose().draw("mpl", style="iqx") import numpy as np from qiskit.utils import algorithm_globals # fix random seeds for reproducibility np.random.seed(5) algorithm_globals.random_seed = 5 from qiskit.algorithms.optimizers import SPSA optimizer = SPSA(maxiter=100) initial_point = np.random.random(ansatz.num_parameters) from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.primitives import Estimator estimator = Estimator() local_vqe = VQE( estimator, ansatz, optimizer, initial_point=initial_point, ) local_vqe_groundstate_solver = GroundStateEigensolver(qubit_mapper, local_vqe) local_vqe_result = local_vqe_groundstate_solver.solve(problem) print(local_vqe_result) from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(group="open") # replace by your runtime provider backend = provider.get_backend("ibmq_qasm_simulator") # select a backend that supports the runtime from qiskit_nature.runtime import VQEClient runtime_vqe = VQEClient( ansatz=ansatz, optimizer=optimizer, initial_point=initial_point, provider=provider, backend=backend, shots=1024, measurement_error_mitigation=True, ) # use a complete measurement fitter for error mitigation runtime_vqe_groundstate_solver = GroundStateEigensolver(qubit_mapper, runtime_vqe) runtime_vqe_result = runtime_vqe_groundstate_solver.solve(problem) print(runtime_vqe_result) runtime_result = runtime_vqe_result.raw_result history = runtime_result.optimizer_history loss = history["energy"] import matplotlib.pyplot as plt plt.rcParams["font.size"] = 14 # plot loss and reference value plt.figure(figsize=(12, 6)) plt.plot(loss + runtime_vqe_result.nuclear_repulsion_energy, label="Runtime VQE") plt.axhline(y=target_energy + 0.2, color="tab:red", ls=":", label="Target + 200mH") plt.axhline(y=target_energy, color="tab:red", ls="--", label="Target") plt.legend(loc="best") plt.xlabel("Iteration") plt.ylabel("Energy [H]") plt.title("VQE energy"); import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit.circuit import Parameter from qiskit import pulse from qiskit.test.mock.backends.almaden import * phase = Parameter('phase') with pulse.build(FakeAlmaden()) as phase_test_sched: pulse.shift_phase(phase, pulse.drive_channel(0)) phase_test_sched.instructions # ()
https://github.com/Advanced-Research-Centre/QPULBA
Advanced-Research-Centre
from qiskit import QuantumCircuit import numpy as np import random from qiskit import Aer, execute import math simulator = Aer.get_backend('statevector_simulator') def display(circ,msg=""): sim_res = execute(circ, simulator).result() statevector = sim_res.get_statevector(circ) qb = int(math.log2(len(statevector))) print("============ State Vector ============", msg) s = 0 for i in statevector: print(' ({:.5f}) |{:0{}b}>'.format(i,s,qb)) s = s+1 print("============..............============") a2 = np.pi * random.random() a3 = np.pi * random.random() # NEW circ1 = QuantumCircuit(4) #display(circ1,"all zero") circ1.ry(a2,1) circ1.ry(a3,2) #display(circ1,"load fsm") circ1.x(0) circ1.toffoli(0,1,3) circ1.x(0) circ1.toffoli(0,2,3) #display(circ1,"step 1") circ1.swap(0,3) #display(circ1,"reset 1") circ1.x(0) circ1.toffoli(0,1,3) circ1.x(0) circ1.toffoli(0,2,3) #display(circ1,"step 2") circ1.swap(0,3) circ1.toffoli(0,2,3) circ1.x(0) circ1.toffoli(0,1,3) circ1.x(0) display(circ1,"reset 2") print(circ1.draw()) circ2 = QuantumCircuit(5) #display(circ2,"all zero") circ2.ry(a2,1) circ2.ry(a3,2) #display(circ2,"load fsm") circ2.x(0) circ2.toffoli(0,1,3) circ2.x(0) circ2.toffoli(0,2,3) #display(circ2,"step 1") circ2.swap(0,3) #display(circ2,"reset 1") circ2.x(0) circ2.toffoli(0,1,4) circ2.x(0) circ2.toffoli(0,2,4) #display(circ2,"step 2") circ2.swap(0,4) display(circ2,"reset 2") print(circ2.draw())
https://github.com/pedroripper/qiskit_tutoriais
pedroripper
from qiskit import * # Para representar o qubit em uma esfera de bloch devemos pensar nele na seguinte forma: # Depois de encontrar o theta, phi que desejamos, vamos ter os valores necessários para plotar nossa # esfera de bloch # Para plotar precisamos chamar a função plot_bloch_vector_spherical() que leva como parâmetro # o vetor de bloch # para encontrar o vetor de bloch seguimos a fórmula # Para o exemplo vamos usar o qubit no estado |+> que fica da seguinte forma: # Para conseguir representar esse estado no formato dado anteriormente vamos precisar # de um theta valendo pi/2 e de um phi valendo 0 # portanto vamos ter o vetor de bloch como (1,0,0) # Finalmente podemos exibir a esfera de bloch from qiskit.visualization import plot_bloch_vector %matplotlib inline plot_bloch_vector([1,0,0], title="Minha Primeira Esfera de Bloch")
https://github.com/quantum-melbourne/qiskit-challenge-22
quantum-melbourne
from qiskit_optimization.algorithms import MinimumEigenOptimizer from qiskit import Aer from qiskit.utils import algorithm_globals, QuantumInstance from qiskit.algorithms import QAOA, NumPyMinimumEigensolver import numpy as np val = [5,6,7,8,9] wt = [4,5,6,7,8] W = 18 def dp(W, wt, val, n): k = [[0 for x in range(W + 1)] for x in range(n + 1)] for i in range(n + 1): for w in range(W + 1): if i == 0 or w == 0: k[i][w] = 0 elif wt[i-1] <= w: k[i][w] = max(val[i-1] + k[i-1][w-wt[i-1]], k[i-1][w]) else: k[i][w] = k[i-1][w] picks=[0 for x in range(n)] volume=W for i in range(n,-1,-1): if (k[i][volume]>k[i-1][volume]): picks[i-1]=1 volume -= wt[i-1] return k[n][W],picks n = len(val) print("optimal value:", dp(W, wt, val, n)[0]) print('\n index of the chosen items:') for i in range(n): if dp(W, wt, val, n)[1][i]: print(i,end=' ') # import packages necessary for application classes. from qiskit_optimization.applications import Knapsack def knapsack_quadratic_program(): # Put values, weights and max_weight parameter for the Knapsack() ############################## # Provide your code here prob = Knapsack(val, wt, W) # ############################## # to_quadratic_program generates a corresponding QuadraticProgram of the instance of the knapsack problem. kqp = prob.to_quadratic_program() return prob, kqp prob,quadratic_program=knapsack_quadratic_program() quadratic_program # Numpy Eigensolver meo = MinimumEigenOptimizer(min_eigen_solver=NumPyMinimumEigensolver()) result = meo.solve(quadratic_program) print('result:\n', result) print('\n index of the chosen items:', prob.interpret(result)) # QAOA seed = 123 algorithm_globals.random_seed = seed qins = QuantumInstance(backend=Aer.get_backend('qasm_simulator'), shots=1000, seed_simulator=seed, seed_transpiler=seed) meo = MinimumEigenOptimizer(min_eigen_solver=QAOA(reps=1, quantum_instance=qins)) result = meo.solve(quadratic_program) print('result:\n', result) print('\n index of the chosen items:', prob.interpret(result)) # Check your answer and submit using the following code from qc_grader import grade_ex4a grade_ex4a(quadratic_program) L1 = [5,3,3,6,9,7,1] L2 = [8,4,5,12,10,11,2] C1 = [1,1,2,1,1,1,2] C2 = [3,2,3,2,4,3,3] C_max = 16 def knapsack_argument(L1, L2, C1, C2, C_max): ############################## # Provide your code here values = [j-i for i,j in zip(L1,L2)] weights = [j-i for i,j in zip(C1,C2)] max_weight = max([i+j for i,j in zip(L1, L2)]) # ############################## return values, weights, max_weight values, weights, max_weight = knapsack_argument(L1, L2, C1, C2, C_max) print(values, weights, max_weight) prob = Knapsack(values = values, weights = weights, max_weight = max_weight) qp = prob.to_quadratic_program() qp # Check your answer and submit using the following code from qc_grader import grade_ex4b grade_ex4b(knapsack_argument) # QAOA seed = 123 algorithm_globals.random_seed = seed qins = QuantumInstance(backend=Aer.get_backend('qasm_simulator'), shots=1000, seed_simulator=seed, seed_transpiler=seed) meo = MinimumEigenOptimizer(min_eigen_solver=QAOA(reps=1, quantum_instance=qins)) result = meo.solve(qp) print('result:', result.x) item = np.array(result.x) revenue=0 for i in range(len(item)): if item[i]==0: revenue+=L1[i] else: revenue+=L2[i] print('total revenue:', revenue) instance_examples = [ { 'L1': [3, 7, 3, 4, 2, 6, 2, 2, 4, 6, 6], 'L2': [7, 8, 7, 6, 6, 9, 6, 7, 6, 7, 7], 'C1': [2, 2, 2, 3, 2, 4, 2, 2, 2, 2, 2], 'C2': [4, 3, 3, 4, 4, 5, 3, 4, 4, 3, 4], 'C_max': 33 }, { 'L1': [4, 2, 2, 3, 5, 3, 6, 3, 8, 3, 2], 'L2': [6, 5, 8, 5, 6, 6, 9, 7, 9, 5, 8], 'C1': [3, 3, 2, 3, 4, 2, 2, 3, 4, 2, 2], 'C2': [4, 4, 3, 5, 5, 3, 4, 5, 5, 3, 5], 'C_max': 38 }, { 'L1': [5, 4, 3, 3, 3, 7, 6, 4, 3, 5, 3], 'L2': [9, 7, 5, 5, 7, 8, 8, 7, 5, 7, 9], 'C1': [2, 2, 4, 2, 3, 4, 2, 2, 2, 2, 2], 'C2': [3, 4, 5, 4, 4, 5, 3, 3, 5, 3, 5], 'C_max': 35 } ] from typing import List, Union import math from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, assemble from qiskit.compiler import transpile from qiskit.circuit import Gate from qiskit.circuit.library.standard_gates import * from qiskit.circuit.library import QFT def phase_return(index_qubits: int, gamma: float, L1: list, L2: list, to_gate=True) -> Union[Gate, QuantumCircuit]: qr_index = QuantumRegister(index_qubits, "index") qc = QuantumCircuit(qr_index) ############################## ### U_1(gamma * (lambda2 - lambda1)) for each qubit ### # Provide your code here ############################## return qc.to_gate(label=" phase return ") if to_gate else qc def subroutine_add_const(data_qubits: int, const: int, to_gate=True) -> Union[Gate, QuantumCircuit]: qc = QuantumCircuit(data_qubits) ############################## ### Phase Rotation ### # Provide your code here ############################## return qc.to_gate(label=" [+"+str(const)+"] ") if to_gate else qc def const_adder(data_qubits: int, const: int, to_gate=True) -> Union[Gate, QuantumCircuit]: qr_data = QuantumRegister(data_qubits, "data") qc = QuantumCircuit(qr_data) ############################## ### QFT ### # Provide your code here ############################## ############################## ### Phase Rotation ### # Use `subroutine_add_const` ############################## ############################## ### IQFT ### # Provide your code here ############################## return qc.to_gate(label=" [ +" + str(const) + "] ") if to_gate else qc def cost_calculation(index_qubits: int, data_qubits: int, list1: list, list2: list, to_gate = True) -> Union[Gate, QuantumCircuit]: qr_index = QuantumRegister(index_qubits, "index") qr_data = QuantumRegister(data_qubits, "data") qc = QuantumCircuit(qr_index, qr_data) for i, (val1, val2) in enumerate(zip(list1, list2)): ############################## ### Add val2 using const_adder controlled by i-th index register (set to 1) ### # Provide your code here ############################## qc.x(qr_index[i]) ############################## ### Add val1 using const_adder controlled by i-th index register (set to 0) ### # Provide your code here ############################## qc.x(qr_index[i]) return qc.to_gate(label=" Cost Calculation ") if to_gate else qc def constraint_testing(data_qubits: int, C_max: int, to_gate = True) -> Union[Gate, QuantumCircuit]: qr_data = QuantumRegister(data_qubits, "data") qr_f = QuantumRegister(1, "flag") qc = QuantumCircuit(qr_data, qr_f) ############################## ### Set the flag register for indices with costs larger than C_max ### # Provide your code here ############################## return qc.to_gate(label=" Constraint Testing ") if to_gate else qc def penalty_dephasing(data_qubits: int, alpha: float, gamma: float, to_gate = True) -> Union[Gate, QuantumCircuit]: qr_data = QuantumRegister(data_qubits, "data") qr_f = QuantumRegister(1, "flag") qc = QuantumCircuit(qr_data, qr_f) ############################## ### Phase Rotation ### # Provide your code here ############################## return qc.to_gate(label=" Penalty Dephasing ") if to_gate else qc def reinitialization(index_qubits: int, data_qubits: int, C1: list, C2: list, C_max: int, to_gate = True) -> Union[Gate, QuantumCircuit]: qr_index = QuantumRegister(index_qubits, "index") qr_data = QuantumRegister(data_qubits, "data") qr_f = QuantumRegister(1, "flag") qc = QuantumCircuit(qr_index, qr_data, qr_f) ############################## ### Reinitialization Circuit ### # Provide your code here ############################## return qc.to_gate(label=" Reinitialization ") if to_gate else qc def mixing_operator(index_qubits: int, beta: float, to_gate = True) -> Union[Gate, QuantumCircuit]: qr_index = QuantumRegister(index_qubits, "index") qc = QuantumCircuit(qr_index) ############################## ### Mixing Operator ### # Provide your code here ############################## return qc.to_gate(label=" Mixing Operator ") if to_gate else qc def solver_function(L1: list, L2: list, C1: list, C2: list, C_max: int) -> QuantumCircuit: # the number of qubits representing answers index_qubits = len(L1) # the maximum possible total cost max_c = sum([max(l0, l1) for l0, l1 in zip(C1, C2)]) # the number of qubits representing data values can be defined using the maximum possible total cost as follows: data_qubits = math.ceil(math.log(max_c, 2)) + 1 if not max_c & (max_c - 1) == 0 else math.ceil(math.log(max_c, 2)) + 2 ### Phase Operator ### # return part def phase_return(): ############################## ### TODO ### ### Paste your code from above cells here ### ############################## # penalty part def subroutine_add_const(): ############################## ### TODO ### ### Paste your code from above cells here ### ############################## # penalty part def const_adder(): ############################## ### TODO ### ### Paste your code from above cells here ### ############################## # penalty part def cost_calculation(): ############################## ### TODO ### ### Paste your code from above cells here ### ############################## # penalty part def constraint_testing(): ############################## ### TODO ### ### Paste your code from above cells here ### ############################## # penalty part def penalty_dephasing(): ############################## ### TODO ### ### Paste your code from above cells here ### ############################## # penalty part def reinitialization(): ############################## ### TODO ### ### Paste your code from above cells here ### ############################## ### Mixing Operator ### def mixing_operator(): ############################## ### TODO ### ### Paste your code from above cells here ### ############################## qr_index = QuantumRegister(index_qubits, "index") # index register qr_data = QuantumRegister(data_qubits, "data") # data register qr_f = QuantumRegister(1, "flag") # flag register cr_index = ClassicalRegister(index_qubits, "c_index") # classical register storing the measurement result of index register qc = QuantumCircuit(qr_index, qr_data, qr_f, cr_index) ### initialize the index register with uniform superposition state ### qc.h(qr_index) ### DO NOT CHANGE THE CODE BELOW p = 5 alpha = 1 for i in range(p): ### set fixed parameters for each round ### beta = 1 - (i + 1) / p gamma = (i + 1) / p ### return part ### qc.append(phase_return(index_qubits, gamma, L1, L2), qr_index) ### step 1: cost calculation ### qc.append(cost_calculation(index_qubits, data_qubits, C1, C2), qr_index[:] + qr_data[:]) ### step 2: Constraint testing ### qc.append(constraint_testing(data_qubits, C_max), qr_data[:] + qr_f[:]) ### step 3: penalty dephasing ### qc.append(penalty_dephasing(data_qubits, alpha, gamma), qr_data[:] + qr_f[:]) ### step 4: reinitialization ### qc.append(reinitialization(index_qubits, data_qubits, C1, C2, C_max), qr_index[:] + qr_data[:] + qr_f[:]) ### mixing operator ### qc.append(mixing_operator(index_qubits, beta), qr_index) ### measure the index ### ### since the default measurement outcome is shown in big endian, it is necessary to reverse the classical bits in order to unify the endian ### qc.measure(qr_index, cr_index[::-1]) return qc # Execute your circuit with following prepare_ex4c() function. # The prepare_ex4c() function works like the execute() function with only QuantumCircuit as an argument. from qc_grader import prepare_ex4c job = prepare_ex4c(solver_function) result = job.result() # Check your answer and submit using the following code from qc_grader import grade_ex4c grade_ex4c(job)
https://github.com/qiskit-community/qopt-best-practices
qiskit-community
# -*- coding: utf-8 -*- # (C) Copyright 2024 IBM. All Rights Reserved. # # 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 logging from typing import Dict, List, Union, Literal import numpy as np from qiskit import QuantumCircuit, QuantumRegister, qasm2, qasm3 from qiskit.circuit import QuantumCircuit, QuantumRegister, Qubit from qiskit.qasm2 import QASM2ExportError, QASM2ParseError from qiskit.transpiler import TranspileLayout from qiskit.transpiler.layout import Layout from qiskit_transpiler_service.wrappers import QiskitTranspilerService # setting backoff logger to error level to avoid too much logging logging.getLogger("backoff").setLevel(logging.ERROR) logger = logging.getLogger(__name__) class TranspileAPI(QiskitTranspilerService): """A helper class that covers some basic funcionality from the Qiskit Transpiler API""" def __init__(self): super().__init__() def transpile( self, circuits: Union[ Union[List[str], str], Union[List[QuantumCircuit], QuantumCircuit] ], optimization_level: int = 1, backend: Union[str, None] = None, coupling_map: Union[List[List[int]], None] = None, ai: Literal["true", "false", "auto"] = "true", qiskit_transpile_options: Dict = None, ai_layout_mode: str = None, ): circuits = circuits if isinstance(circuits, list) else [circuits] qasm_circuits = [_input_to_qasm(circ) for circ in circuits] json_args = { "qasm_circuits": qasm_circuits, } if qiskit_transpile_options is not None: json_args["qiskit_transpile_options"] = qiskit_transpile_options if coupling_map is not None: json_args["backend_coupling_map"] = coupling_map params = { "backend": backend, "optimization_level": optimization_level, "ai": ai, } if ai_layout_mode is not None: params["ai_layout_mode"] = ai_layout_mode transpile_resp = self.request_and_wait( endpoint="transpile", body=json_args, params=params ) logger.debug(f"transpile_resp={transpile_resp}") transpiled_circuits = [] for res, orig_circ in zip(transpile_resp, circuits): try: transpiled_circuits.append(_get_circuit_from_result(res, orig_circ)) except Exception as ex: logger.error("Error transforming the result to a QuantumCircuit object") raise return ( transpiled_circuits if len(transpiled_circuits) > 1 else transpiled_circuits[0] ) def benchmark( self, circuits: Union[ Union[List[str], str], Union[List[QuantumCircuit], QuantumCircuit] ], backend: str, optimization_level: int = 1, qiskit_transpile_options: Dict = None, ): raise Exception("Not implemented") def _input_to_qasm(input_circ: Union[QuantumCircuit, str]): if isinstance(input_circ, QuantumCircuit): try: qasm = qasm2.dumps(input_circ).replace("\n", " ") except QASM2ExportError: qasm = qasm3.dumps(input_circ).replace("\n", " ") elif isinstance(input_circ, str): qasm = input_circ.replace("\n", " ") else: raise TypeError("Input circuits must be QuantumCircuit or qasm string.") return qasm def _get_circuit_from_result(transpile_resp, orig_circuit): transpiled_circuit = _get_circuit_from_qasm(transpile_resp["qasm"]) init_layout = transpile_resp["layout"]["initial"] final_layout = transpile_resp["layout"]["final"] orig_circuit = ( _get_circuit_from_qasm(orig_circuit) if isinstance(orig_circuit, str) else orig_circuit ) transpiled_circuit = QuantumCircuit(len(init_layout)).compose(transpiled_circuit) transpiled_circuit._layout = _create_transpile_layout( init_layout, final_layout, transpiled_circuit, orig_circuit ) return transpiled_circuit def _create_initial_layout(initial, n_used_qubits): """Create initial layout using the initial index layout and the number of active qubits.""" total_qubits = len(initial) q_total = n_used_qubits a_total = total_qubits - q_total initial_layout = Layout() for q in range(q_total): initial_layout.add(initial[q], Qubit(QuantumRegister(q_total, "q"), q)) for a in range(q_total, total_qubits): initial_layout.add( initial[a], Qubit(QuantumRegister(a_total, "ancilla"), a - q_total) ) return initial_layout def _create_input_qubit_mapping(qubits_used, total_qubits): """Create input qubit mapping with the number of active qubits and the total number of qubits.""" input_qubit_mapping = { Qubit(QuantumRegister(qubits_used, "q"), q): q for q in range(qubits_used) } input_ancilla_mapping = { Qubit( QuantumRegister(total_qubits - qubits_used, "ancilla"), q - qubits_used ): q for q in range(qubits_used, total_qubits) } input_qubit_mapping.update(input_ancilla_mapping) return input_qubit_mapping def _create_final_layout(initial, final, circuit): """Create final layout with the initial and final index layout and the circuit.""" final_layout = Layout() q_total = len(initial) q_reg = QuantumRegister(q_total, "q") for i, j in zip(final, initial): q_index = circuit.find_bit(Qubit(q_reg, j)).index qubit = circuit.qubits[q_index] final_layout.add(i, qubit) return final_layout def _create_transpile_layout(initial, final, circuit, orig_circuit): """Build the full transpile layout.""" n_used_qubits = orig_circuit.num_qubits return TranspileLayout( initial_layout=_create_initial_layout( initial=initial, n_used_qubits=n_used_qubits ), # final=final), input_qubit_mapping=_create_input_qubit_mapping( qubits_used=n_used_qubits, total_qubits=len(initial) ), final_layout=_create_final_layout( initial=initial, final=final, circuit=circuit ), _input_qubit_count=n_used_qubits, _output_qubit_list=circuit.qubits, ) def _get_circuit_from_qasm(qasm_string): try: return qasm2.loads( qasm_string, custom_instructions=qasm2.LEGACY_CUSTOM_INSTRUCTIONS, ) except QASM2ParseError: return qasm3.loads(qasm_string)
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
import cirq from cirq import Simulator import numpy as np #instantiate simulator simulator = Simulator() #instantiate qubit qubits = cirq.LineQubit.range(3) #make circuit circuit = cirq.Circuit() circuit.append(cirq.H(qubits[0])) circuit.append(cirq.CNOT(qubits[0], qubits[1])) circuit.append(cirq.H(qubits[2])) circuit.append(cirq.Z(qubits[2])**0.5) #print circuit print(circuit) #space the outputs print("\n\n\n") #print the statevectors result = simulator.simulate(circuit) print(np.around(result.final_state_vector, 3))
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Stabilizer state class. """ from __future__ import annotations import numpy as np from qiskit.exceptions import QiskitError from qiskit.quantum_info.operators.op_shape import OpShape from qiskit.quantum_info.operators.operator import Operator from qiskit.quantum_info.operators.symplectic import Clifford, Pauli, PauliList from qiskit.quantum_info.operators.symplectic.clifford_circuits import _append_x from qiskit.quantum_info.states.quantum_state import QuantumState from qiskit.circuit import QuantumCircuit, Instruction class StabilizerState(QuantumState): """StabilizerState class. Stabilizer simulator using the convention from reference [1]. Based on the internal class :class:`~qiskit.quantum_info.Clifford`. .. code-block:: from qiskit import QuantumCircuit from qiskit.quantum_info import StabilizerState, Pauli # Bell state generation circuit qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) stab = StabilizerState(qc) # Print the StabilizerState print(stab) # Calculate the StabilizerState measurement probabilities dictionary print (stab.probabilities_dict()) # Calculate expectation value of the StabilizerState print (stab.expectation_value(Pauli('ZZ'))) .. parsed-literal:: StabilizerState(StabilizerTable: ['+XX', '+ZZ']) {'00': 0.5, '11': 0.5} 1 References: 1. S. Aaronson, D. Gottesman, *Improved Simulation of Stabilizer Circuits*, Phys. Rev. A 70, 052328 (2004). `arXiv:quant-ph/0406196 <https://arxiv.org/abs/quant-ph/0406196>`_ """ def __init__( self, data: StabilizerState | Clifford | Pauli | QuantumCircuit | Instruction, validate: bool = True, ): """Initialize a StabilizerState object. Args: data (StabilizerState or Clifford or Pauli or QuantumCircuit or qiskit.circuit.Instruction): Data from which the stabilizer state can be constructed. validate (boolean): validate that the stabilizer state data is a valid Clifford. """ # Initialize from another StabilizerState if isinstance(data, StabilizerState): self._data = data._data # Initialize from a Pauli elif isinstance(data, Pauli): self._data = Clifford(data.to_instruction()) # Initialize from a Clifford, QuantumCircuit or Instruction else: self._data = Clifford(data, validate) # Initialize super().__init__(op_shape=OpShape.auto(num_qubits_r=self._data.num_qubits, num_qubits_l=0)) def __eq__(self, other): return (self._data.stab == other._data.stab).all() def __repr__(self): return f"StabilizerState({self._data.stabilizer})" @property def clifford(self): """Return StabilizerState Clifford data""" return self._data def is_valid(self, atol=None, rtol=None): """Return True if a valid StabilizerState.""" return self._data.is_unitary() def _add(self, other): raise NotImplementedError(f"{type(self)} does not support addition") def _multiply(self, other): raise NotImplementedError(f"{type(self)} does not support scalar multiplication") def trace(self) -> float: """Return the trace of the stabilizer state as a density matrix, which equals to 1, since it is always a pure state. Returns: float: the trace (should equal 1). Raises: QiskitError: if input is not a StabilizerState. """ if not self.is_valid(): raise QiskitError("StabilizerState is not a valid quantum state.") return 1.0 def purity(self) -> float: """Return the purity of the quantum state, which equals to 1, since it is always a pure state. Returns: float: the purity (should equal 1). Raises: QiskitError: if input is not a StabilizerState. """ if not self.is_valid(): raise QiskitError("StabilizerState is not a valid quantum state.") return 1.0 def to_operator(self) -> Operator: """Convert state to matrix operator class""" return Clifford(self.clifford).to_operator() def conjugate(self): """Return the conjugate of the operator.""" ret = self.copy() ret._data = ret._data.conjugate() return ret def tensor(self, other: StabilizerState) -> StabilizerState: """Return the tensor product stabilizer state self ⊗ other. Args: other (StabilizerState): a stabilizer state object. Returns: StabilizerState: the tensor product operator self ⊗ other. Raises: QiskitError: if other is not a StabilizerState. """ if not isinstance(other, StabilizerState): other = StabilizerState(other) ret = self.copy() ret._data = self.clifford.tensor(other.clifford) return ret def expand(self, other: StabilizerState) -> StabilizerState: """Return the tensor product stabilizer state other ⊗ self. Args: other (StabilizerState): a stabilizer state object. Returns: StabilizerState: the tensor product operator other ⊗ self. Raises: QiskitError: if other is not a StabilizerState. """ if not isinstance(other, StabilizerState): other = StabilizerState(other) ret = self.copy() ret._data = self.clifford.expand(other.clifford) return ret def evolve( self, other: Clifford | QuantumCircuit | Instruction, qargs: list | None = None ) -> StabilizerState: """Evolve a stabilizer state by a Clifford operator. Args: other (Clifford or QuantumCircuit or qiskit.circuit.Instruction): The Clifford operator to evolve by. qargs (list): a list of stabilizer subsystem positions to apply the operator on. Returns: StabilizerState: the output stabilizer state. Raises: QiskitError: if other is not a StabilizerState. QiskitError: if the operator dimension does not match the specified StabilizerState subsystem dimensions. """ if not isinstance(other, StabilizerState): other = StabilizerState(other) ret = self.copy() ret._data = self.clifford.compose(other.clifford, qargs=qargs) return ret def expectation_value(self, oper: Pauli, qargs: None | list = None) -> complex: """Compute the expectation value of a Pauli operator. Args: oper (Pauli): a Pauli operator to evaluate expval. qargs (None or list): subsystems to apply the operator on. Returns: complex: the expectation value (only 0 or 1 or -1 or i or -i). Raises: QiskitError: if oper is not a Pauli operator. """ if not isinstance(oper, Pauli): raise QiskitError("Operator for expectation value is not a Pauli operator.") num_qubits = self.clifford.num_qubits if qargs is None: qubits = range(num_qubits) else: qubits = qargs # Construct Pauli on num_qubits pauli = Pauli(num_qubits * "I") phase = 0 pauli_phase = (-1j) ** oper.phase if oper.phase else 1 for pos, qubit in enumerate(qubits): pauli.x[qubit] = oper.x[pos] pauli.z[qubit] = oper.z[pos] phase += pauli.x[qubit] & pauli.z[qubit] # Check if there is a stabilizer that anti-commutes with an odd number of qubits # If so the expectation value is 0 for p in range(num_qubits): num_anti = 0 num_anti += np.count_nonzero(pauli.z & self.clifford.stab_x[p]) num_anti += np.count_nonzero(pauli.x & self.clifford.stab_z[p]) if num_anti % 2 == 1: return 0 # Otherwise pauli is (-1)^a prod_j S_j^b_j for Clifford stabilizers # If pauli anti-commutes with D_j then b_j = 1. # Multiply pauli by stabilizers with anti-commuting destabilizers pauli_z = (pauli.z).copy() # Make a copy of pauli.z for p in range(num_qubits): # Check if destabilizer anti-commutes num_anti = 0 num_anti += np.count_nonzero(pauli.z & self.clifford.destab_x[p]) num_anti += np.count_nonzero(pauli.x & self.clifford.destab_z[p]) if num_anti % 2 == 0: continue # If anti-commutes multiply Pauli by stabilizer phase += 2 * self.clifford.stab_phase[p] phase += np.count_nonzero(self.clifford.stab_z[p] & self.clifford.stab_x[p]) phase += 2 * np.count_nonzero(pauli_z & self.clifford.stab_x[p]) pauli_z = pauli_z ^ self.clifford.stab_z[p] # For valid stabilizers, `phase` can only be 0 (= 1) or 2 (= -1) at this point. if phase % 4 != 0: return -pauli_phase return pauli_phase def equiv(self, other: StabilizerState) -> bool: """Return True if the two generating sets generate the same stabilizer group. Args: other (StabilizerState): another StabilizerState. Returns: bool: True if other has a generating set that generates the same StabilizerState. """ if not isinstance(other, StabilizerState): try: other = StabilizerState(other) except QiskitError: return False num_qubits = self.num_qubits if other.num_qubits != num_qubits: return False pauli_orig = PauliList.from_symplectic( self._data.stab_z, self._data.stab_x, 2 * self._data.stab_phase ) pauli_other = PauliList.from_symplectic( other._data.stab_z, other._data.stab_x, 2 * other._data.stab_phase ) # Check that each stabilizer from the original set commutes with each stabilizer # from the other set if not np.all([pauli.commutes(pauli_other) for pauli in pauli_orig]): return False # Compute the expected value of each stabilizer from the original set on the stabilizer state # determined by the other set. The two stabilizer states coincide if and only if the # expected value is +1 for each stabilizer for i in range(num_qubits): exp_val = self.expectation_value(pauli_other[i]) if exp_val != 1: return False return True def probabilities(self, qargs: None | list = None, decimals: None | int = None) -> np.ndarray: """Return the subsystem measurement probability vector. Measurement probabilities are with respect to measurement in the computation (diagonal) basis. Args: qargs (None or list): subsystems to return probabilities for, if None return for all subsystems (Default: None). decimals (None or int): the number of decimal places to round values. If None no rounding is done (Default: None). Returns: np.array: The Numpy vector array of probabilities. """ probs_dict = self.probabilities_dict(qargs, decimals) if qargs is None: qargs = range(self.clifford.num_qubits) probs = np.zeros(2 ** len(qargs)) for key, value in probs_dict.items(): place = int(key, 2) probs[place] = value return probs def probabilities_dict(self, qargs: None | list = None, decimals: None | int = None) -> dict: """Return the subsystem measurement probability dictionary. Measurement probabilities are with respect to measurement in the computation (diagonal) basis. This dictionary representation uses a Ket-like notation where the dictionary keys are qudit strings for the subsystem basis vectors. If any subsystem has a dimension greater than 10 comma delimiters are inserted between integers so that subsystems can be distinguished. Args: qargs (None or list): subsystems to return probabilities for, if None return for all subsystems (Default: None). decimals (None or int): the number of decimal places to round values. If None no rounding is done (Default: None). Returns: dict: The measurement probabilities in dict (ket) form. """ if qargs is None: qubits = range(self.clifford.num_qubits) else: qubits = qargs outcome = ["X"] * len(qubits) outcome_prob = 1.0 probs = {} # probabilities dictionary self._get_probablities(qubits, outcome, outcome_prob, probs) if decimals is not None: for key, value in probs.items(): probs[key] = round(value, decimals) return probs def reset(self, qargs: list | None = None) -> StabilizerState: """Reset state or subsystems to the 0-state. Args: qargs (list or None): subsystems to reset, if None all subsystems will be reset to their 0-state (Default: None). Returns: StabilizerState: the reset state. Additional Information: If all subsystems are reset this will return the ground state on all subsystems. If only some subsystems are reset this function will perform a measurement on those subsystems and evolve the subsystems so that the collapsed post-measurement states are rotated to the 0-state. The RNG seed for this sampling can be set using the :meth:`seed` method. """ # Resetting all qubits does not require sampling or RNG if qargs is None: return StabilizerState(Clifford(np.eye(2 * self.clifford.num_qubits))) randbits = self._rng.integers(2, size=len(qargs)) ret = self.copy() for bit, qubit in enumerate(qargs): # Apply measurement and get classical outcome outcome = ret._measure_and_update(qubit, randbits[bit]) # Use the outcome to apply X gate to any qubits left in the # |1> state after measure, then discard outcome. if outcome == 1: _append_x(ret.clifford, qubit) return ret def measure(self, qargs: list | None = None) -> tuple: """Measure subsystems and return outcome and post-measure state. Note that this function uses the QuantumStates internal random number generator for sampling the measurement outcome. The RNG seed can be set using the :meth:`seed` method. Args: qargs (list or None): subsystems to sample measurements for, if None sample measurement of all subsystems (Default: None). Returns: tuple: the pair ``(outcome, state)`` where ``outcome`` is the measurement outcome string label, and ``state`` is the collapsed post-measurement stabilizer state for the corresponding outcome. """ if qargs is None: qargs = range(self.clifford.num_qubits) randbits = self._rng.integers(2, size=len(qargs)) ret = self.copy() outcome = "" for bit, qubit in enumerate(qargs): outcome = str(ret._measure_and_update(qubit, randbits[bit])) + outcome return outcome, ret def sample_memory(self, shots: int, qargs: None | list = None) -> np.ndarray: """Sample a list of qubit measurement outcomes in the computational basis. Args: shots (int): number of samples to generate. qargs (None or list): subsystems to sample measurements for, if None sample measurement of all subsystems (Default: None). Returns: np.array: list of sampled counts if the order sampled. Additional Information: This function implements the measurement :meth:`measure` method. The seed for random number generator used for sampling can be set to a fixed value by using the stats :meth:`seed` method. """ memory = [] for _ in range(shots): # copy the StabilizerState since measure updates it stab = self.copy() memory.append(stab.measure(qargs)[0]) return memory # ----------------------------------------------------------------------- # Helper functions for calculating the measurement # ----------------------------------------------------------------------- def _measure_and_update(self, qubit, randbit): """Measure a single qubit and return outcome and post-measure state. Note that this function uses the QuantumStates internal random number generator for sampling the measurement outcome. The RNG seed can be set using the :meth:`seed` method. Note that stabilizer state measurements only have three probabilities: (p0, p1) = (0.5, 0.5), (1, 0), or (0, 1) The random case happens if there is a row anti-commuting with Z[qubit] """ num_qubits = self.clifford.num_qubits clifford = self.clifford stab_x = self.clifford.stab_x # Check if there exists stabilizer anticommuting with Z[qubit] # in this case the measurement outcome is random z_anticommuting = np.any(stab_x[:, qubit]) if z_anticommuting == 0: # Deterministic outcome - measuring it will not change the StabilizerState aux_pauli = Pauli(num_qubits * "I") for i in range(num_qubits): if clifford.x[i][qubit]: aux_pauli = self._rowsum_deterministic(clifford, aux_pauli, i + num_qubits) outcome = aux_pauli.phase return outcome else: # Non-deterministic outcome outcome = randbit p_qubit = np.min(np.nonzero(stab_x[:, qubit])) p_qubit += num_qubits # Updating the StabilizerState for i in range(2 * num_qubits): # the last condition is not in the AG paper but we seem to need it if (clifford.x[i][qubit]) and (i != p_qubit) and (i != (p_qubit - num_qubits)): self._rowsum_nondeterministic(clifford, i, p_qubit) clifford.destab[p_qubit - num_qubits] = clifford.stab[p_qubit - num_qubits].copy() clifford.x[p_qubit] = np.zeros(num_qubits) clifford.z[p_qubit] = np.zeros(num_qubits) clifford.z[p_qubit][qubit] = True clifford.phase[p_qubit] = outcome return outcome @staticmethod def _phase_exponent(x1, z1, x2, z2): """Exponent g of i such that Pauli(x1,z1) * Pauli(x2,z2) = i^g Pauli(x1+x2,z1+z2)""" # pylint: disable=invalid-name phase = (x2 * z1 * (1 + 2 * z2 + 2 * x1) - x1 * z2 * (1 + 2 * z1 + 2 * x2)) % 4 if phase < 0: phase += 4 # now phase in {0, 1, 3} if phase == 2: raise QiskitError("Invalid rowsum phase exponent in measurement calculation.") return phase @staticmethod def _rowsum(accum_pauli, accum_phase, row_pauli, row_phase): """Aaronson-Gottesman rowsum helper function""" newr = 2 * row_phase + 2 * accum_phase for qubit in range(row_pauli.num_qubits): newr += StabilizerState._phase_exponent( row_pauli.x[qubit], row_pauli.z[qubit], accum_pauli.x[qubit], accum_pauli.z[qubit] ) newr %= 4 if (newr != 0) & (newr != 2): raise QiskitError("Invalid rowsum in measurement calculation.") accum_phase = int(newr == 2) accum_pauli.x ^= row_pauli.x accum_pauli.z ^= row_pauli.z return accum_pauli, accum_phase @staticmethod def _rowsum_nondeterministic(clifford, accum, row): """Updating StabilizerState Clifford in the non-deterministic rowsum calculation. row and accum are rows in the StabilizerState Clifford.""" row_phase = clifford.phase[row] accum_phase = clifford.phase[accum] z = clifford.z x = clifford.x row_pauli = Pauli((z[row], x[row])) accum_pauli = Pauli((z[accum], x[accum])) accum_pauli, accum_phase = StabilizerState._rowsum( accum_pauli, accum_phase, row_pauli, row_phase ) clifford.phase[accum] = accum_phase x[accum] = accum_pauli.x z[accum] = accum_pauli.z @staticmethod def _rowsum_deterministic(clifford, aux_pauli, row): """Updating an auxilary Pauli aux_pauli in the deterministic rowsum calculation. The StabilizerState itself is not updated.""" row_phase = clifford.phase[row] accum_phase = aux_pauli.phase accum_pauli = aux_pauli row_pauli = Pauli((clifford.z[row], clifford.x[row])) accum_pauli, accum_phase = StabilizerState._rowsum( accum_pauli, accum_phase, row_pauli, row_phase ) aux_pauli = accum_pauli aux_pauli.phase = accum_phase return aux_pauli # ----------------------------------------------------------------------- # Helper functions for calculating the probabilities # ----------------------------------------------------------------------- def _get_probablities(self, qubits, outcome, outcome_prob, probs): """Recursive helper function for calculating the probabilities""" qubit_for_branching = -1 ret = self.copy() for i in range(len(qubits)): qubit = qubits[len(qubits) - i - 1] if outcome[i] == "X": is_deterministic = not any(ret.clifford.stab_x[:, qubit]) if is_deterministic: single_qubit_outcome = ret._measure_and_update(qubit, 0) if single_qubit_outcome: outcome[i] = "1" else: outcome[i] = "0" else: qubit_for_branching = i if qubit_for_branching == -1: str_outcome = "".join(outcome) probs[str_outcome] = outcome_prob return for single_qubit_outcome in range(0, 2): new_outcome = outcome.copy() if single_qubit_outcome: new_outcome[qubit_for_branching] = "1" else: new_outcome[qubit_for_branching] = "0" stab_cpy = ret.copy() stab_cpy._measure_and_update( qubits[len(qubits) - qubit_for_branching - 1], single_qubit_outcome ) stab_cpy._get_probablities(qubits, new_outcome, 0.5 * outcome_prob, probs)
https://github.com/JohnBurke4/qaoa_testing_framework
JohnBurke4
from qiskit import QuantumCircuit from qiskit.circuit.library import QFT import numpy as np from CustomStatePrep import StatePreparation from qiskit.circuit.library import Isometry def QDCT(n, mctMode="v-chain"): if mctMode == "v-chain": ancillaQubits = list(range(n+1, 2*n-1)) qubits = 2*n-1 elif mctMode == "noancilla": ancillaQubits = [] qubits = n+2 elif mctMode == "recursion": ancillaQubits = [n+1] qubits = n+2 qc = QuantumCircuit(qubits) for i in range(n, 0, -1): qc.swap(i, i-1) qc.x(0) qc.h(n+1) for i in range(0, n): qc.cx(n+1, n-i) qft = QFT(n+2, inverse=False, do_swaps=True) # for i in range(0, int(n/2)+1): # qc.swap(i, n+1-i) qc.append(qft, range(0, n+2)) qc.barrier() qc.z(n+1) qc.h(n+1) for i in range(0, n): qc.cx(n, i) qc.barrier() for i in range(n-1, 0, -1): qc.mct(list(range(0, i)) + [n], i, ancilla_qubits=ancillaQubits, mode=mctMode) qc.cx(n, 0) qc.z(n) qc.h(n) for i in range(0, n): qc.x(i) qc.ry(np.pi/4, n) qc.mct(list(range(0, n)), n, ancilla_qubits=ancillaQubits, mode=mctMode) qc.ry(-np.pi/4, n) for i in range(0, n): qc.x(i) qc.name = "QDCT" return qc def permutationCircuit(mat, N, M, N_c, M_c): num_qubits = int(np.log2(N*M)) num_qubits_c = int(np.log2(N_c*M_c)) qc = QuantumCircuit(num_qubits) n = int(np.log2(N)) m = int(np.log2(M)) n_c = int(np.log2(N_c)) m_c = int(np.log2(M_c)) f = mat.flatten() f_c = f # qubit_list = list(range(0, m_c)) + list(range(m, m+n_c)) # qubit_list = list(range(0, m_c+n_c)) qc2 = QuantumCircuit(num_qubits_c) statePrep = Isometry(f_c, num_ancillas_zero=0, num_ancillas_dirty=0) qc.append(statePrep, range(0, num_qubits_c)) # qc.initialize(f_c, range(0, num_qubits_c)) # print(qc2.decompose(reps=2)) for i in range(n_c-1, -1, -1): if (m_c != m): qc.swap(m + i, m_c + i) qc.name = "PERM" return qc def buildCompressedState(comp, rC, cC): normalCompState = comp / np.linalg.norm(comp) r = int(comp.shape[0] / rC) c = int(comp.shape[1] / cC) state = normalCompState[:r, :c] qubits = int(np.log2(comp.size)) qc = QuantumCircuit(qubits) permCirc = permutationCircuit(state, comp.shape[0], comp.shape[1], r, c) qc.append(permCirc, range(0, qubits)) qc.name = "C_S_P" return qc
https://github.com/UST-QuAntiL/nisq-analyzer-content
UST-QuAntiL
from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit # https://quantum-circuit.com/app_details/about/bw5r9HTiTHvQHtCB5 qc = QuantumCircuit() q = QuantumRegister(5, 'q') c = ClassicalRegister(3, 'c') qc.add_register(q) qc.add_register(c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[1]) qc.cx(q[2], q[3]) qc.cu1(0, q[1], q[0]) qc.cx(q[2], q[4]) qc.h(q[0]) qc.cu1(0, q[1], q[2]) qc.cu1(0, q[0], q[2]) qc.h(q[2]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) def get_circuit(**kwargs): """Get circuit of Shor with input 15.""" return qc
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
#量子エラー研究.平均誤差率 from qiskit import IBMQ, transpile from qiskit import QuantumCircuit from qiskit_aer import AerSimulator from qiskit.tools.visualization import plot_histogram from qiskit.providers.fake_provider import FakeVigo device_backend =FakeVigo() circ = QuantumCircuit(3, 3) circ.h(0) circ.cx(0, 1) circ.cx(1, 2) circ.measure([0,1,2],[0,1,2]) sim_ideal = AerSimulator() result = sim_ideal.run(transpile(circ, sim_ideal)).result() counts =result.get_counts(0) plot_histogram(counts, title='Ideal counts for 3-qubit GHZ state') #ibmq-vigo のsimulator sim_vigo = AerSimulator.from_backend(device_backend) tcirc = transpile(circ,sim_vigo) result_noise =sim_vigo.run(tcirc).result() counts_noise = result_noise.get_counts(0) plot_histogram(counts_noise, title="Counts for 3-qubit GHZ device noise model") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/carstenblank/dc-qiskit-qml
carstenblank
# -*- coding: utf-8 -*- # Copyright 2018, Carsten Blank. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. import logging import unittest import numpy import qiskit from sklearn.model_selection import train_test_split from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler, Normalizer from dc_qiskit_qml.distance_based.compact_hadamard.compact_hadamard_classifier import CompactHadamardClassifier from dc_qiskit_qml.encoding_maps import NormedAmplitudeEncoding logging.basicConfig(format=logging.BASIC_FORMAT, level='INFO') log = logging.getLogger(__name__) class FullIris(unittest.TestCase): def test(self): from sklearn.datasets import load_iris X, y = load_iris(return_X_y=True) X = numpy.asarray([x for x, yy in zip(X, y) if yy != 2]) y = numpy.asarray([yy for x, yy in zip(X, y) if yy != 2]) preprocessing_pipeline = Pipeline([ ('scaler', StandardScaler()), ('l2norm', Normalizer(norm='l2', copy=True)) ]) X = preprocessing_pipeline.fit_transform(X, y) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.10, random_state=42) execution_backend = qiskit.Aer.get_backend('qasm_simulator') # type: BaseBackend qml = CompactHadamardClassifier(backend=execution_backend, shots=8192, encoding_map=NormedAmplitudeEncoding()) qml.fit(X_train, y_train) prediction = qml.predict(X_test)
https://github.com/acfilok96/Quantum-Computation
acfilok96
import qiskit from qiskit import * print(qiskit.__version__) %matplotlib inline from qiskit.tools.visualization import plot_histogram circuit = QuantumCircuit(3,3) circuit # qiskit.__dir__() circuit.draw(output='mpl') circuit.x(0) circuit.barrier() circuit.draw(output='mpl') circuit.h(1) circuit.cx(1,2) circuit.draw(output='mpl') circuit.barrier() circuit.cx(0,1) circuit.h(0) circuit.draw(output='mpl') circuit.barrier() circuit.measure([0,1],[0,1]) circuit.draw(output='mpl') circuit.barrier() circuit.cx(1,2) circuit.cx(0,2) circuit.draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, backend=simulator,shots=1024) result = job.result() counts=result.get_counts() print(counts) plot_histogram(counts)
https://github.com/hritiksauw199/Qiskit-textbook-solutions
hritiksauw199
#initialization import matplotlib.pyplot as plt import numpy as np # importing Qiskit from qiskit import IBMQ, Aer, assemble, transpile from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit.providers.ibmq import least_busy # import basic plot tools from qiskit.visualization import plot_histogram from qiskit_textbook.problems import grover_problem_oracle def initialize_s(qc, qubits): """Apply a H-gate to 'qubits' in qc""" for q in qubits: qc.h(q) return qc def diffuser(nqubits): qc = QuantumCircuit(nqubits) # Apply transformation |s> -> |00..0> (H-gates) for qubit in range(nqubits): qc.h(qubit) # Apply transformation |00..0> -> |11..1> (X-gates) for qubit in range(nqubits): qc.x(qubit) # Do multi-controlled-Z gate qc.h(nqubits-1) qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli qc.h(nqubits-1) # Apply transformation |11..1> -> |00..0> for qubit in range(nqubits): qc.x(qubit) # Apply transformation |00..0> -> |s> for qubit in range(nqubits): qc.h(qubit) # We will return the diffuser as a gate U_s = qc.to_gate() U_s.name = "U$_s$" return U_s n = 4 qc = QuantumCircuit(n) oracle1 = grover_problem_oracle(4, variant=2, print_solutions=True) qc = initialize_s(qc, [0,1,2,3]) # we run two iterations here qc.append(oracle1, [0,1,2,3]) qc.append(diffuser(n), [0,1,2,3]) qc.append(oracle1, [0,1,2,3]) qc.append(diffuser(n), [0,1,2,3]) qc.measure_all() qc.draw() aer_sim = Aer.get_backend('aer_simulator') transpiled_qc = transpile(qc, aer_sim) qobj = assemble(transpiled_qc) results = aer_sim.run(qobj).result() counts = results.get_counts() plot_histogram(counts) # Verification of Solution n = 4 oracle = grover_problem_oracle(n, variant=2, print_solutions = True) # 0th variant of oracle, with n qubits qc = QuantumCircuit(n) qc.append(oracle, [0,1,2,3]) n = 4 qc = QuantumCircuit(n) oracle = grover_problem_oracle(4, variant=1, print_solutions=True) qc = initialize_s(qc, [0,1,2,3]) # we run two iterations here qc.append(oracle, [0,1,2,3]) qc.append(diffuser(n), [0,1,2,3]) qc.measure_all() qc.draw() aer_sim = Aer.get_backend('aer_simulator') transpiled_qc = transpile(qc, aer_sim) qobj = assemble(transpiled_qc) results = aer_sim.run(qobj).result() counts = results.get_counts() plot_histogram(counts) n = 4 qc = QuantumCircuit(n) oracle = grover_problem_oracle(4, variant=1, print_solutions=True) qc = initialize_s(qc, [0,1,2,3]) # we run two iterations here qc.append(oracle, [0,1,2,3]) qc.append(diffuser(n), [0,1,2,3]) qc.append(oracle, [0,1,2,3]) qc.append(diffuser(n), [0,1,2,3]) qc.measure_all() qc.draw() aer_sim = Aer.get_backend('aer_simulator') transpiled_qc = transpile(qc, aer_sim) qobj = assemble(transpiled_qc) results = aer_sim.run(qobj).result() counts = results.get_counts() plot_histogram(counts) # define the number of qubits needed n # define your own oracle and the nummber of iterations you need # this code makes use of just the diffuser function def grover_oracle(oracle, iterations): # applying h gates for i in range(n): qc.h(i) #applying the oracle specified a = [] for i in range(n): a.append(i) for i in range(iterations): qc.append(oracle, a) qc.append(diffuser(n), a) qc.measure_all() return qc n = 4 iterations = 2 oracle = grover_problem_oracle(n, variant=1, print_solutions=True) qc = QuantumCircuit(n, n) qc = grover_oracle(oracle, iterations) qc.draw()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the quantum amplitude estimation algorithm.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np from ddt import ddt, idata, data, unpack from qiskit import QuantumRegister, QuantumCircuit, BasicAer from qiskit.circuit.library import QFT, GroverOperator from qiskit.utils import QuantumInstance from qiskit_algorithms import ( AmplitudeEstimation, MaximumLikelihoodAmplitudeEstimation, IterativeAmplitudeEstimation, FasterAmplitudeEstimation, EstimationProblem, ) from qiskit.quantum_info import Operator, Statevector from qiskit.primitives import Sampler class BernoulliStateIn(QuantumCircuit): """A circuit preparing sqrt(1 - p)|0> + sqrt(p)|1>.""" def __init__(self, probability): super().__init__(1) angle = 2 * np.arcsin(np.sqrt(probability)) self.ry(angle, 0) class BernoulliGrover(QuantumCircuit): """The Grover operator corresponding to the Bernoulli A operator.""" def __init__(self, probability): super().__init__(1, global_phase=np.pi) self.angle = 2 * np.arcsin(np.sqrt(probability)) self.ry(2 * self.angle, 0) def power(self, power, matrix_power=False): if matrix_power: return super().power(power, True) powered = QuantumCircuit(1) powered.ry(power * 2 * self.angle, 0) return powered class SineIntegral(QuantumCircuit): r"""Construct the A operator to approximate the integral \int_0^1 \sin^2(x) d x with a specified number of qubits. """ def __init__(self, num_qubits): qr_state = QuantumRegister(num_qubits, "state") qr_objective = QuantumRegister(1, "obj") super().__init__(qr_state, qr_objective) # prepare 1/sqrt{2^n} sum_x |x>_n self.h(qr_state) # apply the sine/cosine term self.ry(2 * 1 / 2 / 2**num_qubits, qr_objective[0]) for i, qubit in enumerate(qr_state): self.cry(2 * 2**i / 2**num_qubits, qubit, qr_objective[0]) @ddt class TestBernoulli(QiskitAlgorithmsTestCase): """Tests based on the Bernoulli A operator. This class tests * the estimation result * the constructed circuits """ def setUp(self): super().setUp() with self.assertWarns(DeprecationWarning): self._statevector = QuantumInstance( backend=BasicAer.get_backend("statevector_simulator"), seed_simulator=2, seed_transpiler=2, ) self._sampler = Sampler(options={"seed": 2}) def qasm(shots=100): with self.assertWarns(DeprecationWarning): qi = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=shots, seed_simulator=2, seed_transpiler=2, ) return qi self._qasm = qasm def sampler_shots(shots=100): return Sampler(options={"shots": shots, "seed": 2}) self._sampler_shots = sampler_shots @idata( [ [0.2, AmplitudeEstimation(2), {"estimation": 0.5, "mle": 0.2}], [0.49, AmplitudeEstimation(3), {"estimation": 0.5, "mle": 0.49}], [0.2, MaximumLikelihoodAmplitudeEstimation([0, 1, 2]), {"estimation": 0.2}], [0.49, MaximumLikelihoodAmplitudeEstimation(3), {"estimation": 0.49}], [0.2, IterativeAmplitudeEstimation(0.1, 0.1), {"estimation": 0.2}], [0.49, IterativeAmplitudeEstimation(0.001, 0.01), {"estimation": 0.49}], [0.2, FasterAmplitudeEstimation(0.1, 3, rescale=False), {"estimation": 0.2}], [0.12, FasterAmplitudeEstimation(0.1, 2, rescale=False), {"estimation": 0.12}], ] ) @unpack def test_statevector(self, prob, qae, expect): """statevector test""" problem = EstimationProblem(BernoulliStateIn(prob), 0, BernoulliGrover(prob)) with self.assertWarns(DeprecationWarning): qae.quantum_instance = self._statevector result = qae.estimate(problem) self._statevector.reset_execution_results() for key, value in expect.items(): self.assertAlmostEqual( value, getattr(result, key), places=3, msg=f"estimate `{key}` failed" ) @idata( [ [0.2, AmplitudeEstimation(2), {"estimation": 0.5, "mle": 0.2}], [0.49, AmplitudeEstimation(3), {"estimation": 0.5, "mle": 0.49}], [0.2, MaximumLikelihoodAmplitudeEstimation([0, 1, 2]), {"estimation": 0.2}], [0.49, MaximumLikelihoodAmplitudeEstimation(3), {"estimation": 0.49}], [0.2, IterativeAmplitudeEstimation(0.1, 0.1), {"estimation": 0.2}], [0.49, IterativeAmplitudeEstimation(0.001, 0.01), {"estimation": 0.49}], [0.2, FasterAmplitudeEstimation(0.1, 3, rescale=False), {"estimation": 0.199}], [0.12, FasterAmplitudeEstimation(0.1, 2, rescale=False), {"estimation": 0.12}], ] ) @unpack def test_sampler(self, prob, qae, expect): """sampler test""" qae.sampler = self._sampler problem = EstimationProblem(BernoulliStateIn(prob), 0, BernoulliGrover(prob)) result = qae.estimate(problem) for key, value in expect.items(): self.assertAlmostEqual( value, getattr(result, key), places=3, msg=f"estimate `{key}` failed" ) @idata( [ [0.2, 100, AmplitudeEstimation(4), {"estimation": 0.14644, "mle": 0.193888}], [0.0, 1000, AmplitudeEstimation(2), {"estimation": 0.0, "mle": 0.0}], [ 0.2, 100, MaximumLikelihoodAmplitudeEstimation([0, 1, 2, 4, 8]), {"estimation": 0.199606}, ], [0.8, 10, IterativeAmplitudeEstimation(0.1, 0.05), {"estimation": 0.811711}], [0.2, 1000, FasterAmplitudeEstimation(0.1, 3, rescale=False), {"estimation": 0.198640}], [ 0.12, 100, FasterAmplitudeEstimation(0.01, 3, rescale=False), {"estimation": 0.119037}, ], ] ) @unpack def test_qasm(self, prob, shots, qae, expect): """qasm test""" with self.assertWarns(DeprecationWarning): qae.quantum_instance = self._qasm(shots) problem = EstimationProblem(BernoulliStateIn(prob), [0], BernoulliGrover(prob)) result = qae.estimate(problem) for key, value in expect.items(): self.assertAlmostEqual( value, getattr(result, key), places=3, msg=f"estimate `{key}` failed" ) @idata( [ [0.2, 100, AmplitudeEstimation(4), {"estimation": 0.14644, "mle": 0.198783}], [0.0, 1000, AmplitudeEstimation(2), {"estimation": 0.0, "mle": 0.0}], [ 0.2, 100, MaximumLikelihoodAmplitudeEstimation([0, 1, 2, 4, 8]), {"estimation": 0.200308}, ], [0.8, 10, IterativeAmplitudeEstimation(0.1, 0.05), {"estimation": 0.811711}], [0.2, 1000, FasterAmplitudeEstimation(0.1, 3, rescale=False), {"estimation": 0.198640}], [ 0.12, 100, FasterAmplitudeEstimation(0.01, 3, rescale=False), {"estimation": 0.120017}, ], ] ) @unpack def test_sampler_with_shots(self, prob, shots, qae, expect): """sampler with shots test""" qae.sampler = self._sampler_shots(shots) problem = EstimationProblem(BernoulliStateIn(prob), [0], BernoulliGrover(prob)) result = qae.estimate(problem) for key, value in expect.items(): self.assertAlmostEqual( value, getattr(result, key), places=3, msg=f"estimate `{key}` failed" ) @data(True, False) def test_qae_circuit(self, efficient_circuit): """Test circuits resulting from canonical amplitude estimation. Build the circuit manually and from the algorithm and compare the resulting unitaries. """ prob = 0.5 problem = EstimationProblem(BernoulliStateIn(prob), objective_qubits=[0]) for m in [2, 5]: qae = AmplitudeEstimation(m) angle = 2 * np.arcsin(np.sqrt(prob)) # manually set up the inefficient AE circuit qr_eval = QuantumRegister(m, "a") qr_objective = QuantumRegister(1, "q") circuit = QuantumCircuit(qr_eval, qr_objective) # initial Hadamard gates for i in range(m): circuit.h(qr_eval[i]) # A operator circuit.ry(angle, qr_objective) if efficient_circuit: qae.grover_operator = BernoulliGrover(prob) for power in range(m): circuit.cry(2 * 2**power * angle, qr_eval[power], qr_objective[0]) else: oracle = QuantumCircuit(1) oracle.z(0) state_preparation = QuantumCircuit(1) state_preparation.ry(angle, 0) grover_op = GroverOperator(oracle, state_preparation) for power in range(m): circuit.compose( grover_op.power(2**power).control(), qubits=[qr_eval[power], qr_objective[0]], inplace=True, ) # fourier transform iqft = QFT(m, do_swaps=False).inverse().reverse_bits() circuit.append(iqft.to_instruction(), qr_eval) actual_circuit = qae.construct_circuit(problem, measurement=False) self.assertEqual(Operator(circuit), Operator(actual_circuit)) @data(True, False) def test_iqae_circuits(self, efficient_circuit): """Test circuits resulting from iterative amplitude estimation. Build the circuit manually and from the algorithm and compare the resulting unitaries. """ prob = 0.5 problem = EstimationProblem(BernoulliStateIn(prob), objective_qubits=[0]) for k in [2, 5]: qae = IterativeAmplitudeEstimation(0.01, 0.05) angle = 2 * np.arcsin(np.sqrt(prob)) # manually set up the inefficient AE circuit q_objective = QuantumRegister(1, "q") circuit = QuantumCircuit(q_objective) # A operator circuit.ry(angle, q_objective) if efficient_circuit: qae.grover_operator = BernoulliGrover(prob) circuit.ry(2 * k * angle, q_objective[0]) else: oracle = QuantumCircuit(1) oracle.z(0) state_preparation = QuantumCircuit(1) state_preparation.ry(angle, 0) grover_op = GroverOperator(oracle, state_preparation) for _ in range(k): circuit.compose(grover_op, inplace=True) actual_circuit = qae.construct_circuit(problem, k, measurement=False) self.assertEqual(Operator(circuit), Operator(actual_circuit)) @data(True, False) def test_mlae_circuits(self, efficient_circuit): """Test the circuits constructed for MLAE""" prob = 0.5 problem = EstimationProblem(BernoulliStateIn(prob), objective_qubits=[0]) for k in [2, 5]: qae = MaximumLikelihoodAmplitudeEstimation(k) angle = 2 * np.arcsin(np.sqrt(prob)) # compute all the circuits used for MLAE circuits = [] # 0th power q_objective = QuantumRegister(1, "q") circuit = QuantumCircuit(q_objective) circuit.ry(angle, q_objective) circuits += [circuit] # powers of 2 for power in range(k): q_objective = QuantumRegister(1, "q") circuit = QuantumCircuit(q_objective) # A operator circuit.ry(angle, q_objective) # Q^(2^j) operator if efficient_circuit: qae.grover_operator = BernoulliGrover(prob) circuit.ry(2 * 2**power * angle, q_objective[0]) else: oracle = QuantumCircuit(1) oracle.z(0) state_preparation = QuantumCircuit(1) state_preparation.ry(angle, 0) grover_op = GroverOperator(oracle, state_preparation) for _ in range(2**power): circuit.compose(grover_op, inplace=True) circuits += [circuit] actual_circuits = qae.construct_circuits(problem, measurement=False) for actual, expected in zip(actual_circuits, circuits): self.assertEqual(Operator(actual), Operator(expected)) @ddt class TestSineIntegral(QiskitAlgorithmsTestCase): """Tests based on the A operator to integrate sin^2(x). This class tests * the estimation result * the confidence intervals """ def setUp(self): super().setUp() with self.assertWarns(DeprecationWarning): self._statevector = QuantumInstance( backend=BasicAer.get_backend("statevector_simulator"), seed_simulator=123, seed_transpiler=41, ) self._sampler = Sampler(options={"seed": 123}) def qasm(shots=100): with self.assertWarns(DeprecationWarning): qi = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=shots, seed_simulator=7192, seed_transpiler=90000, ) return qi self._qasm = qasm def sampler_shots(shots=100): return Sampler(options={"shots": shots, "seed": 7192}) self._sampler_shots = sampler_shots @idata( [ [2, AmplitudeEstimation(2), {"estimation": 0.5, "mle": 0.270290}], [4, MaximumLikelihoodAmplitudeEstimation(4), {"estimation": 0.272675}], [3, IterativeAmplitudeEstimation(0.1, 0.1), {"estimation": 0.272082}], [3, FasterAmplitudeEstimation(0.01, 1), {"estimation": 0.272082}], ] ) @unpack def test_statevector(self, n, qae, expect): """Statevector end-to-end test""" # construct factories for A and Q # qae.state_preparation = SineIntegral(n) estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n]) with self.assertWarns(DeprecationWarning): qae.quantum_instance = self._statevector # result = qae.run(self._statevector) result = qae.estimate(estimation_problem) self._statevector.reset_execution_results() for key, value in expect.items(): self.assertAlmostEqual( value, getattr(result, key), places=3, msg=f"estimate `{key}` failed" ) @idata( [ [2, AmplitudeEstimation(2), {"estimation": 0.5, "mle": 0.2702}], [4, MaximumLikelihoodAmplitudeEstimation(4), {"estimation": 0.2725}], [3, IterativeAmplitudeEstimation(0.1, 0.1), {"estimation": 0.2721}], [3, FasterAmplitudeEstimation(0.01, 1), {"estimation": 0.2792}], ] ) @unpack def test_sampler(self, n, qae, expect): """sampler end-to-end test""" # construct factories for A and Q # qae.state_preparation = SineIntegral(n) qae.sampler = self._sampler estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n]) result = qae.estimate(estimation_problem) for key, value in expect.items(): self.assertAlmostEqual( value, getattr(result, key), places=3, msg=f"estimate `{key}` failed" ) @idata( [ [4, 100, AmplitudeEstimation(2), {"estimation": 0.5, "mle": 0.281196}], [3, 10, MaximumLikelihoodAmplitudeEstimation(2), {"estimation": 0.256878}], [3, 1000, IterativeAmplitudeEstimation(0.01, 0.01), {"estimation": 0.271790}], [3, 1000, FasterAmplitudeEstimation(0.1, 4), {"estimation": 0.274168}], ] ) @unpack def test_qasm(self, n, shots, qae, expect): """QASM simulator end-to-end test.""" estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n]) with self.assertWarns(DeprecationWarning): qae.quantum_instance = self._qasm(shots) result = qae.estimate(estimation_problem) for key, value in expect.items(): self.assertAlmostEqual( value, getattr(result, key), places=3, msg=f"estimate `{key}` failed" ) @idata( [ [4, 1000, AmplitudeEstimation(2), {"estimation": 0.5, "mle": 0.2636}], [3, 10, MaximumLikelihoodAmplitudeEstimation(2), {"estimation": 0.2904}], [3, 1000, IterativeAmplitudeEstimation(0.01, 0.01), {"estimation": 0.2706}], [3, 1000, FasterAmplitudeEstimation(0.1, 4), {"estimation": 0.2764}], ] ) @unpack def test_sampler_with_shots(self, n, shots, qae, expect): """Sampler with shots end-to-end test.""" # construct factories for A and Q qae.sampler = self._sampler_shots(shots) estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n]) result = qae.estimate(estimation_problem) for key, value in expect.items(): self.assertAlmostEqual( value, getattr(result, key), places=3, msg=f"estimate `{key}` failed" ) @idata( [ [ AmplitudeEstimation(3), "mle", { "likelihood_ratio": (0.2494734, 0.3003771), "fisher": (0.2486176, 0.2999286), "observed_fisher": (0.2484562, 0.3000900), }, ], [ MaximumLikelihoodAmplitudeEstimation(3), "estimation", { "likelihood_ratio": (0.2598794, 0.2798536), "fisher": (0.2584889, 0.2797018), "observed_fisher": (0.2659279, 0.2722627), }, ], ] ) @unpack def test_confidence_intervals(self, qae, key, expect): """End-to-end test for all confidence intervals.""" n = 3 estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n]) with self.assertWarns(DeprecationWarning): qae.quantum_instance = self._statevector # statevector simulator result = qae.estimate(estimation_problem) self._statevector.reset_execution_results() methods = ["lr", "fi", "oi"] # short for likelihood_ratio, fisher, observed_fisher alphas = [0.1, 0.00001, 0.9] # alpha shouldn't matter in statevector for alpha, method in zip(alphas, methods): confint = qae.compute_confidence_interval(result, alpha, method) # confidence interval based on statevector should be empty, as we are sure of the result self.assertAlmostEqual(confint[1] - confint[0], 0.0) self.assertAlmostEqual(confint[0], getattr(result, key)) # qasm simulator shots = 100 alpha = 0.01 with self.assertWarns(DeprecationWarning): qae.quantum_instance = self._qasm(shots) result = qae.estimate(estimation_problem) for method, expected_confint in expect.items(): confint = qae.compute_confidence_interval(result, alpha, method) np.testing.assert_array_almost_equal(confint, expected_confint) self.assertTrue(confint[0] <= getattr(result, key) <= confint[1]) def test_iqae_confidence_intervals(self): """End-to-end test for the IQAE confidence interval.""" n = 3 expected_confint = (0.1984050, 0.3511015) estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n]) with self.assertWarns(DeprecationWarning): qae = IterativeAmplitudeEstimation(0.1, 0.01, quantum_instance=self._statevector) # statevector simulator result = qae.estimate(estimation_problem) self._statevector.reset_execution_results() confint = result.confidence_interval # confidence interval based on statevector should be empty, as we are sure of the result self.assertAlmostEqual(confint[1] - confint[0], 0.0) self.assertAlmostEqual(confint[0], result.estimation) # qasm simulator shots = 100 with self.assertWarns(DeprecationWarning): qae.quantum_instance = self._qasm(shots) result = qae.estimate(estimation_problem) confint = result.confidence_interval np.testing.assert_array_almost_equal(confint, expected_confint) self.assertTrue(confint[0] <= result.estimation <= confint[1]) class TestAmplitudeEstimation(QiskitAlgorithmsTestCase): """Specific tests for canonical AE.""" def test_warns_if_good_state_set(self): """Check AE warns if is_good_state is set.""" circuit = QuantumCircuit(1) problem = EstimationProblem(circuit, objective_qubits=[0], is_good_state=lambda x: True) qae = AmplitudeEstimation(num_eval_qubits=1, sampler=Sampler()) with self.assertWarns(Warning): _ = qae.estimate(problem) @ddt class TestFasterAmplitudeEstimation(QiskitAlgorithmsTestCase): """Specific tests for Faster AE.""" def setUp(self): super().setUp() self._sampler = Sampler(options={"seed": 2}) def test_rescaling(self): """Test the rescaling.""" amplitude = 0.8 scaling = 0.25 circuit = QuantumCircuit(1) circuit.ry(2 * np.arcsin(amplitude), 0) problem = EstimationProblem(circuit, objective_qubits=[0]) rescaled = problem.rescale(scaling) rescaled_amplitude = Statevector.from_instruction(rescaled.state_preparation).data[3] self.assertAlmostEqual(scaling * amplitude, rescaled_amplitude) def test_run_without_rescaling(self): """Run Faster AE without rescaling if the amplitude is in [0, 1/4].""" # construct estimation problem prob = 0.11 a_op = QuantumCircuit(1) a_op.ry(2 * np.arcsin(np.sqrt(prob)), 0) problem = EstimationProblem(a_op, objective_qubits=[0]) # construct algo without rescaling backend = BasicAer.get_backend("statevector_simulator") with self.assertWarns(DeprecationWarning): fae = FasterAmplitudeEstimation(0.1, 1, rescale=False, quantum_instance=backend) # run the algo result = fae.estimate(problem) # assert the result is correct self.assertAlmostEqual(result.estimation, prob) # assert no rescaling was used theta = np.mean(result.theta_intervals[-1]) value_without_scaling = np.sin(theta) ** 2 self.assertAlmostEqual(result.estimation, value_without_scaling) def test_sampler_run_without_rescaling(self): """Run Faster AE without rescaling if the amplitude is in [0, 1/4].""" # construct estimation problem prob = 0.11 a_op = QuantumCircuit(1) a_op.ry(2 * np.arcsin(np.sqrt(prob)), 0) problem = EstimationProblem(a_op, objective_qubits=[0]) # construct algo without rescaling fae = FasterAmplitudeEstimation(0.1, 1, rescale=False, sampler=self._sampler) # run the algo result = fae.estimate(problem) # assert the result is correct self.assertAlmostEqual(result.estimation, prob, places=2) # assert no rescaling was used theta = np.mean(result.theta_intervals[-1]) value_without_scaling = np.sin(theta) ** 2 self.assertAlmostEqual(result.estimation, value_without_scaling) def test_rescaling_with_custom_grover_raises(self): """Test that the rescaling option fails if a custom Grover operator is used.""" prob = 0.8 a_op = BernoulliStateIn(prob) q_op = BernoulliGrover(prob) problem = EstimationProblem(a_op, objective_qubits=[0], grover_operator=q_op) # construct algo without rescaling backend = BasicAer.get_backend("statevector_simulator") with self.assertWarns(DeprecationWarning): fae = FasterAmplitudeEstimation(0.1, 1, quantum_instance=backend) # run the algo with self.assertWarns(Warning): _ = fae.estimate(problem) @data(("statevector_simulator", 0.2), ("qasm_simulator", 0.199440)) @unpack def test_good_state(self, backend_str, expect): """Test with a good state function.""" def is_good_state(bitstr): return bitstr[1] == "1" # construct the estimation problem where the second qubit is ignored a_op = QuantumCircuit(2) a_op.ry(2 * np.arcsin(np.sqrt(0.2)), 0) # oracle only affects first qubit oracle = QuantumCircuit(2) oracle.z(0) # reflect only on first qubit q_op = GroverOperator(oracle, a_op, reflection_qubits=[0]) # but we measure both qubits (hence both are objective qubits) problem = EstimationProblem( a_op, objective_qubits=[0, 1], grover_operator=q_op, is_good_state=is_good_state ) # construct algo with self.assertWarns(DeprecationWarning): backend = QuantumInstance( BasicAer.get_backend(backend_str), seed_simulator=2, seed_transpiler=2 ) # cannot use rescaling with a custom grover operator with self.assertWarns(DeprecationWarning): fae = FasterAmplitudeEstimation(0.01, 5, rescale=False, quantum_instance=backend) # run the algo result = fae.estimate(problem) # assert the result is correct self.assertAlmostEqual(result.estimation, expect, places=5) if __name__ == "__main__": unittest.main()
https://github.com/C2QA/bosonic-qiskit
C2QA
# To use the package locally, add the C2QA repository's root folder to the path prior to importing c2qa. import os import sys module_path = os.path.abspath(os.path.join("../..")) if module_path not in sys.path: sys.path.append(module_path) # Cheat to get MS Visual Studio Code Jupyter server to recognize Python venv module_path = os.path.abspath(os.path.join("../../venv/Lib/site-packages")) if module_path not in sys.path: sys.path.append(module_path) import c2qa import numpy as np import qiskit import qiskit.visualization qmr = c2qa.QumodeRegister(1, num_qubits_per_qumode=3) #create a qumoderegister with one qumode circuit = c2qa.CVCircuit(qmr) #create a CV circuit circuit.cv_initialize(4, qmr) #initialize the qumode in the state |4> #simulate and plot the wigner function (more about this in wigner_distribution.ipynb!) state,_,_ = c2qa.wigner.simulate(circuit) plot = c2qa.wigner.plot_wigner(circuit, state) #5 rings correspond to 4 quanta #try out different numbers and plot the wigner functions! #Intialize a qumode register. To map the number of quanta onto qubit states, the number of #classical bits needs to equal the number of qubits representing the qumode. num_qubits = 4 qureg = c2qa.QumodeRegister(1, num_qubits_per_qumode=num_qubits) creg = qiskit.ClassicalRegister(num_qubits) #Initialize circuit as a cuperposition of |0> and |2> circuit = c2qa.CVCircuit(qureg, creg, probe_measure=True) circuit.cv_initialize(1/np.sqrt(2)*np.array([1,0,1]), qureg[0]) #Use the cv_measure method to map the Fock number onto creg! circuit.cv_measure([qureg[0]], creg) #Simulation can use the Aer simulator or the build-in simulate method _, result, fock_counts = c2qa.util.simulate(circuit) #Convert the counts dictionary from binary to base-10 and plot histogram qiskit.visualization.plot_histogram(fock_counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np 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.draw(output='mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeAuckland backend = FakeAuckland() ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) depths = [] for _ in range(100): depths.append( transpile( ghz, backend, layout_method='trivial' # Fixed layout mapped in circuit order ).depth() ) plt.figure(figsize=(8, 6)) plt.hist(depths, align='left', color='#AC557C') plt.xlabel('Depth', fontsize=14) plt.ylabel('Counts', fontsize=14);
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, QuantumRegister from qiskit.circuit.library.standard_gates import HGate qc1 = QuantumCircuit(2) qc1.x(0) qc1.h(1) custom = qc1.to_gate().control(2) qc2 = QuantumCircuit(4) qc2.append(custom, [0, 3, 1, 2]) qc2.draw('mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import transpile, QuantumCircuit import qiskit.quantum_info as qi from qiskit_aer import AerSimulator from qiskit_aer.noise import NoiseModel, amplitude_damping_error from qiskit.tools.visualization import plot_histogram # CNOT matrix operator with qubit-0 as control and qubit-1 as target cx_op = qi.Operator([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]]) # iSWAP matrix operator iswap_op = qi.Operator([[1, 0, 0, 0], [0, 0, 1j, 0], [0, 1j, 0, 0], [0, 0, 0, 1]]) # CNOT in terms of iSWAP and single-qubit gates cx_circ = QuantumCircuit(2, name='cx<iSWAP>') # Add gates cx_circ.sdg(1) cx_circ.h(1) cx_circ.sdg(0) cx_circ.unitary(iswap_op, [0, 1], label='iswap') cx_circ.sdg(0) cx_circ.h(0) cx_circ.sdg(0) cx_circ.unitary(iswap_op, [0, 1], label='iswap') cx_circ.s(1) print(cx_circ) # Simulate the unitary for the circuit using Operator: unitary = qi.Operator(cx_circ) print(unitary) f_ave = qi.average_gate_fidelity(cx_op, unitary) print("Average Gate Fidelity: F = {:f}".format(f_ave)) 'unitary' in AerSimulator().configuration().basis_gates # Error parameters param_q0 = 0.05 # damping parameter for qubit-0 param_q1 = 0.1 # damping parameter for qubit-1 # Construct the error qerror_q0 = amplitude_damping_error(param_q0) qerror_q1 = amplitude_damping_error(param_q1) iswap_error = qerror_q1.tensor(qerror_q0) # Build the noise model by adding the error to the "iswap" gate noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(iswap_error, 'iswap') noise_model.add_basis_gates(['unitary']) print(noise_model.basis_gates) # Bell state circuit where iSWAPS should be inserted at barrier locations bell_circ = QuantumCircuit(2, 2, name='bell') bell_circ.h(0) bell_circ.append(cx_circ, [0, 1]) bell_circ.measure([0,1], [0,1]) print(bell_circ) # Create ideal simulator backend and transpile circuit sim_ideal = AerSimulator() tbell_circ = transpile(bell_circ, sim_ideal) ideal_result = sim_ideal.run(tbell_circ).result() ideal_counts = ideal_result.get_counts(0) plot_histogram(ideal_counts, title='Ideal output for iSWAP bell-state preparation') # Create noisy simulator and transpile circuit sim_noise = AerSimulator(noise_model=noise_model) tbell_circ_noise = transpile(bell_circ, sim_noise) # Run on the simulator without noise noise_result = sim_noise.run(tbell_circ_noise).result() noise_counts = noise_result.get_counts(bell_circ) plot_histogram(noise_counts, title='Noisy output for iSWAP bell-state preparation') import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/OJB-Quantum/Qiskit-Metal-to-Litho
OJB-Quantum
%load_ext autoreload %autoreload 2 import qiskit_metal as metal from qiskit_metal import designs, draw from qiskit_metal import MetalGUI, Dict, open_docs %metal_heading Welcome to Qiskit Metal! from qiskit_metal.qlibrary.qubits.transmon_pocket_6 import TransmonPocket6 from qiskit_metal.qlibrary.qubits.transmon_cross_fl import TransmonCrossFL from qiskit_metal.qlibrary.couplers.tunable_coupler_01 import TunableCoupler01 from qiskit_metal.qlibrary.tlines.meandered import RouteMeander from qiskit_metal.qlibrary.tlines.pathfinder import RoutePathfinder from qiskit_metal.qlibrary.tlines.anchored_path import RouteAnchors from qiskit_metal.qlibrary.lumped.cap_n_interdigital import CapNInterdigital from qiskit_metal.qlibrary.couplers.cap_n_interdigital_tee import CapNInterdigitalTee from qiskit_metal.qlibrary.couplers.coupled_line_tee import CoupledLineTee from qiskit_metal.qlibrary.terminations.launchpad_wb import LaunchpadWirebond from qiskit_metal.qlibrary.terminations.launchpad_wb_coupled import LaunchpadWirebondCoupled design = metal.designs.DesignPlanar() gui = metal.MetalGUI(design) design.overwrite_enabled = True design.chips.main design.chips.main.size.size_x = '11mm' design.chips.main.size.size_y = '9mm' TransmonPocket6.get_template_options(design) options = dict( pad_width = '425 um', pocket_height = '650um', connection_pads=dict( readout = dict(loc_W=0, loc_H=-1, pad_width = '80um', pad_gap = '50um'), bus_01 = dict(loc_W=-1, loc_H=-1, pad_width = '60um', pad_gap = '10um'), bus_02 = dict(loc_W=-1, loc_H=+1, pad_width = '60um', pad_gap = '10um'), bus_03 = dict(loc_W=0, loc_H=+1, pad_width = '90um', pad_gap = '30um'), bus_04 = dict(loc_W=+1, loc_H=+1, pad_width = '60um', pad_gap = '10um'), bus_05 = dict(loc_W=+1, loc_H=-1, pad_width = '60um', pad_gap = '10um') )) q_main = TransmonPocket6(design,'Q_Main', options = dict( pos_x='0mm', pos_y='-1mm', gds_cell_name ='FakeJunction_01', hfss_inductance ='14nH', **options)) gui.rebuild() gui.autoscale() TransmonCrossFL.get_template_options(design) Q1 = TransmonCrossFL(design, 'Q1', options = dict(pos_x = '-2.75mm', pos_y='-1.8mm', connection_pads = dict( bus_01 = dict(connector_location = '180',claw_length ='95um'), readout = dict(connector_location = '0')), fl_options = dict())) Q2 = TransmonCrossFL(design, 'Q2', options = dict(pos_x = '-2.75mm', pos_y='-1.2mm', orientation = '180', connection_pads = dict( bus_02 = dict(connector_location = '0',claw_length ='95um'), readout = dict(connector_location = '180')), fl_options = dict())) tune_c_Q12 = TunableCoupler01(design,'Tune_C_Q12', options = dict(pos_x = '-2.81mm', pos_y = '-1.5mm', orientation=90, c_width='500um')) gui.rebuild() gui.autoscale() Q3 = TransmonPocket6(design,'Q3', options = dict( pos_x='-3mm', pos_y='0.5mm', gds_cell_name ='FakeJunction_01', hfss_inductance ='14nH', connection_pads = dict( bus_03 = dict(loc_W=0, loc_H=-1, pad_width = '80um', pad_gap = '15um'), bus_q3_q4 = dict(loc_W=1, loc_H=-1, pad_width = '80um', pad_gap = '15um'), readout = dict(loc_W=0, loc_H=1, pad_width = '80um', pad_gap = '50um')))) Q4 = TransmonPocket6(design,'Q4', options = dict( pos_x='0mm', pos_y='1mm', gds_cell_name ='FakeJunction_01', hfss_inductance ='14nH', connection_pads = dict( bus_04 = dict(loc_W=0, loc_H=-1, pad_width = '80um', pad_gap = '15um'), bus_q3_q4 = dict(loc_W=-1, loc_H=-1, pad_width = '80um', pad_gap = '15um'), bus_q4_q5 = dict(loc_W=1, loc_H=-1, pad_width = '80um', pad_gap = '15um'), readout = dict(loc_W=0, loc_H=1, pad_width = '80um', pad_gap = '50um')))) Q5 = TransmonPocket6(design,'Q5', options = dict( pos_x='3mm', pos_y='0.5mm', gds_cell_name ='FakeJunction_01', hfss_inductance ='14nH', connection_pads = dict( bus_05 = dict(loc_W=0, loc_H=-1, pad_width = '80um', pad_gap = '15um'), bus_q4_q5 = dict(loc_W=-1, loc_H=-1, pad_width = '80um', pad_gap = '15um'), readout = dict(loc_W=0, loc_H=1, pad_width = '80um', pad_gap = '50um')))) from qiskit_metal.analyses.em.cpw_calculations import guided_wavelength 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" bus_01 = RouteMeander(design,'Bus_01', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Q_Main', pin='bus_01'), end_pin=Dict( component='Q1', pin='bus_01') ), lead=Dict( start_straight='125um', end_straight = '225um' ), meander=Dict( asymmetry = '1305um'), fillet = "99um", total_length = '6mm')) bus_02 = RouteMeander(design,'Bus_02', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Q_Main', pin='bus_02'), end_pin=Dict( component='Q2', pin='bus_02') ), lead=Dict( start_straight='325um', end_straight = '125um' ), meander=Dict( asymmetry = '450um'), fillet = "99um", total_length = '6.4mm')) gui.rebuild() bus_03 = RouteMeander(design,'Bus_03', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Q_Main', pin='bus_03'), end_pin=Dict( component='Q3', pin='bus_03') ), lead=Dict( start_straight='225um', end_straight = '25um' ), meander=Dict( asymmetry = '50um'), fillet = "99um", total_length = '6.8mm')) #To help set the right spacing, jogs can be used to set some initially controlled routing paths from collections import OrderedDict jogs_start = OrderedDict() jogs_start[0] = ["L", '250um'] jogs_start[1] = ["R", '200um'] jogs_end = OrderedDict() jogs_end[0] = ["L", '600um'] bus_04 = RouteMeander(design,'Bus_04', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Q_Main', pin='bus_04'), end_pin=Dict( component='Q4', pin='bus_04') ), lead=Dict( start_straight='225um', #end_straight = '25um', start_jogged_extension=jogs_start, #end_jogged_extension = jogs_end ), meander=Dict( asymmetry = '150um'), fillet = "99um", total_length = '7.2mm')) bus_05 = RouteMeander(design,'Bus_05', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Q_Main', pin='bus_05'), end_pin=Dict( component='Q5', pin='bus_05') ), lead=Dict( start_straight='225um', end_straight = '25um' ), meander=Dict( asymmetry = '50um'), fillet = "99um", total_length = '7.6mm')) gui.rebuild() bus_q3_q4 = RouteMeander(design,'Bus_Q3_Q4', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Q3', pin='bus_q3_q4'), end_pin=Dict( component='Q4', pin='bus_q3_q4') ), lead=Dict( start_straight='125um', end_straight = '125um' ), meander=Dict( asymmetry = '50um'), fillet = "99um", total_length = '6.4mm')) bus_q4_q5 = RouteMeander(design,'Bus_Q4_Q5', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Q4', pin='bus_q4_q5'), end_pin=Dict( component='Q5', pin='bus_q4_q5') ), lead=Dict( start_straight='125um', end_straight = '25um' ), meander=Dict( asymmetry = '50um'), fillet = "99um", total_length = '6.8mm')) gui.rebuild() launch_qmain_read = LaunchpadWirebond(design, 'Launch_QMain_Read', options = dict(pos_x = '2mm', pos_y ='-4mm', orientation = '90')) launch_q1_fl = LaunchpadWirebond(design, 'Launch_Q1_FL', options = dict(pos_x = '0mm', pos_y ='-4mm', orientation = '90', trace_width = '5um', trace_gap = '3um',)) launch_q1_read = LaunchpadWirebondCoupled(design, 'Launch_Q1_Read', options = dict(pos_x = '-2mm', pos_y ='-4mm', orientation = '90')) launch_tcoup_fl = LaunchpadWirebond(design, 'Launch_TuneC_FL', options = dict(pos_x = '-4mm', pos_y ='-4mm', orientation = '90', trace_width = '5um', trace_gap = '3um',)) launch_tcoup_read = LaunchpadWirebondCoupled(design, 'Launch_TuneC_Read', options = dict(pos_x = '-5mm', pos_y ='-3mm', orientation = '0')) launch_q2_read = LaunchpadWirebondCoupled(design, 'Launch_Q2_Read', options = dict(pos_x = '-5mm', pos_y ='-1mm', orientation = '0')) launch_q2_fl = LaunchpadWirebond(design, 'Launch_Q2_FL', options = dict(pos_x = '-5mm', pos_y ='1mm', orientation = '0', trace_width = '5um', trace_gap = '3um',)) launch_nw = LaunchpadWirebond(design, 'Launch_NW',options = dict(pos_x = '-5mm', pos_y='3mm', orientation=0)) launch_ne = LaunchpadWirebond(design, 'Launch_NE',options = dict(pos_x = '5mm', pos_y='3mm', orientation=180)) gui.rebuild() #Main Readout read_q_main_cap = CapNInterdigital(design,'Read_Q_Main_Cap', options = dict(pos_x = '2mm', pos_y ='-3.5mm', orientation = '0')) jogs_end = OrderedDict() jogs_end[0] = ["L", '600um'] jogs_start = OrderedDict() jogs_start[0] = ["L", '250um'] read_q_main = RouteMeander(design,'Read_Q_Main', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Q_Main', pin='readout'), end_pin=Dict( component='Read_Q_Main_Cap', pin='north_end') ), lead=Dict( start_straight='725um', end_straight = '625um', start_jogged_extension = jogs_start, end_jogged_extension = jogs_end ), meander=Dict( asymmetry = '50um'), fillet = "99um", total_length = '5.6mm')) read_q_main_cap_launch = RoutePathfinder(design, 'Read_Q_Main_Cap_Launch', options = dict(hfss_wire_bonds = True, pin_inputs = dict( start_pin=Dict( component='Read_Q_Main_Cap', pin='south_end'), end_pin=Dict( component='Launch_QMain_Read', pin='tie')), lead=Dict( start_straight='0um', end_straight = '0um', #start_jogged_extension = jogs_start, #end_jogged_extension = jogs_end ))) gui.rebuild() #Crossmon's Readouts jogs_end = OrderedDict() jogs_end[0] = ["L", '600um'] jogs_start = OrderedDict() jogs_start[0] = ["L", '250um'] read_q1 = RouteMeander(design,'Read_Q1', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Q1', pin='readout'), end_pin=Dict( component='Launch_Q1_Read', pin='tie') ), lead=Dict( start_straight='250um', end_straight = '25um', #start_jogged_extension = jogs_start, #end_jogged_extension = jogs_end ), meander=Dict( asymmetry = '50um'), fillet = "99um", total_length = '6.8mm')) jogs_end = OrderedDict() jogs_end[0] = ["L", '600um'] jogs_start = OrderedDict() jogs_start[0] = ["L", '250um'] read_tunec = RouteMeander(design,'Read_TuneC', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Tune_C_Q12', pin='Control'), end_pin=Dict( component='Launch_TuneC_Read', pin='tie') ), lead=Dict( start_straight='1525um', end_straight = '125um', #start_jogged_extension = jogs_start, #end_jogged_extension = jogs_end ), meander=Dict( asymmetry = '50um'), fillet = "99um", total_length = '5.8mm')) jogs_end = OrderedDict() jogs_end[0] = ["L", '600um'] jogs_start = OrderedDict() jogs_start[0] = ["L", '250um'] read_q2 = RouteMeander(design,'Read_Q2', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Q2', pin='readout'), end_pin=Dict( component='Launch_Q2_Read', pin='tie') ), lead=Dict( start_straight='350um', end_straight = '0um', #start_jogged_extension = jogs_start, #end_jogged_extension = jogs_end ), meander=Dict( asymmetry = '-450um'), fillet = "99um", total_length = '5.4mm')) gui.rebuild() #Crossmon flux lines flux_line_Q1 = RoutePathfinder(design,'Flux_Line_Q1', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Q1', pin='flux_line'), end_pin=Dict( component='Launch_Q1_FL', pin='tie')), fillet = '99um', trace_width = '5um', trace_gap = '3um', #anchors = anchors )) jogs_start = OrderedDict() jogs_start[0] = ["L", '750um'] flux_line_tunec = RoutePathfinder(design,'Flux_Line_TuneC', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Tune_C_Q12', pin='Flux'), end_pin=Dict( component='Launch_TuneC_FL', pin='tie')), lead=Dict( start_straight='875um', end_straight = '350um', start_jogged_extension = jogs_start, #end_jogged_extension = jogs_end ), fillet = '99um', trace_width = '5um', trace_gap = '3um', #anchors = anchors )) jogs_start = OrderedDict() jogs_start[0] = ["L", '525um'] jogs_start[1] = ["R", '625um'] flux_line_Q2 = RoutePathfinder(design,'Flux_Line_Q2', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Q2', pin='flux_line'), end_pin=Dict( component='Launch_Q2_FL', pin='tie')), lead=Dict( start_straight='175um', end_straight = '150um', start_jogged_extension = jogs_start, #end_jogged_extension = jogs_end ), fillet = '99um', trace_width = '5um', trace_gap = '3um', #anchors = anchors )) gui.rebuild() q3_read_T = CoupledLineTee(design,'Q3_Read_T', options=dict(pos_x = '-3mm', pos_y = '3mm', orientation = '0', coupling_length = '200um', open_termination = False)) #We use finger count to set the width of the gap capacitance, -> N*cap_width + (N-1)*cap_gap q4_read_T = CapNInterdigitalTee(design,'Q4_Read_T', options=dict(pos_x = '0mm', pos_y = '3mm', orientation = '0', finger_length = '0um', finger_count = '8')) q5_read_T = CapNInterdigitalTee(design,'Q5_Read_T', options=dict(pos_x = '3mm', pos_y = '3mm', orientation = '0', finger_length = '50um', finger_count = '11')) gui.rebuild() read_q3 = RouteMeander(design,'Read_Q3', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Q3', pin='readout'), end_pin=Dict( component='Q3_Read_T', pin='second_end') ), lead=Dict( start_straight='150um', end_straight = '150um', #start_jogged_extension = jogs_start, #end_jogged_extension = jogs_end ), meander=Dict( asymmetry = '0um'), fillet = "99um", total_length = '5mm')) read_q4 = RouteMeander(design,'Read_Q4', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Q4', pin='readout'), end_pin=Dict( component='Q4_Read_T', pin='second_end') ), lead=Dict( start_straight='125um', end_straight = '125um', #start_jogged_extension = jogs_start, #end_jogged_extension = jogs_end ), meander=Dict( asymmetry = '0um'), fillet = "99um", total_length = '5.8mm')) read_q5 = RouteMeander(design,'Read_Q5', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Q5', pin='readout'), end_pin=Dict( component='Q5_Read_T', pin='second_end') ), lead=Dict( start_straight='125um', end_straight = '125um', #start_jogged_extension = jogs_start, #end_jogged_extension = jogs_end ), meander=Dict( asymmetry = '0um'), fillet = "99um", total_length = '5.4mm')) gui.rebuild() mp_tl_01 = RoutePathfinder(design, 'ML_TL_01', options = dict(hfss_wire_bonds = True, pin_inputs = dict( start_pin=Dict( component='Launch_NW', pin='tie'), end_pin=Dict( component='Q3_Read_T', pin='prime_start')) )) mp_tl_02 = RoutePathfinder(design, 'ML_TL_02', options = dict(hfss_wire_bonds = True, pin_inputs = dict( start_pin=Dict( component='Q3_Read_T', pin='prime_end'), end_pin=Dict( component='Q4_Read_T', pin='prime_start')) )) mp_tl_03 = RoutePathfinder(design, 'ML_TL_03', options = dict(hfss_wire_bonds = True, pin_inputs = dict( start_pin=Dict( component='Q4_Read_T', pin='prime_end'), end_pin=Dict( component='Q5_Read_T', pin='prime_start')) )) mp_tl_04 = RoutePathfinder(design, 'ML_TL_04', options = dict(hfss_wire_bonds = True, pin_inputs = dict( start_pin=Dict( component='Q5_Read_T', pin='prime_end'), end_pin=Dict( component='Launch_NE', pin='tie')) )) gui.rebuild() from qiskit_metal.analyses.quantization import LOManalysis c1 = LOManalysis(design, "q3d") c1.sim.setup c1.sim.setup.name = 'Tune_Q_Main' c1.sim.setup.max_passes = 16 c1.sim.setup.min_converged_passes = 2 c1.sim.setup.percent_error = 0.05 c1.sim.setup c1.sim.run(name="Q_Main", components=['Q_Main'], open_terminations=[('Q_Main', 'readout'), ('Q_Main', 'bus_01'),('Q_Main', 'bus_02'),('Q_Main', 'bus_03'), ('Q_Main', 'bus_04'), ('Q_Main', 'bus_05')]) c1.sim.capacitance_matrix c1.setup.junctions = Dict({'Lj': 14, 'Cj': 2}) c1.setup.freq_readout = 7.0 c1.setup.freq_bus = [5.6, 5.7, 5.8, 5.9, 6.0] # list of the bus frequencies c1.run_lom() c1.lumped_oscillator_all c1.plot_convergence(); c1.plot_convergence_chi() c1.sim.close() from qiskit_metal.analyses.quantization import EPRanalysis eig_qb = EPRanalysis(design, "hfss") eig_qb.sim.renderer.options['wb_size'] = 5 em_p = eig_qb.sim.setup em_p.name = '3Modes' em_p.min_freq_ghz = 4 em_p.n_modes = 3 em_p.max_passes = 10 em_p.max_delta_f = 0.1 em_p.min_converged = 2 # Design variables can also be added in for direct simulation sweeps. em_p.vars = Dict({'Lj1': '13 nH', 'Cj1': '0 fF', 'Lj2': '15 nH', 'Cj2': '0 fF'}) eig_qb.sim.setup q_main.options.hfss_inductance Q5.options.hfss_inductance q_main.options.hfss_inductance = '13nH' Q5.options.hfss_inductance = '15nH' bus_05.options.total_length = '7.5mm' gui.rebuild() eig_qb.sim.run(name="QMain_Q5_Bus05", components=['Q_Main', 'Q5','Bus_05'], open_terminations=[]) eig_qb.sim.plot_convergences() eig_qb.del_junction() eig_qb.add_junction('jj1', 'Lj1', 'Cj1', rect='JJ_rect_Lj_Q_Main_rect_jj', line='JJ_Lj_Q_Main_rect_jj_') eig_qb.add_junction('jj2', 'Lj2', 'Cj2', rect='JJ_rect_Lj_Q5_rect_jj', line='JJ_Lj_Q5_rect_jj_') eig_qb.setup.sweep_variable = 'Lj1' eig_qb.setup eig_qb.run_epr() # (pyEPR allows to switch modes: eprd.set_mode(1)) eig_qb.sim.close() full_chip_gds = design.renderers.gds full_chip_gds.options full_chip_gds.options['path_filename'] ='../resources/Fake_Junctions.GDS' full_chip_gds.options['no_cheese']['buffer']='50um' full_chip_gds.export_to_gds('Full_Chip_01.gds') # gui.main_window.close()
https://github.com/ukzncqt/QC_Tuts
ukzncqt
!pip install qiskit from qiskit import IBMQ IBMQ.backends() IBMQ.stored_accounts() IBMQ.enable_account("7099aa657902a0c2289d1f31dfcd2166e8491773275a1c891362c73facd343a1aa9d4c77c27328bfca8de4ec42047f50c90ff7df5af406807251b7c7cab96223") IBMQ.backends() IBMQ.load_accounts() IBMQ.backends(operational=True, simulator=False) backend=IBMQ.get_backend('ibmqx4') backend.name() backend.status() from qiskit import execute, QuantumRegister, ClassicalRegister, QuantumCircuit q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q,c) qc.h(q[0]) qc.cx(q[0],q[1]) qc.barrier(q) qc.measure(q,c) qc.draw() job=execute(qc,backend=backend,shots=1024) job.status() res=job.result() res.get_counts() from qiskit.tools.visualization import plot_histogram plot_histogram(res.get_counts())
https://github.com/1chooo/Quantum-Oracle
1chooo
from qiskit import QuantumCircuit,execute from qiskit.providers.aer import AerSimulator from qiskit.visualization import plot_histogram import math qc = QuantumCircuit(1,1) qc.initialize([math.sqrt(1/3), math.sqrt(2/3)],0) qc.measure([0],[0]) print(qc) simulator=AerSimulator() job=execute(qc, backend=simulator, shots=1000) result=job.result() counts=result.get_counts(qc) print("Counts:",counts) plot_histogram(counts)
https://github.com/urwin419/QiskitChecker
urwin419
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) ### removed cx gate ### return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) qc.h(1) return qc
https://github.com/Qiskit/feedback
Qiskit
from qiskit import QuantumCircuit from qiskit.quantum_info import Clifford, random_clifford from qiskit.synthesis.clifford import synth_clifford_greedy, synth_clifford_layers clifford = random_clifford(5, seed=0) print(clifford) qc = synth_clifford_greedy(clifford) qc.draw(output='mpl') qc = synth_clifford_layers(clifford) qc.draw(output='mpl') qc.decompose().draw(output='mpl') import numpy as np from qiskit.synthesis.linear import synth_cnot_count_full_pmh, synth_cnot_depth_line_kms mat = np.array([ [1, 1, 0, 0, 0, 0], [1, 0, 0, 1, 1, 0], [0, 1, 0, 0, 1, 0], [1, 1, 1, 1, 1, 1], [1, 1, 0, 1, 1, 1], [0, 0, 1, 1, 1, 0], ]) qc = synth_cnot_count_full_pmh(mat) qc.draw(output='mpl') qc = synth_cnot_depth_line_kms(mat) qc.draw(output='mpl') from qiskit.synthesis.permutation import synth_permutation_depth_lnn_kms, synth_permutation_acg pattern = [1, 2, 3, 4, 5, 6, 7, 0] qc = synth_permutation_depth_lnn_kms(pattern) qc.draw(output='mpl') qc = synth_permutation_acg(pattern) qc.draw(output='mpl') from qiskit.circuit.library.generalized_gates import LinearFunction from qiskit.transpiler.passes.optimization import CollectLinearFunctions from qiskit.circuit.library import RealAmplitudes ansatz = RealAmplitudes(4, reps=2, entanglement='full') qc = ansatz.decompose() qc.draw(output='mpl') qc_extracted = CollectLinearFunctions()(qc) qc_extracted.draw(output='mpl') from qiskit.compiler import transpile qc_transpiled = transpile(qc_extracted, optimization_level=1) qc_transpiled.draw(output='mpl') qc = QuantumCircuit(2) qc.z(0) qc.cx(0, 1) qc.z(0) qc.cx(0, 1) qc.z(0) qc.cx(0, 1) qc.draw(output='mpl') qc_extracted = CollectLinearFunctions(do_commutative_analysis=True)(qc) qc_extracted.draw(output='mpl') from functools import partial from qiskit.transpiler.passes.optimization.collect_and_collapse import CollectAndCollapse, collect_using_filter_function, collapse_to_operation from qiskit.circuit.library.generalized_gates import PermutationGate # make use of "collect_using_filter_function", where filter_function collects SWAP gates. my_collect_function = partial( collect_using_filter_function, filter_function=lambda node: node.op.name=="swap" and getattr(node.op, "condition", None) is None, split_blocks=False, min_block_size=2, ) # Given a quantum circuit with SWAP gates, create a PermutationGate out of it. def _swap_block_to_permutation_gate(qc: QuantumCircuit): nq = qc.num_qubits pattern = list(range(nq)) for instruction in qc.data: q0 = qc.find_bit(instruction.qubits[0]).index q1 = qc.find_bit(instruction.qubits[1]).index pattern[q0], pattern[q1] = pattern[q1], pattern[q0] return PermutationGate(pattern) # make use of "collapse_to_operation" my_collapse_function = partial(collapse_to_operation, collapse_function=_swap_block_to_permutation_gate) # And that's our pass SwapCollector = CollectAndCollapse(collect_function=my_collect_function, collapse_function=my_collapse_function) qc = QuantumCircuit(4) qc.swap(0, 1) qc.swap(1, 2) qc.swap(2, 3) qc.h(0) qc.swap(0, 1) qc.swap(1, 2) qc.swap(2, 0) qc.draw(output='mpl') qc_extracted = SwapCollector(qc) qc_extracted.draw(output='mpl') qc = QuantumCircuit(6) # Let's append a permutation gate and a linear function qc.append(PermutationGate([1, 2, 3, 4, 0]), [1, 2, 3, 4, 5]) qc.h(range(6)) mat = np.array([ [1, 1, 0, 0, 0, 0], [1, 0, 0, 1, 1, 0], [0, 1, 0, 0, 1, 0], [1, 1, 1, 1, 1, 1], [1, 1, 0, 1, 1, 1], [0, 0, 1, 1, 1, 0], ]) qc.append(LinearFunction(mat), [5, 4, 3, 2, 1, 0]) qc.draw(output='mpl') from qiskit.compiler import transpile qc_transpiled = transpile(qc, optimization_level=1) qc_transpiled.draw(output='mpl') from qiskit.transpiler.passes.synthesis.high_level_synthesis import HLSConfig, HighLevelSynthesis hls_config=HLSConfig( permutation=[("acg", {})], ) qc_transpiled = transpile(qc, optimization_level=1, hls_config=hls_config) qc_transpiled.draw(output='mpl') from qiskit.transpiler.passes.synthesis.high_level_synthesis import HLSConfig, HighLevelSynthesis hls_config=HLSConfig( permutation=[("kms", {})], ) qc_transpiled = transpile(qc, optimization_level=1, hls_config=hls_config) qc_transpiled.draw(output='mpl') from qiskit.transpiler.passes.synthesis.high_level_synthesis import HLSConfig, HighLevelSynthesis hls_config=HLSConfig( use_default_on_unspecified=False, permutation=[("kms", {})], ) qc_transpiled = transpile(qc, optimization_level=1, hls_config=hls_config) qc_transpiled.draw(output='mpl') qc = QuantumCircuit(4) qc.swap(0, 1) qc.swap(1, 2) qc.swap(2, 3) qc.swap(1, 0) qc.swap(2, 3) qc.swap(3, 1) qc.h(0) qc.swap(0, 2) qc.draw(output='mpl') # Use our SwapCollector to extract SWAP blocks and to replace them by PermutationGates qc_extracted = SwapCollector(qc) qc_extracted.draw(output='mpl') # Resynthesize using 'acg' method hls_config = hls_config=HLSConfig( permutation=[("acg", {})], ) qc_resynthesized = HighLevelSynthesis(hls_config=hls_config)(qc_extracted) qc_resynthesized.draw(output='mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import BasicAer from qiskit.compiler import transpile from qiskit.quantum_info.operators import Operator, Pauli from qiskit.quantum_info import process_fidelity from qiskit.extensions import RXGate, XGate, CXGate XX = Operator([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]]) XX XX.data input_dim, output_dim = XX.dim input_dim, output_dim op = Operator(np.random.rand(2 ** 1, 2 ** 2)) print('Input dimensions:', op.input_dims()) print('Output dimensions:', op.output_dims()) op = Operator(np.random.rand(6, 6)) print('Input dimensions:', op.input_dims()) print('Output dimensions:', op.output_dims()) # Force input dimension to be (4,) rather than (2, 2) op = Operator(np.random.rand(2 ** 1, 2 ** 2), input_dims=[4]) print('Input dimensions:', op.input_dims()) print('Output dimensions:', op.output_dims()) # Specify system is a qubit and qutrit op = Operator(np.random.rand(6, 6), input_dims=[2, 3], output_dims=[2, 3]) print('Input dimensions:', op.input_dims()) print('Output dimensions:', op.output_dims()) print('Dimension of input system 0:', op.input_dims([0])) print('Dimension of input system 1:', op.input_dims([1])) # Create an Operator from a Pauli object pauliXX = Pauli('XX') Operator(pauliXX) # Create an Operator for a Gate object Operator(CXGate()) # Create an operator from a parameterized Gate object Operator(RXGate(np.pi / 2)) # Create an operator from a QuantumCircuit object circ = QuantumCircuit(10) circ.h(0) for j in range(1, 10): circ.cx(j-1, j) # Convert circuit to an operator by implicit unitary simulation Operator(circ) # Create an operator XX = Operator(Pauli('XX')) # Add to a circuit circ = QuantumCircuit(2, 2) circ.append(XX, [0, 1]) circ.measure([0,1], [0,1]) circ.draw('mpl') backend = BasicAer.get_backend('qasm_simulator') circ = transpile(circ, backend, basis_gates=['u1','u2','u3','cx']) job = backend.run(circ) job.result().get_counts(0) # Add to a circuit circ2 = QuantumCircuit(2, 2) circ2.append(Pauli('XX'), [0, 1]) circ2.measure([0,1], [0,1]) circ2.draw() A = Operator(Pauli('X')) B = Operator(Pauli('Z')) A.tensor(B) A = Operator(Pauli('X')) B = Operator(Pauli('Z')) A.expand(B) A = Operator(Pauli('X')) B = Operator(Pauli('Z')) A.compose(B) A = Operator(Pauli('X')) B = Operator(Pauli('Z')) A.compose(B, front=True) # Compose XZ with an 3-qubit identity operator op = Operator(np.eye(2 ** 3)) XZ = Operator(Pauli('XZ')) op.compose(XZ, qargs=[0, 2]) # Compose YX in front of the previous operator op = Operator(np.eye(2 ** 3)) YX = Operator(Pauli('YX')) op.compose(XZ, qargs=[0, 2], front=True) XX = Operator(Pauli('XX')) YY = Operator(Pauli('YY')) ZZ = Operator(Pauli('ZZ')) op = 0.5 * (XX + YY - 3 * ZZ) op op.is_unitary() # Compose with a matrix passed as a list Operator(np.eye(2)).compose([[0, 1], [1, 0]]) Operator(Pauli('X')) == Operator(XGate()) Operator(XGate()) == np.exp(1j * 0.5) * Operator(XGate()) # Two operators which differ only by phase op_a = Operator(XGate()) op_b = np.exp(1j * 0.5) * Operator(XGate()) # Compute process fidelity F = process_fidelity(op_a, op_b) print('Process fidelity =', F) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # # your code is here qreg1 = QuantumRegister(2) # quantum register with 2 qubits creg1 = ClassicalRegister(2) # classical register with 2 bits mycircuit1 = QuantumCircuit(qreg1,creg1) # quantum circuit with quantum and classical registers # the first qubit is in |0> # set the second qubit to |1> mycircuit1.x(qreg1[1]) # apply x-gate (NOT operator) # apply Hadamard to both qubits. mycircuit1.h(qreg1[0]) mycircuit1.h(qreg1[1]) # apply CNOT operator, where the controller qubit is the first qubit and the target qubit is the second qubit. mycircuit1.cx(qreg1[0],qreg1[1]) # apply Hadamard to both qubits. mycircuit1.h(qreg1[0]) mycircuit1.h(qreg1[1]) # measure both qubits mycircuit1.measure(qreg1,creg1) # execute the circuit 100 times in the local simulator job = execute(mycircuit1,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(mycircuit1) # print the reverse of the outcome for outcome in counts: reverse_outcome = '' for i in outcome: reverse_outcome = i + reverse_outcome print("Start state: 01, Result state: ",reverse_outcome," Observed",counts[outcome],"times") # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # # your code is here # # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # Create a circuit with 7 qubits. n = 7 qreg2 = QuantumRegister(n) # quantum register with 7 qubits creg2 = ClassicalRegister(n) # classical register with 7 bits mycircuit2 = QuantumCircuit(qreg2,creg2) # quantum circuit with quantum and classical registers # the first six qubits are already in |0> # set the last qubit to |1> mycircuit2.x(qreg2[n-1]) # apply x-gate (NOT operator) # apply Hadamard to all qubits. for i in range(n): mycircuit2.h(qreg2[i]) # apply CNOT operator (first-qubit,last-qubit) # apply CNOT operator (fourth-qubit,last-qubit) # apply CNOT operator (fifth-qubit,last-qubit) mycircuit2.cx(qreg2[0],qreg2[n-1]) mycircuit2.cx(qreg2[3],qreg2[n-1]) mycircuit2.cx(qreg2[4],qreg2[n-1]) # apply Hadamard to all qubits. for i in range(n): mycircuit2.h(qreg2[i]) # measure all qubits mycircuit2.measure(qreg2,creg2) # execute the circuit 100 times in the local simulator job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(mycircuit2) # print the reverse of the outcome for outcome in counts: reverse_outcome = '' for i in outcome: reverse_outcome = i + reverse_outcome print(reverse_outcome,"is observed",counts[outcome],"times") for i in range(len(reverse_outcome)): print("Final q-bit value for nth q-bit",(i+1),"is",reverse_outcome[i])
https://github.com/DylanLi272/QiskitFinalProject
DylanLi272
from qiskit import BasicAer, Aer, IBMQ from qiskit.aqua import QuantumInstance, aqua_globals from qiskit.aqua.algorithms import VQE, ExactEigensolver, NumPyEigensolver from qiskit.aqua.components.initial_states import Zero from qiskit.aqua.components.optimizers import COBYLA, L_BFGS_B, SLSQP, SPSA, CRS from qiskit.aqua.components.variational_forms import RY, RYRZ, SwapRZ from qiskit.aqua.operators import WeightedPauliOperator, Z2Symmetries from qiskit.chemistry import FermionicOperator from qiskit.chemistry.drivers import PySCFDriver, UnitsType from qiskit.chemistry.components.variational_forms import UCCSD from qiskit.chemistry.components.initial_states import HartreeFock from qiskit.providers.aer import QasmSimulator from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors import QuantumError, ReadoutError from qiskit.providers.aer.noise.errors import pauli_error from qiskit.providers.aer.noise.errors import depolarizing_error from qiskit.providers.aer.noise.errors import thermal_relaxation_error from qiskit.providers.aer import noise from qiskit.tools.monitor import job_monitor from qiskit.providers.ibmq import least_busy import warnings IBMQ.load_account() provider = IBMQ.get_provider(group='open') backend = least_busy(provider.backends(simulator=False, operational=True)) import numpy as np import matplotlib.pyplot as plt from functools import partial inter_dist = 1.5108585 driver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0' + str(inter_dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') # please be aware that the idx here with respective to original idx freeze_list = [0] remove_list = [-3, -2] # negative number denotes the reverse order #Classically solve for the lowest eigenvalue def exact_solver(qubitOp): ee = ExactEigensolver(qubitOp) result = ee.run() ref = result['energy'] print('Reference value: {}'.format(ref)) return ref backend = BasicAer.get_backend('statevector_simulator') #Define our noise model based on the ibmq_essex chip chip_name = 'ibmq_essex' device = provider.get_backend(chip_name) coupling_map = device.configuration().coupling_map noise_model = noise.device.basic_device_noise_model(device.properties()) basis_gates = noise_model.basis_gates # Classically solve for the lowest eigenvalue # This is used just to compare how well you VQE approximation is performing def exact_solver(qubitOp): ee = ExactEigensolver(qubitOp) result = ee.run() ref = result['energy'] print('Reference value: {}'.format(ref)) return ref counts = [] values = [] params = [] deviation = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) params.append(parameters) deviation.append(std) # Define your function for computing the qubit operations of LiH def compute_LiH_qubitOp(map_type, inter_dist, basis='sto3g'): # Specify details of our molecule driver = PySCFDriver(atom='Li 0 0 0; H 0 0 ' + str(inter_dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis=basis) # Compute relevant 1 and 2 body integrals. molecule = driver.run() h1 = molecule.one_body_integrals h2 = molecule.two_body_integrals num_particles = molecule.num_alpha + molecule.num_beta num_spin_orbitals = molecule.num_orbitals * 2 nuclear_repulsion_energy = molecule.nuclear_repulsion_energy print("# of electrons: {}".format(num_particles)) print("# of spin orbitals: {}".format(num_spin_orbitals)) # Please be aware that the idx here with respective to original idx freeze_list = [0,1,6,7] remove_list = [0,1,4,5] # negative number denotes the reverse order # Prepare full idx of freeze_list and remove_list # Convert all negative idx to positive num_spin_orbitals -= len(remove_list) # Prepare fermionic hamiltonian with orbital freezing and eliminating, and then map to qubit hamiltonian # and if PARITY mapping is selected, reduction qubits energy_shift = 0.0 qubit_reduction = True if map_type == 'parity' else False ferOp = FermionicOperator(h1=h1, h2=h2) if len(freeze_list) > 0: ferOp, energy_shift = ferOp.fermion_mode_freezing(freeze_list) num_spin_orbitals -= len(freeze_list) num_particles -= len(freeze_list)//2 if len(freeze_list) > 0: ferOp = ferOp.fermion_mode_elimination(remove_list) qubitOp = ferOp.mapping(map_type) qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles) return qubitOp, num_spin_orbitals, num_particles, qubit_reduction, molecule, energy_shift, nuclear_repulsion_energy map_type = "parity" qubitOp, num_spin_orbitals, num_particles, qubit_reduction, molecule, energy_shift, nuclear_repulsion_energy = compute_LiH_qubitOp(map_type, inter_dist) # Classically solve for the exact solution and use that as your reference value ref = exact_solver(qubitOp) # Specify your initial state init_state = HartreeFock(num_spin_orbitals, num_particles, qubit_mapping=map_type) # Select a state preparation ansatz # Equivalently, choose a parameterization for our trial wave function. UCCSD_var_form = UCCSD(num_orbitals=num_spin_orbitals, num_particles=num_particles, qubit_mapping=map_type, initial_state=init_state, two_qubit_reduction=qubit_reduction, reps=2) # Choose where to run/simulate our circuit quantum_instance = backend max_eval = 10000 # Choose the classical optimizer optimizer = SPSA(max_eval) warnings.filterwarnings("ignore") vqe = VQE(qubitOp, UCCSD_var_form, optimizer, callback=store_intermediate_result) vqe_eigenvalue = np.real(vqe.run(backend)['eigenvalue']) # Now compare the results of different compositions of your VQE algorithm! print("VQE value: ", vqe_eigenvalue) vqe_result = np.real(energy_shift + vqe_eigenvalue) print("VQE energy: ", vqe_result) print("HF energy: {}".format(molecule.hf_energy)) print("Reference Value Percent Error: " + str(abs((vqe_eigenvalue-ref)/ref)*100) + "%") print("Energy Value Percent Error: " + str(np.real(abs((vqe_result-molecule.hf_energy)/molecule.hf_energy))*100) + "%") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/liudingshan/QiskitGrovers
liudingshan
from qiskit import * from qiskit.tools.visualization import plot_bloch_multivector import matplotlib.pyplot as plt qr = QuantumRegister(1) cr = ClassicalRegister(1) circuit = QuantumCircuit(qr, cr) circuit.x(0) #simulator = Aer.get_backend('statevector_simulator') simulator = Aer.get_backend('unitary_simulator') result = execute(circuit, backend=simulator).result() #statevector = result.get_statevector() unitary = result.get_unitary() #plot_bloch_multivector(statevector) #plt.show() circuit.measure(qr, cr) #backend = Aer.get_backend('qasm_simulator') #result = execute(circuit, backend=backend, shots=1024).result() #counts = result.get_counts() from qiskit.tools.visualization import plot_histogram plot_histogram(result.get_counts(circuit)) plt.show() #print(statevector) #print(circuit) print(unitary)
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 # initialize two qubits in the zero state and # two classical bits in the zero state in the quantum circuit circuit = QuantumCircuit(3,3) # C gate # (2) => q2 circuit.x(2) circuit.draw(output='mpl') draw_circuit(circuit) # Hadamard (H) gate # (0) => (q0) circuit.h(0) circuit.draw(output='mpl') draw_circuit(circuit) # A controlled-NOT (CX NOT) gate, on control qubit 0 # and target qubit 1, putting the qubits in an entangled state. # (2,1) = > q2(control bit)(quantum bit)(origin) --> q1(target bit)(quantum bit)(destination) circuit.cx(2,1) # (0,2) = > q0(control bit)(quantum bit)(origin) --> q2(target bit)(quantum bit)(destination) circuit.cx(0,2) circuit.draw(output='mpl') draw_circuit(circuit) # measurement between quantum state and classical state # [1,1] => [q1,q1](quantum bit) and [2,0] => [c2,c0](classical bit) circuit.measure([1,1],[2,0]) circuit.draw(output='mpl') draw_circuit(circuit) # The n qubit’s measurement result will be stored in the n classical bit circuit.measure([1,1,2],[2,0,0]) circuit.draw(output='mpl') draw_circuit(circuit) simulator = Aer.get_backend("qasm_simulator") job = execute(circuit, simulator, shots=2024) result = job.result() counts = result.get_counts(circuit) print("Total count for 100 and 101 are: ", counts) # 1. plot_histogram(counts) # 2. from ibm_quantum_widgets import draw_circuit draw_circuit(circuit)
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": ### replaced x gate ### qc.z(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/1chooo/Quantum-Oracle
1chooo
from qiskit import QuantumCircuit, QuantumRegister qrx = QuantumRegister(3, 'x') qry = QuantumRegister(1, 'y') qc = QuantumCircuit(qrx, qry) qc.x(qry) qc.draw("mpl")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.algorithms import AmplificationProblem # the state we desire to find is '11' good_state = ['11'] # specify the oracle that marks the state '11' as a good solution oracle = QuantumCircuit(2) oracle.cz(0, 1) # define Grover's algorithm problem = AmplificationProblem(oracle, is_good_state=good_state) # now we can have a look at the Grover operator that is used in running the algorithm # (Algorithm circuits are wrapped in a gate to appear in composition as a block # so we have to decompose() the op to see it expanded into its component gates.) problem.grover_operator.decompose().draw(output='mpl') from qiskit.algorithms import Grover from qiskit.primitives import Sampler grover = Grover(sampler=Sampler()) result = grover.amplify(problem) print('Result type:', type(result)) print() print('Success!' if result.oracle_evaluation else 'Failure!') print('Top measurement:', result.top_measurement) from qiskit.quantum_info import Statevector oracle = Statevector.from_label('11') problem = AmplificationProblem(oracle, is_good_state=['11']) grover = Grover(sampler=Sampler()) result = grover.amplify(problem) print('Result type:', type(result)) print() print('Success!' if result.oracle_evaluation else 'Failure!') print('Top measurement:', result.top_measurement) problem.grover_operator.oracle.decompose().draw(output='mpl') from qiskit.circuit.library.phase_oracle import PhaseOracle from qiskit.exceptions import MissingOptionalLibraryError # `Oracle` (`PhaseOracle`) as the `oracle` argument expression = '(a & b)' try: oracle = PhaseOracle(expression) problem = AmplificationProblem(oracle) display(problem.grover_operator.oracle.decompose().draw(output='mpl')) except MissingOptionalLibraryError as ex: print(ex) import numpy as np # Specifying `state_preparation` # to prepare a superposition of |01>, |10>, and |11> oracle = QuantumCircuit(3) oracle.ccz(0, 1, 2) theta = 2 * np.arccos(1 / np.sqrt(3)) state_preparation = QuantumCircuit(3) state_preparation.ry(theta, 0) state_preparation.ch(0,1) state_preparation.x(1) state_preparation.h(2) # we only care about the first two bits being in state 1, thus add both possibilities for the last qubit problem = AmplificationProblem(oracle, state_preparation=state_preparation, is_good_state=['110', '111']) # state_preparation print('state preparation circuit:') problem.grover_operator.state_preparation.draw(output='mpl') grover = Grover(sampler=Sampler()) result = grover.amplify(problem) print('Success!' if result.oracle_evaluation else 'Failure!') print('Top measurement:', result.top_measurement) oracle = QuantumCircuit(5) oracle.ccz(0, 1, 2) oracle.draw(output='mpl') from qiskit.circuit.library import GroverOperator grover_op = GroverOperator(oracle, insert_barriers=True) grover_op.decompose().draw(output='mpl') grover_op = GroverOperator(oracle, reflection_qubits=[0, 1, 2], insert_barriers=True) grover_op.decompose().draw(output='mpl') # a list of binary strings good state oracle = QuantumCircuit(2) oracle.cz(0, 1) good_state = ['11', '00'] problem = AmplificationProblem(oracle, is_good_state=good_state) print(problem.is_good_state('11')) # a list of integer good state oracle = QuantumCircuit(2) oracle.cz(0, 1) good_state = [0, 1] problem = AmplificationProblem(oracle, is_good_state=good_state) print(problem.is_good_state('11')) from qiskit.quantum_info import Statevector # `Statevector` good state oracle = QuantumCircuit(2) oracle.cz(0, 1) good_state = Statevector.from_label('11') problem = AmplificationProblem(oracle, is_good_state=good_state) print(problem.is_good_state('11')) # Callable good state def callable_good_state(bitstr): if bitstr == "11": return True return False oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=good_state) print(problem.is_good_state('11')) # integer iteration oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=['11']) grover = Grover(iterations=1) # list iteration oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=['11']) grover = Grover(iterations=[1, 2, 3]) # using sample_from_iterations oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=['11']) grover = Grover(iterations=[1, 2, 3], sample_from_iterations=True) iterations = Grover.optimal_num_iterations(num_solutions=1, num_qubits=8) iterations def to_DIAMACS_CNF_format(bit_rep): return [index+1 if val==1 else -1 * (index + 1) for index, val in enumerate(bit_rep)] oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=['11'], post_processing=to_DIAMACS_CNF_format) problem.post_processing([1, 0, 1]) 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 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/abhishekchak52/quantum-computing-course
abhishekchak52
%matplotlib inline import numpy as np import matplotlib.pyplot as plt # Importing standard Qiskit libraries and configuring account import qiskit from qiskit import QuantumCircuit, execute from qiskit.providers.aer import QasmSimulator, StatevectorSimulator from qiskit.visualization import * from qiskit.quantum_info import * success_msg = 'Your answer is correct.' fail_msg = 'Your answer is not correct. Please try again.' basis_gates = ['id', 'x', 'y', 'z', 's', 't', 'sdg', 'tdg', 'h', 'p', 'sx' ,'r', 'rx', 'ry', 'rz', 'u', 'u1', 'u2', 'u3', 'cx', 'barrier', 'measure', 'snapshot'] qc1 = QuantumCircuit(3) # Insert gates below to create the state qc1.h(0) qc1.cx(0,1) qc1.cx(1,2) # Do not change below this line. You do not need to add an additional measurement. qc1.measure_all() qc1.draw('mpl') try: assert list(qc1.count_ops()) != [], "Circuit cannot be empty" assert set(qc1.count_ops().keys()).difference(basis_gates) == set(), f"Only the following basic gates are allowed: {basis_gates}" assert all([type(gate[0]) == qiskit.circuit.measure.Measure for gate in qc1.data[-3:len(qc1.data)]]), "Measurement must be the last operation in a circuit." sv_check = Statevector.from_instruction(qc1.remove_final_measurements(inplace=False)).equiv((Statevector.from_label('000')+Statevector.from_label('111'))/np.sqrt(2)) assert sv_check, "You did not prepare the correct state." job = execute(qc1, backend=QasmSimulator(), shots=1024, seed_simulator=0) counts = job.result().get_counts() print(success_msg if (sv_check) else fail_msg) except AssertionError as e: print(f'Your code has an error: {e.args[0]}') except Exception as e: print(f'This error occured: {e.args[0]}') plot_histogram(counts) bell_prep_circ = QuantumCircuit(2) bell_prep_circ.h(0) bell_prep_circ.cx(0,1) def superdense_coding_circ(bitstr): ''' bitstr is a 2-character string with possible values '00', '01', '10', '11' ''' qc2 = QuantumCircuit(2) # Enter your code below this line # Prepare a Bell state B_00 below qc2.extend(bell_prep_circ) # Do not remove the following line qc2.snapshot('1') # Apply single-qubit gates only on q_0 to encode the bitstring if (bitstr[0] == '1'): qc2.z(0) if (bitstr[1] == '1'): qc2.x(0) # Do not remove the following line qc2.snapshot('2') # Apply gates to change to the Bell basis qc2.extend(bell_prep_circ.inverse()) # Do not remove the following line qc2.snapshot('3') # Do not change below this line. You do not need to add an additional measurement. qc2.measure_all() return qc2 b00_sv = (Statevector.from_label('00')+Statevector.from_label('11'))/np.sqrt(2) b01_sv = (Statevector.from_label('01')+Statevector.from_label('10'))/np.sqrt(2) b10_sv = (Statevector.from_label('00')-Statevector.from_label('11'))/np.sqrt(2) b11_sv = (Statevector.from_label('01')-Statevector.from_label('10'))/np.sqrt(2) bell_states_sv = [b00_sv, b01_sv, b10_sv, b11_sv] basis_states = ['00', '01', '10', '11'] bell_dict = dict(zip(basis_states, bell_states_sv)) enc_dec_mat = np.zeros((len(basis_states),len(basis_states))) try: for state in basis_states: sv_checks = [] qc = superdense_coding_circ(state) assert list(qc.count_ops()) != [], f" Bitstring {state}: Circuit cannot be empty" assert qc.count_ops()['measure'] <= 2, f" Bitstring {state}: Please remove extra measurements" assert qc.count_ops()['snapshot'] == 3, f" Bitstring {state}: Please do not add or remove snapshots" assert set(qc.count_ops().keys()).difference(basis_gates) == set(), f" Bitstring {state}: Only the following basic gates are allowed: {basis_gates}" assert all([type(gate[0]) == qiskit.circuit.measure.Measure for gate in qc.data[-2:len(qc.data)]]), f" Bitstring {state}: Measurement must be the last operation in a circuit." result = execute(qc.reverse_bits(),backend=QasmSimulator(), shots=1).result().get_counts().most_frequent() assert state == result, f" Bitstring {state}: Your encoding is not correct" enc_dec_mat[int(state,2), int(result,2)] = 1 sv = execute(qc.reverse_bits(), backend=StatevectorSimulator()).result().data()['snapshots']['statevector'] sv_checks.append(b00_sv.equiv(sv['1'][0])) sv_checks.append(bell_dict[state].equiv(sv['2'][0])) sv_checks.append(Statevector.from_label(state).equiv(sv['3'][0])) assert all(np.diag(enc_dec_mat) == np.ones(4)), "Your encoding is not correct" plt.matshow(enc_dec_mat, cmap='binary') plt.title('Superdense Coding Matrix') plt.xlabel("Alice's encoded bits", fontsize=14) plt.ylabel("Bob's decoded bits", fontsize=14) plt.xticks(ticks=range(4), labels=basis_states, fontsize=12) plt.yticks(ticks=range(4), labels=basis_states, fontsize=12) circ_check = all(sv_checks) assert circ_check, "Your circuit does not work for all bitstrings" print(success_msg if circ_check else fail_msg) except AssertionError as e: print(f'Your code has an error: {e.args[0]}') except Exception as e: print(f'This error occured: {e.args[0]}')
https://github.com/derivation/ThinkQuantum
derivation
import numpy as np from numpy import pi import matplotlib.pyplot as plt import matplotlib.image as mpimg from skimage.transform import resize filename = './schrodin_yang.png' im = mpimg.imread(filename) n_pixels = 2**5 im = resize(im, (n_pixels, n_pixels)) data = im[:,:,0].ravel() fig, ax = plt.subplots() ax.imshow(im) n_qubits = int(np.log2(len(data))) from qiskit_aqua.components.initial_states import Custom init_state = Custom(n_qubits, state_vector=data) circ = init_state.construct_circuit('circuit') qr = circ.qregs # circ.draw() circ.h(qr[0][0]) from qiskit import BasicAer, execute simulator = BasicAer.get_backend('statevector_simulator') sim_result = execute(circ, simulator).result() final_state = sim_result.get_statevector(circ) edge = np.real(final_state) n_rows = int(np.sqrt(len(edge))) n_cols = n_rows edge = edge.reshape(n_rows, n_cols) edge[:,::2] = 0 fig, ax = plt.subplots(1,2) ax[0].imshow(edge) ax[1].imshow(im)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np import matplotlib.pyplot as plt try: import cplex from cplex.exceptions import CplexError except: print("Warning: Cplex not found.") import math from qiskit.utils import algorithm_globals from qiskit.algorithms.minimum_eigensolvers import SamplingVQE from qiskit.algorithms.optimizers import SPSA from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Sampler # Initialize the problem by defining the parameters n = 3 # number of nodes + depot (n+1) K = 2 # number of vehicles # Get the data class Initializer: def __init__(self, n): self.n = n def generate_instance(self): n = self.n # np.random.seed(33) np.random.seed(1543) xc = (np.random.rand(n) - 0.5) * 10 yc = (np.random.rand(n) - 0.5) * 10 instance = np.zeros([n, n]) for ii in range(0, n): for jj in range(ii + 1, n): instance[ii, jj] = (xc[ii] - xc[jj]) ** 2 + (yc[ii] - yc[jj]) ** 2 instance[jj, ii] = instance[ii, jj] return xc, yc, instance # Initialize the problem by randomly generating the instance initializer = Initializer(n) xc, yc, instance = initializer.generate_instance() class ClassicalOptimizer: def __init__(self, instance, n, K): self.instance = instance self.n = n # number of nodes self.K = K # number of vehicles def compute_allowed_combinations(self): f = math.factorial return f(self.n) / f(self.K) / f(self.n - self.K) def cplex_solution(self): # refactoring instance = self.instance n = self.n K = self.K my_obj = list(instance.reshape(1, n**2)[0]) + [0.0 for x in range(0, n - 1)] my_ub = [1 for x in range(0, n**2 + n - 1)] my_lb = [0 for x in range(0, n**2)] + [0.1 for x in range(0, n - 1)] my_ctype = "".join(["I" for x in range(0, n**2)]) + "".join( ["C" for x in range(0, n - 1)] ) my_rhs = ( 2 * ([K] + [1 for x in range(0, n - 1)]) + [1 - 0.1 for x in range(0, (n - 1) ** 2 - (n - 1))] + [0 for x in range(0, n)] ) my_sense = ( "".join(["E" for x in range(0, 2 * n)]) + "".join(["L" for x in range(0, (n - 1) ** 2 - (n - 1))]) + "".join(["E" for x in range(0, n)]) ) try: my_prob = cplex.Cplex() self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs) my_prob.solve() except CplexError as exc: print(exc) return x = my_prob.solution.get_values() x = np.array(x) cost = my_prob.solution.get_objective_value() return x, cost def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs): n = self.n prob.objective.set_sense(prob.objective.sense.minimize) prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype) prob.set_log_stream(None) prob.set_error_stream(None) prob.set_warning_stream(None) prob.set_results_stream(None) rows = [] for ii in range(0, n): col = [x for x in range(0 + n * ii, n + n * ii)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [x for x in range(0 + ii, n**2, n)] coef = [1 for x in range(0, n)] rows.append([col, coef]) # Sub-tour elimination constraints: for ii in range(0, n): for jj in range(0, n): if (ii != jj) and (ii * jj > 0): col = [ii + (jj * n), n**2 + ii - 1, n**2 + jj - 1] coef = [1, 1, -1] rows.append([col, coef]) for ii in range(0, n): col = [(ii) * (n + 1)] coef = [1] rows.append([col, coef]) prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs) # Instantiate the classical optimizer class classical_optimizer = ClassicalOptimizer(instance, n, K) # Print number of feasible solutions print("Number of feasible solutions = " + str(classical_optimizer.compute_allowed_combinations())) # Solve the problem in a classical fashion via CPLEX x = None z = None try: x, classical_cost = classical_optimizer.cplex_solution() # Put the solution in the z variable z = [x[ii] for ii in range(n**2) if ii // n != ii % n] # Print the solution print(z) except: print("CPLEX may be missing.") # Visualize the solution def visualize_solution(xc, yc, x, C, n, K, title_str): plt.figure() plt.scatter(xc, yc, s=200) for i in range(len(xc)): plt.annotate(i, (xc[i] + 0.15, yc[i]), size=16, color="r") plt.plot(xc[0], yc[0], "r*", ms=20) plt.grid() for ii in range(0, n**2): if x[ii] > 0: ix = ii // n iy = ii % n plt.arrow( xc[ix], yc[ix], xc[iy] - xc[ix], yc[iy] - yc[ix], length_includes_head=True, head_width=0.25, ) plt.title(title_str + " cost = " + str(int(C * 100) / 100.0)) plt.show() if x is not None: visualize_solution(xc, yc, x, classical_cost, n, K, "Classical") from qiskit_optimization import QuadraticProgram from qiskit_optimization.algorithms import MinimumEigenOptimizer class QuantumOptimizer: def __init__(self, instance, n, K): self.instance = instance self.n = n self.K = K def binary_representation(self, x_sol=0): instance = self.instance n = self.n K = self.K A = np.max(instance) * 100 # A parameter of cost function # Determine the weights w instance_vec = instance.reshape(n**2) w_list = [instance_vec[x] for x in range(n**2) if instance_vec[x] > 0] w = np.zeros(n * (n - 1)) for ii in range(len(w_list)): w[ii] = w_list[ii] # Some variables I will use Id_n = np.eye(n) Im_n_1 = np.ones([n - 1, n - 1]) Iv_n_1 = np.ones(n) Iv_n_1[0] = 0 Iv_n = np.ones(n - 1) neg_Iv_n_1 = np.ones(n) - Iv_n_1 v = np.zeros([n, n * (n - 1)]) for ii in range(n): count = ii - 1 for jj in range(n * (n - 1)): if jj // (n - 1) == ii: count = ii if jj // (n - 1) != ii and jj % (n - 1) == count: v[ii][jj] = 1.0 vn = np.sum(v[1:], axis=0) # Q defines the interactions between variables Q = A * (np.kron(Id_n, Im_n_1) + np.dot(v.T, v)) # g defines the contribution from the individual variables g = ( w - 2 * A * (np.kron(Iv_n_1, Iv_n) + vn.T) - 2 * A * K * (np.kron(neg_Iv_n_1, Iv_n) + v[0].T) ) # c is the constant offset c = 2 * A * (n - 1) + 2 * A * (K**2) try: max(x_sol) # Evaluates the cost distance from a binary representation of a path fun = ( lambda x: np.dot(np.around(x), np.dot(Q, np.around(x))) + np.dot(g, np.around(x)) + c ) cost = fun(x_sol) except: cost = 0 return Q, g, c, cost def construct_problem(self, Q, g, c) -> QuadraticProgram: qp = QuadraticProgram() for i in range(n * (n - 1)): qp.binary_var(str(i)) qp.objective.quadratic = Q qp.objective.linear = g qp.objective.constant = c return qp def solve_problem(self, qp): algorithm_globals.random_seed = 10598 vqe = SamplingVQE(sampler=Sampler(), optimizer=SPSA(), ansatz=RealAmplitudes()) optimizer = MinimumEigenOptimizer(min_eigen_solver=vqe) result = optimizer.solve(qp) # compute cost of the obtained result _, _, _, level = self.binary_representation(x_sol=result.x) return result.x, level # Instantiate the quantum optimizer class with parameters: quantum_optimizer = QuantumOptimizer(instance, n, K) # Check if the binary representation is correct try: if z is not None: Q, g, c, binary_cost = quantum_optimizer.binary_representation(x_sol=z) print("Binary cost:", binary_cost, "classical cost:", classical_cost) if np.abs(binary_cost - classical_cost) < 0.01: print("Binary formulation is correct") else: print("Error in the binary formulation") else: print("Could not verify the correctness, due to CPLEX solution being unavailable.") Q, g, c, binary_cost = quantum_optimizer.binary_representation() print("Binary cost:", binary_cost) except NameError as e: print("Warning: Please run the cells above first.") print(e) qp = quantum_optimizer.construct_problem(Q, g, c) quantum_solution, quantum_cost = quantum_optimizer.solve_problem(qp) print(quantum_solution, quantum_cost) # Put the solution in a way that is compatible with the classical variables x_quantum = np.zeros(n**2) kk = 0 for ii in range(n**2): if ii // n != ii % n: x_quantum[ii] = quantum_solution[kk] kk += 1 # visualize the solution visualize_solution(xc, yc, x_quantum, quantum_cost, n, K, "Quantum") # and visualize the classical for comparison if x is not None: visualize_solution(xc, yc, x, classical_cost, n, K, "Classical") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, execute from qiskit.providers.fake_provider import FakeVigoV2 from qiskit.visualization import plot_gate_map backend = FakeVigoV2() plot_gate_map(backend)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Quantum teleportation example. Note: if you have only cloned the Qiskit repository but not used `pip install`, the examples only work from the root directory. """ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import BasicAer from qiskit import execute ############################################################### # Set the backend name and coupling map. ############################################################### coupling_map = [[0, 1], [0, 2], [1, 2], [3, 2], [3, 4], [4, 2]] backend = BasicAer.get_backend("qasm_simulator") ############################################################### # Make a quantum program for quantum teleportation. ############################################################### q = QuantumRegister(3, "q") c0 = ClassicalRegister(1, "c0") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(1, "c2") qc = QuantumCircuit(q, c0, c1, c2, name="teleport") # Prepare an initial state qc.u(0.3, 0.2, 0.1, q[0]) # Prepare a Bell pair qc.h(q[1]) qc.cx(q[1], q[2]) # Barrier following state preparation qc.barrier(q) # Measure in the Bell basis qc.cx(q[0], q[1]) qc.h(q[0]) qc.measure(q[0], c0[0]) qc.measure(q[1], c1[0]) # Apply a correction qc.barrier(q) qc.z(q[2]).c_if(c0, 1) qc.x(q[2]).c_if(c1, 1) qc.measure(q[2], c2[0]) ############################################################### # Execute. # Experiment does not support feedback, so we use the simulator ############################################################### # First version: not mapped initial_layout = {q[0]: 0, q[1]: 1, q[2]: 2} job = execute(qc, backend=backend, coupling_map=None, shots=1024, initial_layout=initial_layout) result = job.result() print(result.get_counts(qc)) # Second version: mapped to 2x8 array coupling graph job = execute( qc, backend=backend, coupling_map=coupling_map, shots=1024, initial_layout=initial_layout ) result = job.result() print(result.get_counts(qc)) # Both versions should give the same distribution
https://github.com/IvanIsCoding/Quantum
IvanIsCoding
# Superdense Coding %matplotlib inline from qiskit import * # Step 0: Prepare the Bell State bell_circuit = QuantumCircuit(2, 2) bell_circuit.h(0) bell_circuit.cx(0, 1) bell_circuit.barrier() bell_circuit.draw(output="mpl") # Step 1: Prepare Alice circuits depending on b0b1 # Case 00: the circuit has no gates alice_00 = QuantumCircuit(2, 2) alice_00.barrier() alice_00.draw(output="mpl") # Case 01: the circuit has the X gate alice_01 = QuantumCircuit(2, 2) alice_01.x(0) alice_01.barrier() alice_01.draw(output="mpl") # Case 10: the circuit has the Z gate alice_10 = QuantumCircuit(2, 2) alice_10.z(0) alice_10.barrier() alice_10.draw(output="mpl") # Case 11: the circuit has the X gate and then Z gate alice_11 = QuantumCircuit(2, 2) alice_11.x(0) alice_11.z(0) alice_11.barrier() alice_11.draw(output="mpl") # Step 2: Apply the inverted entanglement circuit, and then measure invert_circuit = QuantumCircuit(2, 2) invert_circuit.cx(0, 1) invert_circuit.h(0) invert_circuit.barrier() invert_circuit.measure([0, 1], [1, 0]) # Qiskit measures are always reversed, b1b0 not b0b1 invert_circuit.draw(output="mpl") # When merged, the whole circuit looks like (bell_circuit + alice_11 + invert_circuit).draw(output="mpl") # Now we simulate each outcome, to do so we create an auxiliary function that runs it def simulate_circuit(prep, encoding, decoding): """Returns the counts of the circuit that is combination of the three circuits""" circuit = prep + encoding + decoding simulator = Aer.get_backend("qasm_simulator") job = execute(circuit, simulator, shots = 2**16) result = job.result() count = result.get_counts() return count # For 00 count_00 = simulate_circuit(bell_circuit, alice_00, invert_circuit) visualization.plot_histogram(count_00) # For 01 count_01 = simulate_circuit(bell_circuit, alice_01, invert_circuit) visualization.plot_histogram(count_01) # For 10 count_10 = simulate_circuit(bell_circuit, alice_10, invert_circuit) visualization.plot_histogram(count_10) # For 11 count_11 = simulate_circuit(bell_circuit, alice_11, invert_circuit) visualization.plot_histogram(count_11) # The results match our predictions! # For purposes of reproducibility, the Qiskit version is qiskit.__qiskit_version__
https://github.com/quantumyatra/quantum_computing
quantumyatra
# Useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np from math import pi from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.tools.visualization import circuit_drawer from qiskit.quantum_info import state_fidelity from qiskit import BasicAer backend = BasicAer.get_backend('unitary_simulator') q = QuantumRegister(2) qc = QuantumCircuit(q) qc.cx(q[0],q[1]) qc.draw(output='mpl') job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cy(q[0],q[1]) qc.draw(output='mpl') job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cz(q[0],q[1]) qc.draw(output='mpl') job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.ch(q[0],q[1]) qc.draw(output='mpl') job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.crz(pi/2,q[0],q[1]) qc.draw(output='mpl') job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cu1(pi/2,q[0], q[1]) qc.draw(output='mpl') job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cu3(pi/2, pi/2, pi/2, q[0], q[1]) qc.draw(output='mpl') job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.swap(q[0], q[1]) qc.draw(output='mpl') job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/googlercolin/Qiskit-Course
googlercolin
!pip install mitiq --quiet import warnings warnings.filterwarnings(action='ignore') # Optional warning filter from qiskit import IBMQ IBMQ.save_account('0238b0afc0dc515fe7987b02706791d1719cb89b68befedc125eded0607e6e9e9f26d3eed482f66fdc45fdfceca3aab2edb9519d96b39e9c78040194b86e7858', overwrite=True) import qiskit import qiskit.ignis.verification.randomized_benchmarking as rb from qiskit.transpiler.passes import RemoveBarriers, RemoveFinalMeasurements from mitiq.interface import convert_to_mitiq, convert_from_mitiq n_qubits = 2 depth = 20 qiskit_circuit = rb.randomized_benchmarking_seq( length_vector=[depth], rb_pattern=[range(n_qubits)], group_gates="0", rand_seed=1, )[0][0][0] # Remove Barriers qiskit_circuit=RemoveBarriers()(qiskit_circuit) # Remove Measurements qiskit_circuit=RemoveFinalMeasurements()(qiskit_circuit) # print(qiskit_circuit) # Double conversion trick to rename qubit register circuit = convert_from_mitiq(convert_to_mitiq(qiskit_circuit)[0], "qiskit") print(f"Randomized benchmarking circuit with {len(circuit)} gates generated.") print(circuit) # Set the number of shots shots = 10 ** 5 # Initialize ideal backend (classical noiseless simulator) ideal_backend = qiskit.Aer.get_backend('aer_simulator') # Append measurements circuit_to_run = circuit.copy() circuit_to_run.measure_all() # Run and get count job = ideal_backend.run(circuit_to_run, shots=shots) counts = job.result().get_counts() # Expectation value of A=|00><00| ideal_value = counts["00"] / shots ideal_value from qiskit.test.mock import FakeLima from qiskit.providers.aer.noise import NoiseModel # Set the number of shots shots = 20000 # Select a noisy backend # noisy_backend = qiskit.IBMQ.load_account().get_backend("ibmq_lima") noisy_backend = FakeLima() # Simulator with noise model similar to "ibmq_lima" # Append measurements circuit_to_run = circuit.copy() circuit_to_run.measure_all() # Run and get counts print(f"Executing circuit with {len(circuit)} gates using {shots} shots.") job = noisy_backend.run(circuit_to_run, shots=shots) counts = job.result().get_counts() # Compute expectation value of the observable A=|0><0| noisy_value = counts["00"] / shots noisy_value def executor(circuit, shots=10 ** 5): """Executes the input circuit and returns the noisy expectation value <A>, where A=|00>00|. """ # Select a noisy backend # noisy_backend = qiskit.IBMQ.load_account().get_backend("ibmq_lima") noisy_backend = FakeLima() # Simulator with noise model similar to "ibmq_lima" # Append measurements circuit_to_run = circuit.copy() circuit_to_run.measure_all() # Run and get counts print(f"Executing circuit with {len(circuit)} gates using {shots} shots.") job = noisy_backend.run(circuit_to_run, shots=shots) counts = job.result().get_counts() # Compute expectation value of the observable A=|0><0| noisy_value = counts["00"] / shots return noisy_value noisy_value = executor(circuit) noisy_value from mitiq import zne # By default, noise is scaled by locally folding gates at random, and the default extrapolation is Richardson. Scale factor = 3. zne_value = zne.execute_with_zne(circuit, executor) unmitigated_error = abs(ideal_value - noisy_value) zne_error = abs(ideal_value - zne_value) print(f"Estimation error without Mitiq : {unmitigated_error}") print(f"Estimation error with Mitiq (ZNE): {zne_error}") print(f"ZNE reduced the estimation error by {(unmitigated_error - zne_error) / unmitigated_error :.1%}.") import mitiq @mitiq.zne.zne_decorator() def executor(circuit, shots=10 ** 5): """Executes the input circuit and returns the noisy expectation value <A>, where A=|00>00|. """ # Select a noisy backend # noisy_backend = qiskit.IBMQ.load_account().get_backend("ibmq_lima") noisy_backend = FakeLima() # Simulator with noise model similar to "ibmq_lima" # Append measurements circuit_to_run = circuit.copy() circuit_to_run.measure_all() # Run and get counts print(f"Executing circuit with {len(circuit)} gates using {shots} shots.") job = noisy_backend.run(circuit_to_run, shots=shots) counts = job.result().get_counts() # Compute expectation value of the observable A=|0><0| noisy_value = counts["00"] / shots return noisy_value noisy_value = executor(circuit) noisy_value # Choose a unitary folding function noise_scaling_function = zne.scaling.fold_global noise_scaled_circuit = noise_scaling_function(circuit, scale_factor=3.5) print(f"The input circuit has {len(circuit)} gates") print(f"The scaled circuit has {len(noise_scaled_circuit)} gates") # Examples: # Richardson extrapolation # factory = zne.inference.RichardsonFactory(scale_factors = [1, 1.2, 2, 3, 5.5]) # Exponential extrapolation factory = zne.inference.ExpFactory(scale_factors = [1, 1.5, 2, 3, 3.5], asymptote=0.25) # Exponential adaptive extrapolation # factory = zne.inference.AdaExpFactory(steps=10, asymptote=0.25) zne_value = zne.execute_with_zne(circuit, executor, scale_noise=noise_scaling_function, factory=factory) unmitigated_error = abs(ideal_value - noisy_value) zne_error = abs(ideal_value - zne_value) print(f"Estimation error without Mitiq : {unmitigated_error}") print(f"Estimation error with Mitiq (ZNE): {zne_error}") print(f"ZNE reduced the estimation error by {(unmitigated_error - zne_error) / unmitigated_error :.1%}.") _ = factory.plot_fit() factory.get_expectation_values() factory.get_scale_factors() factory.get_zero_noise_limit() from mitiq import pec # Print error probability of CNOT gate cnot_error_prob = noisy_backend.properties().gate_error("cx", qubits=(0, 1)) cnot_error_prob # a very rough approximation of the error acting on a CNOT gate # print(qiskit.transpile(circuit, backend=noisy_backend)) from mitiq.pec.representations.depolarizing import represent_operation_with_global_depolarizing_noise # Define ideal operation that we aim to represent cnot_circuit = qiskit.QuantumCircuit(qiskit.QuantumRegister(2, name="q")) cnot_circuit.cx(0, 1) # Build representation cnot_rep = represent_operation_with_global_depolarizing_noise(cnot_circuit, noise_level=cnot_error_prob) print(f"Quasi-probability representation with one-norm {cnot_rep.norm :g} generated.") print(cnot_rep) # full quasi-probability representation of the CNOT gate import mitiq.pec.representations.optimal.find_optimal_representation from functools import partial # Set number of probabilistically generated circuits num_samples = 100 # Distribute budget of shots among all circuits shots_per_circuit = shots // num_samples pec_executor = partial(executor, shots=shots_per_circuit) # Run PEC pec_value = pec.execute_with_pec( circuit, pec_executor, representations = [cnot_rep], num_samples=num_samples, random_state=0, ) unmitigated_error = abs(ideal_value - noisy_value) pec_error = abs(ideal_value - pec_value) print(f"Estimation error without Mitiq : {unmitigated_error}") print(f"Estimation error with Mitiq (PEC): {pec_error}") print(f"PEC reduced the estimation error by {(unmitigated_error - pec_error) / unmitigated_error :.1%}.") from mitiq.pec import NoisyOperation, OperationRepresentation def get_richardson_coefficients(scale_factors): """Returns the array of Richardson extrapolation coefficients associated to the input array of scale factors.""" # This is based on the Lagrange interpolation formula richardson_coeffs = [] for l in scale_factors: coeff = 1.0 for l_prime in scale_factors: if l_prime == l: continue coeff *= l_prime / (l_prime - l) richardson_coeffs.append(coeff) return richardson_coeffs def represent_operation_with_nepec(ideal_operation, scale_factors): """Returns the OperationRepresentation contructed by noise scaling and extrapolation.""" coeffs = get_richardson_coefficients(scale_factors) basis_expansion = {} for scale_factor, coeff in zip(scale_factors, coeffs): scaled_op = NoisyOperation(noise_scaling_function(ideal_operation, scale_factor)) basis_expansion[scaled_op] = coeff return OperationRepresentation(ideal_operation, basis_expansion) # scale_factors = [1, 3, 5] scale_factors = [1, 100] # Large scale factors reduce the PEC sampling cost. agn_rep = represent_operation_with_nepec(cnot_circuit, scale_factors) print(f"NEPEC quasi-probability representation with one-norm {agn_rep.norm :g} generated.") print(agn_rep) nepec_value = pec.execute_with_pec( circuit, pec_executor, representations = [agn_rep], num_samples=num_samples, random_state=0, ) unmitigated_error = abs(ideal_value - noisy_value) nepec_error = abs(ideal_value - nepec_value) print(f"Estimation error without Mitiq : {unmitigated_error}") print(f"Estimation error with Mitiq (NEPEC): {nepec_error}") print(f"NEPEC reduced the estimation error by {(unmitigated_error - nepec_error) / unmitigated_error :.1%}.")
https://github.com/msramalho/Teach-Me-Quantum
msramalho
import numpy as np import matplotlib.pyplot as plt %matplotlib inline # importing Qiskit from qiskit import Aer, IBMQ from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import available_backends, execute, register, get_backend, compile from qiskit.tools import visualization from qiskit.tools.visualization import circuit_drawer q = QuantumRegister(6) qc = QuantumCircuit(q) qc.x(q[2]) qc.cx(q[1], q[5]) qc.cx(q[2], q[5]) qc.cx(q[3], q[5]) qc.ccx(q[1], q[2], q[4]) qc.ccx(q[3], q[4], q[5]) qc.ccx(q[1], q[2], q[4]) qc.x(q[2]) circuit_drawer(qc) def black_box_u_f(circuit, f_in, f_out, aux, n, exactly_1_3_sat_formula): """Circuit that computes the black-box function from f_in to f_out. Create a circuit that verifies whether a given exactly-1 3-SAT formula is satisfied by the input. The exactly-1 version requires exactly one literal out of every clause to be satisfied. """ num_clauses = len(exactly_1_3_sat_formula) for (k, clause) in enumerate(exactly_1_3_sat_formula): # This loop ensures aux[k] is 1 if an odd number of literals # are true for literal in clause: if literal > 0: circuit.cx(f_in[literal-1], aux[k]) else: circuit.x(f_in[-literal-1]) circuit.cx(f_in[-literal-1], aux[k]) # Flip aux[k] if all literals are true, using auxiliary qubit # (ancilla) aux[num_clauses] circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) circuit.ccx(f_in[2], aux[num_clauses], aux[k]) # Flip back to reverse state of negative literals and ancilla circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) for literal in clause: if literal < 0: circuit.x(f_in[-literal-1]) # The formula is satisfied if and only if all auxiliary qubits # except aux[num_clauses] are 1 if (num_clauses == 1): circuit.cx(aux[0], f_out[0]) elif (num_clauses == 2): circuit.ccx(aux[0], aux[1], f_out[0]) elif (num_clauses == 3): circuit.ccx(aux[0], aux[1], aux[num_clauses]) circuit.ccx(aux[2], aux[num_clauses], f_out[0]) circuit.ccx(aux[0], aux[1], aux[num_clauses]) else: raise ValueError('We only allow at most 3 clauses') # Flip back any auxiliary qubits to make sure state is consistent # for future executions of this routine; same loop as above. for (k, clause) in enumerate(exactly_1_3_sat_formula): for literal in clause: if literal > 0: circuit.cx(f_in[literal-1], aux[k]) else: circuit.x(f_in[-literal-1]) circuit.cx(f_in[-literal-1], aux[k]) circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) circuit.ccx(f_in[2], aux[num_clauses], aux[k]) circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) for literal in clause: if literal < 0: circuit.x(f_in[-literal-1]) # -- end function def n_controlled_Z(circuit, controls, target): """Implement a Z gate with multiple controls""" if (len(controls) > 2): raise ValueError('The controlled Z with more than 2 ' + 'controls is not implemented') elif (len(controls) == 1): circuit.h(target) circuit.cx(controls[0], target) circuit.h(target) elif (len(controls) == 2): circuit.h(target) circuit.ccx(controls[0], controls[1], target) circuit.h(target) # -- end function def inversion_about_mean(circuit, f_in, n): """Apply inversion about the mean step of Grover's algorithm.""" # Hadamards everywhere for j in range(n): circuit.h(f_in[j]) # D matrix: flips the sign of the state |000> only for j in range(n): circuit.x(f_in[j]) n_controlled_Z(circuit, [f_in[j] for j in range(n-1)], f_in[n-1]) for j in range(n): circuit.x(f_in[j]) # Hadamards everywhere again for j in range(n): circuit.h(f_in[j]) # -- end function qr = QuantumRegister(3) qInvAvg = QuantumCircuit(qr) inversion_about_mean(qInvAvg, qr, 3) circuit_drawer(qInvAvg) """ Grover search implemented in Qiskit. This module contains the code necessary to run Grover search on 3 qubits, both with a simulator and with a real quantum computing device. This code is the companion for the paper "An introduction to quantum computing, without the physics", Giacomo Nannicini, https://arxiv.org/abs/1708.03684. """ def input_state(circuit, f_in, f_out, n): """(n+1)-qubit input state for Grover search.""" for j in range(n): circuit.h(f_in[j]) circuit.x(f_out) circuit.h(f_out) # -- end function # Make a quantum program for the n-bit Grover search. n = 3 # Exactly-1 3-SAT formula to be satisfied, in conjunctive # normal form. We represent literals with integers, positive or # negative, to indicate a Boolean variable or its negation. exactly_1_3_sat_formula = [[1, 2, -3], [-1, -2, -3], [-1, 2, 3]] # Define three quantum registers: 'f_in' is the search space (input # to the function f), 'f_out' is bit used for the output of function # f, aux are the auxiliary bits used by f to perform its # computation. f_in = QuantumRegister(n) f_out = QuantumRegister(1) aux = QuantumRegister(len(exactly_1_3_sat_formula) + 1) # Define classical register for algorithm result ans = ClassicalRegister(n) # Define quantum circuit with above registers grover = QuantumCircuit() grover.add(f_in) grover.add(f_out) grover.add(aux) grover.add(ans) input_state(grover, f_in, f_out, n) T = 2 for t in range(T): # Apply T full iterations black_box_u_f(grover, f_in, f_out, aux, n, exactly_1_3_sat_formula) inversion_about_mean(grover, f_in, n) # Measure the output register in the computational basis for j in range(n): grover.measure(f_in[j], ans[j]) # Execute circuit backend = Aer.get_backend('qasm_simulator') job = execute([grover], backend=backend, shots=1000) result = job.result() # Get counts and plot histogram counts = result.get_counts(grover) visualization.plot_histogram(counts) IBMQ.load_accounts() # get ibmq_16_rueschlikon configuration and coupling map backend = IBMQ.get_backend('ibmq_16_melbourne') backend_config = backend.configuration() backend_coupling = backend_config['coupling_map'] # compile the circuit for ibmq_16_rueschlikon grover_compiled = compile(grover, backend=backend, coupling_map=backend_coupling, seed=1) grover_compiled_qasm = grover_compiled.experiments[0].header.compiled_circuit_qasm print("Number of gates for", backend.name(), "is", len(grover_compiled_qasm.split("\n")) - 4) circuit_drawer(grover)
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/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience
PacktPublishing
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created Nov 2020 @author: hassi """ from qiskit import QuantumCircuit, Aer, execute from qiskit.tools.visualization import plot_histogram from IPython.core.display import display print("Ch 4: Three-qubit coin toss") print("---------------------------") qc = QuantumCircuit(3, 6) qc.h([0,1,2]) qc.measure([0,1,2],[0,1,2]) display(qc.draw('mpl')) backend = Aer.get_backend('qasm_simulator') counts = execute(qc, backend, shots=1000).result().get_counts(qc) display(plot_histogram(counts)) qc.barrier([0,1,2]) qc.reset([0,1,2]) qc.h(0) qc.cx(0,1) qc.cx(0,2) qc.measure([0,1,2],[3,4,5]) display(qc.draw('mpl')) counts = execute(qc, backend, shots=1000).result().get_counts(qc) display(plot_histogram(counts))