repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
# Create a Quantum Circuit acting on a quantum register of three qubits
circ = QuantumCircuit(3)
# Add a H gate on qubit 0, putting this qubit in superposition.
circ.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting
# the qubits in a Bell state.
circ.cx(0, 1)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 2, putting
# the qubits in a GHZ state.
circ.cx(0, 2)
circ.draw('mpl')
from qiskit.quantum_info import Statevector
# Set the intial state of the simulator to the ground state using from_int
state = Statevector.from_int(0, 2**3)
# Evolve the state by the quantum circuit
state = state.evolve(circ)
#draw using latex
state.draw('latex')
from qiskit.visualization import array_to_latex
#Alternative way of representing in latex
array_to_latex(state)
state.draw('qsphere')
state.draw('hinton')
from qiskit.quantum_info import Operator
U = Operator(circ)
# Show the results
U.data
# Create a Quantum Circuit
meas = QuantumCircuit(3, 3)
meas.barrier(range(3))
# map the quantum measurement to the classical bits
meas.measure(range(3), range(3))
# The Qiskit circuit object supports composition.
# Here the meas has to be first and front=True (putting it before)
# as compose must put a smaller circuit into a larger one.
qc = meas.compose(circ, range(3), front=True)
#drawing the circuit
qc.draw('mpl')
# Adding the transpiler to reduce the circuit to QASM instructions
# supported by the backend
from qiskit import transpile
# Use AerSimulator
from qiskit_aer import AerSimulator
backend = AerSimulator()
# First we have to transpile the quantum circuit
# to the low-level QASM instructions used by the
# backend
qc_compiled = transpile(qc, backend)
# Execute the circuit on the qasm simulator.
# We've set the number of repeats of the circuit
# to be 1024, which is the default.
job_sim = backend.run(qc_compiled, shots=1024)
# Grab the results from the job.
result_sim = job_sim.result()
counts = result_sim.get_counts(qc_compiled)
print(counts)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/unitaryfund/mitiq
|
unitaryfund
|
# Copyright (C) Unitary Fund
#
# This source code is licensed under the GPL license (v3) found in the
# LICENSE file in the root directory of this source tree.
import random
import cirq
import networkx as nx
import numpy as np
import pennylane as qml
import pytest
import qiskit
from pennylane.tape import QuantumTape
from mitiq.benchmarks import generate_mirror_circuit
from mitiq.interface.mitiq_cirq import compute_density_matrix
from mitiq.pt.pt import (
CIRQ_NOISE_OP,
PENNYLANE_NOISE_OP,
CNOT_twirling_gates,
CZ_twirling_gates,
pauli_twirl_circuit,
twirl_CNOT_gates,
twirl_CZ_gates,
)
from mitiq.utils import _equal
num_qubits = 2
qubits = cirq.LineQubit.range(num_qubits)
circuit = cirq.Circuit()
circuit.append(cirq.CNOT(*qubits))
circuit.append(cirq.CZ(*qubits))
def amp_damp_executor(circuit: cirq.Circuit, noise: float = 0.005) -> float:
return compute_density_matrix(
circuit, noise_model_function=cirq.amplitude_damp, noise_level=(noise,)
)[0, 0].real
def test_twirl_CNOT_implements_same_unitary():
num_circuits = 1
twirled = twirl_CNOT_gates(circuit, num_circuits=num_circuits)
assert len(twirled) == num_circuits
original_unitary = cirq.unitary(circuit)
twirled_unitary = cirq.unitary(twirled[0])
assert np.array_equal(twirled_unitary, original_unitary) or np.array_equal(
-1 * twirled_unitary, original_unitary
)
def test_twirl_CZ_implements_same_unitary():
num_circuits = 1
twirled = twirl_CZ_gates(circuit, num_circuits=num_circuits)
assert len(twirled) == num_circuits
original_unitary = cirq.unitary(circuit)
twirled_unitary = cirq.unitary(twirled[0])
assert np.array_equal(twirled_unitary, original_unitary) or np.array_equal(
-1 * twirled_unitary, original_unitary
)
def test_CNOT_twirl_table():
a, b = cirq.LineQubit.range(2)
for P, Q, R, S in CNOT_twirling_gates:
circuit = cirq.Circuit(
P.on(a),
Q.on(b),
cirq.CNOT.on(a, b),
R.on(a),
S.on(b),
cirq.CNOT.on(a, b),
)
assert np.allclose(cirq.unitary(circuit), np.eye(4)) or np.allclose(
-1 * cirq.unitary(circuit), np.eye(4)
)
def test_CZ_twirl_table():
a, b = cirq.LineQubit.range(2)
for P, Q, R, S in CZ_twirling_gates:
circuit = cirq.Circuit(
P.on(a),
Q.on(b),
cirq.CZ.on(a, b),
R.on(a),
S.on(b),
cirq.CZ.on(a, b),
)
assert np.allclose(cirq.unitary(circuit), np.eye(4)) or np.allclose(
-1 * cirq.unitary(circuit), np.eye(4)
)
def test_twirl_CNOT_qiskit():
qc = qiskit.QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
num_circuits = 10
twirled = twirl_CNOT_gates(qc, num_circuits=num_circuits)
assert len(twirled) == num_circuits
random_index = random.randint(0, 9)
assert isinstance(twirled[random_index], qiskit.QuantumCircuit)
def test_twirl_CNOT_increases_layer_count():
num_qubits = 3
num_layers = 10
gateset = {cirq.X: 1, cirq.Y: 1, cirq.Z: 1, cirq.H: 1, cirq.CNOT: 2}
circuit = cirq.testing.random_circuit(
num_qubits, num_layers, op_density=0.8, gate_domain=gateset
)
num_CNOTS = sum([op.gate == cirq.CNOT for op in circuit.all_operations()])
twirled = twirl_CNOT_gates(circuit, num_circuits=1)[0]
num_gates_before = len(list(circuit.all_operations()))
num_gates_after = len(list(twirled.all_operations()))
if num_CNOTS:
assert num_gates_after > num_gates_before
else:
assert num_gates_after == num_gates_before
def test_pauli_twirl_circuit():
num_qubits = 3
num_layers = 20
circuit, _ = generate_mirror_circuit(
nlayers=num_layers,
two_qubit_gate_prob=1.0,
connectivity_graph=nx.complete_graph(num_qubits),
)
num_circuits = 10
twirled_output = pauli_twirl_circuit(circuit, num_circuits)
assert len(twirled_output) == num_circuits
@pytest.mark.parametrize(
"twirl_func", [pauli_twirl_circuit, twirl_CNOT_gates, twirl_CZ_gates]
)
def test_no_CNOT_CZ_circuit(twirl_func):
num_qubits = 2
qubits = cirq.LineQubit.range(num_qubits)
circuit = cirq.Circuit()
circuit.append(cirq.X.on_each(qubits))
twirled_output = twirl_func(circuit, 5)
assert len(twirled_output) == 5
for i in range(5):
assert _equal(circuit, twirled_output[i])
@pytest.mark.parametrize("noise_name", ["bit-flip", "depolarize"])
def test_noisy_cirq(noise_name):
p = 0.01
a, b = cirq.LineQubit.range(2)
circuit = cirq.Circuit(cirq.H.on(a), cirq.CNOT.on(a, b), cirq.CZ.on(a, b))
twirled_circuit = pauli_twirl_circuit(
circuit, num_circuits=1, noise_name=noise_name, p=p
)[0]
for i, current_moment in enumerate(twirled_circuit):
for op in current_moment:
if op.gate in [cirq.CNOT, cirq.CZ]:
for next_op in twirled_circuit[i + 1]:
assert next_op.gate == CIRQ_NOISE_OP[noise_name](p=p)
@pytest.mark.parametrize("noise_name", ["bit-flip", "depolarize"])
def test_noisy_pennylane(noise_name):
p = 0.01
ops = [
qml.Hadamard(0),
qml.CNOT((0, 1)),
qml.CZ((0, 1)),
]
circuit = QuantumTape(ops)
twirled_circuit = pauli_twirl_circuit(
circuit, num_circuits=1, noise_name=noise_name, p=p
)[0]
noisy_gates = ["CNOT", "CZ"]
for i, op in enumerate(twirled_circuit.operations):
if op.name in noisy_gates:
for j in range(1, len(op.wires) + 1):
assert (
type(twirled_circuit.operations[i + j])
== PENNYLANE_NOISE_OP[noise_name]
)
|
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.
"""Variational Quantum Imaginary 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 ImaginaryVariationalPrinciple, ImaginaryMcLachlanPrinciple
from .var_qte import VarQTE
from ..imaginary_time_evolver import ImaginaryTimeEvolver
class VarQITE(VarQTE, ImaginaryTimeEvolver):
"""Variational Quantum Imaginary Time Evolution algorithm.
.. code-block::python
import numpy as np
from qiskit_algorithms import TimeEvolutionProblem, VarQITE
from qiskit_algorithms.time_evolvers.variational import ImaginaryMcLachlanPrinciple
from qiskit.circuit.library import EfficientSU2
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 = ImaginaryMcLachlanPrinciple()
time = 1
# without evaluating auxiliary operators
evolution_problem = TimeEvolutionProblem(observable, time)
var_qite = VarQITE(ansatz, init_param_values, var_principle)
evolution_result = var_qite.evolve(evolution_problem)
# evaluating auxiliary operators
aux_ops = [Pauli("XX"), Pauli("YZ")]
evolution_problem = TimeEvolutionProblem(observable, time, aux_operators=aux_ops)
var_qite = VarQITE(ansatz, init_param_values, var_principle, Estimator())
evolution_result = var_qite.evolve(evolution_problem)
"""
def __init__(
self,
ansatz: QuantumCircuit,
initial_parameters: Mapping[Parameter, float] | Sequence[float],
variational_principle: ImaginaryVariationalPrinciple | 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 the ansatz.
variational_principle: Variational Principle to be used. Defaults to
``ImaginaryMcLachlanPrinciple``.
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 = ImaginaryMcLachlanPrinciple()
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/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Piecewise-polynomially-controlled Pauli rotations."""
from __future__ import annotations
from typing import List, Optional
import numpy as np
from qiskit.circuit import QuantumRegister, AncillaRegister, QuantumCircuit
from qiskit.circuit.exceptions import CircuitError
from .functional_pauli_rotations import FunctionalPauliRotations
from .polynomial_pauli_rotations import PolynomialPauliRotations
from .integer_comparator import IntegerComparator
class PiecewisePolynomialPauliRotations(FunctionalPauliRotations):
r"""Piecewise-polynomially-controlled Pauli rotations.
This class implements a piecewise polynomial (not necessarily continuous) function,
:math:`f(x)`, on qubit amplitudes, which is defined through breakpoints and coefficients as
follows.
Suppose the breakpoints :math:`(x_0, ..., x_J)` are a subset of :math:`[0, 2^n-1]`, where
:math:`n` is the number of state qubits. Further on, denote the corresponding coefficients by
:math:`[a_{j,1},...,a_{j,d}]`, where :math:`d` is the highest degree among all polynomials.
Then :math:`f(x)` is defined as:
.. math::
f(x) = \begin{cases}
0, x < x_0 \\
\sum_{i=0}^{i=d}a_{j,i}/2 x^i, x_j \leq x < x_{j+1}
\end{cases}
where if given the same number of breakpoints as polynomials, we implicitly assume
:math:`x_{J+1} = 2^n`.
.. note::
Note the :math:`1/2` factor in the coefficients of :math:`f(x)`, this is consistent with
Qiskit's Pauli rotations.
Examples:
>>> from qiskit import QuantumCircuit
>>> from qiskit.circuit.library.arithmetic.piecewise_polynomial_pauli_rotations import\
... PiecewisePolynomialPauliRotations
>>> qubits, breakpoints, coeffs = (2, [0, 2], [[0, -1.2],[-1, 1, 3]])
>>> poly_r = PiecewisePolynomialPauliRotations(num_state_qubits=qubits,
...breakpoints=breakpoints, coeffs=coeffs)
>>>
>>> qc = QuantumCircuit(poly_r.num_qubits)
>>> qc.h(list(range(qubits)));
>>> qc.append(poly_r.to_instruction(), list(range(qc.num_qubits)));
>>> qc.draw()
┌───┐┌──────────┐
q_0: ┤ H ├┤0 ├
├───┤│ │
q_1: ┤ H ├┤1 ├
└───┘│ │
q_2: ─────┤2 ├
│ pw_poly │
q_3: ─────┤3 ├
│ │
q_4: ─────┤4 ├
│ │
q_5: ─────┤5 ├
└──────────┘
References:
[1]: Haener, T., Roetteler, M., & Svore, K. M. (2018).
Optimizing Quantum Circuits for Arithmetic.
`arXiv:1805.12445 <http://arxiv.org/abs/1805.12445>`_
[2]: Carrera Vazquez, A., Hiptmair, R., & Woerner, S. (2022).
Enhancing the Quantum Linear Systems Algorithm using Richardson Extrapolation.
`ACM Transactions on Quantum Computing 3, 1, Article 2 <https://doi.org/10.1145/3490631>`_
"""
def __init__(
self,
num_state_qubits: Optional[int] = None,
breakpoints: Optional[List[int]] = None,
coeffs: Optional[List[List[float]]] = None,
basis: str = "Y",
name: str = "pw_poly",
) -> None:
"""
Args:
num_state_qubits: The number of qubits representing the state.
breakpoints: The breakpoints to define the piecewise-linear function.
Defaults to ``[0]``.
coeffs: The coefficients of the polynomials for different segments of the
piecewise-linear function. ``coeffs[j][i]`` is the coefficient of the i-th power of x
for the j-th polynomial.
Defaults to linear: ``[[1]]``.
basis: The type of Pauli rotation (``'X'``, ``'Y'``, ``'Z'``).
name: The name of the circuit.
"""
# store parameters
self._breakpoints = breakpoints if breakpoints is not None else [0]
self._coeffs = coeffs if coeffs is not None else [[1]]
# store a list of coefficients as homogeneous polynomials adding 0's where necessary
self._hom_coeffs = []
self._degree = len(max(self._coeffs, key=len)) - 1
for poly in self._coeffs:
self._hom_coeffs.append(poly + [0] * (self._degree + 1 - len(poly)))
super().__init__(num_state_qubits=num_state_qubits, basis=basis, name=name)
@property
def breakpoints(self) -> List[int]:
"""The breakpoints of the piecewise polynomial function.
The function is polynomial in the intervals ``[point_i, point_{i+1}]`` where the last
point implicitly is ``2**(num_state_qubits + 1)``.
Returns:
The list of breakpoints.
"""
if (
self.num_state_qubits is not None
and len(self._breakpoints) == len(self.coeffs)
and self._breakpoints[-1] < 2**self.num_state_qubits
):
return self._breakpoints + [2**self.num_state_qubits]
return self._breakpoints
@breakpoints.setter
def breakpoints(self, breakpoints: List[int]) -> None:
"""Set the breakpoints.
Args:
breakpoints: The new breakpoints.
"""
self._invalidate()
self._breakpoints = breakpoints
if self.num_state_qubits and breakpoints:
self._reset_registers(self.num_state_qubits)
@property
def coeffs(self) -> List[List[float]]:
"""The coefficients of the polynomials.
Returns:
The polynomial coefficients per interval as nested lists.
"""
return self._coeffs
@coeffs.setter
def coeffs(self, coeffs: List[List[float]]) -> None:
"""Set the polynomials.
Args:
coeffs: The new polynomials.
"""
self._invalidate()
self._coeffs = coeffs
# update the homogeneous polynomials and degree
self._hom_coeffs = []
self._degree = len(max(self._coeffs, key=len)) - 1
for poly in self._coeffs:
self._hom_coeffs.append(poly + [0] * (self._degree + 1 - len(poly)))
if self.num_state_qubits and coeffs:
self._reset_registers(self.num_state_qubits)
@property
def mapped_coeffs(self) -> List[List[float]]:
"""The coefficients mapped to the internal representation, since we only compare
x>=breakpoint.
Returns:
The mapped coefficients.
"""
mapped_coeffs = []
# First polynomial
mapped_coeffs.append(self._hom_coeffs[0])
for i in range(1, len(self._hom_coeffs)):
mapped_coeffs.append([])
for j in range(0, self._degree + 1):
mapped_coeffs[i].append(self._hom_coeffs[i][j] - self._hom_coeffs[i - 1][j])
return mapped_coeffs
@property
def contains_zero_breakpoint(self) -> bool | np.bool_:
"""Whether 0 is the first breakpoint.
Returns:
True, if 0 is the first breakpoint, otherwise False.
"""
return np.isclose(0, self.breakpoints[0])
def evaluate(self, x: float) -> float:
"""Classically evaluate the piecewise polynomial rotation.
Args:
x: Value to be evaluated at.
Returns:
Value of piecewise polynomial function at x.
"""
y = 0
for i in range(0, len(self.breakpoints)):
y = y + (x >= self.breakpoints[i]) * (np.poly1d(self.mapped_coeffs[i][::-1])(x))
return y
def _check_configuration(self, raise_on_failure: bool = True) -> bool:
"""Check if the current configuration is valid."""
valid = True
if self.num_state_qubits is None:
valid = False
if raise_on_failure:
raise AttributeError("The number of qubits has not been set.")
if self.num_qubits < self.num_state_qubits + 1:
valid = False
if raise_on_failure:
raise CircuitError(
"Not enough qubits in the circuit, need at least "
"{}.".format(self.num_state_qubits + 1)
)
if len(self.breakpoints) != len(self.coeffs) + 1:
valid = False
if raise_on_failure:
raise ValueError("Mismatching number of breakpoints and polynomials.")
return valid
def _reset_registers(self, num_state_qubits: Optional[int]) -> None:
"""Reset the registers."""
self.qregs = []
if num_state_qubits:
qr_state = QuantumRegister(num_state_qubits)
qr_target = QuantumRegister(1)
self.qregs = [qr_state, qr_target]
# Calculate number of ancilla qubits required
num_ancillas = num_state_qubits + 1
if self.contains_zero_breakpoint:
num_ancillas -= 1
if num_ancillas > 0:
qr_ancilla = AncillaRegister(num_ancillas)
self.add_register(qr_ancilla)
def _build(self):
"""If not already built, build the circuit."""
if self._is_built:
return
super()._build()
circuit = QuantumCircuit(*self.qregs, name=self.name)
qr_state = circuit.qubits[: self.num_state_qubits]
qr_target = [circuit.qubits[self.num_state_qubits]]
# Ancilla for the comparator circuit
qr_ancilla = circuit.qubits[self.num_state_qubits + 1 :]
# apply comparators and controlled linear rotations
for i, point in enumerate(self.breakpoints[:-1]):
if i == 0 and self.contains_zero_breakpoint:
# apply rotation
poly_r = PolynomialPauliRotations(
num_state_qubits=self.num_state_qubits,
coeffs=self.mapped_coeffs[i],
basis=self.basis,
)
circuit.append(poly_r.to_gate(), qr_state[:] + qr_target)
else:
# apply Comparator
comp = IntegerComparator(num_state_qubits=self.num_state_qubits, value=point)
qr_state_full = qr_state[:] + [qr_ancilla[0]] # add compare qubit
qr_remaining_ancilla = qr_ancilla[1:] # take remaining ancillas
circuit.append(
comp.to_gate(), qr_state_full[:] + qr_remaining_ancilla[: comp.num_ancillas]
)
# apply controlled rotation
poly_r = PolynomialPauliRotations(
num_state_qubits=self.num_state_qubits,
coeffs=self.mapped_coeffs[i],
basis=self.basis,
)
circuit.append(
poly_r.to_gate().control(), [qr_ancilla[0]] + qr_state[:] + qr_target
)
# uncompute comparator
circuit.append(
comp.to_gate().inverse(),
qr_state_full[:] + qr_remaining_ancilla[: comp.num_ancillas],
)
self.append(circuit.to_gate(), self.qubits)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.timeline import draw, IQXDebugging
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial')
draw(qc, style=IQXDebugging())
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# -*- 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/PabloMartinezAngerosa/QAOA-uniform-convergence
|
PabloMartinezAngerosa
|
from tsp_qaoa import test_solution
from qiskit.visualization import plot_histogram
import networkx as nx
import numpy as np
import json
import csv
# Array of JSON Objects
header = ['instance','p','distance', 'mean']
length_p = 3
length_instances = 2
with open('qaoa_multiple_p_distance.csv', 'w', encoding='UTF8') as f:
writer = csv.writer(f)
# write the header
writer.writerow(header)
instance_index = 0
for instance in range(length_instances):
instance_index += 1
first_p = False
UNIFORM_CONVERGENCE_P = []
UNIFORM_CONVERGENCE_SAMPLE = []
for p in range(length_p):
p = p+1
if first_p == False:
print("Vuelve a llamar a test_solution")
job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(p=p)
first_p = True
else:
job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(grafo=G, p=p)
# Sort the JSON data based on the value of the brand key
UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["mean"])
convergence_min = UNIFORM_CONVERGENCE_SAMPLE[0]
UNIFORM_CONVERGENCE_P.append({
"mean":convergence_min["mean"],
"probabilities": convergence_min["probabilities"]
})
cauchy_function_nk = UNIFORM_CONVERGENCE_P[len(UNIFORM_CONVERGENCE_P) - 1]
p_index = 0
for p_state in UNIFORM_CONVERGENCE_P:
p_index += 1
print(p_index)
mean = p_state["mean"]
print(p_state)
print(mean)
distance_p_cauchy_function_nk = np.max(np.abs(cauchy_function_nk["probabilities"] - p_state["probabilities"]))
writer.writerow([instance_index, p_index, distance_p_cauchy_function_nk, mean])
|
https://github.com/Seanaventure/HighErrorRateRouting
|
Seanaventure
|
import matplotlib.pyplot as plt
import networkx as nx
import qiskit
import HERR
from qiskit.transpiler import CouplingMap
from qiskit.transpiler.passes.routing import *
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.dagcircuit import DAGCircuit
from qiskit.converters import circuit_to_dag
from qiskit.converters import dag_to_circuit
from math import pi
from qiskit.compiler import transpile, assemble
from qiskit.providers.aer.noise import NoiseModel
import qiskit.providers.aer.noise as noise
from qiskit.tools.visualization import dag_drawer
import random
from qiskit.circuit.instruction import Instruction
import time
def countTwoQubitGates(transpiledCircuit):
num = 0
for gate in transpiledCircuit.data:
# print(type(gate[0]))
if issubclass(type(gate[0]), Instruction):
if gate[0].name == "cx":
num += 1
return num
s = '1101'
n = len(s)
circuit = QuantumCircuit(8, n)
# Step 0
circuit.x(n) # the n+1 qubits are indexed 0...n, so the last qubit is index n
circuit.barrier() # just a visual aid for now
# Step 1
# range(n+1) returns [0,1,2,...,n] in Python. This covers all the qubits
circuit.h(range(n+1))
circuit.barrier() # just a visual aid for now
# Step 2
for ii, yesno in enumerate(reversed(s)):
if yesno == '1':
circuit.cx(ii, n)
circuit.barrier() # just a visual aid for now
# Step 3
# range(n+1) returns [0,1,2,...,n] in Python. This covers all the qubits
circuit.h(range(n+1))
circuit.barrier() # just a visual aid for now
# measure the qubits indexed from 0 to n-1 and store them into the classical bits indexed 0 to n-
circuit.measure(range(n), range(n))
provider = IBMQ.load_account()
backend = provider.get_backend('ibmq_lima')
basis_gates = backend.configuration().basis_gates
squareCouplingList = list()
for i in range(4):
for j in range(4):
if i is not j:
if abs(i-j) == 1:
squareCouplingList.append([i, j])
squareCouplingList.append(([0, 3]))
squareCouplingList.append(([3, 0]))
squareCouplingMap = CouplingMap(squareCouplingList)
gridCouplingList = list()
for i in range(4):
for j in range(4):
if i is not j:
if abs(i-j) == 1:
gridCouplingList.append([i, j])
for i in range(4,8):
for j in range(4,8):
if i is not j:
if abs(i-j) == 1:
gridCouplingList.append([i, j])
gridCouplingList.append(([0, 4]))
gridCouplingList.append(([4, 0]))
gridCouplingList.append(([1, 5]))
gridCouplingList.append(([5, 1]))
gridCouplingList.append(([2, 6]))
gridCouplingList.append(([6, 2]))
gridCouplingList.append(([3, 7]))
gridCouplingList.append(([7, 3]))
gridCouplingMap = CouplingMap(gridCouplingList)
jakatraCouplingList = [[0, 1], [1, 0], [1, 2], [2, 1], [1, 3], [3, 1], [3,5], [5,3], [4,5], [5,4], [6,5], [5,6]]
jakatraCouplingMap = CouplingMap(jakatraCouplingList)
circDag = circuit_to_dag(circuit)
targetCouplingMap = squareCouplingMap
bSwap = BasicSwap(targetCouplingMap)
baseTime = time.perf_counter()
bSwap.run(circDag)
bSwapTime = time.perf_counter() - baseTime
sabreSwap = SabreSwap(targetCouplingMap)
baseTime = time.perf_counter()
sabreSwap.run(circDag)
sabreSwapTime = time.perf_counter() - baseTime
stochasticSwap = StochasticSwap(targetCouplingMap)
baseTime = time.perf_counter()
stochasticSwap.run(circDag)
stochasticSwapTime = time.perf_counter() - baseTime
lookAheadSwap = LookaheadSwap(targetCouplingMap)
baseTime = time.perf_counter()
lookAheadSwap.run(circDag)
lookAheadSwapTime = time.perf_counter() - baseTime
for i in range(200):
# Create a noise model for the simulations
noise_model = noise.NoiseModel()
errorRates = list()
qiskitErrors = list()
for i in range(len(squareCouplingList)//2):
errorRates.append(random.randrange(1, 10, 1)/100.0)
qiskitErrors.append(noise.depolarizing_error(errorRates[i], 2))
edges = targetCouplingMap.get_edges()
uniqueEdges = set()
for edge in edges:
uniqueEdges.add(tuple(sorted(edge)))
noiseGraph = nx.Graph()
noiseGraph.add_nodes_from([0, 7])
errorIdex = 0
for edge in uniqueEdges:
noise_model.add_quantum_error(qiskitErrors[errorIdex], ['cx'], edge)
noiseGraph.add_edge(edge[0], edge[1], weight=1-errorRates[errorIdex])
errorIdex += 1
herr = HERR.HERR(targetCouplingMap, noiseGraph)
basSwap = BasicSwap(targetCouplingMap)
#print(gridCouplingMap)
# Run HERR
baseTime = time.perf_counter()
HERRRes = herr.run(circDag)
HERRSwapTime = time.perf_counter() - baseTime
updatedCirc = dag_to_circuit(HERRRes)
print(str(HERRSwapTime) + " " + str(bSwapTime) + " " + str(sabreSwapTime) + " " + str(stochasticSwapTime) + " " + str(lookAheadSwapTime))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
# You can reverse the order of the qubits.
from qiskit.quantum_info import DensityMatrix
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.t(1)
qc.s(0)
qc.cx(0,1)
matrix = DensityMatrix(qc)
plot_bloch_multivector(matrix, title='My Bloch Spheres', reverse_bits=True)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_city
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
# plot using a Statevector
state = Statevector(qc)
plot_state_city(state)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit.random import random_circuit
circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
display(circuit.draw("mpl"))
from qiskit.quantum_info import SparsePauliOp
observable = SparsePauliOp("XZ")
print(f">>> Observable: {observable.paulis}")
from qiskit.primitives import Estimator
estimator = Estimator()
job = estimator.run(circuit, observable)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f">>> {result}")
print(f" > Expectation value: {result.values[0]}")
circuit = random_circuit(2, 2, seed=1).decompose(reps=1)
observable = SparsePauliOp("IY")
job = estimator.run(circuit, observable)
result = job.result()
display(circuit.draw("mpl"))
print(f">>> Observable: {observable.paulis}")
print(f">>> Expectation value: {result.values[0]}")
circuits = (
random_circuit(2, 2, seed=0).decompose(reps=1),
random_circuit(2, 2, seed=1).decompose(reps=1),
)
observables = (
SparsePauliOp("XZ"),
SparsePauliOp("IY"),
)
job = estimator.run(circuits, observables)
result = job.result()
[display(cir.draw("mpl")) for cir in circuits]
print(f">>> Observables: {[obs.paulis for obs in observables]}")
print(f">>> Expectation values: {result.values.tolist()}")
from qiskit.circuit.library import RealAmplitudes
circuit = RealAmplitudes(num_qubits=2, reps=2).decompose(reps=1)
observable = SparsePauliOp("ZI")
parameter_values = [0, 1, 2, 3, 4, 5]
job = estimator.run(circuit, observable, parameter_values)
result = job.result()
display(circuit.draw("mpl"))
print(f">>> Observable: {observable.paulis}")
print(f">>> Parameter values: {parameter_values}")
print(f">>> Expectation value: {result.values[0]}")
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService(channel="ibm_quantum")
backend = service.backend("ibmq_qasm_simulator")
from qiskit.circuit.random import random_circuit
from qiskit.quantum_info import SparsePauliOp
circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
display(circuit.draw("mpl"))
observable = SparsePauliOp("XZ")
print(f">>> Observable: {observable.paulis}")
from qiskit_ibm_runtime import Estimator
estimator = Estimator(session=backend)
job = estimator.run(circuit, observable)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f">>> {result}")
print(f" > Expectation value: {result.values[0]}")
print(f" > Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Options
options = Options(optimization_level=3, environment={"log_level": "INFO"})
from qiskit_ibm_runtime import Options
options = Options()
options.resilience_level = 1
options.execution.shots = 2048
estimator = Estimator(session=backend, options=options)
result = estimator.run(circuit, observable).result()
print(f">>> Metadata: {result.metadata[0]}")
estimator = Estimator(session=backend, options=options)
result = estimator.run(circuit, observable, shots=1024).result()
print(f">>> Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Options
# optimization_level=3 adds dynamical decoupling
# resilience_level=1 adds readout error mitigation
options = Options(optimization_level=3, resilience_level=1)
estimator = Estimator(session=backend, options=options)
result = estimator.run(circuit, observable).result()
print(f">>> Expectation value: {result.values[0]}")
print(f">>> Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Session, Estimator
with Session(backend=backend, max_time="1h"):
estimator = Estimator()
result = estimator.run(circuit, observable).result()
print(f">>> Expectation value from the first run: {result.values[0]}")
result = estimator.run(circuit, observable).result()
print(f">>> Expectation value from the second run: {result.values[0]}")
from qiskit.circuit.random import random_circuit
sampler_circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
sampler_circuit.measure_all()
display(circuit.draw("mpl"))
from qiskit_ibm_runtime import Session, Sampler, Estimator
with Session(backend=backend):
sampler = Sampler()
estimator = Estimator()
result = sampler.run(sampler_circuit).result()
print(f">>> Quasi Distribution from the sampler job: {result.quasi_dists[0]}")
result = estimator.run(circuit, observable).result()
print(f">>> Expectation value from the estimator job: {result.values[0]}")
from qiskit_ibm_runtime import Session, Sampler, Estimator
with Session(backend=backend):
sampler = Sampler()
estimator = Estimator()
sampler_job = sampler.run(sampler_circuit)
estimator_job = estimator.run(circuit, observable)
print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}")
print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}")
from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler, Estimator, Options
# 1. Initialize account
service = QiskitRuntimeService(channel="ibm_quantum")
# 2. Specify options, such as enabling error mitigation
options = Options(resilience_level=1)
# 3. Select a backend.
backend = service.backend("ibmq_qasm_simulator")
# 4. Create a session
with Session(backend=backend):
# 5. Create primitive instances
sampler = Sampler(options=options)
estimator = Estimator(options=options)
# 6. Submit jobs
sampler_job = sampler.run(sampler_circuit)
estimator_job = estimator.run(circuit, observable)
# 7. Get results
print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}")
print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}")
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
from qiskit.tools.jupyter import *
%qiskit_version_table
%qiskit_copyright
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
import numpy as np
import math
def Sx(j,k,d):
# d = qudit dimension
# j,k = identification of the Gell-Mann matrix
# th = rotation angle
j = j-1; k = k-1
sx = np.zeros((d,d), dtype=complex)
sx[j,k] = 1
sx[k,j] = sx[j,k]
return sx
def Sy(j,k,d):
# d = qudit dimension
# j,k = identification of the Gell-Mann matrix
# th = rotation angle
j = j-1; k = k-1
sy = np.zeros((d,d), dtype=complex)
sy[j,k] = -1j
sy[k,j] = -sy[j,k]
return sy
def Sz(j,d):
# d = qudit dimension
# j = identification of the Gell-Mann matrix
# th = rotation angle
sz = np.zeros((d,d), dtype=complex)
for k in range(0,j+1):
sz[k,k] = math.sqrt(2/(j*(j+1)))
if k == j: # corrige para iniciar k em 0
sz[k,k] = sz[k,k]*(-j)
return sz
d = 2; j = 1; k = 2; Sx(j,k,d), Sy(j,k,d), Sz(j,d)
d = 3; Sx(1,2,d), Sx(1,3,d), Sx(2,3,d)
d = 3; Sy(1,2,d), Sy(1,3,d), Sy(2,3,d)
d = 3; Sz(1,d), Sz(2,d)
1/math.sqrt(3), -2/math.sqrt(3)
def Rx(j,k,d,th):
# d = qudit dimension
# j,k = identification of the Gell-Mann matrix
# th = rotation angle
j = j-1; k = k-1
rx = np.eye(d, dtype=complex)
rx[j,j] = math.cos(th/2)
rx[k,k] = rx[j,j]
rx[j,k] = -1j*math.sin(th/2)
rx[k,j] = rx[j,k]
return rx
def Ry(j,k,d,th):
# d = qudit dimension
# j,k = identification of the Gell-Mann matrix
# th = rotation angle
j = j-1; k = k-1
ry = np.eye(d, dtype=complex)
ry[j,j] = math.cos(th/2)
ry[k,k] = ry[j,j]
ry[j,k] = -math.sin(th/2)
ry[k,j] = -ry[j,k]
return ry
def Rz(j,d,th):
# d = qudit dimension
# j = identification of the Gell-Mann matrix
# th = rotation angle
rz = np.eye(d, dtype=complex)
for k in range(0,j+1):
angle = (th/2)*math.sqrt(2/(j*(j+1)))
if k == j: # corrige para iniciar k em 0
angle = angle*(-j)
rz[k,k] = math.cos(angle) - 1j*math.sin(angle)
return rz
d = 2; j = 1; k = 2; th = 0; Rx(j,k,d,th), Ry(j,k,d,th), Rz(j,d,th)
d = 3; j = 1; k = 2; th = 0; Rx(j,k,d,th), Ry(j,k,d,th), Rz(j,d,th)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
#Import packages
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import time
# import from qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, compile
from qiskit.converters import qobj_to_circuits
from qiskit import Aer, IBMQ
from qiskit.providers.aer import noise
# import tomography library
import qiskit.tools.qcvv.tomography as tomo
# useful additional packages
from qiskit.tools.visualization import plot_state, plot_histogram
from qiskit.tools.qi.qi import state_fidelity, outer
from qiskit.tools.qi.qi import outer
from qiskit.quantum_info import state_fidelity
from qiskit.tools.monitor import job_monitor, backend_overview
from qiskit.providers.ibmq import least_busy
Aer.backends() # No need for credentials for running the next cells
# Determine the job
n = int(input("type number of qubits + enter: "))
# create a n-qubit quantum register
qr = QuantumRegister(n)
cr = ClassicalRegister(n)
my_state = QuantumCircuit(qr, cr, name='my_state')
# desired vector for a n-qubit W state
desired_vector = []
qr_vector = []
n_vector = 2**n
for i in range(n_vector):
desired_vector.append(0)
for j in range(n) :
desired_vector[2**j] = 1/np.sqrt(n)
# choice of the circuit building method (arbitrary or specific)
print("Do you want to use the specific method?")
W_state_circuit = input(" Answer by (y/n) + enter\n").upper()
if (W_state_circuit == "N") :
method = "arbitrary"
# Initialize a n-qubit W quantum state using the arbitrary method
for j in range(n) :
qr_vector.append(qr[j])
my_state.initialize(desired_vector, qr_vector)
else:
# Quantum circuit to make a n-qubit W state using the specific method
method = "specific"
my_state.x(qr[n-1]) #start is |10...0>
for i in range(1,n) :
theta = np.arccos(np.sqrt(1/(n-i+1)))
my_state.ry(-theta,qr[n-i-1])
my_state.cz(qr[n-i],qr[n-i-1])
my_state.ry(theta,qr[n-i-1])
for i in range(1,n) :
my_state.cx(qr[n-i-1],qr[n-i])
# Measurement circuit
measuring = QuantumCircuit(qr, cr, name='measuring')
for i in range(n) :
measuring.measure(qr[i] , cr[i])
test = my_state+measuring
# Test circuit "my_state" : Noise free model on simulator
backend_sim = Aer.get_backend('qasm_simulator')
shots = 1024
job_noisefree = execute(test, backend_sim, shots=shots, max_credits=5)
job_monitor(job_noisefree)
noisefree_count = job_noisefree.result().get_counts(test)
time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
print("Date (DMY):", time_exp)
print(noisefree_count)
plot_histogram(noisefree_count, color=['purple'],
title=str(n) + '- qubit W state, noise free simulation, ' + method + " method")
# QASM from test
QASM_source = test.qasm()
print(QASM_source)
# Draw the circuit
test.draw(output='mpl')
# Execute state tomography using noise free quantum device simulation
# obtain the final state vector
backend_stvct = Aer.get_backend('statevector_simulator')
job = execute(my_state, backend_stvct)
my_state_psi = job.result().get_statevector(my_state)
# construct state tomography set for measurement of qubits [0, ..., n-1] in the Pauli basis
qubit_set = []
for i in range(0,n) :
qubit_set.append(i)
my_state_tomo_set = tomo.state_tomography_set(qubit_set) # default value for meas_basis ='Pauli'.
# add the state tomography measurement circuits to the Quantum Program
my_state_tomo_circuits = tomo.create_tomography_circuits(my_state, qr, cr, my_state_tomo_set)
backend_tomo = Aer.get_backend('qasm_simulator') # for simulation
# take 1024 shots for each measurement basis
# note: reduce this number for larger number of qubits
shots = 1024
mode = "noise free simulation"
my_state_job = execute(my_state_tomo_circuits, backend_tomo, shots=shots)
job_monitor(my_state_job)
my_state_tomo_result = my_state_job.result()
# extract tomography data from results
my_state_tomo_data = tomo.tomography_data(my_state_tomo_result, my_state.name, my_state_tomo_set)
# Quantum fidelity
# reconstruct experimentally measured density matrix
rho_fit = tomo.fit_tomography_data(my_state_tomo_data)
# calculate fidelity of fitted state:
time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
print("Date (DMY):", time_exp)
print('Tomography',str(n)+'-qubit W state on', backend_tomo,
", shots:", shots, ", method:", method, ", mode:", mode)
F_fit = state_fidelity(rho_fit, my_state_psi)
print('Fidelity with theoretical ideal state')
print('F =', F_fit)
IBMQ.load_accounts()
backend_overview() # you may skip running this cell if you want
backend_real = least_busy(IBMQ.backends(operational=True, simulator=False))
print(backend_real)
# Prepare device noise simulation (DNS)
device = backend_real
print("device: ", device)
properties = device.properties()
coupling_map = device.configuration().coupling_map
prepared = False
if device.name() == 'ibmq_16_melbourne' :
gate_times = [
('u1', None, 0), ('u2', None, 100), ('u3', None, 200),
('cx', [1, 0], 678), ('cx', [1, 2], 547), ('cx', [2, 3], 721),
('cx', [4, 3], 733), ('cx', [4, 10], 721), ('cx', [5, 4], 800),
('cx', [5, 6], 800), ('cx', [5, 9], 895), ('cx', [6, 8], 895),
('cx', [7, 8], 640), ('cx', [9, 8], 895), ('cx', [9, 10], 800),
('cx', [11, 10], 721), ('cx', [11, 3], 634), ('cx', [12, 2], 773),
('cx', [13, 1], 2286), ('cx', [13, 12], 1504), ('cx', [], 800)
]
prepared = True
elif device.name() == 'ibmqx4' :
gate_times = [
('u1', None, 0), ('u2', None, 60), ('u3', None, 120),
('cx', [1, 0], 340), ('cx', [2, 0], 424), ('cx', [2, 1], 520),
('cx', [3, 2], 620), ('cx', [3, 4], 420), ('cx', [4, 2], 920)
]
prepared = True
else :
print("No gate times yet defined in this notebook for: ", device)
if prepared :
# Construct the noise model from backend properties and custom gate times
noise_model = noise.device.basic_device_noise_model(properties, gate_times=gate_times)
# Get the basis gates for the noise model
basis_gates = noise_model.basis_gates
print("noise model prepared for", device)
# Execute test using device noise simulation (DNS)
backend_noise = Aer.get_backend('qasm_simulator') # for simulation (DNS)
shots = 1024
mode = "DNS"
job_noise = execute(test, backend_noise,
noise_model=noise_model,
coupling_map=coupling_map,
basis_gates=basis_gates)
job_monitor(job_noise)
print(job_noise.status)
time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
print("Date (DMY):", time_exp)
noisy_count = job_noise.result().get_counts(test)
print(noisy_count)
plot_histogram(noisy_count, color=['cyan'],
title= str(n) + '- qubit W state, ' + mode + ': {}, '.format(device.name()) + method + " method")
# Execute state tomography using device noise simulation (DNS)
# obtain the final state vector
backend_stvct = Aer.get_backend('statevector_simulator')
job = execute(my_state, backend_stvct)
my_state_psi = job.result().get_statevector(my_state)
# construct state tomography set for measurement of qubits [0, ..., n-1] in the Pauli basis
qubit_set = []
for i in range(0,n) :
qubit_set.append(i)
my_state_tomo_set = tomo.state_tomography_set(qubit_set) # default value for meas_basis ='Pauli'.
# add the state tomography measurement circuits to the Quantum Program
my_state_tomo_circuits = tomo.create_tomography_circuits(my_state, qr, cr, my_state_tomo_set)
backend_tomo = Aer.get_backend('qasm_simulator') # for simulation
# take 1024 shots for each measurement basis
# note: reduce this number for larger number of qubits
shots = 1024
mode = "DNS"
my_state_job = execute(my_state_tomo_circuits, backend_tomo,
noise_model=noise_model,
coupling_map=coupling_map,
basis_gates=basis_gates)
job_monitor(my_state_job)
my_state_tomo_result = my_state_job.result()
# extract tomography data from results
my_state_tomo_data = tomo.tomography_data(my_state_tomo_result, my_state.name, my_state_tomo_set)
# Quantum fidelity
# reconstruct experimentally measured density matrix
rho_fit = tomo.fit_tomography_data(my_state_tomo_data)
# calculate fidelity of fitted state:
time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
print("Date (DMY):", time_exp)
print('Tomography',str(n)+'-qubit W state on', backend_tomo,
", shots:", shots, ", method:", method, ", mode:", mode, "of", device)
F_fit = state_fidelity(rho_fit, my_state_psi)
print('Fidelity with theoretical ideal state')
print('F =', F_fit)
plt.xlabel('Number of Entangled Qubits')
plt.ylabel('Quantum Fidelity')
plt.axis([1.4, 6, 0, 1])
plt.grid()
plt.plot([2,3,4,5], [0.788,0.734,0.628,0.542], 'mo-', label="Specific Algorithm - DNS")
plt.plot([2,3,4,5], [0.773,0.682,0.386,0.148], 'cs-', label="Arbitrary Initialization - DNS")
plt.legend()
plt.show()
# Execute test using superconducting quantum computing device (SQC)
#Choose the backend
#backend_noise = Aer.get_backend('qasm_simulator') # for optional test before final experiment
backend_noise = device # for least busy SQC device
# Execute on SQC and get counts
shots = 1024
if backend_noise.name() == "qasm_simulator" : # optional test before final experiment
mode = "DNS"
job_noise = execute(test, backend_noise,
noise_model=noise_model,
coupling_map=coupling_map,
basis_gates=basis_gates)
else: # final experiment on real device
mode = "SQC"
job_noise = execute(test, backend_noise)
job_monitor(job_noise)
print(job_noise.status)
time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
noisy_count = job_noise.result().get_counts(test)
print(noisy_count)
plot_histogram(noisy_count, color=['orange'],
title= str(n) + '- qubit W state, ' + mode + ': {}, '.format(device.name()) + method + " method")
# Execute state tomography on superconducting quantum computing device (SQC)
# obtain the final state vector
backend_stvct = Aer.get_backend('statevector_simulator')
job = execute(my_state, backend_stvct)
my_state_psi = job.result().get_statevector(my_state)
# construct state tomography set for measurement of qubits [0, ..., n-1] in the Pauli basis
qubit_set = []
for i in range(0,n) :
qubit_set.append(i)
my_state_tomo_set = tomo.state_tomography_set(qubit_set) # default value for meas_basis ='Pauli'.
# add the state tomography measurement circuits to the Quantum Program
my_state_tomo_circuits = tomo.create_tomography_circuits(my_state, qr, cr, my_state_tomo_set)
#Choose the backend
#backend_tomo = Aer.get_backend('qasm_simulator') # optional test before final experiment
backend_tomo = device # for least busy SQC device
# take 1024 shots for each measurement basis
# note: reduce this number for larger number of qubits
shots = 1024
# loop: 27 circuits maximum per job to avoid exceeding the allowed limit for the real device.
n_circ = 3**n
i_max = min(27,n_circ)
my_jobs = []
index_job = -1
for i in range(0,n_circ,i_max) :
circs =[]
for j in range(i, i+i_max):
circs.append(my_state_tomo_circuits[j])
if backend_tomo.name() == "qasm_simulator" : # optional test before final experiment
mode = "DNS"
my_state_job = execute(circs, backend_tomo,
noise_model=noise_model,
coupling_map=coupling_map,
basis_gates=basis_gates)
else: # final experiment on real device
mode = "SQC"
my_state_job = execute(circs, backend_tomo, shots=shots)
my_jobs.append(my_state_job)
index_job = index_job + 1
job_monitor(my_jobs[index_job], monitor_async = True)
my_state_new_result = my_state_job.result()
if i == 0:
my_state_tomo_result = my_state_new_result
else:
my_state_tomo_result = my_state_tomo_result + my_state_new_result
# extract tomography data from results
my_state_tomo_data = tomo.tomography_data(my_state_tomo_result, my_state.name, my_state_tomo_set)
# Quantum fidelity
# reconstruct experimentally measured density matrix
rho_fit = tomo.fit_tomography_data(my_state_tomo_data)
# calculate fidelity of fitted state:
time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
print("Date (DMY):", time_exp)
print('Tomography',str(n)+'-qubit W state on', backend_tomo,
", shots:", shots, ", method:", method, ", mode:", mode, device)
F_fit = state_fidelity(rho_fit, my_state_psi)
print('Fidelity with theoretical ideal state')
print('F =', F_fit)
plt.xlabel('Number of Entangled Qubits')
plt.ylabel('Quantum Fidelity')
plt.axis([1.4, 6, 0, 1])
plt.grid()
plt.plot([2,3,4,5], [0.812,0.735,0.592,0.457], 'ro-', label="Specific Algorithm")
plt.plot([2,3,4,5], [0.838,0.539,0.144,0.060], 'bs-', label="Arbitrary Initialization")
plt.legend()
plt.show()
# DSN vs SQC, count histograms
# Shots = 1024
count_noisefree = {'010': 344, '001': 335, '100': 345}
count_DNS = {'110': 42, '010': 258, '111': 9, '011': 38, '000': 76, '001': 281, '100': 286, '101': 34}
count_real = {'001': 274, '000': 129, '010': 224, '011': 20, '100': 282, '111': 14, '101': 46, '110': 35}
plot_histogram([count_noisefree, count_DNS, count_real],
title= 'Determistic W state generation, specific algorithm, device: ibmqx4',
color=['purple','cyan', 'orange'], bar_labels=False,
legend = ['Noise free simulation', 'Device noise simulation','Real quantum device'])
plt.xlabel('Number of Entangled Qubits')
plt.ylabel('Quantum Fidelity')
plt.axis([1.4, 6, 0, 1])
plt.grid()
plt.plot([2,3,4,5], [0.812,0.735,0.592,0.457], 'ro-', label="Specific Algorithm - SQC")
plt.plot([2,3,4,5], [0.838,0.539,0.144,0.060], 'bs-', label="Arbitrary Initialization - SQC")
plt.plot([2,3,4,5], [0.788,0.734,0.628,0.542], 'mo-', label="Specific Algorithm - DNS")
plt.plot([2,3,4,5], [0.773,0.682,0.386,0.148], 'cs-', label="Arbitrary Initialization - DNS")
plt.legend()
plt.show()
|
https://github.com/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience
|
PacktPublishing
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created Nov 2020
@author: hassi
"""
print("Ch 8: How many gates do I have time for")
print("---------------------------------------")
# Import Qiskit and load account
from qiskit import Aer, IBMQ, QuantumCircuit, execute
from qiskit.providers.aer.noise import NoiseModel
from qiskit.tools.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
from IPython.core.display import display
print("Getting providers...")
if not IBMQ.active_account():
IBMQ.load_account()
provider = IBMQ.get_provider()
def select_backend():
# Get all available and operational backends.
print("Getting backends...")
available_backends = provider.backends(filters=lambda b: not b.configuration().simulator and b.configuration().n_qubits > 0 and b.status().operational)
# Fish out criteria to compare
print("{0:20} {1:<10} {2:<10}".format("Name","#Qubits","Pending jobs"))
print("{0:20} {1:<10} {2:<10}".format("----","-------","------------"))
for n in range(0, len(available_backends)):
backend = provider.get_backend(str(available_backends[n]))
print("{0:20} {1:<10}".format(backend.name(),backend.configuration().n_qubits),backend.status().pending_jobs)
select_backend=input("Select a backend:\n")
backend = provider.get_backend(select_backend)
return(backend)
def display_information(backend,n_id,ttype):
micro=10**6
qubit=0
T1=int(backend.properties().t1(qubit)*micro)
T2=int(backend.properties().t2(qubit)*micro)
id_len=backend.properties().gate_length("id",[0])*micro
if ttype=="T1":
T=T1
else:
T=T2
print("\nBackend data:")
print("\nBackend online since:",backend.configuration().online_date.strftime('%Y-%m-%d'))
print("Qubit:",qubit)
print("T1:",T1,"\u03BCs")
print("T2:",T2,"\u03BCs")
print("Readout error:",round(backend.properties().readout_error(qubit)*100,2),"%")
print("Qubit",qubit,"Id length:",round(id_len,3),"\u03BCs")
print(ttype,"-id =", round(T-n_id*id_len,2),"\u03BCs",int((100*n_id*id_len)/T),"%")
return(T)
def build_circuit(ttype,n_id):
qc = QuantumCircuit(1,1)
qc.x(0)
if ttype in ["T2","t2"]:
qc.h(0)
for n in range(int(n_id)):
qc.id(0)
qc.barrier(0)
if ttype in ["T2","t2"]:
qc.h(0)
qc.measure(0,0)
return(qc)
def build_noise_model(backend):
print("Building noise model...")
# Construct the noise model from backend
noise_model = NoiseModel.from_backend(backend)
return(noise_model)
def execute_circuit(backend, circuit,noise_model, n_id):
# Basis gates for the noise model
basis_gates = noise_model.basis_gates
# Coupling map
coupling_map = backend.configuration().coupling_map
# Execute noisy simulation on QASM simulator and get counts
noisy_counts = execute(circuit, Aer.get_backend('qasm_simulator'), noise_model=noise_model, coupling_map=coupling_map, basis_gates=basis_gates).result().get_counts(circuit)
return(noisy_counts)
# Main
def main():
# Set the time type
ttype="T1"
# Select the backend to simulate or run on
backend=select_backend()
back_sim=input("Enter Q to run on the selected backend, S to run on the simulated backend:\n")
if back_sim in ["Q","q"]:
sim=False
else:
sim=True
noise_model=build_noise_model(backend)
n_id=int(input("Number of id gates:\n"))
t=display_information(backend,n_id,ttype)
qc=build_circuit(ttype,n_id)
# Print sample circuit
print("\nSample 5-Id gate",ttype,"circuit:")
display(build_circuit(ttype,5).draw('mpl'))
# Run the circuit on a simulator
job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots=8192)
results = job.result()
sim_counts = results.get_counts()
print("\nRunning:")
print("Results for simulator:",sim_counts)
# Run the circuit
entry={'sim':sim_counts}
legend=['sim']
length=n_id
while length!=0:
qc=build_circuit(ttype,length)
if sim:
noisy_counts=execute_circuit(backend,qc,noise_model,length)
else:
job = execute(qc, backend=backend, shots=8192)
job_monitor(job)
results = job.result()
noisy_counts = results.get_counts()
print("Results for",length,"Id gates:",noisy_counts)
entry.update({str(length):noisy_counts})
legend.append(str(length))
length=int(length/4)
# Store the results in an array
results_array=[]
for i in legend:
results_array.append(entry[i])
# Display the final results
title="ID-circuits on "+str(backend)+" with "+ttype+"= "+str(t)+" \u03BCs"
if sim:
title+=" (Simulated)"
title+=" \nOnline since: "+str(backend.configuration().online_date.strftime('%Y-%m-%d'))
display(plot_histogram(results_array, legend=legend, title=title))
if __name__ == '__main__':
main()
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, execute
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.providers.aer import QasmSimulator
backend = Aer.get_backend('statevector_simulator')
qc1 = QuantumCircuit(4)
# perform gate operations on individual qubits
qc1.x(0)
qc1.y(1)
qc1.z(2)
qc1.s(3)
# Draw circuit
qc1.draw()
# Plot blochshere
out1 = execute(qc1,backend).result().get_statevector()
plot_bloch_multivector(out1)
qc2 = QuantumCircuit(4)
# initialize qubits
qc2.x(range(4))
# perform gate operations on individual qubits
qc2.x(0)
qc2.y(1)
qc2.z(2)
qc2.s(3)
# Draw circuit
qc2.draw()
# Plot blochshere
out2 = execute(qc2,backend).result().get_statevector()
plot_bloch_multivector(out2)
qc3 = QuantumCircuit(4)
# initialize qubits
qc3.h(range(4))
# perform gate operations on individual qubits
qc3.x(0)
qc3.y(1)
qc3.z(2)
qc3.s(3)
# Draw circuit
qc3.draw()
# Plot blochshere
out3 = execute(qc3,backend).result().get_statevector()
plot_bloch_multivector(out3)
qc4 = QuantumCircuit(4)
# initialize qubits
qc4.x(range(4))
qc4.h(range(4))
# perform gate operations on individual qubits
qc4.x(0)
qc4.y(1)
qc4.z(2)
qc4.s(3)
# Draw circuit
qc4.draw()
# Plot blochshere
out4 = execute(qc4,backend).result().get_statevector()
plot_bloch_multivector(out4)
qc5 = QuantumCircuit(4)
# initialize qubits
qc5.h(range(4))
qc5.s(range(4))
# perform gate operations on individual qubits
qc5.x(0)
qc5.y(1)
qc5.z(2)
qc5.s(3)
# Draw circuit
qc5.draw()
# Plot blochshere
out5 = execute(qc5,backend).result().get_statevector()
plot_bloch_multivector(out5)
qc6 = QuantumCircuit(4)
# initialize qubits
qc6.x(range(4))
qc6.h(range(4))
qc6.s(range(4))
# perform gate operations on individual qubits
qc6.x(0)
qc6.y(1)
qc6.z(2)
qc6.s(3)
# Draw circuit
qc6.draw()
# Plot blochshere
out6 = execute(qc6,backend).result().get_statevector()
plot_bloch_multivector(out6)
import qiskit
qiskit.__qiskit_version__
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
import pickle
# plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
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("./")
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="lq")
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"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = zne_wrapper(t3_st_qcs, scale_factors=scale_factors)
print("created zne_qcs (length:", len(zne_qcs), ")")
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-utokyo', group='internal', project='hirashi-jst')
# provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
# print("provider:", provider)
# backend = provider.get_backend("ibmq_jakarta")
shots = 1 << 13
reps = 1 # unused
# Number of trotter steps
print("trotter step: ", num_steps)
# execute: reps = 1
job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた?
print('Job ID', job.job_id())
# QREM
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
cal_results = cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results)
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fidelity = state_fidelity(rho, target_state)
print(fidelity)
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
# 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.providers.aer import QasmSimulator
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.quantum_info import state_fidelity
# Suppress warnings
import warnings
warnings.filterwarnings('ignore')
def trotter_gate(dt, to_instruction = True):
qc = QuantumCircuit(2)
qc.rx(2*dt,0)
qc.rz(2*dt,1)
qc.h(1)
qc.cx(1,0)
qc.rz(-2*dt, 0)
qc.rx(-2*dt, 1)
qc.rz(2*dt, 1)
qc.cx(1,0)
qc.h(1)
qc.rz(2*dt, 0)
return qc.to_instruction() if to_instruction else qc
trotter_gate(np.pi / 6, to_instruction=False).draw("mpl")
# 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)
# Number of trotter steps
trotter_steps = 15 ### CAN BE >= 4
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(7)
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>)
qc.x([5]) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
# Simulate time evolution under H_heis3 Hamiltonian
for _ in range(trotter_steps):
qc.append(Trot_gate, [qr[3], qr[5]])
qc.cx(qr[3], qr[1])
qc.cx(qr[5], qr[3])
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time/trotter_steps})
t3_qc = transpile(qc, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_qc = transpile(t3_qc, optimization_level=3, basis_gates=["sx", "cx", "rz"])
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(t3_qc, [qr[1], qr[3], qr[5]])
# Display circuit for confirmation
# st_qcs[-1].decompose().draw() # view decomposition of trotter gates
st_qcs[-1].draw("mpl") # only view trotter gates
from qiskit.test.mock import FakeJakarta
backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst')
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
print("provider:", provider)
backend = provider.get_backend("ibmq_jakarta")
shots = 8192
reps = 8
jobs = []
for _ in range(reps):
# execute
job = execute(st_qcs, backend, shots=shots)
print('Job ID', job.job_id())
jobs.append(job)
job_ids = \
["624e8c85aacb9bd9c75f4da1",
"624e8c894b515208aa7c6ae2",
"624e8c8ba5d4eeac4977ccf3",
"624e8c8ccfe45c1d4ae5a357",
"624e8c8ef65d78307439029b",
"624e8c9173968c1c2307b2c9",
"624e8c93caa26524ecf199a9",
"624e8c95aacb9b60c25f4da3"]
# QREM
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3)
print('Job ID', cal_job.job_id())
jobs = []
for job_id in job_ids:
jobs.append(backend.retrieve_job(job_id))
cal_job_id = "624e8c97a5d4ee882477ccf4"
cal_job = backend.retrieve_job(cal_job_id)
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_results = cal_job.result()
print("retrieved cal_results")
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
mit_results = []
for i, job in enumerate(jobs):
mit_results.append( meas_fitter.filter.apply(job.result()) )
print("retrieved", i, "th results")
# Compute the state tomography based on the st_qcs quantum circuits and the results from those ciricuits
def state_tomo(result, st_qcs):
# The expected final state; necessary to determine state tomography fidelity
target_state = (One^One^Zero).to_matrix() # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
# Fit state tomography results
tomo_fitter = StateTomographyFitter(result, st_qcs)
rho_fit = tomo_fitter.fit(method='lstsq')
# Compute fidelity
fid = state_fidelity(rho_fit, target_state)
return fid
# Compute tomography fidelities for each repetition
fids = []
for result in mit_results:
fid = state_tomo(result, st_qcs)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
|
https://github.com/Pitt-JonesLab/slam_decomposition
|
Pitt-JonesLab
|
%%capture
%pip install qiskit
%pip install qiskit_ibm_provider
%pip install qiskit-aer
# Importing standard Qiskit libraries
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, QuantumCircuit, transpile, Aer
from qiskit_ibm_provider import IBMProvider
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.circuit.library import C3XGate
# Importing matplotlib
import matplotlib.pyplot as plt
# Importing Numpy, Cmath and math
import numpy as np
import os, math, cmath
from numpy import pi
# Other imports
from IPython.display import display, Math, Latex
# Specify the path to your env file
env_file_path = 'config.env'
# Load environment variables from the file
os.environ.update(line.strip().split('=', 1) for line in open(env_file_path) if '=' in line and not line.startswith('#'))
# Load IBM Provider API KEY
IBMP_API_KEY = os.environ.get('IBMP_API_KEY')
# Loading your IBM Quantum account(s)
IBMProvider.save_account(IBMP_API_KEY, overwrite=True)
# Run the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
qc_b1 = QuantumCircuit(2, 2)
qc_b1.h(0)
qc_b1.cx(0, 1)
qc_b1.draw(output='mpl', style="iqp")
sv = backend.run(qc_b1).result().get_statevector()
sv.draw(output='latex', prefix = "|\Phi^+\\rangle = ")
qc_b2 = QuantumCircuit(2, 2)
qc_b2.x(0)
qc_b2.h(0)
qc_b2.cx(0, 1)
qc_b2.draw(output='mpl', style="iqp")
sv = backend.run(qc_b2).result().get_statevector()
sv.draw(output='latex', prefix = "|\Phi^-\\rangle = ")
qc_b2 = QuantumCircuit(2, 2)
qc_b2.h(0)
qc_b2.cx(0, 1)
qc_b2.z(0)
qc_b2.draw(output='mpl', style="iqp")
sv = backend.run(qc_b2).result().get_statevector()
sv.draw(output='latex', prefix = "|\Phi^-\\rangle = ")
qc_b3 = QuantumCircuit(2, 2)
qc_b3.x(1)
qc_b3.h(0)
qc_b3.cx(0, 1)
qc_b3.draw(output='mpl', style="iqp")
sv = backend.run(qc_b3).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^+\\rangle = ")
qc_b3 = QuantumCircuit(2, 2)
qc_b3.h(0)
qc_b3.cx(0, 1)
qc_b3.x(0)
qc_b3.draw(output='mpl', style="iqp")
sv = backend.run(qc_b3).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^+\\rangle = ")
qc_b4 = QuantumCircuit(2, 2)
qc_b4.x(0)
qc_b4.h(0)
qc_b4.x(1)
qc_b4.cx(0, 1)
qc_b4.draw(output='mpl', style="iqp")
sv = backend.run(qc_b4).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^-\\rangle = ")
qc_b4 = QuantumCircuit(2, 2)
qc_b4.h(0)
qc_b4.cx(0, 1)
qc_b4.x(0)
qc_b4.z(1)
qc_b4.draw(output='mpl', style="iqp")
sv = backend.run(qc_b4).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^-\\rangle = ")
def sv_latex_from_qc(qc, backend):
sv = backend.run(qc).result().get_statevector()
return sv.draw(output='latex')
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(1)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(1)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(1)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(3)
sv_latex_from_qc(qc_ej2, backend)
def circuit_adder (num):
if num<1 or num>8:
raise ValueError("Out of range") ## El enunciado limita el sumador a los valores entre 1 y 8. Quitar esta restricción sería directo.
# Definición del circuito base que vamos a construir
qreg_q = QuantumRegister(4, 'q')
creg_c = ClassicalRegister(1, 'c')
circuit = QuantumCircuit(qreg_q, creg_c)
qbit_position = 0
for element in reversed(np.binary_repr(num)):
if (element=='1'):
circuit.barrier()
match qbit_position:
case 0: # +1
circuit.append(C3XGate(), [qreg_q[0], qreg_q[1], qreg_q[2], qreg_q[3]])
circuit.ccx(qreg_q[0], qreg_q[1], qreg_q[2])
circuit.cx(qreg_q[0], qreg_q[1])
circuit.x(qreg_q[0])
case 1: # +2
circuit.ccx(qreg_q[1], qreg_q[2], qreg_q[3])
circuit.cx(qreg_q[1], qreg_q[2])
circuit.x(qreg_q[1])
case 2: # +4
circuit.cx(qreg_q[2], qreg_q[3])
circuit.x(qreg_q[2])
case 3: # +8
circuit.x(qreg_q[3])
qbit_position+=1
return circuit
add_3 = circuit_adder(3)
add_3.draw(output='mpl', style="iqp")
qc_test_2 = QuantumCircuit(4, 4)
qc_test_2.x(1)
qc_test_2_plus_3 = qc_test_2.compose(add_3)
qc_test_2_plus_3.draw(output='mpl', style="iqp")
sv_latex_from_qc(qc_test_2_plus_3, backend)
qc_test_7 = QuantumCircuit(4, 4)
qc_test_7.x(0)
qc_test_7.x(1)
qc_test_7.x(2)
qc_test_7_plus_8 = qc_test_7.compose(circuit_adder(8))
sv_latex_from_qc(qc_test_7_plus_8, backend)
#qc_test_7_plus_8.draw()
theta = 6.544985
phi = 2.338741
lmbda = 0
alice_1 = 0
alice_2 = 1
bob_1 = 2
qr_alice = QuantumRegister(2, 'Alice')
qr_bob = QuantumRegister(1, 'Bob')
cr = ClassicalRegister(3, 'c')
qc_ej3 = QuantumCircuit(qr_alice, qr_bob, cr)
qc_ej3.barrier(label='1')
qc_ej3.u(theta, phi, lmbda, alice_1);
qc_ej3.barrier(label='2')
qc_ej3.h(alice_2)
qc_ej3.cx(alice_2, bob_1);
qc_ej3.barrier(label='3')
qc_ej3.cx(alice_1, alice_2)
qc_ej3.h(alice_1);
qc_ej3.barrier(label='4')
qc_ej3.measure([alice_1, alice_2], [alice_1, alice_2]);
qc_ej3.barrier(label='5')
qc_ej3.x(bob_1).c_if(alice_2, 1)
qc_ej3.z(bob_1).c_if(alice_1, 1)
qc_ej3.measure(bob_1, bob_1);
qc_ej3.draw(output='mpl', style="iqp")
result = backend.run(qc_ej3, shots=1024).result()
counts = result.get_counts()
plot_histogram(counts)
sv_0 = np.array([1, 0])
sv_1 = np.array([0, 1])
def find_symbolic_representation(value, symbolic_constants={1/np.sqrt(2): '1/√2'}, tolerance=1e-10):
"""
Check if the given numerical value corresponds to a symbolic constant within a specified tolerance.
Parameters:
- value (float): The numerical value to check.
- symbolic_constants (dict): A dictionary mapping numerical values to their symbolic representations.
Defaults to {1/np.sqrt(2): '1/√2'}.
- tolerance (float): Tolerance for comparing values with symbolic constants. Defaults to 1e-10.
Returns:
str or float: If a match is found, returns the symbolic representation as a string
(prefixed with '-' if the value is negative); otherwise, returns the original value.
"""
for constant, symbol in symbolic_constants.items():
if np.isclose(abs(value), constant, atol=tolerance):
return symbol if value >= 0 else '-' + symbol
return value
def array_to_dirac_notation(array, tolerance=1e-10):
"""
Convert a complex-valued array representing a quantum state in superposition
to Dirac notation.
Parameters:
- array (numpy.ndarray): The complex-valued array representing
the quantum state in superposition.
- tolerance (float): Tolerance for considering amplitudes as negligible.
Returns:
str: The Dirac notation representation of the quantum state.
"""
# Ensure the statevector is normalized
array = array / np.linalg.norm(array)
# Get the number of qubits
num_qubits = int(np.log2(len(array)))
# Find indices where amplitude is not negligible
non_zero_indices = np.where(np.abs(array) > tolerance)[0]
# Generate Dirac notation terms
terms = [
(find_symbolic_representation(array[i]), format(i, f"0{num_qubits}b"))
for i in non_zero_indices
]
# Format Dirac notation
dirac_notation = " + ".join([f"{amplitude}|{binary_rep}⟩" for amplitude, binary_rep in terms])
return dirac_notation
def array_to_matrix_representation(array):
"""
Convert a one-dimensional array to a column matrix representation.
Parameters:
- array (numpy.ndarray): The one-dimensional array to be converted.
Returns:
numpy.ndarray: The column matrix representation of the input array.
"""
# Replace symbolic constants with their representations
matrix_representation = np.array([find_symbolic_representation(value) or value for value in array])
# Return the column matrix representation
return matrix_representation.reshape((len(matrix_representation), 1))
def array_to_dirac_and_matrix_latex(array):
"""
Generate LaTeX code for displaying both the matrix representation and Dirac notation
of a quantum state.
Parameters:
- array (numpy.ndarray): The complex-valued array representing the quantum state.
Returns:
Latex: A Latex object containing LaTeX code for displaying both representations.
"""
matrix_representation = array_to_matrix_representation(array)
latex = "Matrix representation\n\\begin{bmatrix}\n" + \
"\\\\\n".join(map(str, matrix_representation.flatten())) + \
"\n\\end{bmatrix}\n"
latex += f'Dirac Notation:\n{array_to_dirac_notation(array)}'
return Latex(latex)
sv_b1 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b1)
sv_b1 = (np.kron(sv_0, sv_0) + np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b1)
sv_b1 = (np.kron(sv_0, sv_0) + np.kron(sv_1, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b1)
sv_b2 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b2 = (np.kron(sv_0, sv_0) + np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b2 = (np.kron(sv_0, sv_0) + np.kron(sv_1, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b2 = (np.kron(sv_0, sv_0) - np.kron(sv_1, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b3 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = np.kron(sv_0, sv_1)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = (np.kron(sv_0, sv_0) - np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = (np.kron(sv_0, sv_1) - np.kron(sv_1, sv_0)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = (np.kron(sv_0, sv_1) + np.kron(sv_1, sv_0)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b4 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b4)
sv_b4 = np.kron(sv_0, sv_1)
array_to_dirac_and_matrix_latex(sv_b4)
sv_b4 = (np.kron(sv_0, sv_0) - np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b4)
sv_b4 = (np.kron(sv_0, sv_1) - np.kron(sv_1, sv_0)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b4)
|
https://github.com/hephaex/Quantum-Computing-Awesome-List
|
hephaex
|
import cirq
import random
def make_quantum_teleportation_circuit(ranX, ranY):
circuit = cirq.Circuit()
msg, alice, bob = cirq.LineQubit.range(3)
## Bell State
circuit.append([cirq.H(alice), cirq.CNOT(alice, bob)])
## Adding random message in message qubit
circuit.append([cirq.X(msg)**ranX, cirq.Y(msg)**ranY])
## Entangling msg and Alice qubits
circuit.append([cirq.CNOT(msg, alice), cirq.H(msg)])
## Measurements
circuit.append([cirq.measure(alice, msg)])
## We use two classical bit from the bell measurement to recover the state of qubit
circuit.append([cirq.CNOT(alice, bob), cirq.CZ(msg, bob)])
return msg, circuit
def main():
## Creating random variable
ranX = random.random()
ranY = random.random()
msg, circuit = make_quantum_teleportation_circuit(ranX, ranY)
## Simulating the circuit
sim = cirq.Simulator()
message = sim.simulate(cirq.Circuit.from_ops([cirq.X(msg)**ranX, cirq.Y(msg)**ranY]))
print("Block Spehere of Alice Qubit")
b0x, b0y, b0z = cirq.bloch_vector_from_state_vector(message.final_state, 0)
print("X: ", round(b0x, 4),
"Y: ", round(b0y, 4),
"Z: ", round(b0z, 4))
print("\n Circuit:")
print(circuit)
final_results = sim.simulate(circuit)
print("\n Block Spehere of Bob's Qubits:")
b2x, b2y, b2z = cirq.bloch_vector_from_state_vector(final_results.final_state, 2)
print("X: ", round(b2x, 4),
"Y: ", round(b2y, 4),
"Z: ", round(b2z, 4))
if __name__ == '__main__':
main()
|
https://github.com/dimple12M/Qiskit-Certification-Guide
|
dimple12M
|
# From IBMQ backends information we know
import qiskit
from qiskit import IBMQ
from qiskit.providers.ibmq import least_busy
from qiskit.tools.jupyter import *
# IBMQ.save_account("Token needs to be provided")
provider = IBMQ.load_account()
%qiskit_backend_overview
backend = provider.get_backend('ibmq_bogota')
backend
%qiskit_version_table
import qiskit
qiskit.__version__
qiskit.__qiskit_version__
%qiskit_job_watcher
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.algorithms.optimizers import SLSQP
from qiskit.circuit.library import TwoLocal
num_qubits = 2
ansatz = TwoLocal(num_qubits, "ry", "cz")
optimizer = SLSQP(maxiter=1000)
ansatz.decompose().draw("mpl", style="iqx")
from qiskit.primitives import Estimator
estimator = Estimator()
from qiskit.algorithms.minimum_eigensolvers import VQE
vqe = VQE(estimator, ansatz, optimizer)
from qiskit.quantum_info import SparsePauliOp
H2_op = SparsePauliOp.from_list([
("II", -1.052373245772859),
("IZ", 0.39793742484318045),
("ZI", -0.39793742484318045),
("ZZ", -0.01128010425623538),
("XX", 0.18093119978423156)
])
result = vqe.compute_minimum_eigenvalue(H2_op)
print(result)
from qiskit.algorithms.optimizers import SPSA
estimator = Estimator(options={"shots": 1000})
vqe.estimator = estimator
vqe.optimizer = SPSA(maxiter=100)
result = vqe.compute_minimum_eigenvalue(operator=H2_op)
print(result)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/we-taper/qiskit-pyzx
|
we-taper
|
from math import pi
import pyzx
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.converters import *
from circuit_translate_main import dag_to_pyzx_circuit, pyzx_circ_to_dag
def optimize(c):
pyzx_graph = c.to_graph()
# Phase 1
pyzx.simplify.full_reduce(pyzx_graph)
# Phase 2
pyzx_circuit = pyzx.extract.streaming_extract(pyzx_graph)
# Phase 3
pyzx_circuit = pyzx_circuit.to_basic_gates()
# Phase 4
try:
# First try including the phase polynomial optimizer
pyzx_circuit = pyzx.optimize.full_optimize(pyzx_circuit)
except TypeError:
# The phase polynomial optimizer only works on Clifford+T circuits.
# Fall back to the basic optimizer
pyzx_circuit = pyzx.optimize.basic_optimization(pyzx_circuit)
# Phase 5
pyzx_circuit = pyzx_circuit.to_basic_gates()
# Phase 6
pyzx_circuit = pyzx_circuit.split_phase_gates()
return pyzx_circuit
q = QuantumRegister(2, 'q')
q_a = QuantumRegister(2, 'a')
c = ClassicalRegister(1, 'c')
circ = QuantumCircuit(q, q_a, c)
# circ.rz(0.1 * pi, q[1])
# circ.cx(q[0], q[1])
# circ.measure(q[0], c[0])
# circ.measure(q[0], c[0])
# circ.measure(q[0], c[0])
# circ.rz(0.2 * pi, q[1])
# circ.cx(q[0], q[1])
# circ.rz(0.3 * pi, q[0])
# circ.x(q[0]).c_if(c, 1)
# circ.rz(0.4 * pi, q[1])
# circ.cx(q[1], q[0])
# circ.h(q_a[0])
# circ.h(q_a[0])
# circ.x(q_a[0])
# circ.rx(pi, q_a[1])
# circ.ry(pi, q_a[1])
# circ.rz(0.1 * pi, q_a[1])
circ.z(q[1])
circ.cx(q[1], q[0])
# circ.measure(q[0], c[0])
circ.reset(q[0])
circ.cx(q[1], q[0])
circ.z(q[1])
print('Before circ')
print(circ.qasm())
dag = circuit_to_dag(circ)
ret = dag_to_pyzx_circuit(dag)
print('pyzx circ (before opt)')
print(ret.circuit.to_qasm())
reduced = optimize(ret.circuit)
print('pyzx circ (after opt)')
print(reduced.to_qasm())
dag_new = pyzx_circ_to_dag(reduced, ret)
print('circ (after opt)')
print(dag_to_circuit(dag_new).qasm())
# =======
# reduced = optimize(ret[0])
# for gate in reduced.gates:
# if isinstance(gate, pyzx.gates.Nonunitary):
# print(gate.stored_data)
# print(reduced.to_qasm())
# >>>>>>> Stashed changes
|
https://github.com/soultanis/Quantum-Database-Search
|
soultanis
|
import grover_test as gt
# Simulator-Backend
# output = gt.build_and_run(3, [1])
# IBMQ-Backend
output = gt.build_and_run(2, [1], real=True, online=True)
print(output)
|
https://github.com/abbarreto/qiskit4
|
abbarreto
|
from sympy import *
init_printing(use_unicode=True)
%matplotlib inline
p00,p01,p10,p11 = symbols('p_{00} p_{01} p_{10} p_{11}')
th,ph = symbols('theta phi')
Psi00 = Matrix([[cos(th)],[0],[0],[sin(th)]])
Psi01 = Matrix([[0],[sin(ph)],[cos(ph)],[0]])
Psi11 = Matrix([[0],[cos(ph)],[-sin(ph)],[0]])
Psi10 = Matrix([[-sin(th)],[0],[0],[cos(th)]])
#Psi00, Psi00.T, Psi00*Psi00.T
rhoX = p00*Psi00*Psi00.T + p01*Psi01*Psi01.T + p10*Psi10*Psi10.T + p11*Psi11*Psi11.T
simplify(rhoX)
def kp(x,y):
return KroneckerProduct(x,y)
I = Matrix([[1,0],[0,1]])
Y = Matrix([[0,-1j],[1j,0]])
Y = Matrix([[0,1],[1,0]])
Z = Matrix([[1,0],[0,-1]])
cxx,cyy,czz,az,bz = symbols('c_{xx} c_{yy} c_{zz} a_{z} b_{z}')
rhoX = (1/4)*(kp(I,I) + cxx*kp(X,X) + cyy*kp(Y,Y) + czz*kp(Z,Z) + az*kp(Z,I) + bz*kp(I,Z))
simplify(rhoX)
th,be,ga = symbols('theta beta gamma')
c00 = cos(th/2)*cos(be/2)*cos(ga/2) + sin(th/2)*sin(be/2)*sin(ga/2)
c01 = cos(th/2)*cos(be/2)*sin(ga/2) - sin(th/2)*sin(be/2)*cos(ga/2)
c10 = cos(th/2)*sin(be/2)*cos(ga/2) - sin(th/2)*cos(be/2)*sin(ga/2)
c11 = cos(th/2)*sin(be/2)*sin(ga/2) + sin(th/2)*cos(be/2)*cos(ga/2)
simplify(c00**2 + c01**2 + c10**2 + c11**2) # ok!
P0 = Matrix([[1,0],[0,0]])
P1 = Matrix([[0,0],[0,1]])
def Ry(th):
return cos(th/2)*I - 1j*sin(th/2)*Y
def Cx_ab():
return KroneckerProduct(P0,I) + KroneckerProduct(P1,X)
def Cx_ba():
return KroneckerProduct(I,P0) + KroneckerProduct(X,P1)
MB = Cx_ab()*KroneckerProduct(Ry(th-ph),I)*Cx_ba()*KroneckerProduct(Ry(th+ph),I) # mudanca de base
simplify(MB)
from qiskit import *
import numpy as np
import math
import qiskit
nshots = 8192
IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibmq_belem')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
# retorna o circuito quantico que prepara um certo estado real de 1 qubit
# coef = array com os 2 coeficientes reais do estado na base computacional
def qc_psi_1qb_real(coef):
qr = QuantumRegister(1)
qc = QuantumCircuit(qr, name='psir_1qb')
th = 2*math.acos(np.abs(coef[0]))
qc.ry(th, qr[0])
return qc
eigvals = [0.1,0.9]
coef = np.sqrt(eigvals)
print(coef)
qc_psi_1qb_real_ = qc_psi_1qb_real(coef)
qc_psi_1qb_real_.draw('mpl')
from qiskit.quantum_info import Statevector
sv = Statevector.from_label('0')
sv
sv = sv.evolve(qc_psi_1qb_real_)
sv
# retorna o circuito quantico que prepara um certo estado real de 2 qubits
# coef = array com os 4 coeficientes reais do estado na base computacional
def qc_psi_2qb_real(coef):
qr = QuantumRegister(2)
qc = QuantumCircuit(qr, name = 'psir_2qb')
xi = 2*math.acos(math.sqrt(coef[0]**2+coef[1]**2))
coef1 = [math.sqrt(coef[0]**2+coef[1]**2),math.sqrt(1-coef[0]**2-coef[1]**2)]
c_psi_1qb_real_ = qc_psi_1qb_real(coef1)
qc.append(c_psi_1qb_real_, [qr[0]])
th0 = 2*math.atan(np.abs(coef[1])/np.abs(coef[0]))
th1 = 2*math.atan(np.abs(coef[3])/np.abs(coef[2]))
qc.x(0)
qc.cry(th0, 0, 1)
qc.x(0)
qc.cry(th1, 0, 1)
return qc
eigvals = [0.1, 0.2, 0.3, 0.4]
coef = np.sqrt(eigvals)
print(coef)
qc_psi_2qb_real_ = qc_psi_2qb_real(coef)
qc_psi_2qb_real_.draw('mpl')
sv = Statevector.from_label('00')
sv
sv = sv.evolve(qc_psi_2qb_real_)
sv # note o ordenamento, o 2º qb é o 1º e o 1º é o 2º (00,10,01,11)
def qc_ry(th):
qr = QuantumRegister(1)
qc = QuantumCircuit(qr, name = 'RY')
qc.ry(th, 0)
return qc
# retorna o circuito quantico que prepara um certo estado real de 3 qubits
# coef = array com os 8 coeficientes reais do estado na base computacional
def qc_psi_3qb_real(coef):
qr = QuantumRegister(3)
qc = QuantumCircuit(qr, name = 'psir_3qb')
d = len(coef)
coef2 = np.zeros(d//2)
th = np.zeros(d//2)
for j in range(0,2):
for k in range(0,2):
coef2[int(str(j)+str(k),2)] = math.sqrt(coef[int(str(j)+str(k)+str(0),2)]**2+coef[int(str(j)+str(k)+str(1),2)]**2)
c_psi_2qb_real_ = qc_psi_2qb_real(coef2)
qc.append(c_psi_2qb_real_, [qr[0],qr[1]])
for j in range(0,2):
for k in range(0,2):
th[int(str(j)+str(k),2)] = 2*math.atan(np.abs(coef[int(str(j)+str(k)+str(1),2)])/np.abs(coef[int(str(j)+str(k)+str(0),2)]))
if j == 0:
qc.x(0)
if k == 0:
qc.x(1)
qc_ry_ = qc_ry(th[int(str(j)+str(k),2)])
ccry = qc_ry_.to_gate().control(2)
qc.append(ccry, [0,1,2])
if j == 0:
qc.x(0)
if k == 0:
qc.x(1)
return qc
list_bin = []
for j in range(0,2**3):
b = "{:03b}".format(j)
list_bin.append(b)
print(list_bin)
eigvals = [0.01,0.1,0.04,0.2,0.05,0.3,0.18,0.12]
coef = np.sqrt(eigvals)
print(coef)
qc_psi_3qb_real_ = qc_psi_3qb_real(coef)
qc_psi_3qb_real_.draw('mpl') # odernamento: '000', '001', '010', '011', '100', '101', '110', '111'
sv = Statevector.from_label('000')
sv
sv = sv.evolve(qc_psi_3qb_real_)
sv # ordenamento aqui: 000 100 010 110 001 101 011 111
# retorna o circuito quantico que prepara um certo estado real de 4 qubits
# coef = array com os 16 coeficientes reais do estado na base computacional
def qc_psi_4qb_real(coef):
qr = QuantumRegister(4)
qc = QuantumCircuit(qr, name = 'psir_4qb')
d = len(coef)
coef3 = np.zeros(d//2)
th = np.zeros(d//2)
for j in range(0,2):
for k in range(0,2):
for l in range(0,2):
coef3[int(str(j)+str(k)+str(l),2)] = math.sqrt(coef[int(str(j)+str(k)+str(l)+str(0),2)]**2+coef[int(str(j)+str(k)+str(l)+str(1),2)]**2)
c_psi_3qb_real_ = qc_psi_3qb_real(coef3)
qc.append(c_psi_3qb_real_, [qr[0],qr[1],qr[2]])
for j in range(0,2):
for k in range(0,2):
for l in range(0,2):
th[int(str(j)+str(k)+str(l),2)] = 2*math.atan(np.abs(coef[int(str(j)+str(k)+str(l)+str(1),2)])/np.abs(coef[int(str(j)+str(k)+str(l)+str(0),2)]))
if j == 0:
qc.x(0)
if k == 0:
qc.x(1)
if l == 0:
qc.x(2)
qc_ry_ = qc_ry(th[int(str(j)+str(k)+str(l),2)])
ccry = qc_ry_.to_gate().control(3)
qc.append(ccry, [0,1,2,3])
if j == 0:
qc.x(0)
if k == 0:
qc.x(1)
if l == 0:
qc.x(2)
return qc
list_bin = []
for j in range(0,2**4):
b = "{:04b}".format(j)
list_bin.append(b)
print(list_bin)
eigvals = np.zeros(2**4)
eigvals[0] = 0.008
for j in range(1,len(eigvals)-1):
eigvals[j] = eigvals[j-1]+0.005
#print(np.sum(eigvals))
eigvals[j+1] = 1 - np.sum(eigvals)
#print(eigvals)
#print(np.sum(eigvals))
coef = np.sqrt(eigvals)
print(coef)
qc_psi_4qb_real_ = qc_psi_4qb_real(coef)
qc_psi_4qb_real_.draw('mpl')
# '0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111'
sv = Statevector.from_label('0000')
sv
sv = sv.evolve(qc_psi_4qb_real_)
sv # ordenamento aqui: 0000 1000 0100 1100 0010 1010 0110 1110 0001 1001 0101 1101 0011 1011 0111 1111
sv[1]
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeBoeblingen
backend = FakeBoeblingen()
ghz = QuantumCircuit(5)
ghz.h(0)
ghz.cx(0,range(1,5))
circ = transpile(ghz, backend, scheduling_method="asap")
circ.draw(output='mpl')
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test functionality to collect, split and consolidate blocks from DAGCircuits."""
import unittest
from qiskit import QuantumRegister, ClassicalRegister
from qiskit.converters import (
circuit_to_dag,
circuit_to_dagdependency,
circuit_to_instruction,
dag_to_circuit,
dagdependency_to_circuit,
)
from qiskit.test import QiskitTestCase
from qiskit.circuit import QuantumCircuit, Measure, Clbit
from qiskit.dagcircuit.collect_blocks import BlockCollector, BlockSplitter, BlockCollapser
class TestCollectBlocks(QiskitTestCase):
"""Tests to verify correctness of collecting, splitting, and consolidating blocks
from DAGCircuit and DAGDependency. Additional tests appear as a part of
CollectLinearFunctions and CollectCliffords passes.
"""
def test_collect_gates_from_dagcircuit_1(self):
"""Test collecting CX gates from DAGCircuits."""
qc = QuantumCircuit(5)
qc.cx(0, 1)
qc.cx(0, 2)
qc.z(0)
qc.cx(0, 3)
qc.cx(0, 4)
block_collector = BlockCollector(circuit_to_dag(qc))
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name == "cx",
split_blocks=False,
min_block_size=2,
)
# The middle z-gate leads to two blocks of size 2 each
self.assertEqual(len(blocks), 2)
self.assertEqual(len(blocks[0]), 2)
self.assertEqual(len(blocks[1]), 2)
def test_collect_gates_from_dagcircuit_2(self):
"""Test collecting both CX and Z gates from DAGCircuits."""
qc = QuantumCircuit(5)
qc.cx(0, 1)
qc.cx(0, 2)
qc.z(0)
qc.cx(0, 3)
qc.cx(0, 4)
block_collector = BlockCollector(circuit_to_dag(qc))
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["cx", "z"],
split_blocks=False,
min_block_size=1,
)
# All of the gates are part of a single block
self.assertEqual(len(blocks), 1)
self.assertEqual(len(blocks[0]), 5)
def test_collect_gates_from_dagcircuit_3(self):
"""Test collecting CX gates from DAGCircuits."""
qc = QuantumCircuit(5)
qc.cx(0, 1)
qc.cx(0, 2)
qc.z(0)
qc.cx(1, 3)
qc.cx(0, 3)
qc.cx(0, 4)
block_collector = BlockCollector(circuit_to_dag(qc))
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["cx"],
split_blocks=False,
min_block_size=1,
)
# We should end up with two CX blocks: even though there is "a path
# around z(0)", without commutativity analysis z(0) prevents from
# including all CX-gates into the same block
self.assertEqual(len(blocks), 2)
def test_collect_gates_from_dagdependency_1(self):
"""Test collecting CX gates from DAGDependency."""
qc = QuantumCircuit(5)
qc.cx(0, 1)
qc.cx(0, 2)
qc.z(0)
qc.cx(0, 3)
qc.cx(0, 4)
block_collector = BlockCollector(circuit_to_dagdependency(qc))
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name == "cx",
split_blocks=False,
min_block_size=1,
)
# The middle z-gate commutes with CX-gates, which leads to a single block of length 4
self.assertEqual(len(blocks), 1)
self.assertEqual(len(blocks[0]), 4)
def test_collect_gates_from_dagdependency_2(self):
"""Test collecting both CX and Z gates from DAGDependency."""
qc = QuantumCircuit(5)
qc.cx(0, 1)
qc.cx(0, 2)
qc.z(0)
qc.cx(0, 3)
qc.cx(0, 4)
block_collector = BlockCollector(circuit_to_dagdependency(qc))
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["cx", "z"],
split_blocks=False,
min_block_size=1,
)
# All the gates are part of a single block
self.assertEqual(len(blocks), 1)
self.assertEqual(len(blocks[0]), 5)
def test_collect_and_split_gates_from_dagcircuit(self):
"""Test collecting and splitting blocks from DAGCircuit."""
qc = QuantumCircuit(6)
qc.cx(0, 1)
qc.cx(3, 5)
qc.cx(2, 4)
qc.swap(1, 0)
qc.cz(5, 3)
block_collector = BlockCollector(circuit_to_dag(qc))
blocks = block_collector.collect_all_matching_blocks(
lambda node: True,
split_blocks=False,
min_block_size=1,
)
# All the gates are part of a single block
self.assertEqual(len(blocks), 1)
self.assertEqual(len(blocks[0]), 5)
# Split the first block into sub-blocks over disjoint qubit sets
# We should get 3 sub-blocks
split_blocks = BlockSplitter().run(blocks[0])
self.assertEqual(len(split_blocks), 3)
def test_collect_and_split_gates_from_dagdependency(self):
"""Test collecting and splitting blocks from DAGDependecy."""
qc = QuantumCircuit(6)
qc.cx(0, 1)
qc.cx(3, 5)
qc.cx(2, 4)
qc.swap(1, 0)
qc.cz(5, 3)
block_collector = BlockCollector(circuit_to_dagdependency(qc))
blocks = block_collector.collect_all_matching_blocks(
lambda node: True,
split_blocks=False,
min_block_size=1,
)
# All the gates are part of a single block
self.assertEqual(len(blocks), 1)
self.assertEqual(len(blocks[0]), 5)
# Split the first block into sub-blocks over disjoint qubit sets
# We should get 3 sub-blocks
split_blocks = BlockSplitter().run(blocks[0])
self.assertEqual(len(split_blocks), 3)
def test_circuit_has_measure(self):
"""Test that block collection works properly when there is a measure in the
middle of the circuit."""
qc = QuantumCircuit(2, 1)
qc.cx(1, 0)
qc.x(0)
qc.x(1)
qc.measure(0, 0)
qc.x(0)
qc.cx(1, 0)
block_collector = BlockCollector(circuit_to_dag(qc))
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["x", "cx"],
split_blocks=False,
min_block_size=1,
)
# measure prevents combining the two blocks
self.assertEqual(len(blocks), 2)
self.assertEqual(len(blocks[0]), 3)
self.assertEqual(len(blocks[1]), 2)
def test_circuit_has_measure_dagdependency(self):
"""Test that block collection works properly when there is a measure in the
middle of the circuit."""
qc = QuantumCircuit(2, 1)
qc.cx(1, 0)
qc.x(0)
qc.x(1)
qc.measure(0, 0)
qc.x(0)
qc.cx(1, 0)
block_collector = BlockCollector(circuit_to_dagdependency(qc))
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["x", "cx"],
split_blocks=False,
min_block_size=1,
)
# measure prevents combining the two blocks
self.assertEqual(len(blocks), 2)
self.assertEqual(len(blocks[0]), 3)
self.assertEqual(len(blocks[1]), 2)
def test_circuit_has_conditional_gates(self):
"""Test that block collection works properly when there the circuit
contains conditional gates."""
qc = QuantumCircuit(2, 1)
qc.x(0)
qc.x(1)
qc.cx(1, 0)
qc.x(1).c_if(0, 1)
qc.x(0)
qc.x(1)
qc.cx(0, 1)
# If the filter_function does not look at conditions, we should collect all
# gates into the block.
block_collector = BlockCollector(circuit_to_dag(qc))
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["x", "cx"],
split_blocks=False,
min_block_size=1,
)
self.assertEqual(len(blocks), 1)
self.assertEqual(len(blocks[0]), 7)
# If the filter_function does look at conditions, we should not collect the middle
# conditional gate (note that x(1) following the measure is collected into the first
# block).
block_collector = BlockCollector(circuit_to_dag(qc))
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["x", "cx"] and not getattr(node.op, "condition", None),
split_blocks=False,
min_block_size=1,
)
self.assertEqual(len(blocks), 2)
self.assertEqual(len(blocks[0]), 4)
self.assertEqual(len(blocks[1]), 2)
def test_circuit_has_conditional_gates_dagdependency(self):
"""Test that block collection works properly when there the circuit
contains conditional gates."""
qc = QuantumCircuit(2, 1)
qc.x(0)
qc.x(1)
qc.cx(1, 0)
qc.x(1).c_if(0, 1)
qc.x(0)
qc.x(1)
qc.cx(0, 1)
# If the filter_function does not look at conditions, we should collect all
# gates into the block.
block_collector = BlockCollector(circuit_to_dagdependency(qc))
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["x", "cx"],
split_blocks=False,
min_block_size=1,
)
self.assertEqual(len(blocks), 1)
self.assertEqual(len(blocks[0]), 7)
# If the filter_function does look at conditions, we should not collect the middle
# conditional gate (note that x(1) following the measure is collected into the first
# block).
block_collector = BlockCollector(circuit_to_dag(qc))
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["x", "cx"] and not getattr(node.op, "condition", None),
split_blocks=False,
min_block_size=1,
)
self.assertEqual(len(blocks), 2)
self.assertEqual(len(blocks[0]), 4)
self.assertEqual(len(blocks[1]), 2)
def test_multiple_collection_methods(self):
"""Test that block collection allows to collect blocks using several different
filter functions."""
qc = QuantumCircuit(5)
qc.cx(0, 1)
qc.cx(0, 2)
qc.swap(1, 4)
qc.swap(4, 3)
qc.z(0)
qc.z(1)
qc.z(2)
qc.z(3)
qc.z(4)
qc.swap(3, 4)
qc.cx(0, 3)
qc.cx(0, 4)
block_collector = BlockCollector(circuit_to_dag(qc))
linear_blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["cx", "swap"],
split_blocks=False,
min_block_size=1,
)
cx_blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["cx"],
split_blocks=False,
min_block_size=1,
)
swapz_blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["swap", "z"],
split_blocks=False,
min_block_size=1,
)
# We should end up with two linear blocks
self.assertEqual(len(linear_blocks), 2)
self.assertEqual(len(linear_blocks[0]), 4)
self.assertEqual(len(linear_blocks[1]), 3)
# We should end up with two cx blocks
self.assertEqual(len(cx_blocks), 2)
self.assertEqual(len(cx_blocks[0]), 2)
self.assertEqual(len(cx_blocks[1]), 2)
# We should end up with one swap,z blocks
self.assertEqual(len(swapz_blocks), 1)
self.assertEqual(len(swapz_blocks[0]), 8)
def test_min_block_size(self):
"""Test that the option min_block_size for collecting blocks works correctly."""
# original circuit
circuit = QuantumCircuit(2)
circuit.cx(0, 1)
circuit.h(0)
circuit.cx(0, 1)
circuit.cx(1, 0)
circuit.h(0)
circuit.cx(0, 1)
circuit.cx(1, 0)
circuit.cx(0, 1)
block_collector = BlockCollector(circuit_to_dag(circuit))
# When min_block_size = 1, we should obtain 3 linear blocks
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["cx", "swap"],
split_blocks=False,
min_block_size=1,
)
self.assertEqual(len(blocks), 3)
# When min_block_size = 2, we should obtain 2 linear blocks
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["cx", "swap"],
split_blocks=False,
min_block_size=2,
)
self.assertEqual(len(blocks), 2)
# When min_block_size = 3, we should obtain 1 linear block
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["cx", "swap"],
split_blocks=False,
min_block_size=3,
)
self.assertEqual(len(blocks), 1)
# When min_block_size = 4, we should obtain no linear blocks
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["cx", "swap"],
split_blocks=False,
min_block_size=4,
)
self.assertEqual(len(blocks), 0)
def test_split_blocks(self):
"""Test that splitting blocks of nodes into sub-blocks works correctly."""
# original circuit is linear
circuit = QuantumCircuit(5)
circuit.cx(0, 2)
circuit.cx(1, 4)
circuit.cx(2, 0)
circuit.cx(0, 3)
circuit.swap(3, 2)
circuit.swap(4, 1)
block_collector = BlockCollector(circuit_to_dag(circuit))
# If we do not split block into sub-blocks, we expect a single linear block.
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["cx", "swap"],
split_blocks=False,
min_block_size=2,
)
self.assertEqual(len(blocks), 1)
# If we do split block into sub-blocks, we expect two linear blocks:
# one over qubits {0, 2, 3}, and another over qubits {1, 4}.
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["cx", "swap"],
split_blocks=True,
min_block_size=2,
)
self.assertEqual(len(blocks), 2)
def test_do_not_split_blocks(self):
"""Test that splitting blocks of nodes into sub-blocks works correctly."""
# original circuit is linear
circuit = QuantumCircuit(5)
circuit.cx(0, 3)
circuit.cx(0, 2)
circuit.cx(1, 4)
circuit.swap(4, 2)
block_collector = BlockCollector(circuit_to_dagdependency(circuit))
# Check that we have a single linear block
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["cx", "swap"],
split_blocks=True,
min_block_size=1,
)
self.assertEqual(len(blocks), 1)
def test_collect_blocks_with_cargs(self):
"""Test collecting and collapsing blocks with classical bits appearing as cargs."""
qc = QuantumCircuit(3)
qc.h(0)
qc.h(1)
qc.h(2)
qc.measure_all()
dag = circuit_to_dag(qc)
# Collect all measure instructions
blocks = BlockCollector(dag).collect_all_matching_blocks(
lambda node: isinstance(node.op, Measure), split_blocks=False, min_block_size=1
)
# We should have a single block consisting of 3 measures
self.assertEqual(len(blocks), 1)
self.assertEqual(len(blocks[0]), 3)
self.assertEqual(blocks[0][0].op, Measure())
self.assertEqual(blocks[0][1].op, Measure())
self.assertEqual(blocks[0][2].op, Measure())
def _collapse_fn(circuit):
op = circuit_to_instruction(circuit)
op.name = "COLLAPSED"
return op
# Collapse block with measures into a single "COLLAPSED" block
dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn)
collapsed_qc = dag_to_circuit(dag)
self.assertEqual(len(collapsed_qc.data), 5)
self.assertEqual(collapsed_qc.data[0].operation.name, "h")
self.assertEqual(collapsed_qc.data[1].operation.name, "h")
self.assertEqual(collapsed_qc.data[2].operation.name, "h")
self.assertEqual(collapsed_qc.data[3].operation.name, "barrier")
self.assertEqual(collapsed_qc.data[4].operation.name, "COLLAPSED")
self.assertEqual(collapsed_qc.data[4].operation.definition.num_qubits, 3)
self.assertEqual(collapsed_qc.data[4].operation.definition.num_clbits, 3)
def test_collect_blocks_with_cargs_dagdependency(self):
"""Test collecting and collapsing blocks with classical bits appearing as cargs,
using DAGDependency."""
qc = QuantumCircuit(3)
qc.h(0)
qc.h(1)
qc.h(2)
qc.measure_all()
dag = circuit_to_dagdependency(qc)
# Collect all measure instructions
blocks = BlockCollector(dag).collect_all_matching_blocks(
lambda node: isinstance(node.op, Measure), split_blocks=False, min_block_size=1
)
# We should have a single block consisting of 3 measures
self.assertEqual(len(blocks), 1)
self.assertEqual(len(blocks[0]), 3)
self.assertEqual(blocks[0][0].op, Measure())
self.assertEqual(blocks[0][1].op, Measure())
self.assertEqual(blocks[0][2].op, Measure())
def _collapse_fn(circuit):
op = circuit_to_instruction(circuit)
op.name = "COLLAPSED"
return op
# Collapse block with measures into a single "COLLAPSED" block
dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn)
collapsed_qc = dagdependency_to_circuit(dag)
self.assertEqual(len(collapsed_qc.data), 5)
self.assertEqual(collapsed_qc.data[0].operation.name, "h")
self.assertEqual(collapsed_qc.data[1].operation.name, "h")
self.assertEqual(collapsed_qc.data[2].operation.name, "h")
self.assertEqual(collapsed_qc.data[3].operation.name, "barrier")
self.assertEqual(collapsed_qc.data[4].operation.name, "COLLAPSED")
self.assertEqual(collapsed_qc.data[4].operation.definition.num_qubits, 3)
self.assertEqual(collapsed_qc.data[4].operation.definition.num_clbits, 3)
def test_collect_blocks_with_clbits(self):
"""Test collecting and collapsing blocks with classical bits appearing under
condition."""
qc = QuantumCircuit(4, 3)
qc.cx(0, 1).c_if(0, 1)
qc.cx(2, 3)
qc.cx(1, 2)
qc.cx(0, 1)
qc.cx(2, 3).c_if(1, 0)
dag = circuit_to_dag(qc)
# Collect all cx gates (including the conditional ones)
blocks = BlockCollector(dag).collect_all_matching_blocks(
lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1
)
# We should have a single block consisting of all CX nodes
self.assertEqual(len(blocks), 1)
self.assertEqual(len(blocks[0]), 5)
def _collapse_fn(circuit):
op = circuit_to_instruction(circuit)
op.name = "COLLAPSED"
return op
# Collapse block with measures into a single "COLLAPSED" block
dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn)
collapsed_qc = dag_to_circuit(dag)
self.assertEqual(len(collapsed_qc.data), 1)
self.assertEqual(collapsed_qc.data[0].operation.name, "COLLAPSED")
self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 4)
self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 2)
def test_collect_blocks_with_clbits_dagdependency(self):
"""Test collecting and collapsing blocks with classical bits appearing
under conditions, using DAGDependency."""
qc = QuantumCircuit(4, 3)
qc.cx(0, 1).c_if(0, 1)
qc.cx(2, 3)
qc.cx(1, 2)
qc.cx(0, 1)
qc.cx(2, 3).c_if(1, 0)
dag = circuit_to_dagdependency(qc)
# Collect all cx gates (including the conditional ones)
blocks = BlockCollector(dag).collect_all_matching_blocks(
lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1
)
# We should have a single block consisting of all CX nodes
self.assertEqual(len(blocks), 1)
self.assertEqual(len(blocks[0]), 5)
def _collapse_fn(circuit):
op = circuit_to_instruction(circuit)
op.name = "COLLAPSED"
return op
# Collapse block with measures into a single "COLLAPSED" block
dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn)
collapsed_qc = dagdependency_to_circuit(dag)
self.assertEqual(len(collapsed_qc.data), 1)
self.assertEqual(collapsed_qc.data[0].operation.name, "COLLAPSED")
self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 4)
self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 2)
def test_collect_blocks_with_clbits2(self):
"""Test collecting and collapsing blocks with classical bits appearing under
condition."""
qreg = QuantumRegister(4, "qr")
creg = ClassicalRegister(3, "cr")
cbit = Clbit()
qc = QuantumCircuit(qreg, creg, [cbit])
qc.cx(0, 1).c_if(creg[1], 1)
qc.cx(2, 3).c_if(cbit, 0)
qc.cx(1, 2)
qc.cx(0, 1).c_if(creg[2], 1)
dag = circuit_to_dag(qc)
# Collect all cx gates (including the conditional ones)
blocks = BlockCollector(dag).collect_all_matching_blocks(
lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1
)
# We should have a single block consisting of all CX nodes
self.assertEqual(len(blocks), 1)
self.assertEqual(len(blocks[0]), 4)
def _collapse_fn(circuit):
op = circuit_to_instruction(circuit)
op.name = "COLLAPSED"
return op
# Collapse block with measures into a single "COLLAPSED" block
dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn)
collapsed_qc = dag_to_circuit(dag)
self.assertEqual(len(collapsed_qc.data), 1)
self.assertEqual(collapsed_qc.data[0].operation.name, "COLLAPSED")
self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 4)
self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 3)
def test_collect_blocks_with_clbits2_dagdependency(self):
"""Test collecting and collapsing blocks with classical bits appearing under
condition, using DAGDependency."""
qreg = QuantumRegister(4, "qr")
creg = ClassicalRegister(3, "cr")
cbit = Clbit()
qc = QuantumCircuit(qreg, creg, [cbit])
qc.cx(0, 1).c_if(creg[1], 1)
qc.cx(2, 3).c_if(cbit, 0)
qc.cx(1, 2)
qc.cx(0, 1).c_if(creg[2], 1)
dag = circuit_to_dag(qc)
# Collect all cx gates (including the conditional ones)
blocks = BlockCollector(dag).collect_all_matching_blocks(
lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1
)
# We should have a single block consisting of all CX nodes
self.assertEqual(len(blocks), 1)
self.assertEqual(len(blocks[0]), 4)
def _collapse_fn(circuit):
op = circuit_to_instruction(circuit)
op.name = "COLLAPSED"
return op
# Collapse block with measures into a single "COLLAPSED" block
dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn)
collapsed_qc = dag_to_circuit(dag)
self.assertEqual(len(collapsed_qc.data), 1)
self.assertEqual(collapsed_qc.data[0].operation.name, "COLLAPSED")
self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 4)
self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 3)
def test_collect_blocks_with_cregs(self):
"""Test collecting and collapsing blocks with classical registers appearing under
condition."""
qreg = QuantumRegister(4, "qr")
creg = ClassicalRegister(3, "cr")
creg2 = ClassicalRegister(2, "cr2")
qc = QuantumCircuit(qreg, creg, creg2)
qc.cx(0, 1).c_if(creg, 3)
qc.cx(1, 2)
qc.cx(0, 1).c_if(creg[2], 1)
dag = circuit_to_dag(qc)
# Collect all cx gates (including the conditional ones)
blocks = BlockCollector(dag).collect_all_matching_blocks(
lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1
)
# We should have a single block consisting of all CX nodes
self.assertEqual(len(blocks), 1)
self.assertEqual(len(blocks[0]), 3)
def _collapse_fn(circuit):
op = circuit_to_instruction(circuit)
op.name = "COLLAPSED"
return op
# Collapse block with measures into a single "COLLAPSED" block
dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn)
collapsed_qc = dag_to_circuit(dag)
self.assertEqual(len(collapsed_qc.data), 1)
self.assertEqual(collapsed_qc.data[0].operation.name, "COLLAPSED")
self.assertEqual(len(collapsed_qc.data[0].operation.definition.cregs), 1)
self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 3)
self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 3)
def test_collect_blocks_with_cregs_dagdependency(self):
"""Test collecting and collapsing blocks with classical registers appearing under
condition, using DAGDependency."""
qreg = QuantumRegister(4, "qr")
creg = ClassicalRegister(3, "cr")
creg2 = ClassicalRegister(2, "cr2")
qc = QuantumCircuit(qreg, creg, creg2)
qc.cx(0, 1).c_if(creg, 3)
qc.cx(1, 2)
qc.cx(0, 1).c_if(creg[2], 1)
dag = circuit_to_dagdependency(qc)
# Collect all cx gates (including the conditional ones)
blocks = BlockCollector(dag).collect_all_matching_blocks(
lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1
)
# We should have a single block consisting of all CX nodes
self.assertEqual(len(blocks), 1)
self.assertEqual(len(blocks[0]), 3)
def _collapse_fn(circuit):
op = circuit_to_instruction(circuit)
op.name = "COLLAPSED"
return op
# Collapse block with measures into a single "COLLAPSED" block
dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn)
collapsed_qc = dagdependency_to_circuit(dag)
self.assertEqual(len(collapsed_qc.data), 1)
self.assertEqual(collapsed_qc.data[0].operation.name, "COLLAPSED")
self.assertEqual(len(collapsed_qc.data[0].operation.definition.cregs), 1)
self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 3)
self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 3)
def test_collect_blocks_backwards_dagcircuit(self):
"""Test collecting H gates from DAGCircuit in the forward vs. the reverse
directions."""
qc = QuantumCircuit(4)
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
qc.cx(1, 2)
qc.z(0)
qc.z(1)
qc.z(2)
qc.z(3)
block_collector = BlockCollector(circuit_to_dag(qc))
# When collecting in the forward direction, there are two blocks of
# single-qubit gates: the first of size 6, and the second of size 2.
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["h", "z"],
split_blocks=False,
min_block_size=1,
collect_from_back=False,
)
self.assertEqual(len(blocks), 2)
self.assertEqual(len(blocks[0]), 6)
self.assertEqual(len(blocks[1]), 2)
# When collecting in the backward direction, there are also two blocks of
# single-qubit ates: but now the first is of size 2, and the second is of size 6.
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["h", "z"],
split_blocks=False,
min_block_size=1,
collect_from_back=True,
)
self.assertEqual(len(blocks), 2)
self.assertEqual(len(blocks[0]), 2)
self.assertEqual(len(blocks[1]), 6)
def test_collect_blocks_backwards_dagdependency(self):
"""Test collecting H gates from DAGDependency in the forward vs. the reverse
directions."""
qc = QuantumCircuit(4)
qc.z(0)
qc.z(1)
qc.z(2)
qc.z(3)
qc.cx(1, 2)
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
block_collector = BlockCollector(circuit_to_dagdependency(qc))
# When collecting in the forward direction, there are two blocks of
# single-qubit gates: the first of size 6, and the second of size 2.
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["h", "z"],
split_blocks=False,
min_block_size=1,
collect_from_back=False,
)
self.assertEqual(len(blocks), 2)
self.assertEqual(len(blocks[0]), 6)
self.assertEqual(len(blocks[1]), 2)
# When collecting in the backward direction, there are also two blocks of
# single-qubit ates: but now the first is of size 1, and the second is of size 7
# (note that z(1) and CX(1, 2) commute).
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["h", "z"],
split_blocks=False,
min_block_size=1,
collect_from_back=True,
)
self.assertEqual(len(blocks), 2)
self.assertEqual(len(blocks[0]), 1)
self.assertEqual(len(blocks[1]), 7)
def test_split_layers_dagcircuit(self):
"""Test that splitting blocks of nodes into layers works correctly."""
# original circuit is linear
circuit = QuantumCircuit(5)
circuit.cx(0, 2)
circuit.cx(1, 4)
circuit.cx(2, 0)
circuit.cx(0, 3)
circuit.swap(3, 2)
circuit.swap(4, 1)
block_collector = BlockCollector(circuit_to_dag(circuit))
# If we split the gates into depth-1 layers, we expect four linear blocks:
# CX(0, 2), CX(1, 4)
# CX(2, 0), CX(4, 1)
# CX(0, 3)
# CX(3, 2)
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["cx", "swap"],
split_blocks=False,
min_block_size=1,
split_layers=True,
)
self.assertEqual(len(blocks), 4)
self.assertEqual(len(blocks[0]), 2)
self.assertEqual(len(blocks[1]), 2)
self.assertEqual(len(blocks[2]), 1)
self.assertEqual(len(blocks[3]), 1)
def test_split_layers_dagdependency(self):
"""Test that splitting blocks of nodes into layers works correctly."""
# original circuit is linear
circuit = QuantumCircuit(5)
circuit.cx(0, 2)
circuit.cx(1, 4)
circuit.cx(2, 0)
circuit.cx(0, 3)
circuit.swap(3, 2)
circuit.swap(4, 1)
block_collector = BlockCollector(circuit_to_dagdependency(circuit))
# If we split the gates into depth-1 layers, we expect four linear blocks:
# CX(0, 2), CX(1, 4)
# CX(2, 0), CX(4, 1)
# CX(0, 3)
# CX(3, 2)
blocks = block_collector.collect_all_matching_blocks(
lambda node: node.op.name in ["cx", "swap"],
split_blocks=False,
min_block_size=1,
split_layers=True,
)
self.assertEqual(len(blocks), 4)
self.assertEqual(len(blocks[0]), 2)
self.assertEqual(len(blocks[1]), 2)
self.assertEqual(len(blocks[2]), 1)
self.assertEqual(len(blocks[3]), 1)
if __name__ == "__main__":
unittest.main()
|
https://github.com/HuangJunye/Qiskit-for-GameDev
|
HuangJunye
|
import sys
sys.path.append('/Users/kirais/Documents/GitHub/Qiskit-for-GameDev/pygame/')
from qgame import CircuitGridModel, CircuitGridNode
from qgame import circuit_node_types as node_types
from qiskit import QuantumCircuit
circuit_grid_model = CircuitGridModel(qubit_count=3, circuit_depth=6)
print(circuit_grid_model)
qasm_str = circuit_grid_model.create_qasm_for_circuit()
print(qasm_str)
circuit = QuantumCircuit.from_qasm_str(qasm_str)
circuit.draw()
print(CircuitGridNode(node_types.X))
circuit_grid_model.set_node(qubit_index=1,depth_index=0,circuit_grid_node=CircuitGridNode(node_types.X))
print(circuit_grid_model)
qasm_str = circuit_grid_model.create_qasm_for_circuit()
print(qasm_str)
circuit = QuantumCircuit.from_qasm_str(qasm_str)
circuit.draw()
circuit_grid_model.set_node(0,1,CircuitGridNode(node_types.H))
circuit_grid_model.set_node(2,1,CircuitGridNode(node_types.H))
print(circuit_grid_model)
qasm_str = circuit_grid_model.create_qasm_for_circuit()
print(qasm_str)
circuit = QuantumCircuit.from_qasm_str(qasm_str)
circuit.draw()
from qiskit import BasicAer, execute, ClassicalRegister
def paddle_before_measurement(circuit, qubit_num, shot_num):
backend_sv_sim = BasicAer.get_backend('statevector_simulator')
job_sim = execute(circuit, backend_sv_sim, shots=shot_num)
result_sim = job_sim.result()
state = result_sim.get_statevector(circuit, decimals=3)
probability = (state*state).real
return probability
probability = paddle_before_measurement(circuit, 3, 1000)
print(probability)
from matplotlib import pyplot as plt
from matplotlib.patches import Rectangle
plt.figure(figsize=(20,1))
ax = plt.gca()
for i in range(8):
ax.add_patch(Rectangle((i/8, 0), 1/8, 1, alpha=probability[i]+0.05, fc='k', ec='k'))
# add statvector labels
ax.text(0/8+1/40,-1,r"$\left|000\right\rangle$", fontsize=36)
ax.text(1/8+1/40,-1,r"$\left|001\right\rangle$", fontsize=36)
ax.text(2/8+1/40,-1,r"$\left|010\right\rangle$", fontsize=36)
ax.text(3/8+1/40,-1,r"$\left|011\right\rangle$", fontsize=36)
ax.text(4/8+1/40,-1,r"$\left|100\right\rangle$", fontsize=36)
ax.text(5/8+1/40,-1,r"$\left|101\right\rangle$", fontsize=36)
ax.text(6/8+1/40,-1,r"$\left|110\right\rangle$", fontsize=36)
ax.text(7/8+1/40,-1,r"$\left|110\right\rangle$", fontsize=36)
plt.axis('off')
plt.show()
from copy import deepcopy
def paddle_after_measurement(circuit, qubit_num, shot_num):
backend_sv_sim = BasicAer.get_backend('qasm_simulator')
circuit.measure(circuit.qregs[0], circuit.cregs[0])
job_sim = execute(circuit, backend_sv_sim, shots=shot_num)
result_sim = job_sim.result()
counts = result_sim.get_counts(circuit)
return int(list(counts.keys())[0], 2)
result = paddle_after_measurement(circuit, 3, 100)
print(result)
from matplotlib import pyplot as plt
from matplotlib.patches import Rectangle
plt.figure(figsize=(20,1))
ax = plt.gca()
for i in range(8):
if i == result:
ax.add_patch(Rectangle((i/8, 0), 1/8, 1, alpha=1, fc='k', ec='k'))
else:
ax.add_patch(Rectangle((i/8, 0), 1/8, 1, alpha=0, fc='k', ec='k'))
# add statvector labels
ax.text(0/8+1/40,-1,r"$\left|000\right\rangle$", fontsize=36)
ax.text(1/8+1/40,-1,r"$\left|001\right\rangle$", fontsize=36)
ax.text(2/8+1/40,-1,r"$\left|010\right\rangle$", fontsize=36)
ax.text(3/8+1/40,-1,r"$\left|011\right\rangle$", fontsize=36)
ax.text(4/8+1/40,-1,r"$\left|100\right\rangle$", fontsize=36)
ax.text(5/8+1/40,-1,r"$\left|101\right\rangle$", fontsize=36)
ax.text(6/8+1/40,-1,r"$\left|110\right\rangle$", fontsize=36)
ax.text(7/8+1/40,-1,r"$\left|110\right\rangle$", fontsize=36)
plt.axis('off')
plt.show()
|
https://github.com/rodolfocarobene/SPVQE
|
rodolfocarobene
|
import itertools
import warnings
import numpy as np
import PySimpleGUI as psg
from qiskit import IBMQ, Aer
from qiskit.algorithms.optimizers import ADAM, CG, COBYLA, L_BFGS_B, NFT, SPSA
from qiskit.ignis.mitigation import CompleteMeasFitter
from qiskit.providers.aer import QasmSimulator
from qiskit.providers.aer.noise import NoiseModel
from qiskit.utils import QuantumInstance
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import ParityMapper
warnings.simplefilter("ignore")
def get_default_opt():
print("Loading default values")
values = {
"molecule": "H3+",
"spin": 0,
"charge": 0,
"basis": ["sto-6g"],
"varforms": ["TwoLocal"],
"backend": ["hardware"],
"noise": ["None"],
"shots": 2048,
"correction": ["False"],
"optimizer": ["SPSA"],
"dist_min": 1.4,
"dist_max": 3.5,
"dist_delta": 11,
"lagrangiana": ["True", "Series"],
"lag_op": ["spin-squared"],
"lag_value_num": 2,
"lag_mult_num_min": 1,
"lag_mult_num_max": 4,
"lag_mult_num_delta": 10,
"lag_value_spin2": 0,
"lag_mult_spin2_min": 0.5,
"lag_mult_spin2_max": 4,
"lag_mult_spin2_delta": 10,
"lag_value_spinz": 0,
"lag_mult_spinz_min": 0.2,
"lag_mult_spinz_max": 0.2,
"lag_mult_spinz_delta": 0.1,
"series_itermax_min": 5,
"series_itermax_max": 20,
"series_itermax_step": 25,
"series_step_min": 0.1,
"series_step_max": 1,
"series_step_step": 9,
"series_lamb_min": 2,
"series_lamb_max": 6,
"series_lamb_step": 10,
}
return values
def get_layout():
possible_molecules = [
"H3+",
"H2",
"H2+",
"H2*",
"H2-",
"H2--",
"H4",
"H4*",
"Li2",
"Li2+",
"LiH",
"H2O",
"C2H4",
"N2",
"Li3+",
"Na-",
"HeH+",
]
possible_forms = ["TwoLocal", "SO(4)", "UCCSD", "EfficientSU(2)"]
possible_basis = ["sto-3g", "sto-6g"]
possible_noise = ["None", "ibmq_santiago", "ibmq_bogota", "ibm_perth", "ibmq_lima"]
possible_bool = ["True", "False"]
possible_lag = ["True", "False", "Series", "AUGSeries"]
possible_optim = ["COBYLA", "CG", "SPSA", "L_BFGS_B", "ADAM", "NFT"]
possible_lag_op = ["number", "spin-squared", "spin-z", "num+spin2", "spin2+spinz", "num+spinz", "num+spin2+spinz"]
possible_backend = ["statevector_simulator", "qasm_simulator", "qasm_simulator_online", "hardware", "qasm_gpu"]
layout = [
[
psg.Text("Molecola"),
psg.Combo(possible_molecules, default_value="H3+", size=(5, 1), key="molecule"),
psg.Text("Basis"),
psg.Listbox(possible_basis, default_values=["sto-6g"], select_mode="extended", size=(7, 2), key="basis"),
],
[
psg.Text("Scegli forma variazionale"),
psg.Listbox(
possible_forms, default_values=["TwoLocal"], select_mode="extended", size=(12, 4), key="varforms"
),
],
[
psg.Text("Scegli il tipo di backend"),
psg.Listbox(
possible_backend,
default_values=["statevector_simulator"],
select_mode="extended",
size=(17, 4),
key="backend",
),
psg.Text("shots"),
psg.Input(default_text=1024, size=(4, 10), key="shots"),
],
[
psg.Text("Scegli l'eventuale rumore"),
psg.Listbox(possible_noise, default_values=["None"], select_mode="extended", size=(14, 5), key="noise"),
],
[
psg.Text("Correction"),
psg.Listbox(possible_bool, default_values=["False"], select_mode="extended", size=(5, 2), key="correction"),
],
[
psg.Text("Optimizer"),
psg.Listbox(
possible_optim, default_values=["COBYLA"], select_mode="extended", size=(8, 6), key="optimizer"
),
],
[
psg.Text("Distanze: Min"),
psg.Input(default_text=0.3, size=(4, 10), key="dist_min"),
psg.Text(" Max"),
psg.Input(default_text=3.5, size=(4, 10), key="dist_max"),
psg.Text(" Delta"),
psg.Input(default_text=0.1, size=(4, 10), key="dist_delta"),
],
[
psg.Text("Lagrangiana"),
psg.Listbox(
possible_lag, default_values=["Series"], select_mode="extended", size=(10, 4), key="lagrangiana"
),
],
[
psg.Text("LagSeries(itermax) MIN:"),
psg.Input(default_text=10, size=(4, 10), key="series_itermax_min"),
psg.Text("MAX: "),
psg.Input(default_text=20, size=(4, 10), key="series_itermax_max"),
psg.Text("DELTA: "),
psg.Input(default_text=20, size=(4, 10), key="series_itermax_step"),
],
[
psg.Text("LagSeries(step) MIN:"),
psg.Input(default_text=0.2, size=(4, 10), key="series_step_min"),
psg.Text("MAX: "),
psg.Input(default_text=1, size=(4, 10), key="series_step_max"),
psg.Text("DELTA: "),
psg.Input(default_text=10, size=(4, 10), key="series_step_step"),
],
[
psg.Text("LagSeries(lamb) MIN:"),
psg.Input(default_text=2, size=(4, 10), key="series_lamb_min"),
psg.Text("MAX: "),
psg.Input(default_text=6, size=(4, 10), key="series_lamb_max"),
psg.Text("DELTA: "),
psg.Input(default_text=10, size=(4, 10), key="series_lamb_step"),
],
[
psg.Text("Operatore"),
psg.Listbox(possible_lag_op, default_values=["number"], select_mode="extended", size=(18, 7), key="lag_op"),
],
[
psg.Text("NUMBER: Value"),
psg.Input(default_text=2, size=(4, 10), key="lag_value_num"),
psg.Text("Mult: min"),
psg.Input(default_text=0.2, size=(4, 10), key="lag_mult_num_min"),
psg.Text("max"),
psg.Input(default_text=1, size=(4, 10), key="lag_mult_num_max"),
psg.Text("delta"),
psg.Input(default_text=10, size=(4, 10), key="lag_mult_num_delta"),
],
[
psg.Text("SPIN-2: Value"),
psg.Input(default_text=0, size=(4, 10), key="lag_value_spin2"),
psg.Text("Mult: min"),
psg.Input(default_text=0.2, size=(4, 10), key="lag_mult_spin2_min"),
psg.Text("max"),
psg.Input(default_text=1, size=(4, 10), key="lag_mult_spin2_max"),
psg.Text("delta"),
psg.Input(default_text=10, size=(4, 10), key="lag_mult_spin2_delta"),
],
[
psg.Text("SPIN-Z: Value"),
psg.Input(default_text=0, size=(4, 10), key="lag_value_spinz"),
psg.Text("Mult: min"),
psg.Input(default_text=0.2, size=(4, 10), key="lag_mult_spinz_min"),
psg.Text("max"),
psg.Input(default_text=1, size=(4, 10), key="lag_mult_spinz_max"),
psg.Text("delta"),
psg.Input(default_text=10, size=(4, 10), key="lag_mult_spinz_delta"),
],
[psg.Button("Inizia calcolo", font=("Times New Roman", 12))],
]
return layout
def retrive_VQE_options(argv):
if "fast" in argv:
values = get_default_opt()
else:
layout = get_layout()
win = psg.Window("Definisci opzioni per VQE", layout, resizable=True, font="Lucida", text_justification="left")
e_useless, values = win.read()
win.close()
set_optimizers(values)
set_backend_and_noise(values)
lagops = set_lagrange_ops(values)
if values["dist_min"] >= values["dist_max"]:
values["dist_max"] = values["dist_min"] + values["dist_delta"] / 2
options = {
"dist": {"min": values["dist_min"], "max": values["dist_max"], "delta": values["dist_delta"]},
"molecule": {
"molecule": values["molecule"],
"spin": get_spin(values["molecule"]),
"charge": get_charge(values["molecule"]),
"basis": values["basis"],
},
"varforms": values["varforms"],
"quantum_instance": values["backend"],
"shots": int(values["shots"]),
"optimizer": values["optimizer"],
"converter": QubitConverter(mapper=ParityMapper(), two_qubit_reduction=True),
"lagrange": {
"active": values["lagrangiana"],
"operators": lagops,
},
"series": {
"itermax": np.arange(
int(values["series_itermax_min"]), int(values["series_itermax_max"]), int(values["series_itermax_step"])
),
"step": np.arange(
float(values["series_step_min"]), float(values["series_step_max"]), float(values["series_step_step"])
),
"lamb": np.arange(
float(values["series_lamb_min"]), float(values["series_lamb_max"]), float(values["series_lamb_step"])
),
},
}
options = set_dist_and_geometry(options)
print_chose_options(options)
return options
def set_ops_num_spin2(values, lagops_list):
mults_num = np.arange(
float(values["lag_mult_num_min"]), float(values["lag_mult_num_max"]), float(values["lag_mult_num_delta"])
)
mults_spin2 = np.arange(
float(values["lag_mult_spin2_min"]), float(values["lag_mult_spin2_max"]), float(values["lag_mult_spin2_delta"])
)
for mult_num in mults_num:
for mult_spin2 in mults_spin2:
mult_num = np.round(mult_num, 2)
mult_spin2 = np.round(mult_spin2, 2)
templist = []
templist.append(("number", int(values["lag_value_num"]), mult_num))
templist.append(("spin-squared", int(values["lag_value_spin2"]), mult_spin2))
lagops_list.append(templist)
def set_ops_num_spinz(values, lagops_list):
mults_num = np.arange(
float(values["lag_mult_num_min"]), float(values["lag_mult_num_max"]), float(values["lag_mult_num_delta"])
)
mults_spinz = np.arange(
float(values["lag_mult_spinz_min"]), float(values["lag_mult_spinz_max"]), float(values["lag_mult_spinz_delta"])
)
for mult_num in mults_num:
for mult_spinz in mults_spinz:
mult_num = np.round(mult_num, 2)
mult_spinz = np.round(mult_spinz, 2)
templist = []
templist.append(("number", int(values["lag_value_num"]), mult_num))
templist.append(("spin-z", int(values["lag_value_spinz"]), mult_spinz))
lagops_list.append(templist)
def set_ops_spin2_spinz(values, lagops_list):
mults_spin2 = np.arange(
float(values["lag_mult_spin2_min"]), float(values["lag_mult_spin2_max"]), float(values["lag_mult_spin2_delta"])
)
mults_spinz = np.arange(
float(values["lag_mult_spinz_min"]), float(values["lag_mult_spinz_max"]), float(values["lag_mult_spinz_delta"])
)
for mult_spin2 in mults_spin2:
for mult_spinz in mults_spinz:
mult_spin2 = np.round(mult_spin2, 2)
mult_spinz = np.round(mult_spinz, 2)
templist = []
templist.append(("spin-squared", int(values["lag_value_spin2"]), mult_spin2))
templist.append(("spin-z", int(values["lag_value_spinz"]), mult_spinz))
lagops_list.append(templist)
def set_ops_num_spin2_spinz(values, lagops_list):
mults_spin2 = np.arange(
float(values["lag_mult_spin2_min"]), float(values["lag_mult_spin2_max"]), float(values["lag_mult_spin2_delta"])
)
mults_num = np.arange(
float(values["lag_mult_num_min"]), float(values["lag_mult_num_max"]), float(values["lag_mult_num_delta"])
)
mults_spinz = np.arange(
float(values["lag_mult_spinz_min"]), float(values["lag_mult_spinz_max"]), float(values["lag_mult_spinz_delta"])
)
for mult_spin2 in mults_spin2:
for mult_spinz in mults_spinz:
for mult_num in mults_num:
mult_spin2 = np.round(mult_spin2, 2)
mult_spinz = np.round(mult_spinz, 2)
mult_num = np.round(mult_num, 2)
templist = []
templist.append(("spin-squared", int(values["lag_value_spin2"]), mult_spin2))
templist.append(("spin-z", int(values["lag_value_spinz"]), mult_spinz))
templist.append(("number", int(values["lag_value_num"]), mult_num))
lagops_list.append(templist)
def set_ops_num(values, lagops_list, operator):
mults = np.arange(
float(values["lag_mult_num_min"]), float(values["lag_mult_num_max"]), float(values["lag_mult_num_delta"])
)
for mult in mults:
mult = np.round(mult, 2)
lagops_list.append([(operator, int(values["lag_value_num"]), mult)])
def set_ops_spin2(values, lagops_list, operator):
mults = np.arange(
float(values["lag_mult_spin2_min"]), float(values["lag_mult_spin2_max"]), float(values["lag_mult_spin2_delta"])
)
for mult in mults:
mult = np.round(mult, 2)
lagops_list.append([(operator, int(values["lag_value_spin2"]), mult)])
def set_ops_spinz(values, lagops_list, operator):
mults = np.arange(
float(values["lag_mult_spinz_min"]), float(values["lag_mult_spinz_max"]), float(values["lag_mult_spinz_delta"])
)
for mult in mults:
mult = np.round(mult, 2)
lagops_list.append([(operator, int(values["lag_value_spinz"]), mult)])
def set_lagrange_ops(values):
if float(values["lag_mult_num_min"]) >= float(values["lag_mult_num_max"]):
values["lag_mult_num_max"] = float(values["lag_mult_num_min"]) + float(values["lag_mult_num_delta"]) / 2
if float(values["lag_mult_spin2_min"]) >= float(values["lag_mult_spin2_max"]):
values["lag_mult_spin2_max"] = float(values["lag_mult_spin2_min"]) + float(values["lag_mult_spin2_delta"]) / 2
if float(values["lag_mult_spinz_min"]) >= float(values["lag_mult_spinz_max"]):
values["lag_mult_spinz_max"] = float(values["lag_mult_spinz_min"]) + float(values["lag_mult_spinz_delta"]) / 2
if values["lagrangiana"] == ["False"]:
lagops_list = [[("dummy", 0, 0)]]
else:
lagops_list = []
for operator in values["lag_op"]:
if operator == "number":
set_ops_num(values, lagops_list, operator)
elif operator == "spin-squared":
set_ops_spin2(values, lagops_list, operator)
elif operator == "spin-z":
set_ops_spinz(values, lagops_list, operator)
elif operator == "num+spin2":
set_ops_num_spin2(values, lagops_list)
elif operator == "num+spinz":
set_ops_num_spinz(values, lagops_list)
elif operator == "spin2+spinz":
set_ops_spin2_spinz(values, lagops_list)
elif operator == "num+spin2+spinz":
set_ops_num_spin2_spinz(values, lagops_list)
return lagops_list
def print_chose_options(options):
quantum_instance_name = []
for ist in options["quantum_instance"]:
quantum_instance_name.append(ist[1])
optimizers_name = []
for opt in options["optimizer"]:
optimizers_name.append(opt[1])
print("OPZIONI SCELTE")
print("mol_type: ", options["molecule"]["molecule"])
print("charge: ", options["molecule"]["charge"])
print("spin: ", options["molecule"]["spin"])
print("dist: ", options["dists"])
print("basis: ", options["molecule"]["basis"])
print("varforms: ", options["varforms"])
print("instances: ", quantum_instance_name)
print("optimizer: ", optimizers_name)
if options["lagrange"]["active"][0] != "False":
print(
"lagrange: ",
"\n\tactive: ",
options["lagrange"]["active"],
"\n\toperator: ",
options["lagrange"]["operators"],
)
print(
"series: ",
"\n\titermax: ",
options["series"]["itermax"],
"\n\tstep: ",
options["series"]["step"],
"\n\tlamb: ",
options["series"]["lamb"],
)
def set_optimizers(values):
optimizers = []
for opt in values["optimizer"]:
if opt == "CG":
optimizers.append((CG(maxiter=50), "CG"))
elif opt == "COBYLA":
optimizers.append((COBYLA(), "COBYLA"))
elif opt == "ADAM":
optimizers.append((ADAM(maxiter=100), "ADAM"))
elif opt == "L_BFGS_B":
optimizers.append((L_BFGS_B(maxiter=100), "LBFGSB"))
elif opt == "SPSA":
optimizers.append((SPSA(maxiter=500), "SPSA"))
elif opt == "NFT":
optimizers.append((NFT(maxiter=200), "NFT"))
values["optimizer"] = optimizers
def set_backend_and_noise(values):
quantum_instance_list = []
provider = IBMQ.load_account()
iteratore = list(itertools.product(values["backend"], values["noise"], values["correction"]))
for backend, noise, corr in iteratore:
if backend == "statevector_simulator":
quantum_instance = QuantumInstance(Aer.get_backend("statevector_simulator"))
noise = "None"
elif backend == "qasm_simulator":
quantum_instance = QuantumInstance(
backend=QasmSimulator(), shots=int(values["shots"]) # Aer.get_backend('qasm_simulator'),
)
elif backend == "qasm_gpu":
quantum_instance = QuantumInstance(
backend=Aer.get_backend("qasm_simulator"),
backend_options={"method": "statevector_gpu"},
shots=int(values["shots"]),
)
elif backend == "qasm_simulator_online":
quantum_instance = QuantumInstance(
backend=provider.backend.ibmq_qasm_simulator,
# provider.get_backend('ibmq_qasm_simulator'), #QasmSimulator(method='statevector'),
shots=int(values["shots"]),
)
elif backend == "hardware":
mybackend = provider.get_backend("ibmq_bogota") # just dummy, for hardware
quantum_instance = mybackend
if backend == "qasm_simulator" and noise != "None":
device = provider.get_backend(noise)
coupling_map = device.configuration().coupling_map
noise_model = NoiseModel.from_backend(device)
quantum_instance.coupling_map = coupling_map
quantum_instance.noise_model = noise_model
name = backend + "_" + noise
if backend == "qasm_simulator" and noise != "None" and corr == "True":
quantum_instance.measurement_error_mitigation_cls = CompleteMeasFitter
quantum_instance.measurement_error_mitigation_shots = 1000
name += "_corrected"
quantum_instance_list.append((quantum_instance, name))
values["backend"] = quantum_instance_list
def set_dist_and_geometry(options):
minimo = float(options["dist"]["min"])
massimo = float(options["dist"]["max"])
delta = float(options["dist"]["delta"])
dist = np.arange(minimo, massimo, delta)
options["dists"] = dist
geometries = []
mol_type = options["molecule"]["molecule"]
if mol_type == "H3+":
alt = np.sqrt(dist**2 - (dist / 2) ** 2, dtype="float64")
for i, single_dist in enumerate(dist):
geom = "H .0 .0 .0; H .0 .0 " + str(single_dist)
geom += "; H .0 " + str(alt[i]) + " " + str(single_dist / 2)
geometries.append(geom)
elif mol_type == "Na-":
geometries.append("Na .0 .0 .0")
elif mol_type == "HeH+":
for i, single_dist in enumerate(dist):
geom = "He .0 .0 .0; H .0 .0 " + str(single_dist)
geometries.append(geom)
elif mol_type == "Li3+":
alt = np.sqrt(dist**2 - (dist / 2) ** 2, dtype="float64")
for i, single_dist in enumerate(dist):
geom = "Li .0 .0 .0; Li .0 .0 " + str(single_dist)
geom += "; Li .0 " + str(alt[i]) + " " + str(single_dist / 2)
geometries.append(geom)
elif mol_type == "C2H4":
bot_alt = np.sin(180 - 121.3) * 1.087
fixed_dist = np.cos(180 - 121.3) * 1.087
for i, single_dist in enumerate(dist):
top_alt = np.sin(180 - 121.3) * single_dist
geom1 = "H " + str(-fixed_dist) + " " + str(top_alt) + " 0.0; "
geom2 = "H " + str(-fixed_dist) + " " + str(-bot_alt) + " 0.0; "
geom3 = "C 0.0 0.0 0.0; C " + str(single_dist) + " 0.0 0.0; "
geom4 = "H " + str(fixed_dist) + " " + str(top_alt) + " 0.0; "
geom5 = "H " + str(fixed_dist) + " " + str(-bot_alt) + " 0.0"
geom = geom1 + geom2 + geom3 + geom4 + geom5
geometries.append(geom)
elif "H2O" in mol_type:
for single_dist in dist:
alt = single_dist * np.cos(0.25)
lung = single_dist * np.sin(0.25) + 0.9584
geom = "H .0 .0 .0; O .0 .0 0.9584; H .0 " + str(alt) + " " + str(lung)
geometries.append(geom)
elif "H2" in mol_type:
for single_dist in dist:
geom = "H .0 .0 .0; H .0 .0 " + str(single_dist)
geometries.append(geom)
elif "N2" in mol_type:
for single_dist in dist:
geom = "N .0 .0 .0; N .0 .0 " + str(single_dist)
geometries.append(geom)
elif "H4" in mol_type:
for single_dist in dist:
geom = "H .0 .0 .0; H .0 .0 " + str(single_dist)
geom += "; H .0 .0 " + str(2 * single_dist) + "; H .0 .0 " + str(3 * single_dist)
geometries.append(geom)
elif "Li2" in mol_type:
for single_dist in dist:
geom = "Li .0 .0 .0; Li .0 .0 " + str(single_dist)
geometries.append(geom)
elif "LiH" in mol_type:
for single_dist in dist:
geom = "Li .0 .0 .0; H .0 .0 " + str(single_dist)
geometries.append(geom)
options["geometries"] = geometries
return options
def get_spin(mol_opt):
mol_type = mol_opt
if mol_type == "H3+":
spin = 0
if mol_type == "Li3+":
spin = 0
elif mol_type == "H2":
spin = 0
elif mol_type == "H2*":
spin = 2
elif mol_type == "H2+":
spin = 1
elif mol_type == "H2-":
spin = 1
elif mol_type == "H2--":
spin = 0
elif mol_type == "H4":
spin = 0
elif mol_type == "H4*":
spin = 2
elif mol_type == "Li2":
spin = 0
elif mol_type == "Li2+":
spin = 1
elif mol_type == "H2O":
spin = 0
elif mol_type == "LiH":
spin = 0
elif mol_type == "C2H4":
spin = 0
elif mol_type == "N2":
spin = 0
elif mol_type == "Na-":
spin = 0
elif mol_type == "HeH+":
spin = 0
return spin
def get_charge(mol_opt):
mol_type = mol_opt
if mol_type == "H3+":
charge = 1
if mol_type == "Li3+":
charge = 1
elif mol_type == "H2":
charge = 0
elif mol_type == "H2*":
charge = 0
elif mol_type == "H2+":
charge = 1
elif mol_type == "H2-":
charge = -1
elif mol_type == "H2--":
charge = -2
elif mol_type == "H4":
charge = 0
elif mol_type == "H4*":
charge = 0
elif mol_type == "Li2":
charge = 0
elif mol_type == "Li2+":
charge = 1
elif mol_type == "LiH":
charge = 0
elif mol_type == "H2O":
charge = 0
elif mol_type == "C2H4":
charge = 0
elif mol_type == "N2":
charge = 0
elif mol_type == "Na-":
charge = -1
elif mol_type == "HeH+":
charge = 1
return charge
|
https://github.com/1chooo/Quantum-Oracle
|
1chooo
|
# %% [markdown]
# # 第1章原始程式碼
# %%
#Program 1.1 The first quantum program
from qiskit import QuantumCircuit
print("Hello, Qubit!")
qc = QuantumCircuit(1,1)
qc.measure([0], [0])
print("This is a quantum circuit of 1 qubit and 1 bit:")
qc.draw('mpl')
# %%
#Program 1.2 Design a quantum circuit with 5 qubits and 3 classical bits
from qiskit import QuantumCircuit
print("This is a quantum circuit of 5 qubits and 2 bits:")
qc = QuantumCircuit(5, 2)
qc.measure([1,3], [0,1])
qc.draw('mpl')
# %%
#Program 1.3 Name and label quantum bits and classical bits
from qiskit import QuantumRegister,ClassicalRegister,QuantumCircuit
qrx = QuantumRegister(3,'x')
qry = QuantumRegister(2,'y')
qrz = QuantumRegister(1,'z')
cr = ClassicalRegister(4,'c')
qc = QuantumCircuit(qrx,qry,qrz,cr)
qc.measure([qrx[1],qrx[2]], [cr[0],cr[1]])
qc.measure([4,5], [2,3])
qc.draw('mpl')
# %%
#Program 1.4 Transpile and execute quantum circuit on simulator
from qiskit import QuantumCircuit, transpile, execute
from qiskit.providers.aer import AerSimulator
sim = AerSimulator()
qc = QuantumCircuit(1, 1)
qc.measure([0], [0])
print(qc)
cqc = transpile(qc, sim)
job=execute(cqc, backend=sim, shots=1000)
result = job.result()
counts = result.get_counts(qc)
print("Total counts for qubit states are:",counts)
# %%
#Program 1.5 Execute quantum circuit (program) on simulator
from qiskit import QuantumCircuit, execute
from qiskit.providers.aer import AerSimulator
sim = AerSimulator()
qc = QuantumCircuit(1, 1)
qc.measure([0], [0])
print(qc)
job=execute(qc, backend=sim, shots=1000)
result = job.result()
counts = result.get_counts(qc)
print("Total counts for qubit states are:",counts)
# %%
#Program 1.6 Execute quantum circuit (program) on least busy quantum computer
from qiskit import QuantumCircuit, IBMQ, execute
from qiskit.providers.ibmq import least_busy
from qiskit.tools.monitor import job_monitor
qc = QuantumCircuit(1, 1)
qc.measure([0], [0])
print(qc)
IBMQ.save_account('your_token',overwrite=True)
IBMQ.load_account()
provider=IBMQ.get_provider(group='open')
print(provider)
qcomp = least_busy(provider.backends(simulator=False))
print("The least busy quantum computer is:",qcomp)
job=execute(qc, backend=qcomp, shots=1000)
job_monitor(job)
result = job.result()
counts = result.get_counts(qc)
print("Total counts for qubit states are:",counts)
# %%
#Program 1.7 Execute quantum circuit (program) on proper quantum computer
from qiskit import QuantumCircuit, IBMQ, execute
from qiskit.tools.monitor import job_monitor
qc = QuantumCircuit(1, 1)
qc.measure([0], [0])
print(qc)
#IBMQ.save_account('......',overwrite=True)
#IBMQ.load_account()
provider = IBMQ.get_provider(group='open')
qcomp = provider.get_backend('ibmq_lima')
job=execute(qc, backend=qcomp, shots=1000)
job_monitor(job)
result = job.result()
counts = result.get_counts(qc)
print("Total counts for qubit states are:",counts)
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
# define a quantum register with a single qubit
q = QuantumRegister(1,"q")
# define a classical register with a single bit
c = ClassicalRegister(1,"c")
# define a quantum circuit
qc = QuantumCircuit(q,c)
# apply the first Hadamard
qc.h(q[0])
# the first measurement
qc.measure(q,c)
# apply the second Hadamard if the measurement outcome is 0
qc.h(q[0]).c_if(c,0)
# the second measurement
qc.measure(q[0],c)
# draw the circuit
qc.draw(output="mpl")
job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1000)
counts = job.result().get_counts(qc)
print(counts)
# 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
# define a quantum register with a single qubit
q = QuantumRegister(1)
# define a classical register with a single bit
c = ClassicalRegister(1,"c")
# define a quantum circuit
qc = QuantumCircuit(q,c)
# start in state |1>
qc.x(q[0])
# apply the first Hadamard
qc.h(q[0])
# the first measurement
qc.measure(q,c)
# apply the second Hadamard if the measurement outcome is 1
qc.h(q[0]).c_if(c,1)
# the second measurement
qc.measure(q[0],c)
# draw the circuit
qc.draw(output="mpl")
# execute the circuit 1000 times in the local simulator
job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1000)
counts = job.result().get_counts(qc)
print(counts)
# 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
# define a quantum register with a single qubit
q = QuantumRegister(1)
# define a classical register with a single bit
c = ClassicalRegister(1,"c")
# define a quantum circuit
qc = QuantumCircuit(q,c)
for i in range(3):
qc.h(q[0]).c_if(c,0)
qc.measure(q,c)
# draw the circuit
qc.draw(output="mpl")
# execute the circuit 1000 times in the local simulator
job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1000)
counts = job.result().get_counts(qc)
print(counts)
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
# import randrange for random choices
from random import randrange
#
# your code is here
#
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
# import randrange for random choices
from random import randrange
# define a quantum register with a single qubit
q = QuantumRegister(1)
# define a classical register with a single bit
c = ClassicalRegister(1,"c")
# define a quantum circuit
qc = QuantumCircuit(q,c)
shot = 10000
observe = [0,0]
qc.h(q[0])
qc.measure(q,c)
observe = [shot/2,shot/2]
for i in range(4):
x = randrange(2)
if x==0:
observe[0] = observe[0] / 2
observe[1] = observe[1] + observe[0]
else:
observe[1] = observe[1] / 2
observe[0] = observe[0] + observe[1]
qc.h(q[0]).c_if(c,x)
qc.measure(q,c)
# draw the circuit
qc.draw(output="mpl")
print('0:',round(observe[0]),'1:',round(observe[1]))
# execute the circuit 10000 times in the local simulator
job = execute(qc,Aer.get_backend('qasm_simulator'),shots=shot)
counts = job.result().get_counts(qc)
print(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 2017, 2020
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Quick program to test the quantum information states modules."""
import unittest
import numpy as np
from qiskit import QiskitError
from qiskit.test import QiskitTestCase
from qiskit.quantum_info.states import DensityMatrix, Statevector
from qiskit.quantum_info import state_fidelity
from qiskit.quantum_info import purity
from qiskit.quantum_info import entropy
from qiskit.quantum_info import concurrence
from qiskit.quantum_info import entanglement_of_formation
from qiskit.quantum_info import mutual_information
from qiskit.quantum_info.states import shannon_entropy
from qiskit.quantum_info import negativity
class TestStateMeasures(QiskitTestCase):
"""Tests state measure functions"""
def test_state_fidelity_statevector(self):
"""Test state_fidelity function for statevector inputs"""
psi1 = [0.70710678118654746, 0, 0, 0.70710678118654746]
psi2 = [0.0, 0.70710678118654746, 0.70710678118654746, 0.0]
self.assertAlmostEqual(state_fidelity(psi1, psi1), 1.0, places=7, msg="vector-vector input")
self.assertAlmostEqual(state_fidelity(psi2, psi2), 1.0, places=7, msg="vector-vector input")
self.assertAlmostEqual(state_fidelity(psi1, psi2), 0.0, places=7, msg="vector-vector input")
psi1 = Statevector([0.70710678118654746, 0, 0, 0.70710678118654746])
psi2 = Statevector([0.0, 0.70710678118654746, 0.70710678118654746, 0.0])
self.assertAlmostEqual(state_fidelity(psi1, psi1), 1.0, places=7, msg="vector-vector input")
self.assertAlmostEqual(state_fidelity(psi2, psi2), 1.0, places=7, msg="vector-vector input")
self.assertAlmostEqual(state_fidelity(psi1, psi2), 0.0, places=7, msg="vector-vector input")
psi1 = Statevector([1, 0, 0, 1]) # invalid state
psi2 = Statevector([1, 0, 0, 0])
self.assertRaises(QiskitError, state_fidelity, psi1, psi2)
self.assertRaises(QiskitError, state_fidelity, psi1, psi2, validate=True)
self.assertEqual(state_fidelity(psi1, psi2, validate=False), 1)
def test_state_fidelity_density_matrix(self):
"""Test state_fidelity function for density matrix inputs"""
rho1 = [[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0], [0.5, 0, 0, 0.5]]
mix = [[0.25, 0, 0, 0], [0, 0.25, 0, 0], [0, 0, 0.25, 0], [0, 0, 0, 0.25]]
self.assertAlmostEqual(state_fidelity(rho1, rho1), 1.0, places=7, msg="matrix-matrix input")
self.assertAlmostEqual(state_fidelity(mix, mix), 1.0, places=7, msg="matrix-matrix input")
self.assertAlmostEqual(state_fidelity(rho1, mix), 0.25, places=7, msg="matrix-matrix input")
rho1 = DensityMatrix(rho1)
mix = DensityMatrix(mix)
self.assertAlmostEqual(state_fidelity(rho1, rho1), 1.0, places=7, msg="matrix-matrix input")
self.assertAlmostEqual(state_fidelity(mix, mix), 1.0, places=7, msg="matrix-matrix input")
self.assertAlmostEqual(state_fidelity(rho1, mix), 0.25, places=7, msg="matrix-matrix input")
rho1 = DensityMatrix([1, 0, 0, 0])
mix = DensityMatrix(np.diag([1, 0, 0, 1]))
self.assertRaises(QiskitError, state_fidelity, rho1, mix)
self.assertRaises(QiskitError, state_fidelity, rho1, mix, validate=True)
self.assertEqual(state_fidelity(rho1, mix, validate=False), 1)
def test_state_fidelity_mixed(self):
"""Test state_fidelity function for statevector and density matrix inputs"""
psi1 = Statevector([0.70710678118654746, 0, 0, 0.70710678118654746])
rho1 = DensityMatrix([[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0], [0.5, 0, 0, 0.5]])
mix = DensityMatrix([[0.25, 0, 0, 0], [0, 0.25, 0, 0], [0, 0, 0.25, 0], [0, 0, 0, 0.25]])
self.assertAlmostEqual(state_fidelity(psi1, rho1), 1.0, places=7, msg="vector-matrix input")
self.assertAlmostEqual(state_fidelity(psi1, mix), 0.25, places=7, msg="vector-matrix input")
self.assertAlmostEqual(state_fidelity(rho1, psi1), 1.0, places=7, msg="matrix-vector input")
def test_purity_statevector(self):
"""Test purity function on statevector inputs"""
psi = Statevector([1, 0, 0, 0])
self.assertEqual(purity(psi), 1)
self.assertEqual(purity(psi, validate=True), 1)
self.assertEqual(purity(psi, validate=False), 1)
psi = [0.70710678118654746, 0.70710678118654746]
self.assertAlmostEqual(purity(psi), 1)
self.assertAlmostEqual(purity(psi, validate=True), 1)
self.assertAlmostEqual(purity(psi, validate=False), 1)
psi = np.array([0.5, 0.5j, -0.5j, -0.5])
self.assertAlmostEqual(purity(psi), 1)
self.assertAlmostEqual(purity(psi, validate=True), 1)
self.assertAlmostEqual(purity(psi, validate=False), 1)
psi = Statevector([1, 0, 0, 1])
self.assertRaises(QiskitError, purity, psi)
self.assertRaises(QiskitError, purity, psi, validate=True)
self.assertEqual(purity(psi, validate=False), 4)
def test_purity_density_matrix(self):
"""Test purity function on density matrix inputs"""
rho = DensityMatrix(np.diag([1, 0, 0, 0]))
self.assertEqual(purity(rho), 1)
self.assertEqual(purity(rho, validate=True), 1)
self.assertEqual(purity(rho, validate=False), 1)
rho = np.diag([0.25, 0.25, 0.25, 0.25])
self.assertEqual(purity(rho), 0.25)
self.assertEqual(purity(rho, validate=True), 0.25)
self.assertEqual(purity(rho, validate=False), 0.25)
rho = [[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0], [0.5, 0, 0, 0.5]]
self.assertEqual(purity(rho), 1)
self.assertEqual(purity(rho, validate=True), 1)
self.assertEqual(purity(rho, validate=False), 1)
rho = np.diag([1, 0, 0, 1])
self.assertRaises(QiskitError, purity, rho)
self.assertRaises(QiskitError, purity, rho, validate=True)
self.assertEqual(purity(rho, validate=False), 2)
def test_purity_equivalence(self):
"""Test purity is same for equivalent inputs"""
for alpha, beta in [
(0, 0),
(0, 0.25),
(0.25, 0),
(0.33, 0.33),
(0.5, 0.5),
(0.75, 0.25),
(0, 0.75),
]:
psi = Statevector([alpha, beta, 0, 1j * np.sqrt(1 - alpha**2 - beta**2)])
rho = DensityMatrix(psi)
self.assertAlmostEqual(purity(psi), purity(rho))
def test_entropy_statevector(self):
"""Test entropy function on statevector inputs"""
test_psis = [
[1, 0],
[0, 1, 0, 0],
[0.5, 0.5, 0.5, 0.5],
[0.5, 0.5j, -0.5j, 0.5],
[0.70710678118654746, 0, 0, -0.70710678118654746j],
[0.70710678118654746] + (14 * [0]) + [0.70710678118654746j],
]
for psi_ls in test_psis:
self.assertEqual(entropy(psi_ls), 0)
self.assertEqual(entropy(np.array(psi_ls)), 0)
def test_entropy_density_matrix(self):
"""Test entropy function on density matrix inputs"""
# Density matrix input
rhos = [DensityMatrix(np.diag([0.5] + (n * [0]) + [0.5])) for n in range(1, 5)]
for rho in rhos:
self.assertAlmostEqual(entropy(rho), 1)
self.assertAlmostEqual(entropy(rho, base=2), 1)
self.assertAlmostEqual(entropy(rho, base=np.e), -1 * np.log(0.5))
# Array input
for prob in [0.001, 0.3, 0.7, 0.999]:
rho = np.diag([prob, 1 - prob])
self.assertAlmostEqual(entropy(rho), shannon_entropy([prob, 1 - prob]))
self.assertAlmostEqual(
entropy(rho, base=np.e), shannon_entropy([prob, 1 - prob], base=np.e)
)
self.assertAlmostEqual(entropy(rho, base=2), shannon_entropy([prob, 1 - prob], base=2))
# List input
rho = [[0.5, 0], [0, 0.5]]
self.assertAlmostEqual(entropy(rho), 1)
def test_entropy_equivalence(self):
"""Test entropy is same for equivalent inputs"""
for alpha, beta in [
(0, 0),
(0, 0.25),
(0.25, 0),
(0.33, 0.33),
(0.5, 0.5),
(0.75, 0.25),
(0, 0.75),
]:
psi = Statevector([alpha, beta, 0, 1j * np.sqrt(1 - alpha**2 - beta**2)])
rho = DensityMatrix(psi)
self.assertAlmostEqual(entropy(psi), entropy(rho))
def test_concurrence_statevector(self):
"""Test concurrence function on statevector inputs"""
# Statevector input
psi = Statevector([0.70710678118654746, 0, 0, -0.70710678118654746j])
self.assertAlmostEqual(concurrence(psi), 1)
# List input
psi = [1, 0, 0, 0]
self.assertAlmostEqual(concurrence(psi), 0)
# Array input
psi = np.array([0.5, 0.5, 0.5, 0.5])
self.assertAlmostEqual(concurrence(psi), 0)
# Larger than 2 qubit input
psi_ls = [0.70710678118654746] + (14 * [0]) + [0.70710678118654746j]
psi = Statevector(psi_ls, dims=(2, 8))
self.assertAlmostEqual(concurrence(psi), 1)
psi = Statevector(psi_ls, dims=(4, 4))
self.assertAlmostEqual(concurrence(psi), 1)
psi = Statevector(psi_ls, dims=(8, 2))
self.assertAlmostEqual(concurrence(psi), 1)
def test_concurrence_density_matrix(self):
"""Test concurrence function on density matrix inputs"""
# Density matrix input
rho1 = DensityMatrix([[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0], [0.5, 0, 0, 0.5]])
rho2 = DensityMatrix([[0, 0, 0, 0], [0, 0.5, -0.5j, 0], [0, 0.5j, 0.5, 0], [0, 0, 0, 0]])
self.assertAlmostEqual(concurrence(rho1), 1)
self.assertAlmostEqual(concurrence(rho2), 1)
self.assertAlmostEqual(concurrence(0.5 * rho1 + 0.5 * rho2), 0)
self.assertAlmostEqual(concurrence(0.75 * rho1 + 0.25 * rho2), 0.5)
# List input
rho = [[0.5, 0.5, 0, 0], [0.5, 0.5, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
self.assertEqual(concurrence(rho), 0)
# Array input
rho = np.diag([0.25, 0.25, 0.25, 0.25])
self.assertEqual(concurrence(rho), 0)
def test_concurrence_equivalence(self):
"""Test concurrence is same for equivalent inputs"""
for alpha, beta in [
(0, 0),
(0, 0.25),
(0.25, 0),
(0.33, 0.33),
(0.5, 0.5),
(0.75, 0.25),
(0, 0.75),
]:
psi = Statevector([alpha, beta, 0, 1j * np.sqrt(1 - alpha**2 - beta**2)])
rho = DensityMatrix(psi)
self.assertAlmostEqual(concurrence(psi), concurrence(rho))
def test_entanglement_of_formation_statevector(self):
"""Test entanglement of formation function on statevector inputs"""
# Statevector input
psi = Statevector([0.70710678118654746, 0, 0, -0.70710678118654746j])
self.assertAlmostEqual(entanglement_of_formation(psi), 1)
# List input
psi = [1, 0, 0, 0]
self.assertAlmostEqual(entanglement_of_formation(psi), 0)
# Array input
psi = np.array([0.5, 0.5, 0.5, 0.5])
self.assertAlmostEqual(entanglement_of_formation(psi), 0)
# Larger than 2 qubit input
psi_ls = [0.70710678118654746] + (14 * [0]) + [0.70710678118654746j]
psi = Statevector(psi_ls, dims=(2, 8))
self.assertAlmostEqual(entanglement_of_formation(psi), 1)
psi = Statevector(psi_ls, dims=(4, 4))
self.assertAlmostEqual(entanglement_of_formation(psi), 1)
psi = Statevector(psi_ls, dims=(8, 2))
self.assertAlmostEqual(entanglement_of_formation(psi), 1)
def test_entanglement_of_formation_density_matrix(self):
"""Test entanglement of formation function on density matrix inputs"""
# Density matrix input
rho1 = DensityMatrix([[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0], [0.5, 0, 0, 0.5]])
rho2 = DensityMatrix([[0, 0, 0, 0], [0, 0.5, -0.5j, 0], [0, 0.5j, 0.5, 0], [0, 0, 0, 0]])
self.assertAlmostEqual(entanglement_of_formation(rho1), 1)
self.assertAlmostEqual(entanglement_of_formation(rho2), 1)
self.assertAlmostEqual(entanglement_of_formation(0.5 * rho1 + 0.5 * rho2), 0)
self.assertAlmostEqual(
entanglement_of_formation(0.75 * rho1 + 0.25 * rho2), 0.35457890266527003
)
# List input
rho = [[0.5, 0.5, 0, 0], [0.5, 0.5, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
self.assertEqual(entanglement_of_formation(rho), 0)
# Array input
rho = np.diag([0.25, 0.25, 0.25, 0.25])
self.assertEqual(entanglement_of_formation(rho), 0)
def test_entanglement_of_formation_equivalence(self):
"""Test entanglement of formation is same for equivalent inputs"""
for alpha, beta in [
(0, 0),
(0, 0.25),
(0.25, 0),
(0.33, 0.33),
(0.5, 0.5),
(0.75, 0.25),
(0, 0.75),
]:
psi = Statevector([alpha, beta, 0, 1j * np.sqrt(1 - alpha**2 - beta**2)])
rho = DensityMatrix(psi)
self.assertAlmostEqual(entanglement_of_formation(psi), entanglement_of_formation(rho))
def test_mutual_information_statevector(self):
"""Test mutual_information function on statevector inputs"""
# Statevector input
psi = Statevector([0.70710678118654746, 0, 0, -0.70710678118654746j])
self.assertAlmostEqual(mutual_information(psi), 2)
# List input
psi = [1, 0, 0, 0]
self.assertAlmostEqual(mutual_information(psi), 0)
# Array input
psi = np.array([0.5, 0.5, 0.5, 0.5])
self.assertAlmostEqual(mutual_information(psi), 0)
# Larger than 2 qubit input
psi_ls = [0.70710678118654746] + (14 * [0]) + [0.70710678118654746j]
psi = Statevector(psi_ls, dims=(2, 8))
self.assertAlmostEqual(mutual_information(psi), 2)
psi = Statevector(psi_ls, dims=(4, 4))
self.assertAlmostEqual(mutual_information(psi), 2)
psi = Statevector(psi_ls, dims=(8, 2))
self.assertAlmostEqual(mutual_information(psi), 2)
def test_mutual_information_density_matrix(self):
"""Test mutual_information function on density matrix inputs"""
# Density matrix input
rho1 = DensityMatrix([[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0], [0.5, 0, 0, 0.5]])
rho2 = DensityMatrix([[0, 0, 0, 0], [0, 0.5, -0.5j, 0], [0, 0.5j, 0.5, 0], [0, 0, 0, 0]])
self.assertAlmostEqual(mutual_information(rho1), 2)
self.assertAlmostEqual(mutual_information(rho2), 2)
# List input
rho = [[0.5, 0.5, 0, 0], [0.5, 0.5, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
self.assertEqual(mutual_information(rho), 0)
# Array input
rho = np.diag([0.25, 0.25, 0.25, 0.25])
self.assertEqual(mutual_information(rho), 0)
def test_mutual_information_equivalence(self):
"""Test mutual_information is same for equivalent inputs"""
for alpha, beta in [
(0, 0),
(0, 0.25),
(0.25, 0),
(0.33, 0.33),
(0.5, 0.5),
(0.75, 0.25),
(0, 0.75),
]:
psi = Statevector([alpha, beta, 0, 1j * np.sqrt(1 - alpha**2 - beta**2)])
rho = DensityMatrix(psi)
self.assertAlmostEqual(mutual_information(psi), mutual_information(rho))
def test_negativity_statevector(self):
"""Test negativity function on statevector inputs"""
# Constructing separable quantum statevector
state = Statevector([1 / np.sqrt(2), 1 / np.sqrt(2), 0, 0])
negv = negativity(state, [0])
self.assertAlmostEqual(negv, 0, places=7)
# Constructing entangled quantum statevector
state = Statevector([0, 1 / np.sqrt(2), -1 / np.sqrt(2), 0])
negv = negativity(state, [1])
self.assertAlmostEqual(negv, 0.5, places=7)
def test_negativity_density_matrix(self):
"""Test negativity function on density matrix inputs"""
# Constructing separable quantum state
rho = DensityMatrix.from_label("10+")
negv = negativity(rho, [0, 1])
self.assertAlmostEqual(negv, 0, places=7)
negv = negativity(rho, [0, 2])
self.assertAlmostEqual(negv, 0, places=7)
# Constructing entangled quantum state
rho = DensityMatrix([[0, 0, 0, 0], [0, 0.5, -0.5, 0], [0, -0.5, 0.5, 0], [0, 0, 0, 0]])
negv = negativity(rho, [0])
self.assertAlmostEqual(negv, 0.5, places=7)
negv = negativity(rho, [1])
self.assertAlmostEqual(negv, 0.5, places=7)
if __name__ == "__main__":
unittest.main()
|
https://github.com/magn5452/QiskitQaoa
|
magn5452
|
from matplotlib import pyplot as plt
from qiskit import QuantumCircuit, Aer, assemble
from qiskit.extensions import HamiltonianGate
from qiskit.providers import aer
from qiskit.providers.aer import StatevectorSimulator
from qiskit.quantum_info import Operator
from qiskit.visualization import plot_histogram
from VehicleRouting.standard.concretization.CircuitPlotter import MPLCircuitPlotter
circuit = QuantumCircuit(4)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.h(3)
circuit.measure_all()
circuit_plotter = MPLCircuitPlotter()
circuit_plotter.plot(circuit)
backend = StatevectorSimulator(precision='single')
backend.shots = 2 ** 8
counts = backend.run(circuit).result().get_counts()
plt.show()
|
https://github.com/hugoecarl/TSP-Problem-Study
|
hugoecarl
|
import math
import matplotlib.pyplot as plt
%matplotlib inline
class TSP:
def __init__(self):
self.flat_mat = flat_mat
self.n = 0
self.melhor_dist = 1e11
self.pontos = []
self.melhores_pontos = []
def busca_exaustiva(self, flat_mat, n, ite):
if ite == n:
dist = 0
for j in range(1, n):
dist += flat_mat[self.pontos[j-1] * n + self.pontos[j]]
dist += flat_mat[self.pontos[n-1] * n + self.pontos[0]]
if dist < self.melhor_dist:
self.melhor_dist = dist
self.melhores_pontos = self.pontos[:]
return
for i in range(n):
if self.pontos[i] == -1:
self.pontos[i] = ite
self.busca_exaustiva(flat_mat, n, ite + 1)
self.pontos[i] = -1
def dist_mat(self):
x = []
y = []
flat_mat = [] #matriz 1 dimensao contendo todas as distancias possiveis entre os pontos para facilitar cálculo.
while True:
try:
temp = input("Digite a coordenada x y: ").split()
x.append(float(temp[0]))
y.append(float(temp[1]))
except:
break
for i in range(len(x)):
for j in range(len(y)):
flat_mat.append(math.sqrt((x[i] - x[j])**2 + (y[i] - y[j])**2))
return flat_mat, x, y
def get_results(self):
self.flat_mat, x, _ = self.dist_mat()
self.n = len(x)
self.pontos = [-1]*self.n
self.pontos[0] = 0
self.busca_exaustiva(self.flat_mat, self.n, 1)
return self.melhor_dist, self.melhores_pontos
Tsp = TSP()
distancia, pontos = Tsp.get_results()
print("Melhor distancia encontrada: ", distancia)
print("Melhor caminho encontrado: ", pontos)
#plota gráfico
def connectpoints(x,y,p1,p2):
x1, x2 = x[p1], x[p2]
y1, y2 = y[p1], y[p2]
plt.plot([x1,x2],[y1,y2],'ro-')
for i in range(1, len(pontos)):
connectpoints(x,y,pontos[i-1],pontos[i])
connectpoints(x,y,pontos[len(x)-1],pontos[0])
plt.title("Percurso")
plt.show()
%%time
%%cmd
python TSP.py < in-1.txt
type out-1.txt
python TSP.py < in-2.txt
type out-2.txt
python TSP.py < in-3.txt
type out-3.txt
python TSP.py < in-4.txt
type out-4.txt
from qiskit import IBMQ
import numpy as np
#IBMQ.save_account('seu-tokenIBMQ-para-rodar-localmente')
IBMQ.load_account()
from qiskit import Aer
from qiskit.tools.visualization import plot_histogram
from qiskit.circuit.library import TwoLocal
from qiskit.optimization.applications.ising import max_cut, tsp
from qiskit.aqua.algorithms import VQE, NumPyMinimumEigensolver
from qiskit.aqua.components.optimizers import SPSA
from qiskit.aqua import aqua_globals
from qiskit.aqua import QuantumInstance
from qiskit.optimization.applications.ising.common import sample_most_likely
from qiskit.optimization.algorithms import MinimumEigenOptimizer
from qiskit.optimization.problems import QuadraticProgram
import logging
from qiskit.aqua import set_qiskit_aqua_logging
#Preparando os dados segundo os imputs do usuario para serem resolvidos pelo qiskit max 4 pontos por limitação de qubits
coord = []
flat_mat, x, y = TSP().dist_mat()
dist_mat = np.array(flat_mat).reshape(len(x),len(x))
for i, j in zip(x, y):
coord.append([i,j])
ins = tsp.TspData('TSP_Q', dim=len(x), coord=np.array(coord), w=dist_mat)
qubitOp, offset = tsp.get_operator(ins)
print('Offset:', offset)
print('Ising Hamiltonian:')
print(qubitOp.print_details())
#Usando o numpyMinimumEigensolver como o solver do problema para resolver de forma quantica
ee = NumPyMinimumEigensolver(qubitOp)
result = ee.run()
print('energy:', result.eigenvalue.real)
print('tsp objective:', result.eigenvalue.real + offset)
x_Q = sample_most_likely(result.eigenstate)
print('feasible:', tsp.tsp_feasible(x_Q))
z = tsp.get_tsp_solution(x_Q)
print('solution:', z)
print('solution objective:', tsp.tsp_value(z, ins.w))
for i in range(1, len(z)):
connectpoints(x,y,z[i-1],z[i])
connectpoints(x,y,z[len(x)-1],z[0])
plt.title("Percurso")
plt.show()
#instanciando o simulador ou o computador real importante lembrar que nao ira funcionar para mais de 4 pontos pelo numero de qubits disponibilizados pela IBM que sao apenas 16 para o simulador qasm e 15 para a maquina quantica
provider = IBMQ.get_provider(hub = 'ibm-q')
device = provider.get_backend('ibmq_16_melbourne')
aqua_globals.random_seed = np.random.default_rng(123)
seed = 10598
backend = Aer.get_backend('qasm_simulator')
#descomentar essa linha caso queira rodar na maquina real
#backend = device
quantum_instance = QuantumInstance(backend, seed_simulator=seed, seed_transpiler=seed)
#rodando no simulador quantico
spsa = SPSA(maxiter=10)
ry = TwoLocal(qubitOp.num_qubits, 'ry', 'cz', reps=5, entanglement='linear')
vqe = VQE(qubitOp, ry, spsa, quantum_instance=quantum_instance)
result = vqe.run(quantum_instance)
print('energy:', result.eigenvalue.real)
print('time:', result.optimizer_time)
x = sample_most_likely(result.eigenstate)
print('feasible:', tsp.tsp_feasible(x_Q))
z = tsp.get_tsp_solution(x_Q)
print('solution:', z)
print('solution objective:', tsp.tsp_value(z, ins.w))
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""UnitaryGate tests"""
import json
import numpy
from numpy.testing import assert_allclose
import qiskit
from qiskit.extensions.unitary import UnitaryGate
from qiskit.test import QiskitTestCase
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit.converters import circuit_to_dag, dag_to_circuit
from qiskit.quantum_info.random import random_unitary
from qiskit.quantum_info.operators import Operator
from qiskit.transpiler.passes import CXCancellation
class TestUnitaryGate(QiskitTestCase):
"""Tests for the Unitary class."""
def test_set_matrix(self):
"""Test instantiation"""
try:
UnitaryGate([[0, 1], [1, 0]])
# pylint: disable=broad-except
except Exception as err:
self.fail(f"unexpected exception in init of Unitary: {err}")
def test_set_matrix_raises(self):
"""test non-unitary"""
try:
UnitaryGate([[1, 1], [1, 0]])
# pylint: disable=broad-except
except Exception:
pass
else:
self.fail("setting Unitary with non-unitary did not raise")
def test_set_init_with_unitary(self):
"""test instantiation of new unitary with another one (copy)"""
uni1 = UnitaryGate([[0, 1], [1, 0]])
uni2 = UnitaryGate(uni1)
self.assertEqual(uni1, uni2)
self.assertFalse(uni1 is uni2)
def test_conjugate(self):
"""test conjugate"""
ymat = numpy.array([[0, -1j], [1j, 0]])
uni = UnitaryGate([[0, 1j], [-1j, 0]])
self.assertTrue(numpy.array_equal(uni.conjugate().to_matrix(), ymat))
def test_adjoint(self):
"""test adjoint operation"""
uni = UnitaryGate([[0, 1j], [-1j, 0]])
self.assertTrue(numpy.array_equal(uni.adjoint().to_matrix(), uni.to_matrix()))
class TestUnitaryCircuit(QiskitTestCase):
"""Matrix gate circuit tests."""
def test_1q_unitary(self):
"""test 1 qubit unitary matrix"""
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
matrix = numpy.array([[1, 0], [0, 1]])
qc.x(qr[0])
qc.append(UnitaryGate(matrix), [qr[0]])
# test of qasm output
self.log.info(qc.qasm())
# test of text drawer
self.log.info(qc)
dag = circuit_to_dag(qc)
dag_nodes = dag.named_nodes("unitary")
self.assertTrue(len(dag_nodes) == 1)
dnode = dag_nodes[0]
self.assertIsInstance(dnode.op, UnitaryGate)
self.assertEqual(dnode.qargs, (qr[0],))
assert_allclose(dnode.op.to_matrix(), matrix)
def test_2q_unitary(self):
"""test 2 qubit unitary matrix"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
sigmax = numpy.array([[0, 1], [1, 0]])
sigmay = numpy.array([[0, -1j], [1j, 0]])
matrix = numpy.kron(sigmax, sigmay)
qc.x(qr[0])
uni2q = UnitaryGate(matrix)
qc.append(uni2q, [qr[0], qr[1]])
passman = PassManager()
passman.append(CXCancellation())
qc2 = passman.run(qc)
# test of qasm output
self.log.info(qc2.qasm())
# test of text drawer
self.log.info(qc2)
dag = circuit_to_dag(qc)
nodes = dag.two_qubit_ops()
self.assertEqual(len(nodes), 1)
dnode = nodes[0]
self.assertIsInstance(dnode.op, UnitaryGate)
self.assertEqual(dnode.qargs, (qr[0], qr[1]))
assert_allclose(dnode.op.to_matrix(), matrix)
qc3 = dag_to_circuit(dag)
self.assertEqual(qc2, qc3)
def test_3q_unitary(self):
"""test 3 qubit unitary matrix on non-consecutive bits"""
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
sigmax = numpy.array([[0, 1], [1, 0]])
sigmay = numpy.array([[0, -1j], [1j, 0]])
matrix = numpy.kron(sigmay, numpy.kron(sigmax, sigmay))
qc.x(qr[0])
uni3q = UnitaryGate(matrix)
qc.append(uni3q, [qr[0], qr[1], qr[3]])
qc.cx(qr[3], qr[2])
# test of text drawer
self.log.info(qc)
dag = circuit_to_dag(qc)
nodes = dag.multi_qubit_ops()
self.assertEqual(len(nodes), 1)
dnode = nodes[0]
self.assertIsInstance(dnode.op, UnitaryGate)
self.assertEqual(dnode.qargs, (qr[0], qr[1], qr[3]))
assert_allclose(dnode.op.to_matrix(), matrix)
def test_1q_unitary_int_qargs(self):
"""test single qubit unitary matrix with 'int' and 'list of ints' qubits argument"""
sigmax = numpy.array([[0, 1], [1, 0]])
sigmaz = numpy.array([[1, 0], [0, -1]])
# new syntax
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.unitary(sigmax, 0)
qc.unitary(sigmax, qr[1])
qc.unitary(sigmaz, [0, 1])
# expected circuit
qc_target = QuantumCircuit(qr)
qc_target.append(UnitaryGate(sigmax), [0])
qc_target.append(UnitaryGate(sigmax), [qr[1]])
qc_target.append(UnitaryGate(sigmaz), [[0, 1]])
self.assertEqual(qc, qc_target)
def test_qobj_with_unitary_matrix(self):
"""test qobj output with unitary matrix"""
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
sigmax = numpy.array([[0, 1], [1, 0]])
sigmay = numpy.array([[0, -1j], [1j, 0]])
matrix = numpy.kron(sigmay, numpy.kron(sigmax, sigmay))
qc.rx(numpy.pi / 4, qr[0])
uni = UnitaryGate(matrix)
qc.append(uni, [qr[0], qr[1], qr[3]])
qc.cx(qr[3], qr[2])
qobj = qiskit.compiler.assemble(qc)
instr = qobj.experiments[0].instructions[1]
self.assertEqual(instr.name, "unitary")
assert_allclose(numpy.array(instr.params[0]).astype(numpy.complex64), matrix)
# check conversion to dict
qobj_dict = qobj.to_dict()
class NumpyEncoder(json.JSONEncoder):
"""Class for encoding json str with complex and numpy arrays."""
def default(self, obj):
if isinstance(obj, numpy.ndarray):
return obj.tolist()
if isinstance(obj, complex):
return (obj.real, obj.imag)
return json.JSONEncoder.default(self, obj)
# check json serialization
self.assertTrue(isinstance(json.dumps(qobj_dict, cls=NumpyEncoder), str))
def test_labeled_unitary(self):
"""test qobj output with unitary matrix"""
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
sigmax = numpy.array([[0, 1], [1, 0]])
sigmay = numpy.array([[0, -1j], [1j, 0]])
matrix = numpy.kron(sigmax, sigmay)
uni = UnitaryGate(matrix, label="xy")
qc.append(uni, [qr[0], qr[1]])
qobj = qiskit.compiler.assemble(qc)
instr = qobj.experiments[0].instructions[0]
self.assertEqual(instr.name, "unitary")
self.assertEqual(instr.label, "xy")
def test_qasm_unitary_only_one_def(self):
"""test that a custom unitary can be converted to qasm and the
definition is only written once"""
qr = QuantumRegister(2, "q0")
cr = ClassicalRegister(1, "c0")
qc = QuantumCircuit(qr, cr)
matrix = numpy.array([[1, 0], [0, 1]])
unitary_gate = UnitaryGate(matrix)
qc.x(qr[0])
qc.append(unitary_gate, [qr[0]])
qc.append(unitary_gate, [qr[1]])
expected_qasm = (
"OPENQASM 2.0;\n"
'include "qelib1.inc";\n'
"gate unitary q0 { u(0,0,0) q0; }\n"
"qreg q0[2];\ncreg c0[1];\n"
"x q0[0];\n"
"unitary q0[0];\n"
"unitary q0[1];\n"
)
self.assertEqual(expected_qasm, qc.qasm())
def test_qasm_unitary_twice(self):
"""test that a custom unitary can be converted to qasm and that if
the qasm is called twice it is the same every time"""
qr = QuantumRegister(2, "q0")
cr = ClassicalRegister(1, "c0")
qc = QuantumCircuit(qr, cr)
matrix = numpy.array([[1, 0], [0, 1]])
unitary_gate = UnitaryGate(matrix)
qc.x(qr[0])
qc.append(unitary_gate, [qr[0]])
qc.append(unitary_gate, [qr[1]])
expected_qasm = (
"OPENQASM 2.0;\n"
'include "qelib1.inc";\n'
"gate unitary q0 { u(0,0,0) q0; }\n"
"qreg q0[2];\ncreg c0[1];\n"
"x q0[0];\n"
"unitary q0[0];\n"
"unitary q0[1];\n"
)
self.assertEqual(expected_qasm, qc.qasm())
self.assertEqual(expected_qasm, qc.qasm())
def test_qasm_2q_unitary(self):
"""test that a 2 qubit custom unitary can be converted to qasm"""
qr = QuantumRegister(2, "q0")
cr = ClassicalRegister(1, "c0")
qc = QuantumCircuit(qr, cr)
matrix = numpy.asarray([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]])
unitary_gate = UnitaryGate(matrix)
qc.x(qr[0])
qc.append(unitary_gate, [qr[0], qr[1]])
qc.append(unitary_gate, [qr[1], qr[0]])
expected_qasm = (
"OPENQASM 2.0;\n"
'include "qelib1.inc";\n'
"gate unitary q0,q1 { u(pi,-pi/2,pi/2) q0; u(pi,pi/2,-pi/2) q1; }\n"
"qreg q0[2];\n"
"creg c0[1];\n"
"x q0[0];\n"
"unitary q0[0],q0[1];\n"
"unitary q0[1],q0[0];\n"
)
self.assertEqual(expected_qasm, qc.qasm())
def test_qasm_unitary_noop(self):
"""Test that an identity unitary can be converted to OpenQASM 2"""
qc = QuantumCircuit(QuantumRegister(3, "q0"))
qc.unitary(numpy.eye(8), qc.qubits)
expected_qasm = (
"OPENQASM 2.0;\n"
'include "qelib1.inc";\n'
"gate unitary q0,q1,q2 { }\n"
"qreg q0[3];\n"
"unitary q0[0],q0[1],q0[2];\n"
)
self.assertEqual(expected_qasm, qc.qasm())
def test_unitary_decomposition(self):
"""Test decomposition for unitary gates over 2 qubits."""
qc = QuantumCircuit(3)
qc.unitary(random_unitary(8, seed=42), [0, 1, 2])
self.assertTrue(Operator(qc).equiv(Operator(qc.decompose())))
def test_unitary_decomposition_via_definition(self):
"""Test decomposition for 1Q unitary via definition."""
mat = numpy.array([[0, 1], [1, 0]])
self.assertTrue(numpy.allclose(Operator(UnitaryGate(mat).definition).data, mat))
def test_unitary_decomposition_via_definition_2q(self):
"""Test decomposition for 2Q unitary via definition."""
mat = numpy.array([[0, 0, 1, 0], [0, 0, 0, -1], [1, 0, 0, 0], [0, -1, 0, 0]])
self.assertTrue(numpy.allclose(Operator(UnitaryGate(mat).definition).data, mat))
def test_unitary_control(self):
"""Test parameters of controlled - unitary."""
mat = numpy.array([[0, 1], [1, 0]])
gate = UnitaryGate(mat).control()
self.assertTrue(numpy.allclose(gate.params, mat))
self.assertTrue(numpy.allclose(gate.base_gate.params, mat))
|
https://github.com/sarthag/Quantum-Algos-using-Qiskit
|
sarthag
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, plot_bloch_vector, plot_histogram
from qiskit.compiler import transpile, assemble
from qiskit.tools.monitor import job_monitor
from qiskit.providers.ibmq import least_busy
import matplotlib
import numpy as np
%pylab inline
qc = QuantumCircuit(4,3)
qc.x(3)
qc.h(range(3))
reps = 1
for count in range(3):
for i in range (reps):
qc.cp(pi/4, count, 3)
reps *= 2
qc.barrier()
qc.draw('mpl')
def inv_qft(qc, n):
for qubit in range (n//2):
qc.swap(qubit, n-qubit-1)
for j in range(n):
for m in range(j):
qc.cp(-pi/(2*(j-m)), m, j)
qc.h(j)
inv_qft(qc, 3)
qc.barrier()
qc.measure(range(3), range(3))
qc.draw('mpl')
qasm_sim = Aer.get_backend('qasm_simulator')
shots = 1
qobj = assemble(qc, qasm_sim)
results = qasm_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts)
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 4 and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
shots = 1024
transpiled_circuit = transpile(qc, backend)
qobj = assemble(transpiled_circuit, shots=shots)
job = backend.run(qobj)
job_monitor(job, interval=2)
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_aer.utils import approximate_quantum_error, approximate_noise_model
import numpy as np
# Import Aer QuantumError functions that will be used
from qiskit_aer.noise import amplitude_damping_error, reset_error, pauli_error
from qiskit.quantum_info import Kraus
gamma = 0.23
error = amplitude_damping_error(gamma)
results = approximate_quantum_error(error, operator_string="reset")
print(results)
p = (1 + gamma - np.sqrt(1 - gamma)) / 2
q = 0
print("")
print("Expected results:")
print("P(0) = {}".format(1-(p+q)))
print("P(1) = {}".format(p))
print("P(2) = {}".format(q))
gamma = 0.23
K0 = np.array([[1,0],[0,np.sqrt(1-gamma)]])
K1 = np.array([[0,np.sqrt(gamma)],[0,0]])
results = approximate_quantum_error(Kraus([K0, K1]), operator_string="reset")
print(results)
reset_to_0 = Kraus([np.array([[1,0],[0,0]]), np.array([[0,1],[0,0]])])
reset_to_1 = Kraus([np.array([[0,0],[1,0]]), np.array([[0,0],[0,1]])])
reset_kraus = [reset_to_0, reset_to_1]
gamma = 0.23
error = amplitude_damping_error(gamma)
results = approximate_quantum_error(error, operator_list=reset_kraus)
print(results)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
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/apcarrik/qiskit-dev
|
apcarrik
|
import numpy as np
from qiskit import *
from matplotlib import pyplot
### Opaque Gates
from qiskit.circuit import Gate
my_gate = Gate(name='my_gate', num_qubits=2, params=[])
qr = QuantumRegister(3, 'q')
circ = QuantumCircuit(qr)
circ.append(my_gate, [qr[0], qr[1]])
circ.append(my_gate, [qr[1], qr[2]])
circ.draw('mpl')
pyplot.show()
### Composite Gates
# build a sub-circuit
sub_q = QuantumRegister(2)
sub_circ = QuantumCircuit(sub_q, name="sub_circ")
sub_circ.h(sub_q[0])
sub_circ.crz(1, sub_q[0], sub_q[1])
sub_circ.barrier()
sub_circ.id(sub_q[1])
sub_circ.u(1,2,-2, sub_q[0])
# convert to a gate and stick it into an arbitrary place in the bigger circuit
sub_inst = sub_circ.to_instruction()
qr = QuantumRegister(3, 'q')
circ = QuantumCircuit(qr)
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.cx(qr[1], qr[2])
circ.append(sub_inst, [qr[1], qr[2]])
circ.draw('mpl')
pyplot.show()
# decompose sub-circuit
decomposed_circ = circ.decompose()
decomposed_circ.draw('mpl')
pyplot.show()
### Parameterized Circuits
from qiskit.circuit import Parameter
theta = Parameter('θ')
n=5
qc = QuantumCircuit(n,1)
qc.h(0)
for i in range(n-1):
qc.cx(i, i+1)
qc.barrier()
qc.rz(theta, range(5))
qc.barrier()
for i in reversed(range(n-1)):
qc.cx(i, i+1)
qc.h(0)
qc.measure(0,0)
qc.draw('mpl')
pyplot.show()
print(qc.parameters)
# binding parameters
import numpy as np
theta_range = np.linspace(0, 2*np.pi, 128)
circuits = [qc.bind_parameters({theta: theta_val}) for theta_val in theta_range]
circuits[-1].draw('mpl') # Last of 128 circuits
pyplot.show()
job = execute(qc,
backend=BasicAer.get_backend('qasm_simulator'),
parameter_binds=[{theta: theta_val} for theta_val in theta_range]
)
counts = job.result().get_counts()
print(len(counts))
# plot oscillation in qubit 0 as theta value changes
fig = pyplot.figure(figsize=(8,6))
ax = fig.add_subplot(111)
ax.plot(theta_range, list(map(lambda c: c.get('0', 0), counts)), '.-', label='0')
ax.plot(theta_range, list(map(lambda c: c.get('1', 0), counts)), '.-', label='1')
ax.set_xticks([i * np.pi / 2 for i in range(5)])
ax.set_xticklabels(['0', r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3\pi}{2}$', r'$2\pi$'],
fontsize = 14)
ax.set_xlabel('θ', fontsize=14)
ax.set_ylabel('Counts', fontsize=14)
ax.legend(fontsize=14)
pyplot.show()
### Reducing Compilation Cost
import time
from itertools import combinations
from qiskit.compiler import assemble
from qiskit.test.mock import FakeVigo
# start with compiling over bound circuits
start = time.time()
qcs = []
theta_range = np.linspace(0, 2*np.pi, 32)
for n in theta_range:
qc = QuantumCircuit(5)
for k in range(8):
for i,j in combinations(range(5),2):
qc.cx(i,j)
qc.rz(n, range(5))
for i,j in combinations(range(5), 2):
qc.cx(i,j)
qcs.append(qc)
compiled_circuits = transpile(qcs, backend=FakeVigo())
qobj = assemble(compiled_circuits, backend=FakeVigo())
end = time.time()
print('Time compiling over set of bound circuits: ', end-start, 's')
# now, compile over parametrized circuits, then bind
start = time.time()
qc = QuantumCircuit(5)
theta = Parameter('theta')
for k in range(8):
for i,j in combinations(range(5), 2):
qc.cx(i,j)
qc.rz(theta, range(5))
for i,j in combinations(range(5), 2):
qc.cx(i,j)
transpiled_qc = transpile(qc, backend = FakeVigo())
qobj = assemble([transpiled_qc.bind_parameters({theta: n})
for n in theta_range], backend=FakeVigo())
end = time.time()
print('Time compiling over parameterized circuit, then binding: ', end-start, 's')
### Composition
# Parameterized circuits can be composed like standard quantum circuits, but
# the parameter names in each circuit must be unique across all circuits, unless
# the circuits use the same parameter
phi = Parameter('phi')
sub_circ1 = QuantumCircuit(2, name='sc_1')
sub_circ1.rz(phi, 0)
sub_circ1.rx(phi, 1)
sub_circ2 = QuantumCircuit(2, name='sc_2')
sub_circ2.rz(phi, 0)
sub_circ2.rx(phi, 1)
qc = QuantumCircuit(4)
qr = qc.qregs[0]
qc.append(sub_circ1.to_instruction(), [qr[0], qr[1]])
qc.append(sub_circ2.to_instruction(), [qr[0], qr[1]])
qc.append(sub_circ2.to_instruction(), [qr[2], qr[3]])
print(qc.draw())
# The following raises an error: "QiskitError: 'Name conflict on adding parameter: phi'"
# phi2 = Parameter('phi')
# qc.u(0.1, phi2, 0.3, 0)
# To insert a subcircuit under a different parameterization, the to_instruction method accepts an
# optional argument (parameter_map) which, when present, will generate instructions with the source parameter
# replaced by a new parameter.
p = Parameter('p')
qc = QuantumCircuit(3, name='oracle')
qc.rz(p, 0)
qc.cx(0,1)
qc.rz(p,1)
qc.cx(1, 2)
qc.rz(p, 2)
theta = Parameter('theta')
phi = Parameter('phi')
gamma = Parameter('gamma')
qr = QuantumRegister(9)
larger_qc = QuantumCircuit(qr)
larger_qc.append(qc.to_instruction({p: theta}), qr[0:3])
larger_qc.append(qc.to_instruction({p: phi}), qr[3:6])
larger_qc.append(qc.to_instruction({p: gamma}), qr[6:9])
print(larger_qc.draw())
print(larger_qc.decompose().draw())
|
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/OJB-Quantum/Qiskit-Metal-to-Litho
|
OJB-Quantum
|
import numpy as np
import qiskit_metal as metal
from qiskit_metal import designs, draw, MetalGUI, Dict, open_docs
#design.overwrite_enabled = True
#design.chips.main
#design.chips.main.size.size_x = '11mm'
#design.chips.main.size.size_y = '9mm'
# To launch the qiskit metal GUI,use the method MetalGUI.
design = designs.DesignPlanar()
gui = MetalGUI(design)
gui.screenshot()
%metal_heading Connecting QPins with coplanar waveguides (CPWs)
from qiskit_metal.qlibrary.qubits.transmon_pocket import TransmonPocket
# Allow running the same cell here multiple times to overwrite changes
design.overwrite_enabled = True
## Custom options for all the transmons
options = dict(
# Some options we want to modify from the deafults
# (see below for defaults)
pad_width = '425 um',
pocket_height = '650um',
# Adding 4 connectors (see below for defaults)
connection_pads=dict(
a = dict(loc_W=+1,loc_H=+1),
b = dict(loc_W=-1,loc_H=+1, pad_height='30um'),
c = dict(loc_W=+1,loc_H=-1, pad_width='200um'),
d = dict(loc_W=-1,loc_H=-1, pad_height='50um')
)
)
## Create 4 transmons
q1 = TransmonPocket(design, 'Q1', options = dict(
pos_x='+2.55mm', pos_y='+0.0mm', **options))
q2 = TransmonPocket(design, 'Q2', options = dict(
pos_x='+0.0mm', pos_y='-0.9mm', orientation = '90', **options))
q3 = TransmonPocket(design, 'Q3', options = dict(
pos_x='-2.55mm', pos_y='+0.0mm', **options))
q4 = TransmonPocket(design, 'Q4', options = dict(
pos_x='+0.0mm', pos_y='+0.9mm', orientation = '90', **options))
## Rebuild the design
gui.rebuild()
gui.autoscale()
gui.toggle_docks(True)
gui.screenshot()
# Import the basic cpw QComponent from the QLibrary. It is a class called RouteMeander. We can see its default options using RouteMeander.get_template_options(design)
from qiskit_metal.qlibrary.tlines.meandered import RouteMeander
RouteMeander.get_template_options(design)
options = Dict(
meander=Dict(
lead_start='0.1mm',
lead_end='0.1mm',
asymmetry='0 um')
)
def connect(component_name: str, component1: str, pin1: str, component2: str, pin2: str,
length: str,
asymmetry='0 um', flip=False):
"""Connect two pins with a CPW."""
myoptions = Dict(
pin_inputs=Dict(
start_pin=Dict(
component=component1,
pin=pin1),
end_pin=Dict(
component=component2,
pin=pin2)),
lead=Dict(
start_straight='0.13mm'
),
total_length=length,
fillet = '90um')
myoptions.update(options)
myoptions.meander.asymmetry = asymmetry
myoptions.meander.lead_direction_inverted = 'true' if flip else 'false'
return RouteMeander(design, component_name, myoptions)
asym = 150
cpw1 = connect('cpw1', 'Q1', 'd', 'Q2', 'c', '6.0 mm', f'+{asym}um')
cpw2 = connect('cpw2', 'Q3', 'c', 'Q2', 'a', '6.1 mm', f'-{asym}um', flip=True)
cpw3 = connect('cpw3', 'Q3', 'a', 'Q4', 'b', '6.0 mm', f'+{asym}um')
cpw4 = connect('cpw4', 'Q1', 'b', 'Q4', 'd', '6.1 mm', f'-{asym}um', flip=True)
gui.rebuild()
gui.autoscale()
gui.toggle_docks(True)
gui.highlight_components(['Q1','Q2','Q3','Q4','cpw1','cpw2','cpw3','cpw4'])
gui.screenshot()
design.components.keys()
# We can access the created CPW from the design too.
design.components.cpw2
# The design can have variables, which can be used in the component options.
design.variables.cpw_width = '10um'
design.variables.cpw_gap = '6um'
gui.rebuild()
# Ex: we can all qubit pads using the variables.
cpw1.options.lead.end_straight = '100um'
cpw2.options.lead.end_straight = '100um'
cpw3.options.lead.end_straight = '100um'
cpw4.options.lead.end_straight = '100um'
# Set variables in the design
design.variables.pad_width = '450 um'
design.variables.cpw_width = '25 um'
design.variables.cpw_gap = '12 um'
# Assign variables to component options
q1.options.pad_width = 'pad_width'
q2.options.pad_width = 'pad_width'
q3.options.pad_width = 'pad_width'
q4.options.pad_width = 'pad_width'
# Rebuild all compoinent and refresh the gui
gui.rebuild()
gui.autoscale()
gui.screenshot()
%metal_heading Render to GDS
gds = design.renderers.gds
gds.options.path_filename
gds.options.path_filename = '../resources/Fake_Junctions.GDS'
q1.options
gds.options.path_filename = "../resources/Fake_Junctions.GDS"
# Not sure what's going on here, however the GDS file is downloadable from the Qiskit Metal GUI.
design.renderers.gds.export_to_gds("4-Transmon_design.gds")
# Basic and crazy shapes.
# See their source code to see how to get started on a few simple examples.
from qiskit_metal.qlibrary.sample_shapes.n_square_spiral import NSquareSpiral
# print(NSquareSpiral.get_template_options(design))
ops = {
'n': '10',
'width': '5um',
'radius': '100um',
'gap': '22um',
'pos_x': '0.65mm',
'pos_y': '2.2mm',
'orientation': '0',
'subtract': 'False'}
NSquareSpiral(design, 'spiral', ops)
NSquareSpiral(design, 'spiral_cut', {**ops, **dict(subtract=True, width='22um', gap='10um')})
gui.rebuild()
# To see source, try ??NSquareSpiral. Go to the actual source file and edit it, copy it, or edit it in the GUI using the Edit Source button.
from qiskit_metal.qlibrary.tlines.straight_path import RouteStraight
# CpwStraightLine.get_template_options(design)
myoptions = Dict(
pin_inputs=Dict(
start_pin=Dict(
component='Q4',
pin='c'),
end_pin=Dict(
component='spiral',
pin='spiralPin'))
)
RouteStraight(design, 'cpw_s1', myoptions);
gui.rebuild()
qcomponents = ['spiral', 'cpw_s1']
gui.highlight_components(qcomponents)
gui.zoom_on_components(qcomponents)
gui.screenshot()
# N-Gon version. Orientation is in degrees.
from qiskit_metal.qlibrary.sample_shapes.n_gon import NGon
# display(NGon.get_template_options(design))
ops = {
'n': '6',
'radius': '250um',
'pos_x': '-0.85mm',
'pos_y': '2.0mm',
'orientation': '0',
'subtract': 'False',
'helper': 'False',
'chip': 'main',
'layer': '1'}
NGon(design, 'ngon', ops)
NGon(design, 'ngon_negative', {**ops, **dict(subtract=True, radius='350um')})
gui.rebuild()
gui.zoom_on_components(['ngon_negative'])
gui.screenshot()
# Generate a circle with certain radius.
from qiskit_metal.qlibrary.sample_shapes.circle_raster import CircleRaster
display(CircleRaster.get_template_options(design))
ops = { 'radius': '10um',
'pos_x': '-1.5mm',
'pos_y': '2mm',
'resolution': '16',
'cap_style': 'round',
'subtract': 'False',
'helper': 'False',
'chip': 'main',
'layer': '1'}
CircleRaster(design, 'CircleRaster', ops)
gui.rebuild()
gui.zoom_on_components(['CircleRaster'])
gui.screenshot()
# Generate a hollow rectangle. Orientation is in degrees.
from qiskit_metal.qlibrary.sample_shapes.rectangle_hollow import RectangleHollow
display(RectangleHollow.get_template_options(design))
ops = { 'width': '500um',
'height': '300um',
'pos_x': '-2.3mm',
'pos_y': '2mm',
'orientation': '0',
'subtract': 'False',
'helper': 'False',
'chip': 'main',
'layer': '1',
'inner': { 'width': '250um',
'height': '100um',
'offset_x': '40um',
'offset_y': '-20um',
'orientation': '15'}}
RectangleHollow(design, 'RectangleHollow', ops)
gui.rebuild()
gui.zoom_on_components(['RectangleHollow'])
gui.screenshot()
gui.autoscale()
gui.screenshot()
# Return the boundry box of the geometry, for example: q1.qgeometry_bounds().
# The function returns a tuple containing (minx, miny, maxx, maxy) bound values for the bounds of the component as a whole.
for name, qcomponent in design.components.items():
print(f"{name:10s} : {qcomponent.qgeometry_bounds()}")
# We can get all the QGeometry of a QComponent. There are several kinds, such as path and poly. Let us look at all the polygons used to create qubit q1.
q1.qgeometry_table('poly')
q1.qgeometry_table('path')
q1.qgeometry_table('junction')
# Use this code to close the Qiskit Metal GUI.
gui.main_window.close()
|
https://github.com/MiChaelinzo/Quantum-time-travel
|
MiChaelinzo
|
from qiskit import QuantumCircuit
from qiskit.circuit.library import ZZFeatureMap
from qiskit.ml.datasets import ad_hoc_data
from qiskit.circuit.library import TwoLocal
from qiskit.aqua import QuantumInstance
from qiskit.aqua.algorithms import QSVM
# Prepare data (example using ad hoc dataset)
feature_dim = 2
sample_total, training_input, test_input, class_labels = ad_hoc_data(
training_size=20,
test_size=10,
n=feature_dim,
gap=0.3,
plot_data=False
)
# Feature map and ansatz
feature_map = ZZFeatureMap(feature_dimension=feature_dim, reps=2)
ansatz = TwoLocal(feature_dim, ['ry', 'rz'], 'cz', reps=2)
# QSVM setup
qsvm = QSVM(feature_map, ansatz, training_input, test_input, class_labels)
# Run QSVM (using a simulator backend)
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1024)
result = qsvm.run(quantum_instance)
# Analyze results (example: prediction accuracy)
print(f'Testing accuracy: {result["testing_accuracy"]}')
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
#!/usr/bin/env python3
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Utility to check that slow imports are not used in the default path."""
import subprocess
import sys
# This is not unused: importing it sets up sys.modules
import qiskit # pylint: disable=unused-import
def _main():
optional_imports = [
"networkx",
"sympy",
"pydot",
"pygments",
"ipywidgets",
"scipy.stats",
"matplotlib",
"qiskit.providers.aer",
"qiskit.providers.ibmq",
"qiskit.ignis",
"qiskit.aqua",
"docplex",
]
modules_imported = []
for mod in optional_imports:
if mod in sys.modules:
modules_imported.append(mod)
if not modules_imported:
sys.exit(0)
res = subprocess.run(
[sys.executable, "-X", "importtime", "-c", "import qiskit"],
capture_output=True,
encoding="utf8",
check=True,
)
import_tree = [
x.split("|")[-1]
for x in res.stderr.split("\n")
if "RuntimeWarning" not in x or "warnings.warn" not in x
]
indent = -1
matched_module = None
for module in import_tree:
line_indent = len(module) - len(module.lstrip())
module_name = module.strip()
if module_name in modules_imported:
if indent > 0:
continue
indent = line_indent
matched_module = module_name
if indent > 0:
if line_indent < indent:
print(f"ERROR: {matched_module} is imported via {module_name}")
indent = -1
matched_module = None
sys.exit(len(modules_imported))
if __name__ == "__main__":
_main()
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
import numpy as np
def cnot_matrix_ab(d):
cn = np.zeros((d**2,d**2),dtype=int)
for p in range(0,d): # d^2 elementos não nulos
for q in range(0,d):
cn[p*d+(p+q)%d,p*d+q] = 1
return cn
d=2; cn = cnot_matrix_ab(d); print(cn)
d=3; cn = cnot_matrix_ab(d); print(cn)
d=4; cn = cnot_matrix_ab(d); print(cn)
import numpy as np
def cnot_matrix(d, ctr):
cn = np.zeros((d**2,d**2),dtype=int)
if ctr == 'a':
for p in range(0,d):
for q in range(0,d):
cn[p*d+(p+q)%d,p*d+q] = 1
elif ctr == 'b':
for p in range(0,d):
for q in range(0,d):
cn[((q+p)%d)*d+q,p*d+q] = 1
return cn
d=2; print(cnot_matrix(d, 'b')) # ok!
d=3; print(cnot_matrix(d, 'b'))
def den2dec(local,d):
# local = list with the local computational base state values
# d = individual qudit dimension
N = len(local)
j = 0
for k in range(0,N):
j += local[k]*d**(N-1-k)
return j # value of the global computational basis index
# example: 3 qutrits
d = 3; N = 3
local = [0,0,0]
for j0 in range(0,3):
for j1 in range(0,3):
for j2 in range(0,3):
local = [j0,j1,j2]
j = den2dec(local,d)
print('j0 j1 j2 =',j0,j1,j2,', j =',j)
def dec2den(j,N,d):
den = [0 for k in range(0,N)]
jv = j
for k in range(0,N):
if jv >= d**(N-1-k):
den[k] = jv//(d**(N-1-k))
jv = jv - den[k]*d**(N-1-k)
return den
N = 3; d = 3
for j in range(0,d**N):
print('j=',j,', den=', dec2den(j,N,d))
def dec2den_opt(j,N,d): # optmized version
den = [0 for k in range(0,N)]
if j < d:
den[N-1] = j; return den
rem = [] # list for the remainders
k = j
while k >= d:
rem.append(k%d)
k = k//d
rem.append(k%d)
for j in range(0,len(rem)):
den[N-1-j] = rem[j]
return den
N = 3; d = 3
for j in range(0,d**N):
print('j=',j,', den=', dec2den_opt(j,N,d))
def cnot_qudits(d,N,t,c):
# d = qudit dimension; N = No. of qudits; t = target qudit (0,...,N-1); c = control qudit (0,...,N-1)
D = d**N; cnot = np.zeros((D,D), dtype=int) # set all d^2N elements to 0
for k in range (0,d**N):
localr = dec2den_opt(k,N,d) # sequence os values for the local basis
locall = localr.copy() # copy the right list to the left list
locall[t] = (localr[t]+localr[c])%d
globall = den2dec(locall,d)
cnot[globall,k] = 1
return cnot
d=2; N=2; t=1; c=0; cnot = cnot_qudits(d,N,t,c); print(cnot) # ok!
d=2; N=2; t=0; c=1; cnot = cnot_qudits(d,N,t,c); print(cnot) # ok!
d=3; N=2; t=1; c=0; cnot = cnot_qudits(d,N,t,c); print(cnot) # ok!
d=2; N=3; t=2; c=0; cnot = cnot_qudits(d,N,t,c); print(cnot) # ok
from sympy import init_printing, Matrix
init_printing(use_unicode=True)
from sympy.physics.quantum import TensorProduct
def tp(x,y):
return TensorProduct(x,y)
s1 = Matrix([[0,1],[1,0]]); s0 = Matrix([[1,0],[0,1]]); P0 = Matrix([[1,0],[0,0]]); P1 = Matrix([[0,0],[0,1]])
cnot03 = tp(tp(P0,s0),s0) + tp(tp(P1,s0),s1); cnot03
d=3; N=3; t=1; c=0; cnot = cnot_qudits(d,N,t,c); print(cnot) # ok
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
ghz = QuantumCircuit(5)
ghz.h(0)
ghz.cx(0,range(1,5))
ghz.draw(output='mpl')
|
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
|
SaashaJoshi
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
# our backend is the Pulse Simulator
from resources import helper
from qiskit.providers.aer import PulseSimulator
backend_sim = PulseSimulator()
# sample duration for pulse instructions
dt = 1e-9
# create the model
duffing_model = helper.get_transmon(dt)
# get qubit frequency from Duffing model
qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift()
import numpy as np
# visualization tools
import matplotlib.pyplot as plt
plt.style.use('dark_background')
# unit conversion factors -> all backend properties returned in SI (Hz, sec, etc)
GHz = 1.0e9 # Gigahertz
MHz = 1.0e6 # Megahertz
kHz = 1.0e3 # kilohertz
us = 1.0e-6 # microseconds
ns = 1.0e-9 # nanoseconds
from qiskit import pulse
from qiskit.pulse import Play, Acquire
from qiskit.pulse.pulse_lib import GaussianSquare
# qubit to be used throughout the notebook
qubit = 0
### Collect the necessary channels
drive_chan = pulse.DriveChannel(qubit)
meas_chan = pulse.MeasureChannel(qubit)
acq_chan = pulse.AcquireChannel(qubit)
# Construct a measurement schedule and add it to an InstructionScheduleMap
meas_samples = 1200
meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150)
measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit))
inst_map = pulse.InstructionScheduleMap()
inst_map.add('measure', [qubit], measure_sched)
# save the measurement/acquire pulse for later
measure = inst_map.get('measure', qubits=[qubit])
from qiskit.pulse import pulse_lib
def build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma):
### create a Rabi schedule (already done)
### create a Gaussian Rabi pulse using pulse_lib
### play Rabi pulse on the Rabi schedule and return
rabi_schedule = pulse.Schedule(name='rabi_experiment')
### WRITE YOUR CODE BETWEEN THESE LINES - START
rabi_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp,
sigma=drive_sigma)
rabi_schedule = pulse.Schedule()
rabi_schedule += Play(rabi_pulse, drive_chan)
### WRITE YOUR CODE BETWEEN THESE LINES - END
# add measurement to rabi_schedule
# << indicates time shift the beginning to the start of the schedule
rabi_schedule += measure << rabi_schedule.duration
return rabi_schedule
# Gaussian pulse parameters, with varying amplitude
drive_duration = 128
num_rabi_points = 41
drive_amps = np.linspace(0, 0.9, num_rabi_points)
drive_sigma = 16
# now vary the amplitude for each drive amp
rabi_schedules = []
for drive_amp in drive_amps:
rabi_schedules.append(build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma))
rabi_schedules[-1].draw()
# assemble the schedules into a Qobj
from qiskit import assemble
rabi_qobj = assemble(**helper.get_params('rabi', globals()))
answer1a = rabi_qobj
# run the simulation
rabi_result = backend_sim.run(rabi_qobj, duffing_model).result()
# retrieve the data from the experiment
rabi_values = helper.get_values_from_result(rabi_result, qubit)
fit_params, y_fit = helper.fit_sinusoid(drive_amps, rabi_values, [1, 0, 0.5, 0])
plt.scatter(drive_amps, rabi_values, color='white')
plt.plot(drive_amps, y_fit, color='red')
drive_period = fit_params[2] # get period of rabi oscillation
plt.axvline(0, color='red', linestyle='--')
plt.axvline(drive_period/2, color='red', linestyle='--')
plt.xlabel("Drive amp [a.u.]", fontsize=15)
plt.ylabel("Measured signal [a.u.]", fontsize=15)
plt.show()
print("Pi pulse amplitude is %f"%float(drive_period/2))
# x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees
x90_pulse = pulse_lib.gaussian(duration=drive_duration,
amp=drive_period/4,
sigma=drive_sigma,
name='x90_pulse')
# Ramsey experiment parameters
time_max_us = 0.4
time_step_us = 0.0035
times_us = np.arange(0.1, time_max_us, time_step_us)
# Convert to units of dt
delay_times_dt = times_us * us / dt
def build_ramsey_pulse_schedule(delay):
### create a Ramsey pulse schedule (already done)
### play an x90 pulse on the drive channel
### play another x90 pulse after delay
### add measurement pulse to schedule
ramsey_schedule = pulse.Schedule(name='ramsey_experiment')
### HINT: include delay by adding it to the duration of the schedule
### round delay to nearest integer with int(delay)
### WRITE YOUR CODE BETWEEN THESE LINES - START
ramsey_schedule = pulse.Schedule()
ramsey_schedule += Play(x90_pulse, drive_chan)
ramsey_schedule += Play(x90_pulse, drive_chan) << ramsey_schedule.duration + int(delay)
ramsey_schedule += measure << ramsey_schedule.duration
### WRITE YOUR CODE BETWEEN THESE LINES - END
return ramsey_schedule
# create schedules for Ramsey experiment
ramsey_schedules = []
for delay in delay_times_dt:
ramsey_schedules.append(build_ramsey_pulse_schedule(delay))
ramsey_schedules[-1].draw()
# assemble the schedules into a Qobj
# the helper will drive the pulses off-resonantly by an unknown value
ramsey_qobj = assemble(**helper.get_params('ramsey', globals()))
answer1b = ramsey_qobj
# run the simulation
ramsey_result = backend_sim.run(ramsey_qobj, duffing_model).result()
# retrieve the data from the experiment
ramsey_values = helper.get_values_from_result(ramsey_result, qubit)
# off-resonance component
fit_params, y_fit = helper.fit_sinusoid(times_us, ramsey_values, [1, 0.7, 0.1, 0.25])
_, _, ramsey_period_us, _, = fit_params
del_f_MHz = 1/ramsey_period_us # freq is MHz since times in us
plt.scatter(times_us, np.real(ramsey_values), color='white')
plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.6f} MHz")
plt.xlim(np.min(times_us), np.max(times_us))
plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15)
plt.ylabel('Measured Signal [a.u.]', fontsize=15)
plt.title('Ramsey Experiment', fontsize=15)
plt.legend(loc=3)
plt.show()
print("Drive is off-resonant by %f MHz"%float(del_f_MHz))
name = 'Saasha Joshi'
email = 'saashajoshi08@gmail.com'
from grading_tools import grade
grade(answer1a, name, email, 'lab6', 'ex1a')
grade(answer1b, name, email, 'lab6', 'ex1b')
from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();'));
from grading_tools import send_code;send_code('ex1.ipynb')
|
https://github.com/qiskit-community/qiskit-jku-provider
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
""" pauli common functions """
import logging
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.algorithms import AlgorithmError
from qiskit.circuit import Parameter, ParameterExpression
from qiskit.qasm import pi
from qiskit.quantum_info import Pauli # pylint: disable=unused-import
logger = logging.getLogger(__name__)
# pylint: disable=too-many-arguments,too-many-branches,too-many-locals
def pauli_measurement(circuit, pauli, qreg, creg, barrier=False):
"""
Add the proper post-rotation gate on the circuit.
Args:
circuit (QuantumCircuit): the circuit to be modified.
pauli (Pauli): the pauli will be added.
qreg (QuantumRegister): the quantum register associated with the circuit.
creg (ClassicalRegister): the classical register associated with the circuit.
barrier (bool, optional): whether or not add barrier before measurement.
Returns:
QuantumCircuit: the original circuit object with post-rotation gate
"""
num_qubits = pauli.num_qubits
for qubit_idx in range(num_qubits):
if pauli.x[qubit_idx]:
if pauli.z[qubit_idx]:
# Measure Y
circuit.sdg(qreg[qubit_idx]) # sdg
circuit.h(qreg[qubit_idx]) # h
else:
# Measure X
circuit.h(qreg[qubit_idx]) # h
if barrier:
circuit.barrier(qreg[qubit_idx])
circuit.measure(qreg[qubit_idx], creg[qubit_idx])
return circuit
def measure_pauli_z(data, pauli):
"""
Appropriate post-rotations on the state are assumed.
Args:
data (dict): a dictionary of the form data = {'00000': 10} ({str: int})
pauli (Pauli): a Pauli object
Returns:
float: Expected value of paulis given data
"""
observable = 0.0
num_shots = sum(data.values())
p_z_or_x = np.logical_or(pauli.z, pauli.x)
for key, value in data.items():
bitstr = np.asarray(list(key))[::-1].astype(int).astype(bool)
# pylint: disable=no-member
sign = -1.0 if np.logical_xor.reduce(np.logical_and(bitstr, p_z_or_x)) else 1.0
observable += sign * value
observable /= num_shots
return observable
def covariance(data, pauli_1, pauli_2, avg_1, avg_2):
"""
Compute the covariance matrix element between two
Paulis, given the measurement outcome.
Appropriate post-rotations on the state are assumed.
Args:
data (dict): a dictionary of the form data = {'00000': 10} ({str:int})
pauli_1 (Pauli): a Pauli class member
pauli_2 (Pauli): a Pauli class member
avg_1 (float): expectation value of pauli_1 on `data`
avg_2 (float): expectation value of pauli_2 on `data`
Returns:
float: the element of the covariance matrix between two Paulis
"""
cov = 0.0
num_shots = sum(data.values())
if num_shots == 1:
return cov
p1_z_or_x = np.logical_or(pauli_1.z, pauli_1.x)
p2_z_or_x = np.logical_or(pauli_2.z, pauli_2.x)
for key, value in data.items():
bitstr = np.asarray(list(key))[::-1].astype(int).astype(bool)
# pylint: disable=no-member
sign_1 = (
-1.0 if np.logical_xor.reduce(np.logical_and(bitstr, p1_z_or_x)) else 1.0
)
sign_2 = (
-1.0 if np.logical_xor.reduce(np.logical_and(bitstr, p2_z_or_x)) else 1.0
)
cov += (sign_1 - avg_1) * (sign_2 - avg_2) * value
cov /= num_shots - 1
return cov
# pylint: disable=invalid-name
def suzuki_expansion_slice_pauli_list(pauli_list, lam_coef, expansion_order):
"""
Compute the list of pauli terms for a single slice of the suzuki expansion following the paper
https://arxiv.org/pdf/quant-ph/0508139.pdf.
Args:
pauli_list (list[list[complex, Pauli]]): The slice's weighted Pauli list for the
suzuki expansion
lam_coef (float): The parameter lambda as defined in said paper,
adjusted for the evolution time and the number of time slices
expansion_order (int): The order for suzuki expansion
Returns:
list: slice pauli list
"""
if expansion_order == 1:
half = [[lam_coef / 2 * c, p] for c, p in pauli_list]
res = half + list(reversed(half))
else:
p_k = (4 - 4 ** (1 / (2 * expansion_order - 1))) ** -1
side_base = suzuki_expansion_slice_pauli_list(
pauli_list, lam_coef * p_k, expansion_order - 1
)
side = side_base * 2
middle = suzuki_expansion_slice_pauli_list(
pauli_list, lam_coef * (1 - 4 * p_k), expansion_order - 1
)
res = side + middle + side
return res
def check_commutativity(op_1, op_2, anti=False):
"""
Check the (anti-)commutativity between two operators.
Args:
op_1 (WeightedPauliOperator): operator
op_2 (WeightedPauliOperator): operator
anti (bool): if True, check anti-commutativity, otherwise check commutativity.
Returns:
bool: whether or not two operators are commuted or anti-commuted.
"""
com = op_1 * op_2 - op_2 * op_1 if not anti else op_1 * op_2 + op_2 * op_1
com.simplify()
return bool(com.is_empty())
# pylint: disable=too-many-statements
def evolution_instruction(
pauli_list,
evo_time,
num_time_slices,
controlled=False,
power=1,
use_basis_gates=True,
shallow_slicing=False,
barrier=False,
):
"""
Construct the evolution circuit according to the supplied specification.
Args:
pauli_list (list([[complex, Pauli]])): The list of pauli terms corresponding
to a single time slice to be evolved
evo_time (Union(complex, float, Parameter, ParameterExpression)): The evolution time
num_time_slices (int): The number of time slices for the expansion
controlled (bool, optional): Controlled circuit or not
power (int, optional): The power to which the unitary operator is to be raised
use_basis_gates (bool, optional): boolean flag for indicating only using basis
gates when building circuit.
shallow_slicing (bool, optional): boolean flag for indicating using shallow
qc.data reference repetition for slicing
barrier (bool, optional): whether or not add barrier for every slice
Returns:
Instruction: The Instruction corresponding to specified evolution.
Raises:
AlgorithmError: power must be an integer and greater or equal to 1
ValueError: Unrecognized pauli
"""
if not isinstance(power, int) or power < 1:
raise AlgorithmError("power must be an integer and greater or equal to 1.")
state_registers = QuantumRegister(pauli_list[0][1].num_qubits)
if controlled:
inst_name = f"Controlled-Evolution^{power}"
ancillary_registers = QuantumRegister(1)
qc_slice = QuantumCircuit(state_registers, ancillary_registers, name=inst_name)
else:
inst_name = f"Evolution^{power}"
qc_slice = QuantumCircuit(state_registers, name=inst_name)
# for each pauli [IXYZ]+, record the list of qubit pairs needing CX's
cnot_qubit_pairs = [None] * len(pauli_list)
# for each pauli [IXYZ]+, record the highest index of the nontrivial pauli gate (X,Y, or Z)
top_xyz_pauli_indices = [-1] * len(pauli_list)
for pauli_idx, pauli in enumerate(reversed(pauli_list)):
n_qubits = pauli[1].num_qubits
# changes bases if necessary
nontrivial_pauli_indices = []
for qubit_idx in range(n_qubits):
# pauli I
if not pauli[1].z[qubit_idx] and not pauli[1].x[qubit_idx]:
continue
if cnot_qubit_pairs[pauli_idx] is None:
nontrivial_pauli_indices.append(qubit_idx)
if pauli[1].x[qubit_idx]:
# pauli X
if not pauli[1].z[qubit_idx]:
if use_basis_gates:
qc_slice.h(state_registers[qubit_idx])
else:
qc_slice.h(state_registers[qubit_idx])
# pauli Y
elif pauli[1].z[qubit_idx]:
if use_basis_gates:
qc_slice.u(pi / 2, -pi / 2, pi / 2, state_registers[qubit_idx])
else:
qc_slice.rx(pi / 2, state_registers[qubit_idx])
# pauli Z
elif pauli[1].z[qubit_idx] and not pauli[1].x[qubit_idx]:
pass
else:
raise ValueError(f"Unrecognized pauli: {pauli[1]}")
if nontrivial_pauli_indices:
top_xyz_pauli_indices[pauli_idx] = nontrivial_pauli_indices[-1]
# insert lhs cnot gates
if cnot_qubit_pairs[pauli_idx] is None:
cnot_qubit_pairs[pauli_idx] = list(
zip(
sorted(nontrivial_pauli_indices)[:-1],
sorted(nontrivial_pauli_indices)[1:],
)
)
for pair in cnot_qubit_pairs[pauli_idx]:
qc_slice.cx(state_registers[pair[0]], state_registers[pair[1]])
# insert Rz gate
if top_xyz_pauli_indices[pauli_idx] >= 0:
# Because Parameter does not support complexity number operation; thus, we do
# the following tricks to generate parameterized instruction.
# We assume the coefficient in the pauli is always real. and can not do imaginary time
# evolution
if isinstance(evo_time, (Parameter, ParameterExpression)):
lam = 2.0 * pauli[0] / num_time_slices
lam = lam.real if lam.imag == 0 else lam
lam = lam * evo_time
else:
lam = (2.0 * pauli[0] * evo_time / num_time_slices).real
if not controlled:
if use_basis_gates:
qc_slice.p(lam, state_registers[top_xyz_pauli_indices[pauli_idx]])
else:
qc_slice.rz(lam, state_registers[top_xyz_pauli_indices[pauli_idx]])
else:
if use_basis_gates:
qc_slice.p(
lam / 2, state_registers[top_xyz_pauli_indices[pauli_idx]]
)
qc_slice.cx(
ancillary_registers[0],
state_registers[top_xyz_pauli_indices[pauli_idx]],
)
qc_slice.p(
-lam / 2, state_registers[top_xyz_pauli_indices[pauli_idx]]
)
qc_slice.cx(
ancillary_registers[0],
state_registers[top_xyz_pauli_indices[pauli_idx]],
)
else:
qc_slice.crz(
lam,
ancillary_registers[0],
state_registers[top_xyz_pauli_indices[pauli_idx]],
)
# insert rhs cnot gates
for pair in reversed(cnot_qubit_pairs[pauli_idx]):
qc_slice.cx(state_registers[pair[0]], state_registers[pair[1]])
# revert bases if necessary
for qubit_idx in range(n_qubits):
if pauli[1].x[qubit_idx]:
# pauli X
if not pauli[1].z[qubit_idx]:
if use_basis_gates:
qc_slice.h(state_registers[qubit_idx])
else:
qc_slice.h(state_registers[qubit_idx])
# pauli Y
elif pauli[1].z[qubit_idx]:
if use_basis_gates:
qc_slice.u(-pi / 2, -pi / 2, pi / 2, state_registers[qubit_idx])
else:
qc_slice.rx(-pi / 2, state_registers[qubit_idx])
# repeat the slice
if shallow_slicing:
logger.info(
"Under shallow slicing mode, the qc.data reference is repeated shallowly. "
"Thus, changing gates of one slice of the output circuit might affect "
"other slices."
)
if barrier:
qc_slice.barrier(state_registers)
qc_slice.data *= num_time_slices * power
qc = qc_slice
else:
qc = QuantumCircuit(*qc_slice.qregs, name=inst_name)
for _ in range(num_time_slices * power):
qc.append(qc_slice, qc.qubits)
if barrier:
qc.barrier(state_registers)
return qc.to_instruction()
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests PassManagerConfig"""
from qiskit import QuantumRegister
from qiskit.providers.backend import Backend
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeMelbourne, FakeArmonk, FakeHanoi, FakeHanoiV2
from qiskit.providers.basicaer import QasmSimulatorPy
from qiskit.transpiler.coupling import CouplingMap
from qiskit.transpiler.passmanager_config import PassManagerConfig
class TestPassManagerConfig(QiskitTestCase):
"""Test PassManagerConfig.from_backend()."""
def test_config_from_backend(self):
"""Test from_backend() with a valid backend.
`FakeHanoi` is used in this testcase. This backend has `defaults` attribute
that contains an instruction schedule map.
"""
backend = FakeHanoi()
config = PassManagerConfig.from_backend(backend)
self.assertEqual(config.basis_gates, backend.configuration().basis_gates)
self.assertEqual(config.inst_map, backend.defaults().instruction_schedule_map)
self.assertEqual(
str(config.coupling_map), str(CouplingMap(backend.configuration().coupling_map))
)
def test_config_from_backend_v2(self):
"""Test from_backend() with a BackendV2 instance."""
backend = FakeHanoiV2()
config = PassManagerConfig.from_backend(backend)
self.assertEqual(config.basis_gates, backend.operation_names)
self.assertEqual(config.inst_map, backend.instruction_schedule_map)
self.assertEqual(config.coupling_map.get_edges(), backend.coupling_map.get_edges())
def test_invalid_backend(self):
"""Test from_backend() with an invalid backend."""
with self.assertRaises(AttributeError):
PassManagerConfig.from_backend(Backend())
def test_from_backend_and_user(self):
"""Test from_backend() with a backend and user options.
`FakeMelbourne` is used in this testcase. This backend does not have
`defaults` attribute and thus not provide an instruction schedule map.
"""
qr = QuantumRegister(4, "qr")
initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]]
backend = FakeMelbourne()
config = PassManagerConfig.from_backend(
backend, basis_gates=["user_gate"], initial_layout=initial_layout
)
self.assertEqual(config.basis_gates, ["user_gate"])
self.assertNotEqual(config.basis_gates, backend.configuration().basis_gates)
self.assertIsNone(config.inst_map)
self.assertEqual(
str(config.coupling_map), str(CouplingMap(backend.configuration().coupling_map))
)
self.assertEqual(config.initial_layout, initial_layout)
def test_from_backendv1_inst_map_is_none(self):
"""Test that from_backend() works with backend that has defaults defined as None."""
backend = FakeHanoi()
backend.defaults = lambda: None
config = PassManagerConfig.from_backend(backend)
self.assertIsInstance(config, PassManagerConfig)
self.assertIsNone(config.inst_map)
def test_simulator_backend_v1(self):
"""Test that from_backend() works with backendv1 simulator."""
backend = QasmSimulatorPy()
config = PassManagerConfig.from_backend(backend)
self.assertIsInstance(config, PassManagerConfig)
self.assertIsNone(config.inst_map)
self.assertIsNone(config.coupling_map)
def test_invalid_user_option(self):
"""Test from_backend() with an invalid user option."""
with self.assertRaises(TypeError):
PassManagerConfig.from_backend(FakeMelbourne(), invalid_option=None)
def test_str(self):
"""Test string output."""
pm_config = PassManagerConfig.from_backend(FakeArmonk())
# For testing remove instruction schedule map it's str output is non-deterministic
# based on hash seed
pm_config.inst_map = None
str_out = str(pm_config)
expected = """Pass Manager Config:
initial_layout: None
basis_gates: ['id', 'rz', 'sx', 'x']
inst_map: None
coupling_map: None
layout_method: None
routing_method: None
translation_method: None
scheduling_method: None
instruction_durations: id(0,): 7.111111111111111e-08 s
rz(0,): 0.0 s
sx(0,): 7.111111111111111e-08 s
x(0,): 7.111111111111111e-08 s
measure(0,): 4.977777777777777e-06 s
backend_properties: {'backend_name': 'ibmq_armonk',
'backend_version': '2.4.3',
'gates': [{'gate': 'id',
'name': 'id0',
'parameters': [{'date': datetime.datetime(2021, 3, 15, 0, 38, 15, tzinfo=tzoffset(None, -14400)),
'name': 'gate_error',
'unit': '',
'value': 0.00019769550670970334},
{'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)),
'name': 'gate_length',
'unit': 'ns',
'value': 71.11111111111111}],
'qubits': [0]},
{'gate': 'rz',
'name': 'rz0',
'parameters': [{'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)),
'name': 'gate_error',
'unit': '',
'value': 0},
{'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)),
'name': 'gate_length',
'unit': 'ns',
'value': 0}],
'qubits': [0]},
{'gate': 'sx',
'name': 'sx0',
'parameters': [{'date': datetime.datetime(2021, 3, 15, 0, 38, 15, tzinfo=tzoffset(None, -14400)),
'name': 'gate_error',
'unit': '',
'value': 0.00019769550670970334},
{'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)),
'name': 'gate_length',
'unit': 'ns',
'value': 71.11111111111111}],
'qubits': [0]},
{'gate': 'x',
'name': 'x0',
'parameters': [{'date': datetime.datetime(2021, 3, 15, 0, 38, 15, tzinfo=tzoffset(None, -14400)),
'name': 'gate_error',
'unit': '',
'value': 0.00019769550670970334},
{'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)),
'name': 'gate_length',
'unit': 'ns',
'value': 71.11111111111111}],
'qubits': [0]}],
'general': [],
'last_update_date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)),
'qubits': [[{'date': datetime.datetime(2021, 3, 15, 0, 36, 17, tzinfo=tzoffset(None, -14400)),
'name': 'T1',
'unit': 'us',
'value': 182.6611165336624},
{'date': datetime.datetime(2021, 3, 14, 0, 33, 45, tzinfo=tzoffset(None, -18000)),
'name': 'T2',
'unit': 'us',
'value': 237.8589220110257},
{'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)),
'name': 'frequency',
'unit': 'GHz',
'value': 4.971852852405576},
{'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)),
'name': 'anharmonicity',
'unit': 'GHz',
'value': -0.34719293148282626},
{'date': datetime.datetime(2021, 3, 15, 0, 35, 20, tzinfo=tzoffset(None, -14400)),
'name': 'readout_error',
'unit': '',
'value': 0.02400000000000002},
{'date': datetime.datetime(2021, 3, 15, 0, 35, 20, tzinfo=tzoffset(None, -14400)),
'name': 'prob_meas0_prep1',
'unit': '',
'value': 0.0234},
{'date': datetime.datetime(2021, 3, 15, 0, 35, 20, tzinfo=tzoffset(None, -14400)),
'name': 'prob_meas1_prep0',
'unit': '',
'value': 0.024599999999999955},
{'date': datetime.datetime(2021, 3, 15, 0, 35, 20, tzinfo=tzoffset(None, -14400)),
'name': 'readout_length',
'unit': 'ns',
'value': 4977.777777777777}]]}
approximation_degree: None
seed_transpiler: None
timing_constraints: None
unitary_synthesis_method: default
unitary_synthesis_plugin_config: None
target: None
"""
self.assertEqual(str_out, expected)
|
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
|
ronitd2002
|
from qiskit import QuantumCircuit
# Create a new circuit with a single qubit
qc = QuantumCircuit(1)
# Add a Not gate to qubit 0
qc.x(0)
# Return a drawing of the circuit using MatPlotLib ("mpl"). This is the
# last line of the cell, so the drawing appears in the cell output.
qc.draw("mpl")
### CHECK QISKIT VERSION
import qiskit
qiskit.__version__
### CHECK OTHER DEPENDENCIES
%pip show pylatexenc matplotlib qc_grader
#qc-grader should be 0.18.8 (or higher)
### Imports
from qiskit import QuantumCircuit
from qiskit.quantum_info import SparsePauliOp
from qiskit_ibm_runtime import EstimatorV2 as Estimator
from qiskit_aer import AerSimulator
import matplotlib.pyplot as plt
from qc_grader.challenges.iqc_2024 import grade_lab0_ex1
# Create a new circuit with two qubits
qc = QuantumCircuit(2)
# Add a Hadamard gate to qubit 0
qc.h(0)
# Perform a CNOT gate on qubit 1, controlled by qubit 0
qc.cx(0, 1)
# Return a drawing of the circuit using MatPlotLib ("mpl"). This is the
# last line of the cell, so the drawing appears in the cell output.
qc.draw("mpl")
# The ZZ applies a Z operator on qubit 0, and a Z operator on qubit 1
ZZ = SparsePauliOp('ZZ')
# The ZI applies a Z operator on qubit 0, and an Identity operator on qubit 1
ZI = SparsePauliOp('ZI')
# The IX applies an Identity operator on qubit 0, and an X operator on qubit 1
IX = SparsePauliOp('IX')
### Write your code below here ###
IZ = SparsePauliOp('IZ')
XX = SparsePauliOp('XX')
XI = SparsePauliOp('XI')
### Follow the same naming convention we used above
## Don't change any code past this line, but remember to run the cell.
observables = [IZ, IX, ZI, XI, ZZ, XX]
# Submit your answer using following code
grade_lab0_ex1(observables)
# Set up the Estimator
estimator = Estimator(backend=AerSimulator())
# Submit the circuit to Estimator
pub = (qc, observables)
job = estimator.run(pubs=[pub])
# Collect the data
data = ['IZ', 'IX', 'ZI', 'XI', 'ZZ', 'XX']
values = job.result()[0].data.evs
# Set up our graph
container = plt.plot(data, values, '-o')
# Label each axis
plt.xlabel('Observables')
plt.ylabel('Values')
# Draw the final graph
plt.show()
container = plt.bar(data, values, width=0.8)
plt.xlabel('Observables')
plt.ylabel('Values')
plt.show()
|
https://github.com/maryrbarros2/QuantumAlgorithms_Qiskit
|
maryrbarros2
|
# Do the necessary imports
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, BasicAer, IBMQ
from qiskit.visualization import plot_histogram, plot_bloch_multivector
### Creating 3 qubit and 2 classical bits in each separate register
qr = QuantumRegister(3)
crz = ClassicalRegister(1)
crx = ClassicalRegister(1)
teleportation_circuit = QuantumCircuit(qr, crz, crx)
### A third party eve helps to create an entangled state
def create_bell_pair(qc, a, b):
qc.h(a)
qc.cx(a, b)
create_bell_pair(teleportation_circuit, 1, 2)
teleportation_circuit.draw()
def alice_gates(qc, a, b):
qc.cx(a, b)
qc.h(a)
teleportation_circuit.barrier()
alice_gates(teleportation_circuit, 0, 1)
teleportation_circuit.draw()
def measure_and_send(qc, a, b):
qc.barrier()
qc.measure(a,0)
qc.measure(b,1)
teleportation_circuit.barrier()
measure_and_send(teleportation_circuit, 0, 1)
teleportation_circuit.draw()
def bob_gates(qc, qubit, crz, crx):
qc.x(qubit).c_if(crx, 1)
qc.z(qubit).c_if(crz, 1)
teleportation_circuit.barrier()
bob_gates(teleportation_circuit, 2, crz, crx)
teleportation_circuit.draw()
from qiskit.extensions import Initialize
import math
qc = QuantumCircuit(1)
initial_state = [0,1]
init_gate = Initialize(initial_state)
# qc.append(initialize_qubit, [0])
qr = QuantumRegister(3) # Protocol uses 3 qubits
crz = ClassicalRegister(1) # and 2 classical registers
crx = ClassicalRegister(1)
qc = QuantumCircuit(qr, crz, crx)
# First, let's initialise Alice's q0
qc.append(init_gate, [0])
qc.barrier()
# Now begins the teleportation protocol
create_bell_pair(qc, 1, 2)
qc.barrier()
# Send q1 to Alice and q2 to Bob
alice_gates(qc, 0, 1)
# Alice then sends her classical bits to Bob
measure_and_send(qc, 0, 1)
# Bob decodes qubits
bob_gates(qc, 2, crz, crx)
qc.draw()
backend = BasicAer.get_backend('statevector_simulator')
out_vector = execute(qc, backend).result().get_statevector()
plot_bloch_multivector(out_vector)
inverse_init_gate = init_gate.gates_to_uncompute()
qc.append(inverse_init_gate, [2])
qc.draw()
cr_result = ClassicalRegister(1)
qc.add_register(cr_result)
qc.measure(2,2)
qc.draw()
backend = BasicAer.get_backend('qasm_simulator')
counts = execute(qc, backend, shots=1024).result().get_counts()
plot_histogram(counts)
def bob_gates(qc, a, b, c):
qc.cz(a, c)
qc.cx(b, c)
qc = QuantumCircuit(3,1)
# First, let's initialise Alice's q0
qc.append(init_gate, [0])
qc.barrier()
# Now begins the teleportation protocol
create_bell_pair(qc, 1, 2)
qc.barrier()
# Send q1 to Alice and q2 to Bob
alice_gates(qc, 0, 1)
qc.barrier()
# Alice sends classical bits to Bob
bob_gates(qc, 0, 1, 2)
# We undo the initialisation process
qc.append(inverse_init_gate, [2])
# See the results, we only care about the state of qubit 2
qc.measure(2,0)
# View the results:
qc.draw()
from qiskit import IBMQ
IBMQ.save_account('### IMB TOKEN ')
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
from qiskit.providers.ibmq import least_busy
backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 3 and
not b.configuration().simulator and b.status().operational==True))
job_exp = execute(qc, backend=backend, shots=8192)
exp_result = job_exp.result()
exp_measurement_result = exp_result.get_counts(qc)
print(exp_measurement_result)
plot_histogram(exp_measurement_result)
error_rate_percent = sum([exp_measurement_result[result] for result in exp_measurement_result.keys() if result[0]=='1']) \
* 100./ sum(list(exp_measurement_result.values()))
print("The experimental error rate : ", error_rate_percent, "%")
|
https://github.com/AlphaMiyaL/Qiskit-Quantum-Journey
|
AlphaMiyaL
|
#imports
import matplotlib.pyplot as plt
import numpy as np
from qiskit import *
from qiskit.providers.ibmq import least_busy
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
clause_list = [[0,1],
[0,2],
[1,3],
[2,3]]
def XOR(qc, a, b, output):
qc.cx(a, output)
qc.cx(b, output)
# We will use separate registers to name the bits
in_qubits = QuantumRegister(2, name='input')
out_qubit = QuantumRegister(1, name='output')
qc = QuantumCircuit(in_qubits, out_qubit)
XOR(qc, in_qubits[0], in_qubits[1], out_qubit)
qc.draw()
# Create separate registers to name bits
var_qubits = QuantumRegister(4, name='v') # variable bits
clause_qubits = QuantumRegister(4, name='c') # bits to store clause-checks
# Create quantum circuit
qc = QuantumCircuit(var_qubits, clause_qubits)
# Use XOR gate to check each clause
i = 0
for clause in clause_list:
XOR(qc, clause[0], clause[1], clause_qubits[i])
i += 1
qc.draw()
# Create separate registers to name bits
var_qubits = QuantumRegister(4, name='v')
clause_qubits = QuantumRegister(4, name='c')
output_qubit = QuantumRegister(1, name='out')
qc = QuantumCircuit(var_qubits, clause_qubits, output_qubit)
# Compute clauses
i = 0
for clause in clause_list:
XOR(qc, clause[0], clause[1], clause_qubits[i])
i += 1
# Flip 'output' bit if all clauses are satisfied
qc.mct(clause_qubits, output_qubit)
qc.draw()
var_qubits = QuantumRegister(4, name='v')
clause_qubits = QuantumRegister(4, name='c')
output_qubit = QuantumRegister(1, name='out')
cbits = ClassicalRegister(4, name='cbits')
qc = QuantumCircuit(var_qubits, clause_qubits, output_qubit, cbits)
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
def sudoku_oracle(qc, clause_list, clause_qubits):
# Compute clauses
i = 0
for clause in clause_list:
XOR(qc, clause[0], clause[1], clause_qubits[i])
i += 1
# Flip 'output' bit if all clauses are satisfied
qc.mct(clause_qubits, output_qubit)
# Uncompute clauses to reset clause-checking bits to 0
i = 0
for clause in clause_list:
XOR(qc, clause[0], clause[1], clause_qubits[i])
i += 1
sudoku_oracle(qc, clause_list, clause_qubits)
qc.draw()
var_qubits = QuantumRegister(4, name='v')
clause_qubits = QuantumRegister(4, name='c')
output_qubit = QuantumRegister(1, name='out')
cbits = ClassicalRegister(4, name='cbits')
qc = QuantumCircuit(var_qubits, clause_qubits, output_qubit, cbits)
# Initialize 'out0' in state |->
qc.initialize([1, -1]/np.sqrt(2), output_qubit)
# Initialize qubits in state |s>
qc.h(var_qubits)
qc.barrier() # for visual separation
## First Iteration
# Apply our oracle
sudoku_oracle(qc, clause_list, clause_qubits)
qc.barrier() # for visual separation
# Apply our diffuser
qc.append(diffuser(4), [0,1,2,3])
## Second Iteration
sudoku_oracle(qc, clause_list, clause_qubits)
qc.barrier() # for visual separation
# Apply our diffuser
qc.append(diffuser(4), [0,1,2,3])
# Measure the variable qubits
qc.measure(var_qubits, cbits)
qc.draw(fold=-1)
# Simulate and plot results
backend = Aer.get_backend('aer_simulator')
#provider = IBMQ.load_account()
#backend = provider.get_backend('ibm_oslo')
job = execute(qc, backend=backend, shots=1024)
print("job id:", job.job_id())
job_monitor(job)
result = job.result()
plot_histogram(result.get_counts())
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_optimization import QuadraticProgram
problem = QuadraticProgram("sample")
problem.binary_var("x")
problem.binary_var("y")
problem.maximize(linear={"x": 1, "y": -2})
print(problem.prettyprint())
from qiskit.algorithms import NumPyMinimumEigensolver
from qiskit_optimization.algorithms import MinimumEigenOptimizer
mes = NumPyMinimumEigensolver()
meo = MinimumEigenOptimizer(min_eigen_solver=mes)
result = meo.solve(problem)
print(result)
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit_optimization.algorithms import MinimumEigenOptimizer
mes = NumPyMinimumEigensolver()
meo = MinimumEigenOptimizer(min_eigen_solver=mes)
result = meo.solve(problem)
print(result)
from qiskit import BasicAer
from qiskit.algorithms import QAOA
from qiskit.algorithms.optimizers import COBYLA
from qiskit.utils import QuantumInstance
from qiskit_optimization.algorithms import MinimumEigenOptimizer
backend = BasicAer.get_backend("qasm_simulator")
shots = 1000
qins = QuantumInstance(backend=backend, shots=shots)
mes = QAOA(optimizer=COBYLA(), quantum_instance=qins)
meo = MinimumEigenOptimizer(min_eigen_solver=mes)
result = meo.solve(problem)
print(result)
from qiskit.algorithms.minimum_eigensolvers import QAOA
from qiskit.algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import MinimumEigenOptimizer
shots = 1000
mes = QAOA(sampler=Sampler(), optimizer=COBYLA())
meo = MinimumEigenOptimizer(min_eigen_solver=mes)
result = meo.solve(problem)
print(result)
from qiskit import BasicAer
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import RealAmplitudes
from qiskit.utils import QuantumInstance
from qiskit_optimization.algorithms import MinimumEigenOptimizer
backend = BasicAer.get_backend("qasm_simulator")
shots = 1000
qins = QuantumInstance(backend=backend, shots=shots)
mes = VQE(ansatz=RealAmplitudes(), optimizer=COBYLA(), quantum_instance=qins)
meo = MinimumEigenOptimizer(min_eigen_solver=mes)
result = meo.solve(problem)
print(result)
from qiskit.algorithms.minimum_eigensolvers import SamplingVQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import RealAmplitudes
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import MinimumEigenOptimizer
mes = SamplingVQE(sampler=Sampler(), ansatz=RealAmplitudes(), optimizer=COBYLA())
meo = MinimumEigenOptimizer(min_eigen_solver=mes)
result = meo.solve(problem)
print(result)
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import RealAmplitudes
from qiskit.primitives import Estimator
from qiskit_optimization.algorithms import MinimumEigenOptimizer
mes = VQE(estimator=Estimator(), ansatz=RealAmplitudes(), optimizer=COBYLA())
try:
meo = MinimumEigenOptimizer(min_eigen_solver=mes)
except TypeError as ex:
print(ex)
from qiskit import BasicAer
from qiskit.algorithms import QAOA
from qiskit.algorithms.optimizers import COBYLA
from qiskit.utils import QuantumInstance
from qiskit_optimization.algorithms import WarmStartQAOAOptimizer, SlsqpOptimizer
backend = BasicAer.get_backend("qasm_simulator")
shots = 1000
qins = QuantumInstance(backend=backend, shots=shots)
qaoa = QAOA(optimizer=COBYLA(), quantum_instance=qins)
optimizer = WarmStartQAOAOptimizer(
pre_solver=SlsqpOptimizer(), relax_for_pre_solver=True, qaoa=qaoa, epsilon=0.25
)
result = optimizer.solve(problem)
print(result)
from qiskit.algorithms.minimum_eigensolvers import QAOA
from qiskit.algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import WarmStartQAOAOptimizer, SlsqpOptimizer
qaoa = QAOA(sampler=Sampler(), optimizer=COBYLA())
optimizer = WarmStartQAOAOptimizer(
pre_solver=SlsqpOptimizer(), relax_for_pre_solver=True, qaoa=qaoa, epsilon=0.25
)
result = optimizer.solve(problem)
print(result)
from qiskit import BasicAer
from qiskit.algorithms.optimizers import COBYLA
from qiskit.utils import QuantumInstance
from qiskit_optimization.algorithms import GroverOptimizer
backend = BasicAer.get_backend("qasm_simulator")
shots = 1000
qins = QuantumInstance(backend=backend, shots=shots)
optimizer = GroverOptimizer(num_value_qubits=3, num_iterations=3, quantum_instance=qins)
result = optimizer.solve(problem)
print(result)
from qiskit.algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import GroverOptimizer
optimizer = GroverOptimizer(num_value_qubits=3, num_iterations=3, sampler=Sampler())
result = optimizer.solve(problem)
print(result)
from qiskit import BasicAer
from qiskit.algorithms.optimizers import COBYLA
from qiskit.utils import QuantumInstance
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import GroverOptimizer
backend = BasicAer.get_backend("qasm_simulator")
shots = 1000
qins = QuantumInstance(backend=backend, shots=shots)
try:
optimizer = GroverOptimizer(
num_value_qubits=3, num_iterations=3, quantum_instance=qins, sampler=Sampler()
)
# raises an error because both quantum_instance and sampler are set.
except ValueError as ex:
print(ex)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/deveshq/QC-with-qiskit
|
deveshq
|
#initialization
import matplotlib.pyplot as plt
import numpy as np
import math
# importing Qiskit
from qiskit import IBMQ, Aer, transpile, assemble
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
# import basic plot tools
from qiskit.visualization import plot_histogram
qpe = QuantumCircuit(4, 3)
qpe.x(3)
#Apply Hadamard gate
for qubit in range(3):
qpe.h(qubit)
qpe.draw()
repetitions = 1
for counting_qubit in range(3):
for i in range(repetitions):
qpe.cp(math.pi/4, counting_qubit, 3); # This is CU # we use 2*pi*(1/theta)
repetitions *= 2
qpe.draw()
def qft_dagger(qc, n):
"""n-qubit QFTdagger the first n qubits in circ"""
# Don't forget the Swaps!
for qubit in range(n//2):
qc.swap(qubit, n-qubit-1)
for j in range(n):
for m in range(j):
qc.cp(-math.pi/float(2**(j-m)), m, j)
qc.h(j)
qpe.barrier()
# Apply inverse QFT
qft_dagger(qpe, 3)
# Measure
qpe.barrier()
for n in range(3):
qpe.measure(n,n)
qpe.draw()
aer_sim = Aer.get_backend('aer_simulator')
shots = 2048
t_qpe = transpile(qpe, aer_sim)
qobj = assemble(t_qpe, shots=shots)
results = aer_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
# Create and set up circuit
qpe2 = QuantumCircuit(4, 3)
# Apply H-Gates to counting qubits:
for qubit in range(3):
qpe2.h(qubit)
# Prepare our eigenstate |psi>:
qpe2.x(3)
# Do the controlled-U operations:
angle = 2*math.pi/3
repetitions = 1
for counting_qubit in range(3):
for i in range(repetitions):
qpe2.cp(angle, counting_qubit, 3);
repetitions *= 2
# Do the inverse QFT:
qft_dagger(qpe2, 3)
# Measure of course!
for n in range(3):
qpe2.measure(n,n)
qpe2.draw()
# Let's see the results!
aer_sim = Aer.get_backend('aer_simulator')
shots = 4096
t_qpe2 = transpile(qpe2, aer_sim)
qobj = assemble(t_qpe2, shots=shots)
results = aer_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
# Create and set up circuit
qpe3 = QuantumCircuit(6, 5)
# Apply H-Gates to counting qubits:
for qubit in range(5):
qpe3.h(qubit)
# Prepare our eigenstate |psi>:
qpe3.x(5)
# Do the controlled-U operations:
angle = 2*math.pi/3
repetitions = 1
for counting_qubit in range(5):
for i in range(repetitions):
qpe3.cp(angle, counting_qubit, 5);
repetitions *= 2
# Do the inverse QFT:
qft_dagger(qpe3, 5)
# Measure of course!
qpe3.barrier()
for n in range(5):
qpe3.measure(n,n)
qpe3.draw()
# Let's see the results!
aer_sim = Aer.get_backend('aer_simulator')
shots = 4096
t_qpe3 = transpile(qpe3, aer_sim)
qobj = assemble(t_qpe3, shots=shots)
results = aer_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
#General imports
import numpy as np
#Operator Imports
from qiskit.opflow import Z, X, I, StateFn, CircuitStateFn, SummedOp
from qiskit.opflow.gradients import Gradient, NaturalGradient, QFI, Hessian
#Circuit imports
from qiskit.circuit import QuantumCircuit, QuantumRegister, Parameter, ParameterVector, ParameterExpression
from qiskit.circuit.library import EfficientSU2
# Instantiate the quantum state
a = Parameter('a')
b = Parameter('b')
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(a, q[0])
qc.rx(b, q[0])
# Instantiate the Hamiltonian observable
H = (2 * X) + Z
# Combine the Hamiltonian observable and the state
op = ~StateFn(H) @ CircuitStateFn(primitive=qc, coeff=1.)
# Print the operator corresponding to the expectation value
print(op)
params = [a, b]
# Define the values to be assigned to the parameters
value_dict = {a: np.pi / 4, b: np.pi}
# Convert the operator and the gradient target params into the respective operator
grad = Gradient().convert(operator = op, params = params)
# Print the operator corresponding to the Gradient
print(grad)
# Assign the parameters and evaluate the gradient
grad_result = grad.assign_parameters(value_dict).eval()
print('Gradient', grad_result)
# Define the Hamiltonian with fixed coefficients
H = 0.5 * X - 1 * Z
# Define the parameters w.r.t. we want to compute the gradients
params = [a, b]
# Define the values to be assigned to the parameters
value_dict = { a: np.pi / 4, b: np.pi}
# Combine the Hamiltonian observable and the state into an expectation value operator
op = ~StateFn(H) @ CircuitStateFn(primitive=qc, coeff=1.)
print(op)
# Convert the expectation value into an operator corresponding to the gradient w.r.t. the state parameters using
# the parameter shift method.
state_grad = Gradient(grad_method='param_shift').convert(operator=op, params=params)
# Print the operator corresponding to the gradient
print(state_grad)
# Assign the parameters and evaluate the gradient
state_grad_result = state_grad.assign_parameters(value_dict).eval()
print('State gradient computed with parameter shift', state_grad_result)
# Convert the expectation value into an operator corresponding to the gradient w.r.t. the state parameter using
# the linear combination of unitaries method.
state_grad = Gradient(grad_method='lin_comb').convert(operator=op, params=params)
# Print the operator corresponding to the gradient
print(state_grad)
# Assign the parameters and evaluate the gradient
state_grad_result = state_grad.assign_parameters(value_dict).eval()
print('State gradient computed with the linear combination method', state_grad_result)
# Convert the expectation value into an operator corresponding to the gradient w.r.t. the state parameter using
# the finite difference method.
state_grad = Gradient(grad_method='fin_diff').convert(operator=op, params=params)
# Print the operator corresponding to the gradient
print(state_grad)
# Assign the parameters and evaluate the gradient
state_grad_result = state_grad.assign_parameters(value_dict).eval()
print('State gradient computed with finite difference', state_grad_result)
# Besides the method to compute the circuit gradients resp. QFI, a regularization method can be chosen:
# `ridge` or `lasso` with automatic parameter search or `perturb_diag_elements` or `perturb_diag`
# which perturb the diagonal elements of the QFI.
nat_grad = NaturalGradient(grad_method='lin_comb', qfi_method='lin_comb_full', regularization='ridge').convert(
operator=op, params=params)
# Assign the parameters and evaluate the gradient
nat_grad_result = nat_grad.assign_parameters(value_dict).eval()
print('Natural gradient computed with linear combination of unitaries', nat_grad_result)
# Instantiate the Hamiltonian observable
H = X
# Instantiate the quantum state with two parameters
a = Parameter('a')
b = Parameter('b')
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(a, q[0])
qc.rx(b, q[0])
# Combine the Hamiltonian observable and the state
op = ~StateFn(H) @ CircuitStateFn(primitive=qc, coeff=1.)
# Convert the operator and the hessian target coefficients into the respective operator
hessian = Hessian().convert(operator = op, params = [a, b])
# Define the values to be assigned to the parameters
value_dict = {a: np.pi / 4, b: np.pi/4}
# Assign the parameters and evaluate the Hessian w.r.t. the Hamiltonian coefficients
hessian_result = hessian.assign_parameters(value_dict).eval()
print('Hessian \n', np.real(np.array(hessian_result)))
# Define parameters
params = [a, b]
# Get the operator object representing the Hessian
state_hess = Hessian(hess_method='param_shift').convert(operator=op, params=params)
# Assign the parameters and evaluate the Hessian
hessian_result = state_hess.assign_parameters(value_dict).eval()
print('Hessian computed using the parameter shift method\n', (np.array(hessian_result)))
# Get the operator object representing the Hessian
state_hess = Hessian(hess_method='lin_comb').convert(operator=op, params=params)
# Assign the parameters and evaluate the Hessian
hessian_result = state_hess.assign_parameters(value_dict).eval()
print('Hessian computed using the linear combination of unitaries method\n', (np.array(hessian_result)))
# Get the operator object representing the Hessian using finite difference
state_hess = Hessian(hess_method='fin_diff').convert(operator=op, params=params)
# Assign the parameters and evaluate the Hessian
hessian_result = state_hess.assign_parameters(value_dict).eval()
print('Hessian computed with finite difference\n', (np.array(hessian_result)))
# Wrap the quantum circuit into a CircuitStateFn
state = CircuitStateFn(primitive=qc, coeff=1.)
# Convert the state and the parameters into the operator object that represents the QFI
qfi = QFI(qfi_method='lin_comb_full').convert(operator=state, params=params)
# Define the values for which the QFI is to be computed
values_dict = {a: np.pi / 4, b: 0.1}
# Assign the parameters and evaluate the QFI
qfi_result = qfi.assign_parameters(values_dict).eval()
print('full QFI \n', np.real(np.array(qfi_result)))
# Convert the state and the parameters into the operator object that represents the QFI
# and set the approximation to 'block_diagonal'
qfi = QFI('overlap_block_diag').convert(operator=state, params=params)
# Assign the parameters and evaluate the QFI
qfi_result = qfi.assign_parameters(values_dict).eval()
print('Block-diagonal QFI \n', np.real(np.array(qfi_result)))
# Convert the state and the parameters into the operator object that represents the QFI
# and set the approximation to 'diagonal'
qfi = QFI('overlap_diag').convert(operator=state, params=params)
# Assign the parameters and evaluate the QFI
qfi_result = qfi.assign_parameters(values_dict).eval()
print('Diagonal QFI \n', np.real(np.array(qfi_result)))
# Execution Imports
from qiskit import Aer
from qiskit.utils import QuantumInstance
# Algorithm Imports
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import CG
from qiskit.opflow import I, X, Z
from qiskit.circuit import QuantumCircuit, ParameterVector
from scipy.optimize import minimize
# Instantiate the system Hamiltonian
h2_hamiltonian = -1.05 * (I ^ I) + 0.39 * (I ^ Z) - 0.39 * (Z ^ I) - 0.01 * (Z ^ Z) + 0.18 * (X ^ X)
# This is the target energy
h2_energy = -1.85727503
# Define the Ansatz
wavefunction = QuantumCircuit(2)
params = ParameterVector('theta', length=8)
it = iter(params)
wavefunction.ry(next(it), 0)
wavefunction.ry(next(it), 1)
wavefunction.rz(next(it), 0)
wavefunction.rz(next(it), 1)
wavefunction.cx(0, 1)
wavefunction.ry(next(it), 0)
wavefunction.ry(next(it), 1)
wavefunction.rz(next(it), 0)
wavefunction.rz(next(it), 1)
# Define the expectation value corresponding to the energy
op = ~StateFn(h2_hamiltonian) @ StateFn(wavefunction)
grad = Gradient(grad_method='lin_comb')
qi_sv = QuantumInstance(Aer.get_backend('aer_simulator_statevector'),
shots=1,
seed_simulator=2,
seed_transpiler=2)
#Conjugate Gradient algorithm
optimizer = CG(maxiter=50)
# Gradient callable
vqe = VQE(wavefunction, optimizer=optimizer, gradient=grad, quantum_instance=qi_sv)
result = vqe.compute_minimum_eigenvalue(h2_hamiltonian)
print('Result:', result.optimal_value, 'Reference:', h2_energy)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/Bikramaditya0154/Quantum-Simulation-of-the-ground-states-of-Li-and-Li-2-using-Variational-Quantum-EIgensolver
|
Bikramaditya0154
|
from qiskit import Aer
from qiskit_nature.drivers import UnitsType, Molecule
from qiskit_nature.drivers.second_quantization import (
ElectronicStructureDriverType,
ElectronicStructureMoleculeDriver,
)
from qiskit_nature.problems.second_quantization import ElectronicStructureProblem
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import JordanWignerMapper
molecule = Molecule(
geometry=[["Li", [0.0, 0.0, 0.0]]], charge=2, multiplicity=2
)
driver = ElectronicStructureMoleculeDriver(
molecule, basis="sto3g", driver_type=ElectronicStructureDriverType.PYSCF
)
es_problem = ElectronicStructureProblem(driver)
qubit_converter = QubitConverter(JordanWignerMapper())
from qiskit.providers.aer import StatevectorSimulator
from qiskit import Aer
from qiskit.utils import QuantumInstance
from qiskit_nature.algorithms import VQEUCCFactory
quantum_instance = QuantumInstance(backend=Aer.get_backend("aer_simulator_statevector"))
vqe_solver = VQEUCCFactory(quantum_instance=quantum_instance)
from qiskit.algorithms import VQE
from qiskit.circuit.library import TwoLocal
tl_circuit = TwoLocal(
rotation_blocks=["h", "rx"],
entanglement_blocks="cz",
entanglement="full",
reps=2,
parameter_prefix="y",
)
another_solver = VQE(
ansatz=tl_circuit,
quantum_instance=QuantumInstance(Aer.get_backend("aer_simulator_statevector")),
)
from qiskit_nature.algorithms import GroundStateEigensolver
calc = GroundStateEigensolver(qubit_converter, vqe_solver)
res = calc.solve(es_problem)
print(res)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can show the phase of each state and use
# degrees instead of radians
from qiskit.quantum_info import DensityMatrix
import numpy as np
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_qsphere
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
qc.z(1)
matrix = DensityMatrix(qc)
plot_state_qsphere(matrix,
show_state_phases = True, use_degrees = True)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# Create circuit to test transpiler on
from qiskit import QuantumCircuit
from qiskit.circuit.library import GroverOperator, Diagonal
oracle = Diagonal([1]*7 + [-1])
qc = QuantumCircuit(3)
qc.h([0,1,2])
qc = qc.compose(GroverOperator(oracle))
# Use Statevector object to calculate the ideal output
from qiskit.quantum_info import Statevector
ideal_distribution = Statevector.from_instruction(qc).probabilities_dict()
from qiskit.visualization import plot_histogram
plot_histogram(ideal_distribution)
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
backend = service.backend('ibm_algiers')
# Need to add measurements to the circuit
qc.measure_all()
from qiskit import transpile
circuits = []
for optimization_level in [0, 3]:
t_qc = transpile(qc,
backend,
optimization_level=optimization_level,
seed_transpiler=0)
print(f'CNOTs (optimization_level={optimization_level}): ',
t_qc.count_ops()['cx'])
circuits.append(t_qc)
from qiskit.transpiler import PassManager, InstructionDurations
from qiskit.transpiler.passes import ASAPSchedule, DynamicalDecoupling
from qiskit.circuit.library import XGate
# Get gate durations so the transpiler knows how long each operation takes
durations = InstructionDurations.from_backend(backend)
# This is the sequence we'll apply to idling qubits
dd_sequence = [XGate(), XGate()]
# Run scheduling and dynamic decoupling passes on circuit
pm = PassManager([ASAPSchedule(durations),
DynamicalDecoupling(durations, dd_sequence)]
)
circ_dd = pm.run(circuits[1])
# Add this new circuit to our list
circuits.append(circ_dd)
from qiskit_ibm_runtime import Sampler, Session
with Session(service=service, backend=backend):
sampler = Sampler()
job = sampler.run(
circuits=circuits, # sample all three circuits
skip_transpilation=True,
shots=8000)
result = job.result()
from qiskit.visualization import plot_histogram
binary_prob = [quasi_dist.binary_probabilities() for quasi_dist in result.quasi_dists]
plot_histogram(binary_prob+[ideal_distribution],
bar_labels=False,
legend=['optimization_level=0',
'optimization_level=3',
'optimization_level=3 + dd',
'ideal distribution'])
from qiskit.quantum_info import hellinger_fidelity
for counts in result.quasi_dists:
print(
f"{hellinger_fidelity(counts.binary_probabilities(), ideal_distribution):.3f}"
)
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
from qiskit.tools.jupyter import *
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-pocket-guide
|
qiskit-community
|
from qiskit import BasicAer
print(BasicAer.backends())
from qiskit import QuantumCircuit,BasicAer,transpile
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
backend = BasicAer.get_backend("qasm_simulator")
tqc = transpile(qc, backend)
job = backend.run(tqc, shots=1000)
result = job.result()
counts = result.get_counts(tqc)
print(counts)
from qiskit import QuantumCircuit,BasicAer,transpile
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
backend = BasicAer.get_backend("statevector_simulator")
tqc = transpile(qc, backend)
job = backend.run(tqc)
result = job.result()
statevector = result.get_statevector(tqc, 4)
print(statevector)
from qiskit import QuantumCircuit,BasicAer,transpile
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
backend = BasicAer.get_backend("unitary_simulator")
tqc = transpile(qc, backend)
job = backend.run(tqc)
result = job.result()
unitary = result.get_unitary(tqc, 4)
print(unitary)
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
# This is a comment
# A comment is used for explanations/descriptions/etc.
# Comments do not affect the programs
# let's define an integer variable named a
a = 5
# let's print its value
print(a)
# let's define three integer variables named a, b, and c
a = 2
b = 4
c = a + b # summation of a and b
# let's print their values together
print(a,b,c)
# a single space will automatically appear in between
# let's print their values in reverse order
print(c,b,a)
# let's print their summation and multiplication
print(a+b+c,a*b*c)
# let's define variables with string/text values
hw = "hello world" # we can use double quotes
hqw = 'hello quantum world' # we can use single quotes
# let's print them
print(hw)
print(hqw)
# let's print them together by inserting another string in between
print(hw,"and",hqw)
# let's concatenate a few strings
d = "Hello " + 'World' + " but " + 'Quantum ' + "World"
# let's print the result
print(d)
# let's print numeric and string values together
print("a =",a,", b =",b,", a+b =",a+b)
# let's subtract two numbers
d = a-b
print(a,b,d)
# let's divide two numbers
d = a/b
print(a,b,d)
# let's divide integers over integers
# the result is always an integer (with possible integer remainder)
d = 33 // 6
print(d)
# reminder/mod operator
r = 33 % 6
# 33 mod 6 = 3
# or when 33 is divided by 6 over integers, the reminder is 3
# 33 = 5 * 6 + 3
# let's print the result
print(r)
# Booleen variables
t = True
f = False
# let's print their values
print(t,f)
# print their negations
print(not t)
print("the negation of",t,"is",not t)
print(not f)
print("the negation of",f,"is",not f)
# define a float variable
d = -3.4444
# let's print its value and its square
print(d, d * d)
e = (23*13) - (11 * 15)
print(e)
# we can use more than one variable
# left is the variable for the left part of the expression
# we start with the multiplication inside the parentheses
left = 34*11
# we continue with the substruction inside the parentheses
# we reuse the variable named left
left = 123 - left
# we reuse left again for the multiplication with -3
left = -3 * left
# right is the variable for the right part of the expression
# we use the same idea here
right = 23 * 15
right = 5 + right
right = 4 * right
# at the end, we use left for the result
left = left + right
# let's print the result
print(left)
#
# your solution is here
#
n1,n2,n3 = 3,-4,6
print(n1,n2,n3)
r1 = (2 * n1 + 3 * n2)*2 - 5 *n3
print(r1)
#
# your solution is here
#
n1,n2,n3 = 3,-4,6
up = (n1-n2) * (n2-n3)
down = (n3-n1) * (n3+1)
result = up/down
print (result)
#
# your solution is here
#
N = "Arya"
S = "Shah"
print("hello from the quantum world to",N,S)
|
https://github.com/matteoacrossi/oqs-jupyterbook
|
matteoacrossi
|
# Imports
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit, Aer, execute
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
import matplotlib.pyplot as plt
from qiskit.quantum_info import partial_trace
from qiskit.quantum_info.states import DensityMatrix
def depolarizing_channel(q, p, system, ancillae):
"""Returns a QuantumCircuit implementing depolarizing channel on q[system]
Args:
q (QuantumRegister): the register to use for the circuit
p (float): the probability for the channel between 0 and 1
system (int): index of the system qubit
ancillae (list): list of indices for the ancillary qubits
Returns:
A QuantumCircuit object
"""
dc = QuantumCircuit(q)
#
theta = 1/2 * np.arccos(1-2*p)
#
dc.ry(theta, q[ancillae[0]])
dc.ry(theta, q[ancillae[1]])
dc.ry(theta, q[ancillae[2]])
dc.cx(q[ancillae[0]], q[system])
dc.cy(q[ancillae[1]], q[system])
dc.cz(q[ancillae[2]], q[system])
return dc
# We create the quantum circuit
q = QuantumRegister(5, name='q')
# Index of the system qubit
system = 2
# Indices of the ancillary qubits
ancillae = [1, 3, 4]
# Prepare the qubit in a state that has coherence and different populations
prepare_state = QuantumCircuit(q)
prepare_state.u(np.pi/4, np.pi/4, 0, q[system])
# For example, let's consider 10 equally spaced values of p
p_values = np.linspace(0, 1, 10)
# Here we will create a list of results for each different value of p
tomography_circuits = []
for p in p_values:
circ = prepare_state + depolarizing_channel(q, p, system, ancillae)
tomography_circuits.append(state_tomography_circuits(circ, q[system]))
tomography_results = []
for tomo_circ in tomography_circuits:
job = execute(tomo_circ, Aer.get_backend('qasm_simulator'), shots=8192)
tomography_results.append(job.result())
tomo_rhos = np.zeros((2,2,len(p_values)), dtype=complex)
for (i, p) in enumerate(p_values):
tomo_fitter = StateTomographyFitter(tomography_results[i], tomography_circuits[i])
tomo_rhos[:,:,i] = tomo_fitter.fit()
# Simulated results
plt.plot(p_values, np.real(tomo_rhos[0,1,:]),"C0*", label='Re $\\rho_{01}$')
plt.plot(p_values, np.imag(tomo_rhos[0,1,:]),"C1*", label='Im $\\rho_{01}$')
plt.plot(p_values, np.real(tomo_rhos[0,0,:]),"C2x", label='$\\rho_{00}$')
plt.plot(p_values, np.real(tomo_rhos[1,1,:]),"C3x", label='$\\rho_{11}$')
# Theoretical prediction
# We obtain the density operator of the initial state
rho0 = partial_trace(DensityMatrix.from_instruction(prepare_state), [0, 1, 3, 4]).data
plt.plot(p_values, np.real(rho0[0,1])*(1-p_values), "C0", linewidth=.5)
plt.plot(p_values, np.imag(rho0[0,1])*(1-p_values), "C1", linewidth=.5)
plt.plot(p_values, 0.5*p_values + np.real(rho0[0,0])*(1-p_values), "C2", linewidth=.5)
plt.plot(p_values, 0.5*p_values + np.real(rho0[1,1])*(1-p_values), "C3", linewidth=.5)
plt.xlabel('p')
plt.ylabel('$\\rho_{xx}$')
plt.legend();
plt.title("SIMULATION Depol. channel. Full tomo. $|\\psi_0\\rangle = U_3(\\pi/4,\\pi/4,0)|0\\rangle$");
|
https://github.com/Pitt-JonesLab/slam_decomposition
|
Pitt-JonesLab
|
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
import numpy as np
# %matplotlib widget
from qiskit import transpile
from qiskit import QuantumCircuit
from qiskit.circuit.random import random_circuit
from slam.utils.transpiler_pass.weyl_decompose import (
RootiSwapWeylDecomposition as decomposer,
)
from qiskit.transpiler.passes import (
Collect2qBlocks,
ConsolidateBlocks,
Unroll3qOrMore,
Optimize1qGates,
)
from slam.utils.gates.custom_gates import RiSwapGate
from qiskit.circuit.library import CXGate
from qiskit.converters import circuit_to_dag
from qiskit.transpiler.basepasses import TransformationPass
from qiskit.quantum_info import Operator
from slam.basis import MixedOrderBasisCircuitTemplate
from slam.utils.polytopes.polytope_wrap import monodromy_range_from_target
from slam.utils.gates.family_extend import recursive_sibling_check
from slam.utils.gates.bare_candidates import get_group_name
from slam.utils.gates.duraton_scaling import cost_scaling, atomic_cost_scaling
from slam.utils.gates.winner_selection import pick_winner
from qiskit.transpiler.basepasses import AnalysisPass
from qiskit.transpiler.passes import CountOps
from qiskit.dagcircuit import DAGOpNode, DAGCircuit
from qiskit.transpiler import PassManager
from itertools import product
from slam.utils.circuit_suite import benchmark_lambdas
# load square-lattice coupling map or all-to-all
from qiskit.transpiler import CouplingMap
coupling_map = CouplingMap.from_grid(8, 8)
coupling_map = CouplingMap.from_grid(3, 3)
# coupling_map = CouplingMap.from_full(16)
# load qiskit transpiler with pass for coupling map
induce_swaps = lambda qc: transpile(qc, coupling_map=coupling_map, optimization_level=3)
qc = benchmark_lambdas[3](9)
# turn off logging
logger.setLevel(logging.ERROR)
qc = induce_swaps(qc)
# turn back on logging
logger.setLevel(logging.INFO)
duration_1q = 0.1
benchmark_lambdas[3](9).draw("mpl")
from slam.utils.transpiler_pass.speed_limit_pass import (
pass_manager_basic,
pass_manager_slam,
pass_manager_optimized_sqiswap,
)
qc.draw("mpl")
qc = QuantumCircuit(2)
qc.cx(0, 1)
qc.swap(0, 1)
qc.barrier()
qc.cx(1, 0)
# qc.swap(0,1)
# qc.h(1)
# qc.crz(np.pi/2, 0, 1)
# qc.h(0)
from weylchamber import c1c2c3
print(c1c2c3(Operator(qc).data))
qc.draw(output="mpl")
qc.draw("mpl")
pm = pass_manager_basic(gate="sqiswap", duration_1q=duration_1q)
transp1 = pm.run(qc)
# transp1.draw(output='mpl')
print(0.1 * 247 + 0.5 * 246)
print(0.1 * 5 + 1.9 * 45 + 1.3 * 56)
pm = pass_manager_optimized_sqiswap(duration_1q=duration_1q, speed_method="linear")
transp1 = pm.run(qc)
# transp1.draw(output='mpl')
method = ["linear", "mid", "squared", "hardware"][0]
strategy = ["basic_overall", "lambda_weight", "basic_smush", "lambda_smush"][3]
use_fam = 0
pm = pass_manager_slam(
strategy=strategy,
family_extension=use_fam,
speed_method=method,
duration_1q=duration_1q,
coupling_map=coupling_map,
)
transp0 = pm.run(qc)
transp0.draw(output="mpl")
|
https://github.com/jlapeyre/Qurt.jl
|
jlapeyre
|
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit import Clbit, Qubit
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import CXCancellation
from qiskit.dagcircuit import DAGCircuit
import qiskit.dagcircuit
from qiskit.circuit import QuantumCircuit, Qubit
from qiskit.converters import circuit_to_dag
import rustworkx as rx
def make_cnot_circuit():
nq = 2
qc = QuantumCircuit(nq)
(n1, n2, n3) = (4, 5, 3)
for _ in range(n1):
qc.cx(0, 1)
for _ in range(n2):
qc.cx(1, 0)
for _ in range(n3):
qc.cx(0, 1)
return qc
def cancel_cnots(qc):
pass_manager = PassManager()
pass_manager.append(CXCancellation())
out_circuit = pass_manager.run(qc)
return out_circuit
def make_and_cancel():
qc = make_cnot_circuit()
cancel_cnots(qc)
|
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/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
import numpy as np
import math
def Sx(j,k,d):
# d = qudit dimension
# j,k = identification of the Gell-Mann matrix
# th = rotation angle
j = j-1; k = k-1
sx = np.zeros((d,d), dtype=complex)
sx[j,k] = 1
sx[k,j] = sx[j,k]
return sx
def Sy(j,k,d):
# d = qudit dimension
# j,k = identification of the Gell-Mann matrix
# th = rotation angle
j = j-1; k = k-1
sy = np.zeros((d,d), dtype=complex)
sy[j,k] = -1j
sy[k,j] = -sy[j,k]
return sy
def Sz(j,d):
# d = qudit dimension
# j = identification of the Gell-Mann matrix
# th = rotation angle
sz = np.zeros((d,d), dtype=complex)
for k in range(0,j+1):
sz[k,k] = math.sqrt(2/(j*(j+1)))
if k == j: # corrige para iniciar k em 0
sz[k,k] = sz[k,k]*(-j)
return sz
d = 2; j = 1; k = 2; Sx(j,k,d), Sy(j,k,d), Sz(j,d)
d = 3; Sx(1,2,d), Sx(1,3,d), Sx(2,3,d)
d = 3; Sy(1,2,d), Sy(1,3,d), Sy(2,3,d)
d = 3; Sz(1,d), Sz(2,d)
1/math.sqrt(3), -2/math.sqrt(3)
def Rx(j,k,d,th):
# d = qudit dimension
# j,k = identification of the Gell-Mann matrix
# th = rotation angle
j = j-1; k = k-1
rx = np.eye(d, dtype=complex)
rx[j,j] = math.cos(th/2)
rx[k,k] = rx[j,j]
rx[j,k] = -1j*math.sin(th/2)
rx[k,j] = rx[j,k]
return rx
def Ry(j,k,d,th):
# d = qudit dimension
# j,k = identification of the Gell-Mann matrix
# th = rotation angle
j = j-1; k = k-1
ry = np.eye(d, dtype=complex)
ry[j,j] = math.cos(th/2)
ry[k,k] = ry[j,j]
ry[j,k] = -math.sin(th/2)
ry[k,j] = -ry[j,k]
return ry
def Rz(j,d,th):
# d = qudit dimension
# j = identification of the Gell-Mann matrix
# th = rotation angle
rz = np.eye(d, dtype=complex)
for k in range(0,j+1):
angle = (th/2)*math.sqrt(2/(j*(j+1)))
if k == j: # corrige para iniciar k em 0
angle = angle*(-j)
rz[k,k] = math.cos(angle) - 1j*math.sin(angle)
return rz
d = 2; j = 1; k = 2; th = 0; Rx(j,k,d,th), Ry(j,k,d,th), Rz(j,d,th)
d = 3; j = 1; k = 2; th = 0; Rx(j,k,d,th), Ry(j,k,d,th), Rz(j,d,th)
|
https://github.com/drobiu/quantum-project
|
drobiu
|
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from src.logic.find_color_positions import FCP
from src.util.util import run_qc
secret_string = [3, 2, 2, 0]
print("Input string:", secret_string)
print("\nPerforming FUC\n")
colors = np.zeros(4)
for i in secret_string:
colors[i] = 1
results = []
colors = list(colors)
print("FCP result:", colors)
print("\nPerforming FCP\n")
if not np.array_equal(np.array(colors), np.ones_like(colors)):
zero = colors.index(0)
for i in range(4):
if colors[i] == 0:
results.append(np.zeros(4))
print("Color", i, ": -")
continue
qy = QuantumRegister(8, name='qy')
y = QuantumRegister(4, name='y')
s = QuantumRegister(3)
c = ClassicalRegister(4)
qc = QuantumCircuit(y, qy, s, c)
qc = FCP(qc, y, qy, s, secret_string, c=i, d=zero)
qc.measure(y[:], c[::-1])
result = run_qc(qc, with_QI=False, verbose=False)
curr_result = list(result.get_counts(qc).keys())
assert len(curr_result) == 1
print("Color", i, ":", curr_result[0])
results.append(list(map(int, str(curr_result[0]))))
result_string = np.zeros(4)
for i in range(4):
for j, n in enumerate(results[i]):
if n == 1:
result_string[j] = i
print(result_string)
|
https://github.com/18520339/uts-quantum-computing
|
18520339
|
from IPython.display import YouTubeVideo
YouTubeVideo('BYKc2RnQMqo', width=858, height=540)
!pip install qiskit --quiet
!pip install qiskit-aer --quiet
!pip install pylatexenc --quiet
# @markdown ### **1. Import `Qiskit` and essential packages** { display-mode: "form" }
from qiskit import QuantumCircuit, transpile, assemble
from qiskit.circuit.library import QFT
from qiskit_aer import AerSimulator
from fractions import Fraction
import random
import sympy
import math
# @markdown ### **2. Controlled Modular Multiplication for $U(x) = a^x mod N$** { display-mode: "form" }
class CtrlMultCircuit(QuantumCircuit):
def __init__(self, a, binary_power, N):
super().__init__(N.bit_length())
self.a = a
self.power = 2 ** binary_power # Convert binary to decimal
self.N = N
self.name = f'{self.a}^{self.power} mod {self.N}'
self._create_circuit()
def _create_circuit(self):
for dec_power in range(self.power):
a_exp = self.a ** dec_power % self.N
for i in range(self.num_qubits):
if a_exp >> i & 1: self.x(i)
for j in range(i + 1, self.num_qubits):
if a_exp >> j & 1: self.swap(i, j)
# @markdown ### **3. Quantum Phase Estimation with `Modular Exponentiation` and `Quantum Fourier Transform` to find period $r$** { display-mode: "form" }
# @markdown 
class QPECircuit(QuantumCircuit):
def __init__(self, a, N):
super().__init__(2 * N.bit_length(), N.bit_length())
self.a = a
self.N = N
self._create_circuit()
def _modular_exponentiation(self):
for qbit_idx in range(self.num_qubits // 2):
self.append(
CtrlMultCircuit(self.a, qbit_idx, self.N).to_gate().control(),
[qbit_idx] + list(range(self.num_qubits // 2, 2 * self.num_qubits // 2))
)
def _create_circuit(self):
self.h(range(self.num_qubits // 2)) # Apply Hadamard gates to the first n qubits
self.x(self.num_qubits - 1)
self.barrier()
self._modular_exponentiation() # Apply controlled modular exponentiation
self.barrier()
self.append(
QFT(self.num_qubits // 2, inverse=True),
range(self.num_qubits // 2) # Apply inverse QFT to the first n qubits
)
def collapse(self, simulator):
self.measure(range(self.num_qubits // 2), range(self.num_qubits // 2))
transpiled_circuit = transpile(self, simulator)
self.collapse_result = simulator.run(transpiled_circuit, memory=True).result()
return self.collapse_result
# @markdown ### **4. Completed Shor's Algorithm for Integer Factorization** { display-mode: "form" }
class ShorAlgorithm:
def __init__(self, N, max_attempts=-1, random_coprime_only=False, simulator=None):
self.N = N
self.simulator = simulator
self.max_attempts = max_attempts # -1 for all possible values of a
self.random_coprime_only = random_coprime_only # True to select only coprime values of a and N
def execute(self):
is_N_invalid = self._is_N_invalid()
if is_N_invalid: return is_N_invalid
# Only coprime values remain if random_coprime_only is enabled,
# Otherwise select a random integer in [2, N) as initial guess
a_values = [a for a in range(2, self.N) if not self.random_coprime_only or (math.gcd(a, self.N) == 1)]
print(f'[INFO] {len(a_values)} possible values of a: {a_values}')
self.max_attempts = len(a_values) if self.max_attempts <= -1 else min(self.max_attempts, len(a_values))
attempts_count = 0
while attempts_count < self.max_attempts:
print(f'\n===== Attempt {attempts_count + 1}/{self.max_attempts} =====')
attempts_count += 1
self.chosen_a = random.choice(a_values)
self.r = 1
print(f'[START] Chosen base a: {self.chosen_a}')
if not self.random_coprime_only:
gcd = math.gcd(self.chosen_a, self.N)
if gcd != 1:
print(f'=> {self.chosen_a} and {self.N} share common factor: {self.N} = {gcd} * {self.N // gcd}')
return gcd, self.N // gcd
print(f'>>> {self.chosen_a} and {self.N} are coprime => Perform Quantum Phase Estimation to find {self.chosen_a}^r - 1 = 0 (MOD {self.N})')
if not self._quantum_period_finding():
a_values.remove(self.chosen_a)
self.r = self.chosen_a = self.qpe_circuit = None
continue
factors = self._classical_postprocess()
if factors: return factors
a_values.remove(self.chosen_a)
self.r = self.chosen_a = self.qpe_circuit = None
print(f'[FAIL] No non-trivial factors found after {self.max_attempts} attempts.')
def _is_N_invalid(self):
if self.N <= 3:
print('[ERR] N must be > 3')
return 1, self.N
if self.N % 2 == 0:
print(f'=> {self.N} is an even number: {self.N} = 2 * {self.N // 2}')
return 2, self.N // 2
if sympy.isprime(self.N):
print(f'=> {self.N} is a prime number: {self.N} = 1 * {self.N}')
return 1, self.N
max_exponent = int(math.log2(self.N)) # Start with a large exponent and reduce
for k in range(max_exponent, 1, -1):
p = round(self.N ** (1 / k))
if p ** k == self.N:
print(f'=> {self.N} is a power of prime: {self.N} = {p}^{k}')
return p, k
return False
def _quantum_period_finding(self):
while self.chosen_a ** self.r % self.N != 1: # QPE + continued fractions may find wrong r
self.qpe_circuit = QPECircuit(self.chosen_a, self.N) # Find phase s/r
result = self.qpe_circuit.collapse(self.simulator)
state_bin = result.get_memory()[0]
state_dec = int(state_bin, 2) # Convert to decimal
bits_count = 2 ** (self.N.bit_length() - 1)
phase = state_dec / bits_count
# Continued fraction to find r
self.r = Fraction(phase).limit_denominator(self.N).denominator # Get fraction that most closely approximates phase
if self.r > self.N or self.r == 1: # Safety check to avoid infinite loops
print(f'[ERR] Invalid period found: r = {self.r} => Retry with different a.')
return False
print(f'>>> Output State: |{state_bin}⟩ = {state_dec} (dec) => Phase = {state_dec} / {bits_count} = {phase:.3f}')
return True
def _classical_postprocess(self):
# Classical postprocessing to find factors from the period
print(f'>>> Found r = {self.r} => a^{{r/2}} ± 1 = {self.chosen_a:.0f}^{self.r/2:.0f} ± 1')
if self.r % 2 != 0:
print(f'[ERR] r = {self.r} is odd => Retry with different a.')
return None
int1, int2 = self.chosen_a ** (self.r // 2) - 1, self.chosen_a ** (self.r // 2) + 1
if int1 % self.N == 0 or int2 % self.N == 0:
print(f'[ERR] {self.chosen_a}^{self.r/2:.0f} ± 1 is a multiple of {self.N} => Retry with different a.')
return None
factor1, factor2 = math.gcd(int1, self.N), math.gcd(int2, self.N)
if factor1 not in [1, self.N] and factor2 not in [1, self.N]: # Check to see if factor is non-trivial
print(f'[DONE] Successfully found non-trivial factors: {self.N} = {factor1} * {factor2}')
return factor1, factor2
print(f'[FAIL] Trivial factors found: [1, {self.N}] => Retry with different a.')
return None
# @markdown ### **5. Run the Factorization** { display-mode: "form" }
number_to_factor = 21 # @param {type:"slider", min: 15, max: 55, step: 1}
max_attempts = -1 # @param {type:"slider", min:-1, max:100, step:10}
random_coprime_only = False # @param {type:"boolean"}
# @markdown ***Note**: `max_attempts` will be limited to number of available values.
shor = ShorAlgorithm(number_to_factor, max_attempts, random_coprime_only, AerSimulator())
factors = shor.execute()
try: display(shor.qpe_circuit.draw(output='mpl', fold=-1))
except Exception: pass
|
https://github.com/intrinsicvardhan/QuantumComputingAlgos
|
intrinsicvardhan
|
# Do the necessary imports
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import IBMQ, Aer, transpile, assemble
from qiskit.visualization import plot_histogram, plot_bloch_multivector, array_to_latex
from qiskit.extensions import Initialize
from qiskit.ignis.verification import marginal_counts
from qiskit.quantum_info import random_statevector
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
## SETUP
# Protocol uses 3 qubits and 2 classical bits in 2 different registers
qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits
crz = ClassicalRegister(1, name="crz") # and 2 classical bits
crx = ClassicalRegister(1, name="crx") # in 2 different registers
teleportation_circuit = QuantumCircuit(qr, crz, crx)
def create_bell_pair(qc, a, b):
qc.h(a)
qc.cx(a,b)
qr = QuantumRegister(3, name="q")
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx")
teleportation_circuit = QuantumCircuit(qr, crz, crx)
create_bell_pair(teleportation_circuit, 1, 2)
teleportation_circuit.draw()
def alice_gates(qc, psi, a):
qc.cx(psi, a)
qc.h(psi)
qr = QuantumRegister(3, name="q")
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx")
teleportation_circuit = QuantumCircuit(qr, crz, crx)
## STEP 1
create_bell_pair(teleportation_circuit, 1, 2)
## STEP 2
teleportation_circuit.barrier() # Use barrier to separate steps
alice_gates(teleportation_circuit, 0, 1)
teleportation_circuit.draw()
def measure_and_send(qc, a, b):
"""Measures qubits a & b and 'sends' the results to Bob"""
qc.barrier()
qc.measure(a,0)
qc.measure(b,1)
qr = QuantumRegister(3, name="q")
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx")
teleportation_circuit = QuantumCircuit(qr, crz, crx)
create_bell_pair(teleportation_circuit, 1, 2)
teleportation_circuit.barrier() # Use barrier to separate steps
alice_gates(teleportation_circuit, 0, 1)
measure_and_send(teleportation_circuit, 0 ,1)
teleportation_circuit.draw()
def bob_gates(qc, qubit, crz, crx):
qc.x(qubit).c_if(crx, 1) # Apply gates if the registers
qc.z(qubit).c_if(crz, 1) # are in the state '1'
qr = QuantumRegister(3, name="q")
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx")
teleportation_circuit = QuantumCircuit(qr, crz, crx)
## STEP 1
create_bell_pair(teleportation_circuit, 1, 2)
## STEP 2
teleportation_circuit.barrier() # Use barrier to separate steps
alice_gates(teleportation_circuit, 0, 1)
## STEP 3
measure_and_send(teleportation_circuit, 0, 1)
## STEP 4
teleportation_circuit.barrier() # Use barrier to separate steps
bob_gates(teleportation_circuit, 2, crz, crx)
teleportation_circuit.draw()
# Create random 1-qubit state
psi = random_statevector(2)
# Display it nicely
display(array_to_latex(psi, prefix="|\\psi\\rangle ="))
# Show it on a Bloch sphere
plot_bloch_multivector(psi)
init_gate = Initialize(psi)
init_gate.label = "init"
## SETUP
qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits
crz = ClassicalRegister(1, name="crz") # and 2 classical registers
crx = ClassicalRegister(1, name="crx")
qc = QuantumCircuit(qr, crz, crx)
## STEP 0
# First, let's initialize Alice's q0
qc.append(init_gate, [0])
qc.barrier()
## STEP 1
# Now begins the teleportation protocol
create_bell_pair(qc, 1, 2)
qc.barrier()
## STEP 2
# Send q1 to Alice and q2 to Bob
alice_gates(qc, 0, 1)
## STEP 3
# Alice then sends her classical bits to Bob
measure_and_send(qc, 0, 1)
## STEP 4
# Bob decodes qubits
bob_gates(qc, 2, crz, crx)
# Display the circuit
qc.draw()
sim = Aer.get_backend('aer_simulator')
qc.save_statevector()
out_vector = sim.run(qc).result().get_statevector()
plot_bloch_multivector(out_vector)
|
https://github.com/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/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""A swap strategy pass for blocks of commuting gates."""
from __future__ import annotations
from collections import defaultdict
from qiskit.circuit import Gate, QuantumCircuit, Qubit
from qiskit.converters import circuit_to_dag
from qiskit.dagcircuit import DAGCircuit, DAGOpNode
from qiskit.transpiler import TransformationPass, Layout, TranspilerError
from qiskit.transpiler.passes.routing.commuting_2q_gate_routing.swap_strategy import SwapStrategy
from qiskit.transpiler.passes.routing.commuting_2q_gate_routing.commuting_2q_block import (
Commuting2qBlock,
)
class Commuting2qGateRouter(TransformationPass):
"""A class to swap route one or more commuting gates to the coupling map.
This pass routes blocks of commuting two-qubit gates encapsulated as
:class:`.Commuting2qBlock` instructions. This pass will not apply to other instructions.
The mapping to the coupling map is done using swap strategies, see :class:`.SwapStrategy`.
The swap strategy should suit the problem and the coupling map. This transpiler pass
should ideally be executed before the quantum circuit is enlarged with any idle ancilla
qubits. Otherwise we may swap qubits outside of the portion of the chip we want to use.
Therefore, the swap strategy and its associated coupling map do not represent physical
qubits. Instead, they represent an intermediate mapping that corresponds to the physical
qubits once the initial layout is applied. The example below shows how to map a four
qubit :class:`.PauliEvolutionGate` to qubits 0, 1, 3, and 4 of the five qubit device with
the coupling map
.. parsed-literal::
0 -- 1 -- 2
|
3
|
4
To do this we use a line swap strategy for qubits 0, 1, 3, and 4 defined it in terms
of virtual qubits 0, 1, 2, and 3.
.. code-block:: python
from qiskit import QuantumCircuit
from qiskit.opflow import PauliSumOp
from qiskit.circuit.library import PauliEvolutionGate
from qiskit.transpiler import Layout, CouplingMap, PassManager
from qiskit.transpiler.passes import FullAncillaAllocation
from qiskit.transpiler.passes import EnlargeWithAncilla
from qiskit.transpiler.passes import ApplyLayout
from qiskit.transpiler.passes import SetLayout
from qiskit.transpiler.passes.routing.commuting_2q_gate_routing import (
SwapStrategy,
FindCommutingPauliEvolutions,
Commuting2qGateRouter,
)
# Define the circuit on virtual qubits
op = PauliSumOp.from_list([("IZZI", 1), ("ZIIZ", 2), ("ZIZI", 3)])
circ = QuantumCircuit(4)
circ.append(PauliEvolutionGate(op, 1), range(4))
# Define the swap strategy on qubits before the initial_layout is applied.
swap_strat = SwapStrategy.from_line([0, 1, 2, 3])
# Chose qubits 0, 1, 3, and 4 from the backend coupling map shown above.
backend_cmap = CouplingMap(couplinglist=[(0, 1), (1, 2), (1, 3), (3, 4)])
initial_layout = Layout.from_intlist([0, 1, 3, 4], *circ.qregs)
pm_pre = PassManager(
[
FindCommutingPauliEvolutions(),
Commuting2qGateRouter(swap_strat),
SetLayout(initial_layout),
FullAncillaAllocation(backend_cmap),
EnlargeWithAncilla(),
ApplyLayout(),
]
)
# Insert swap gates, map to initial_layout and finally enlarge with ancilla.
pm_pre.run(circ).draw("mpl")
This pass manager relies on the ``current_layout`` which corresponds to the qubit layout as
swap gates are applied. The pass will traverse all nodes in the dag. If a node should be
routed using a swap strategy then it will be decomposed into sub-instructions with swap
layers in between and the ``current_layout`` will be modified. Nodes that should not be
routed using swap strategies will be added back to the dag taking the ``current_layout``
into account.
"""
def __init__(
self,
swap_strategy: SwapStrategy | None = None,
edge_coloring: dict[tuple[int, int], int] | None = None,
) -> None:
r"""
Args:
swap_strategy: An instance of a :class:`.SwapStrategy` that holds the swap layers
that are used, and the order in which to apply them, to map the instruction to
the hardware. If this field is not given if should be contained in the
property set of the pass. This allows other passes to determine the most
appropriate swap strategy at run-time.
edge_coloring: An optional edge coloring of the coupling map (I.e. no two edges that
share a node have the same color). If the edge coloring is given then the commuting
gates that can be simultaneously applied given the current qubit permutation are
grouped according to the edge coloring and applied according to this edge
coloring. Here, a color is an int which is used as the index to define and
access the groups of commuting gates that can be applied simultaneously.
If the edge coloring is not given then the sets will be built-up using a
greedy algorithm. The edge coloring is useful to position gates such as
``RZZGate``\s next to swap gates to exploit CX cancellations.
"""
super().__init__()
self._swap_strategy = swap_strategy
self._bit_indices: dict[Qubit, int] | None = None
self._edge_coloring = edge_coloring
def run(self, dag: DAGCircuit) -> DAGCircuit:
"""Run the pass by decomposing the nodes it applies on.
Args:
dag: The dag to which we will add swaps.
Returns:
A dag where swaps have been added for the intended gate type.
Raises:
TranspilerError: If the swap strategy was not given at init time and there is
no swap strategy in the property set.
TranspilerError: If the quantum circuit contains more than one qubit register.
TranspilerError: If there are qubits that are not contained in the quantum register.
"""
if self._swap_strategy is None:
swap_strategy = self.property_set["swap_strategy"]
if swap_strategy is None:
raise TranspilerError("No swap strategy given at init or in the property set.")
else:
swap_strategy = self._swap_strategy
if len(dag.qregs) != 1:
raise TranspilerError(
f"{self.__class__.__name__} runs on circuits with one quantum register."
)
if len(dag.qubits) != next(iter(dag.qregs.values())).size:
raise TranspilerError("Circuit has qubits not contained in the qubit register.")
new_dag = dag.copy_empty_like()
current_layout = Layout.generate_trivial_layout(*dag.qregs.values())
# Used to keep track of nodes that do not decompose using swap strategies.
accumulator = new_dag.copy_empty_like()
for node in dag.topological_op_nodes():
if isinstance(node.op, Commuting2qBlock):
# Check that the swap strategy creates enough connectivity for the node.
self._check_edges(dag, node, swap_strategy)
# Compose any accumulated non-swap strategy gates to the dag
accumulator = self._compose_non_swap_nodes(accumulator, current_layout, new_dag)
# Decompose the swap-strategy node and add to the dag.
new_dag.compose(self.swap_decompose(dag, node, current_layout, swap_strategy))
else:
accumulator.apply_operation_back(node.op, node.qargs, node.cargs)
self._compose_non_swap_nodes(accumulator, current_layout, new_dag)
return new_dag
def _compose_non_swap_nodes(
self, accumulator: DAGCircuit, layout: Layout, new_dag: DAGCircuit
) -> DAGCircuit:
"""Add all the non-swap strategy nodes that we have accumulated up to now.
This method also resets the node accumulator to an empty dag.
Args:
layout: The current layout that keeps track of the swaps.
new_dag: The new dag that we are building up.
accumulator: A DAG to keep track of nodes that do not decompose
using swap strategies.
Returns:
A new accumulator with the same registers as ``new_dag``.
"""
# Add all the non-swap strategy nodes that we have accumulated up to now.
order = layout.reorder_bits(new_dag.qubits)
order_bits: list[int | None] = [None] * len(layout)
for idx, val in enumerate(order):
order_bits[val] = idx
new_dag.compose(accumulator, qubits=order_bits)
# Re-initialize the node accumulator
return new_dag.copy_empty_like()
def _position_in_cmap(self, dag: DAGCircuit, j: int, k: int, layout: Layout) -> tuple[int, ...]:
"""A helper function to track the movement of virtual qubits through the swaps.
Args:
j: The index of decision variable j (i.e. virtual qubit).
k: The index of decision variable k (i.e. virtual qubit).
layout: The current layout that takes into account previous swap gates.
Returns:
The position in the coupling map of the virtual qubits j and k as a tuple.
"""
bit0 = dag.find_bit(layout.get_physical_bits()[j]).index
bit1 = dag.find_bit(layout.get_physical_bits()[k]).index
return bit0, bit1
def _build_sub_layers(
self, current_layer: dict[tuple[int, int], Gate]
) -> list[dict[tuple[int, int], Gate]]:
"""A helper method to build-up sets of gates to simultaneously apply.
This is done with an edge coloring if the ``edge_coloring`` init argument was given or with
a greedy algorithm if not. With an edge coloring all gates on edges with the same color
will be applied simultaneously. These sublayers are applied in the order of their color,
which is an int, in increasing color order.
Args:
current_layer: All gates in the current layer can be applied given the qubit ordering
of the current layout. However, not all gates in the current layer can be applied
simultaneously. This function creates sub-layers by building up sub-layers
of gates. All gates in a sub-layer can simultaneously be applied given the coupling
map and current qubit configuration.
Returns:
A list of gate dicts that can be applied. The gates a position 0 are applied first.
A gate dict has the qubit tuple as key and the gate to apply as value.
"""
if self._edge_coloring is not None:
return self._edge_coloring_build_sub_layers(current_layer)
else:
return self._greedy_build_sub_layers(current_layer)
def _edge_coloring_build_sub_layers(
self, current_layer: dict[tuple[int, int], Gate]
) -> list[dict[tuple[int, int], Gate]]:
"""The edge coloring method of building sub-layers of commuting gates."""
sub_layers: list[dict[tuple[int, int], Gate]] = [
{} for _ in set(self._edge_coloring.values())
]
for edge, gate in current_layer.items():
color = self._edge_coloring[edge]
sub_layers[color][edge] = gate
return sub_layers
@staticmethod
def _greedy_build_sub_layers(
current_layer: dict[tuple[int, int], Gate]
) -> list[dict[tuple[int, int], Gate]]:
"""The greedy method of building sub-layers of commuting gates."""
sub_layers = []
while len(current_layer) > 0:
current_sub_layer, remaining_gates = {}, {}
blocked_vertices: set[tuple] = set()
for edge, evo_gate in current_layer.items():
if blocked_vertices.isdisjoint(edge):
current_sub_layer[edge] = evo_gate
# A vertex becomes blocked once a gate is applied to it.
blocked_vertices = blocked_vertices.union(edge)
else:
remaining_gates[edge] = evo_gate
current_layer = remaining_gates
sub_layers.append(current_sub_layer)
return sub_layers
def swap_decompose(
self, dag: DAGCircuit, node: DAGOpNode, current_layout: Layout, swap_strategy: SwapStrategy
) -> DAGCircuit:
"""Take an instance of :class:`.Commuting2qBlock` and map it to the coupling map.
The mapping is done with the swap strategy.
Args:
dag: The dag which contains the :class:`.Commuting2qBlock` we route.
node: A node whose operation is a :class:`.Commuting2qBlock`.
current_layout: The layout before the swaps are applied. This function will
modify the layout so that subsequent gates can be properly composed on the dag.
swap_strategy: The swap strategy used to decompose the node.
Returns:
A dag that is compatible with the coupling map where swap gates have been added
to map the gates in the :class:`.Commuting2qBlock` to the hardware.
"""
trivial_layout = Layout.generate_trivial_layout(*dag.qregs.values())
gate_layers = self._make_op_layers(dag, node.op, current_layout, swap_strategy)
# Iterate over and apply gate layers
max_distance = max(gate_layers.keys())
circuit_with_swap = QuantumCircuit(len(dag.qubits))
for i in range(max_distance + 1):
# Get current layer and replace the problem indices j,k by the corresponding
# positions in the coupling map. The current layer corresponds
# to all the gates that can be applied at the ith swap layer.
current_layer = {}
for (j, k), local_gate in gate_layers.get(i, {}).items():
current_layer[self._position_in_cmap(dag, j, k, current_layout)] = local_gate
# Not all gates that are applied at the ith swap layer can be applied at the same
# time. We therefore greedily build sub-layers.
sub_layers = self._build_sub_layers(current_layer)
# Apply sub-layers
for sublayer in sub_layers:
for edge, local_gate in sublayer.items():
circuit_with_swap.append(local_gate, edge)
# Apply SWAP gates
if i < max_distance:
for swap in swap_strategy.swap_layer(i):
(j, k) = [trivial_layout.get_physical_bits()[vertex] for vertex in swap]
circuit_with_swap.swap(j, k)
current_layout.swap(j, k)
return circuit_to_dag(circuit_with_swap)
def _make_op_layers(
self, dag: DAGCircuit, op: Commuting2qBlock, layout: Layout, swap_strategy: SwapStrategy
) -> dict[int, dict[tuple, Gate]]:
"""Creates layers of two-qubit gates based on the distance in the swap strategy."""
gate_layers: dict[int, dict[tuple, Gate]] = defaultdict(dict)
for node in op.node_block:
edge = (dag.find_bit(node.qargs[0]).index, dag.find_bit(node.qargs[1]).index)
bit0 = layout.get_virtual_bits()[dag.qubits[edge[0]]]
bit1 = layout.get_virtual_bits()[dag.qubits[edge[1]]]
distance = swap_strategy.distance_matrix[bit0, bit1]
gate_layers[distance][edge] = node.op
return gate_layers
def _check_edges(self, dag: DAGCircuit, node: DAGOpNode, swap_strategy: SwapStrategy):
"""Check if the swap strategy can create the required connectivity.
Args:
node: The dag node for which to check if the swap strategy provides enough connectivity.
swap_strategy: The swap strategy that is being used.
Raises:
TranspilerError: If there is an edge that the swap strategy cannot accommodate
and if the pass has been configured to raise on such issues.
"""
required_edges = set()
for sub_node in node.op:
edge = (dag.find_bit(sub_node.qargs[0]).index, dag.find_bit(sub_node.qargs[1]).index)
required_edges.add(edge)
# Check that the swap strategy supports all required edges
if not required_edges.issubset(swap_strategy.possible_edges):
raise TranspilerError(
f"{swap_strategy} cannot implement all edges in {required_edges}."
)
|
https://github.com/acfilok96/Quantum-Computation
|
acfilok96
|
import qiskit
print(qiskit.__version__)
from qiskit.aqua.algorithms import Shor
from qiskit.aqua import QuantumInstance
import numpy as np
from qiskit import QuantumCircuit, Aer, execute
from qiskit.tools.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend=backend, shots=1024)
my_shor = Shor(N=2189,a=4,quantum_instance=quantum_instance)
Shor.run(my_shor)
|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
import unittest
import sys
import os
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + '/../src')
from bb84.participant import Participant
from bb84.sender import Sender
from bb84.receiver import Receiver
from qiskit import Aer
ALICE = 'Alice'
BOB = 'Bob'
EXAMPLE_LIST_1 = [1, 0, 0, 1, 0, 1, 1]
EXAMPLE_LIST_2 = [1, 1, 0, 0, 0, 1, 0]
ORIGINAL_BITS_SIZE = len(EXAMPLE_LIST_1)
INDEX_SHARED_KEY = 2
def is_lambda(x):
return callable(x) and x.__name__ == '<lambda>'
class BB84EntitiesTests(unittest.TestCase):
def setUp(self):
self.sender = Sender(ALICE, ORIGINAL_BITS_SIZE)
self.receiver = Receiver(BOB, ORIGINAL_BITS_SIZE)
@unittest.expectedFailure
def test_participant(self):
_ = Participant('Participant', ORIGINAL_BITS_SIZE)
def test_name(self):
self.assertEqual(self.sender.name, ALICE)
self.assertEqual(self.receiver.name, BOB)
def test_original_bits_size(self):
self.assertEqual(self.sender.original_bits_size, ORIGINAL_BITS_SIZE)
self.assertEqual(self.receiver.original_bits_size, ORIGINAL_BITS_SIZE)
def test_setter_values(self):
self.sender.set_values(EXAMPLE_LIST_1)
self.receiver.set_values(EXAMPLE_LIST_1)
self.assertEqual(self.sender.values, EXAMPLE_LIST_1)
self.assertEqual(self.receiver.values, EXAMPLE_LIST_1)
def test_set_random_values(self):
self.sender.set_values()
self.receiver.set_values()
self.assertTrue(isinstance(self.sender.values, list) and \
len(self.sender.values) == ORIGINAL_BITS_SIZE)
self.assertTrue(isinstance(self.receiver.values, list) and \
len(self.receiver.values) == ORIGINAL_BITS_SIZE)
def test_show_values(self):
self.assertTrue(self.sender.show_values is not None)
self.assertTrue(self.receiver.show_values is not None)
def test_setter_axes(self):
self.sender.set_axes(EXAMPLE_LIST_1)
self.receiver.set_axes(EXAMPLE_LIST_1)
self.assertEqual(self.sender.axes, EXAMPLE_LIST_1)
self.assertEqual(self.receiver.axes, EXAMPLE_LIST_1)
def test_set_random_axes(self):
self.sender.set_axes()
self.receiver.set_axes()
self.assertTrue(isinstance(self.sender.axes, list) and \
len(self.sender.axes) == ORIGINAL_BITS_SIZE)
self.assertTrue(isinstance(self.receiver.axes, list) and \
len(self.receiver.axes) == ORIGINAL_BITS_SIZE)
def test_show_axes(self):
self.assertTrue(self.sender.show_axes is not None)
self.assertTrue(self.receiver.show_axes is not None)
def test_remove_garbage(self):
self.sender.set_values(EXAMPLE_LIST_1)
self.receiver.set_values(EXAMPLE_LIST_2)
self.sender.set_axes(EXAMPLE_LIST_1)
self.receiver.set_axes(EXAMPLE_LIST_2)
self.sender.remove_garbage(EXAMPLE_LIST_2)
self.receiver.remove_garbage(EXAMPLE_LIST_1)
def test_check_key(self):
self.test_remove_garbage()
shared_key = self.receiver.key[:INDEX_SHARED_KEY]
self.assertTrue(self.sender.check_key(shared_key))
def test_confirm_key(self):
self.test_check_key()
shared_key = self.receiver.key[:INDEX_SHARED_KEY]
self.sender.confirm_key(len(shared_key))
def test_is_safe_key(self):
self.test_confirm_key()
self.assertTrue(self.sender.is_safe_key)
def test_show_key(self):
self.test_is_safe_key()
self.assertTrue(self.sender.show_key is not None)
def test_generate_otp(self):
self.test_is_safe_key()
self.sender.generate_otp(ORIGINAL_BITS_SIZE)
self.assertTrue(isinstance(self.sender.otp, list))
def test_show_otp(self):
self.test_generate_otp()
self.assertTrue(self.sender.show_otp is not None)
def test_xor_otp_message(self):
self.test_generate_otp()
msg = 'qwertyuiopasdfghjklñzxcvbnm012345789QWERTYUIOPASDFGHJKLÑZXCVBNM,._-'
encoded_msg = self.sender.xor_otp_message(msg)
decoded_msg = self.sender.xor_otp_message(encoded_msg)
self.assertEqual(decoded_msg, msg)
def test_encode_quantum_message(self):
self.test_set_random_axes()
self.test_set_random_values()
self.msg = self.sender.encode_quantum_message()
for i, qc in enumerate(self.msg):
for gate in qc.data:
if gate[0].name == 'x':
self.assertTrue(self.sender.values[i] == 1)
if gate[0].name == 'h':
self.assertTrue(self.sender.axes[i] == 1)
def test_decode_quantum_message(self):
self.test_encode_quantum_message()
backend = Aer.get_backend('aer_simulator')
self.msg = self.receiver.decode_quantum_message(self.msg, 1, backend)
for i in self.receiver.axes:
if self.receiver.axes[i] == self.sender.axes[i]:
self.assertEqual(self.receiver.values[i], self.sender.values[i])
if __name__ == '__main__':
unittest.main()
|
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
|
MonitSharma
|
from qiskit.circuit import QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit.visualization import plot_histogram
def decimal_to_binary(decimal):
binary = ""
if decimal == 0:
return "0"
while decimal > 0:
binary = str(decimal % 2) + binary
decimal //= 2
return binary
# Example usage
decimal_number = 42
binary_number = decimal_to_binary(decimal_number)
print(f"The binary representation of {decimal_number} is: {binary_number}")
def binary_to_decimal(binary):
decimal = 0
power = len(binary) - 1
for digit in binary:
decimal += int(digit) * (2 ** power)
power -= 1
return decimal
# Example usage
binary_number = "101010"
decimal_number = binary_to_decimal(binary_number)
print(f"The decimal representation of {binary_number} is: {decimal_number}")
qcirc = QuantumCircuit(8)
qcirc.measure_all()
qcirc.draw()
qcirc.draw('mpl')
from qiskit.primitives import Sampler, Estimator, BackendEstimator, BackendSampler
backend = AerSimulator() # decide the backend on which to run the circuit
sampler = BackendSampler(backend) # create a sampler object
sampler2 = Sampler()
result = sampler.run(qcirc).result() # run the circuit and save the results
result
print("Counts",result.quasi_dists[0])
plot_histogram(result.quasi_dists[0])
qcirc = QuantumCircuit(1) # only a single qubit quantum circuit
qcirc.draw('mpl') # let's visualize the circuit
qcirc.initialize([1,0])
qcirc.draw('mpl')
qcirc.measure_all() # applying the measurement
qcirc.draw('mpl')
result = sampler.run(qcirc).result()
counts = result.quasi_dists[0]
counts
plot_histogram(counts)
result = sampler.run(qcirc, shots = 2000).result()
counts = result.quasi_dists[0]
counts
plot_histogram(counts)
from qiskit import QuantumRegister, ClassicalRegister
qr = QuantumRegister(1,'q0') # you can specifically name the qubit q0
cr = ClassicalRegister(1,'c0')
qc = QuantumCircuit(qr, cr) # combine the quantum and classical register
qc.initialize([1,0],0)
qc.measure(0,0) # apply the measurement as operator
qc.draw('mpl')
result = sampler.run(qc, shots = 2000).result()
counts = result.quasi_dists[0]
counts
plot_histogram(counts)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the QAOA algorithm with opflow."""
import unittest
from test.python.algorithms import QiskitAlgorithmsTestCase
from functools import partial
import numpy as np
from scipy.optimize import minimize as scipy_minimize
from ddt import ddt, idata, unpack
import rustworkx as rx
from qiskit import QuantumCircuit
from qiskit_algorithms.minimum_eigensolvers import QAOA
from qiskit_algorithms.optimizers import COBYLA, NELDER_MEAD
from qiskit.circuit import Parameter
from qiskit.opflow import PauliSumOp
from qiskit.quantum_info import Pauli
from qiskit.result import QuasiDistribution
from qiskit.primitives import Sampler
from qiskit.utils import algorithm_globals
I = PauliSumOp.from_list([("I", 1)])
X = PauliSumOp.from_list([("X", 1)])
W1 = np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]])
P1 = 1
M1 = (I ^ I ^ I ^ X) + (I ^ I ^ X ^ I) + (I ^ X ^ I ^ I) + (X ^ I ^ I ^ I)
S1 = {"0101", "1010"}
W2 = np.array(
[
[0.0, 8.0, -9.0, 0.0],
[8.0, 0.0, 7.0, 9.0],
[-9.0, 7.0, 0.0, -8.0],
[0.0, 9.0, -8.0, 0.0],
]
)
P2 = 1
M2 = None
S2 = {"1011", "0100"}
CUSTOM_SUPERPOSITION = [1 / np.sqrt(15)] * 15 + [0]
@ddt
class TestQAOA(QiskitAlgorithmsTestCase):
"""Test QAOA with MaxCut."""
def setUp(self):
super().setUp()
self.seed = 10598
algorithm_globals.random_seed = self.seed
self.sampler = Sampler()
@idata(
[
[W1, P1, M1, S1],
[W2, P2, M2, S2],
]
)
@unpack
def test_qaoa(self, w, reps, mixer, solutions):
"""QAOA test"""
self.log.debug("Testing %s-step QAOA with MaxCut on graph\n%s", reps, w)
qubit_op, _ = self._get_operator(w)
qaoa = QAOA(self.sampler, COBYLA(), reps=reps, mixer=mixer)
with self.assertWarns(DeprecationWarning):
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
graph_solution = self._get_graph_solution(x)
self.assertIn(graph_solution, solutions)
@idata(
[
[W1, P1, S1],
[W2, P2, S2],
]
)
@unpack
def test_qaoa_qc_mixer(self, w, prob, solutions):
"""QAOA test with a mixer as a parameterized circuit"""
self.log.debug(
"Testing %s-step QAOA with MaxCut on graph with a mixer as a parameterized circuit\n%s",
prob,
w,
)
optimizer = COBYLA()
qubit_op, _ = self._get_operator(w)
num_qubits = qubit_op.num_qubits
mixer = QuantumCircuit(num_qubits)
theta = Parameter("θ")
mixer.rx(theta, range(num_qubits))
qaoa = QAOA(self.sampler, optimizer, reps=prob, mixer=mixer)
with self.assertWarns(DeprecationWarning):
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
graph_solution = self._get_graph_solution(x)
self.assertIn(graph_solution, solutions)
def test_qaoa_qc_mixer_many_parameters(self):
"""QAOA test with a mixer as a parameterized circuit with the num of parameters > 1."""
optimizer = COBYLA()
qubit_op, _ = self._get_operator(W1)
num_qubits = qubit_op.num_qubits
mixer = QuantumCircuit(num_qubits)
for i in range(num_qubits):
theta = Parameter("θ" + str(i))
mixer.rx(theta, range(num_qubits))
qaoa = QAOA(self.sampler, optimizer, reps=2, mixer=mixer)
with self.assertWarns(DeprecationWarning):
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
self.log.debug(x)
graph_solution = self._get_graph_solution(x)
self.assertIn(graph_solution, S1)
def test_qaoa_qc_mixer_no_parameters(self):
"""QAOA test with a mixer as a parameterized circuit with zero parameters."""
qubit_op, _ = self._get_operator(W1)
num_qubits = qubit_op.num_qubits
mixer = QuantumCircuit(num_qubits)
# just arbitrary circuit
mixer.rx(np.pi / 2, range(num_qubits))
qaoa = QAOA(self.sampler, COBYLA(), reps=1, mixer=mixer)
with self.assertWarns(DeprecationWarning):
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
# we just assert that we get a result, it is not meaningful.
self.assertIsNotNone(result.eigenstate)
def test_change_operator_size(self):
"""QAOA change operator size test"""
qubit_op, _ = self._get_operator(
np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]])
)
qaoa = QAOA(self.sampler, COBYLA(), reps=1)
with self.assertWarns(DeprecationWarning):
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
graph_solution = self._get_graph_solution(x)
with self.subTest(msg="QAOA 4x4"):
self.assertIn(graph_solution, {"0101", "1010"})
qubit_op, _ = self._get_operator(
np.array(
[
[0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0],
]
)
)
with self.assertWarns(DeprecationWarning):
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
graph_solution = self._get_graph_solution(x)
with self.subTest(msg="QAOA 6x6"):
self.assertIn(graph_solution, {"010101", "101010"})
@idata([[W2, S2, None], [W2, S2, [0.0, 0.0]], [W2, S2, [1.0, 0.8]]])
@unpack
def test_qaoa_initial_point(self, w, solutions, init_pt):
"""Check first parameter value used is initial point as expected"""
qubit_op, _ = self._get_operator(w)
first_pt = []
def cb_callback(eval_count, parameters, mean, metadata):
nonlocal first_pt
if eval_count == 1:
first_pt = list(parameters)
qaoa = QAOA(
self.sampler,
COBYLA(),
initial_point=init_pt,
callback=cb_callback,
)
with self.assertWarns(DeprecationWarning):
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
graph_solution = self._get_graph_solution(x)
with self.subTest("Initial Point"):
# If None the preferred random initial point of QAOA variational form
if init_pt is None:
self.assertLess(result.eigenvalue, -0.97)
else:
self.assertListEqual(init_pt, first_pt)
with self.subTest("Solution"):
self.assertIn(graph_solution, solutions)
def test_qaoa_random_initial_point(self):
"""QAOA random initial point"""
w = rx.adjacency_matrix(
rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed)
)
qubit_op, _ = self._get_operator(w)
qaoa = QAOA(self.sampler, NELDER_MEAD(disp=True), reps=2)
with self.assertWarns(DeprecationWarning):
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
self.assertLess(result.eigenvalue, -0.97)
def test_optimizer_scipy_callable(self):
"""Test passing a SciPy optimizer directly as callable."""
w = rx.adjacency_matrix(
rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed)
)
qubit_op, _ = self._get_operator(w)
qaoa = QAOA(
self.sampler,
partial(scipy_minimize, method="Nelder-Mead", options={"maxiter": 2}),
)
with self.assertWarns(DeprecationWarning):
result = qaoa.compute_minimum_eigenvalue(qubit_op)
self.assertEqual(result.cost_function_evals, 5)
def _get_operator(self, weight_matrix):
"""Generate Hamiltonian for the max-cut problem of a graph.
Args:
weight_matrix (numpy.ndarray) : adjacency matrix.
Returns:
PauliSumOp: operator for the Hamiltonian
float: a constant shift for the obj function.
"""
num_nodes = weight_matrix.shape[0]
pauli_list = []
shift = 0
for i in range(num_nodes):
for j in range(i):
if weight_matrix[i, j] != 0:
x_p = np.zeros(num_nodes, dtype=bool)
z_p = np.zeros(num_nodes, dtype=bool)
z_p[i] = True
z_p[j] = True
pauli_list.append([0.5 * weight_matrix[i, j], Pauli((z_p, x_p))])
shift -= 0.5 * weight_matrix[i, j]
opflow_list = [(pauli[1].to_label(), pauli[0]) for pauli in pauli_list]
with self.assertWarns(DeprecationWarning):
return PauliSumOp.from_list(opflow_list), shift
def _get_graph_solution(self, x: np.ndarray) -> str:
"""Get graph solution from binary string.
Args:
x : binary string as numpy array.
Returns:
a graph solution as string.
"""
return "".join([str(int(i)) for i in 1 - x])
def _sample_most_likely(self, state_vector: QuasiDistribution) -> np.ndarray:
"""Compute the most likely binary string from state vector.
Args:
state_vector: Quasi-distribution.
Returns:
Binary string as numpy.ndarray of ints.
"""
values = list(state_vector.values())
n = int(np.log2(len(values)))
k = np.argmax(np.abs(values))
x = np.zeros(n)
for i in range(n):
x[i] = k % 2
k >>= 1
return x
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
qc.draw('mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.timeline import draw, IQXSimple
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial')
draw(qc, style=IQXSimple())
|
https://github.com/MartenSkogh/QiskitVQEWrapper
|
MartenSkogh
|
import sys
import numpy as np
import scipy as sp
import re
from copy import deepcopy
from pprint import pprint
from timeit import default_timer as timer
from enum import Enum
from qiskit import Aer
from qiskit.aqua import QuantumInstance
from qiskit.aqua.operators import Z2Symmetries
from qiskit.aqua.algorithms.minimum_eigen_solvers import VQE
from qiskit.aqua.algorithms import ExactEigensolver
from qiskit.aqua.components.optimizers import SLSQP, L_BFGS_B, COBYLA, SPSA
from qiskit.chemistry.core import Hamiltonian, TransformationType, QubitMappingType
from qiskit.chemistry.drivers import PySCFDriver, GaussianDriver, UnitsType, HFMethodType
from qiskit.chemistry.components.variational_forms import UCCSD
from qiskit.chemistry.components.initial_states import HartreeFock
class DriverType(Enum):
""" DriverType Enum """
PYSCF = 'PySCF'
GAUSSIAN = 'Gaussian'
class VQEWrapper():
def __init__(self):
### MOLECULE ###
# These things need to be set before running
self.molecule_string = None
# You can make a pretty educated guess for these two
self.spin = None
self.charge = None
self.qmolecule = None
### CHEMISTRY DRIVER ###
#Basis has to be in a format accepted by Gaussian (sto-3g, 6-31g)
self.basis = 'sto-3g'
self.chem_driver = DriverType.GAUSSIAN
self.hf_method = HFMethodType.UHF
self.length_unit = UnitsType.ANGSTROM
self.gaussian_checkfile = ''
self.driver = None
self.core = None
### HAMILTONIAN ###
self.transformation = TransformationType.FULL
self.qubit_mapping = QubitMappingType.JORDAN_WIGNER
self.two_qubit_reduction = False
self.freeze_core = True
self.orbital_reduction = []
self.qubit_op = None
self.aux_ops = None
self.initial_point = None
self.optimizer = SLSQP(maxiter=5000)
self.ansatz = 'UCCSD'
self.excitation_type = 'sd'
self.num_time_slices = 1
self.shallow_circuit_concat = False
self.vqe_algo = None
self.var_form = None
self.vqe_callback = None
self.vqe_time = None
### BACKEND CONFIG ###
#Choose the backend (use Aer instead of BasicAer)
self.simulator = 'statevector_simulator'
self.shots = 1024
self.seed_simulator = None
self.seed_transpiler = None
self.noise_model = None
self.measurement_error_mitigation_cls = None
self.backend_options = {}
def opt_str(self):
match = re.search(r'optimizers.[A-z]+.(.+) object', str(self.optimizer))
opt_str = match.group(1)
return opt_str
def gaussian_config(self):
#Format properties to a string fitting the gaussian input format
if self.gaussian_checkfile != '':
chk = f'%Chk={self.gaussian_checkfile}\n'
else:
chk = ''
gaussian_config = chk + f'# {self.hf_method.value}/{self.basis} scf(conventional)\n\nMolecule\n\n{self.charge} {self.spin+1}\n'
gaussian_config = gaussian_config + self.molecule_string.replace('; ','\n') + '\n\n'
return gaussian_config
def initiate(self):
self.init_backend()
self.init_driver()
self.init_core()
self.init_ops()
self.init_init_state()
self.init_var_form()
self.init_vqe()
def init_driver(self):
if self.chem_driver.value == 'PySCF':
if self.hf_method == HFMethodType.RHF and self.spin % 2 == 0:
print(f'WARNING: Restricted Hartree-Fock (RHF) cannot handle unpaired electrons!')
print(f'Switching to Unrestricted Hartree-Fock!')
self.chem_driver = HFMethodType.UHF
self.driver = PySCFDriver(atom=self.molecule_string,
unit=self.length_unit,
charge=self.charge,
spin=self.spin,
hf_method=self.hf_method,
basis=self.basis)
elif self.chem_driver.value == 'Gaussian':
self.driver = GaussianDriver(config=self.gaussian_config())
self.qmolecule = self.driver.run()
def init_backend(self):
self.backend = Aer.get_backend(self.simulator)
self.quantum_instance = QuantumInstance(backend=self.backend,
shots=self.shots,
seed_simulator = self.seed_simulator,
seed_transpiler = self.seed_transpiler,
noise_model = self.noise_model,
measurement_error_mitigation_cls = self.measurement_error_mitigation_cls,
backend_options = self.backend_options)
def init_core(self):
self.core = Hamiltonian(transformation=self.transformation,
qubit_mapping=self.qubit_mapping,
two_qubit_reduction=self.two_qubit_reduction,
freeze_core=self.freeze_core,
orbital_reduction=self.orbital_reduction)
def init_ops(self):
self.qubit_op, self.aux_ops = self.core.run(self.qmolecule)
#Initial state
def init_init_state(self):
self.init_state = HartreeFock(num_orbitals=self.core._molecule_info['num_orbitals'],
qubit_mapping=self.core._qubit_mapping,
two_qubit_reduction=self.core._two_qubit_reduction,
num_particles=self.core._molecule_info['num_particles'])
#Set up VQE
def init_vqe(self):
self.vqe_algo = VQE(self.qubit_op,
self.var_form,
self.optimizer,
initial_point=self.initial_point,
callback=self.vqe_callback)
def init_var_form(self):
if self.ansatz.upper() == 'UCCSD':
# UCCSD Ansatz
self.var_form = UCCSD(num_orbitals=self.core._molecule_info['num_orbitals'],
num_particles=self.core._molecule_info['num_particles'],
initial_state=self.init_state,
qubit_mapping=self.core._qubit_mapping,
two_qubit_reduction=self.core._two_qubit_reduction,
num_time_slices=self.num_time_slices,
excitation_type=self.excitation_type,
shallow_circuit_concat=self.shallow_circuit_concat)
else:
if self.var_form is None:
raise ValueError('No variational form specified!')
def print_config(self):
print(f'\n\n=== MOLECULAR INFORMATION ===')
print(f'* Molecule string: {self.molecule_string}')
print(f'* Charge: {self.charge}')
print(f'* Spin (2S): {self.spin}')
print(f'* Basis set: {self.basis}')
print(f'* Num orbitals: {self.qmolecule.num_orbitals}')
print(f'* Lenght Unit: {self.length_unit}')
print(f'* HF method: {self.hf_method}')
print(f'\n\n=== HAMILTONIAN INFORMATION ===')
print(f'* Transformation type: {self.transformation}')
print(f'* Qubit mapping: {self.qubit_mapping}')
print(f'* Two qubit reduction: {self.two_qubit_reduction}')
print(f'* Freeze core: {self.freeze_core}')
print(f'* Orbital reduction: {self.orbital_reduction}')
print(f'\n\n=== CHEMISTRY DRIVER INFORMATION ===')
print(f'* Not yet implemented!')
print(f'\n\n=== BACKEND INFORMATION ===')
print(f'* Not yet implemented!')
def run_vqe(self):
#Run the algorithm
vqe_start = timer()
self.vqe_result = self.vqe_algo.run(self.quantum_instance)
self.vqe_time = timer() - vqe_start
#Get the results
result = self.core.process_algorithm_result(self.vqe_result)
return result
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
from qiskit import QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import CommutationAnalysis, CommutativeCancellation
circuit = QuantumCircuit(5)
# Quantum Instantaneous Polynomial Time example
circuit.cx(0, 1)
circuit.cx(2, 1)
circuit.cx(4, 3)
circuit.cx(2, 3)
circuit.z(0)
circuit.z(4)
circuit.cx(0, 1)
circuit.cx(2, 1)
circuit.cx(4, 3)
circuit.cx(2, 3)
circuit.cx(3, 2)
print(circuit)
pm = PassManager()
pm.append([CommutationAnalysis(), CommutativeCancellation()])
new_circuit = pm.run(circuit)
print(new_circuit)
|
https://github.com/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/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
from qiskit import *
nshots = 8192
qiskit.IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
simulator = Aer.get_backend('qasm_simulator')
device = provider.get_backend('ibmq_lima')
from qiskit.tools.visualization import plot_histogram
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.tools.monitor import job_monitor, backend_overview, backend_monitor
def qc_ent_dist():
qc = QuantumCircuit(2, name = 'E dist')
qc.h([0]); qc.cx(0, 1)
return qc
qc_ent_dist_ = qc_ent_dist(); qc_ent_dist_.draw(output = 'mpl')
def qc_bb_cb():
qc = QuantumCircuit(2, name = 'BB->CB')
qc.cx(0,1); qc.h(0)
return qc
qc_bb_cb_ = qc_bb_cb(); qc_bb_cb_.draw(output = 'mpl')
def qc_teleport(th, ph, lb):
qc = QuantumCircuit(3)
qc_ent_dist_ = qc_ent_dist(); qc.append(qc_ent_dist_, [1, 2]) # distribuição de emaranhamento
qc.barrier()
qc.u(th, ph, lb, [0]) # Preparação do estado a ser teletransportado
qc.barrier()
qc_bb_cb_ = qc_bb_cb(); qc.append(qc_bb_cb_, [0, 1]) # Base de Bell para base computacional
qc.barrier()
qc.cx(1, 2); qc.cz(0, 2) # infor clássica + unitária de Bob
return qc
qc_teleport_ = qc_teleport(0.1, 0.5, 0); qc_teleport_.decompose().draw(output = 'mpl')
import numpy as np
import math
th, ph, lb = 0, 0, 0;
rho_teo = np.array([[math.cos(th/2)**2, (math.cos(ph)+1j*math.sin(ph))*math.sin(th/2)*math.cos(th/2)],
[(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2)*math.cos(th/2), math.sin(th/2)**2]])
qc_teleport_ = qc_teleport(0.1, 0.5, 0)
qstc = state_tomography_circuits(qc_teleport_, [2])
# simulação
job = qiskit.execute(qstc, Aer.get_backend('qasm_simulator'), shots = nshots)
qstf = StateTomographyFitter(job.result(), qstc)
rho_sim = qstf.fit(method='lstsq')
print('rho_teo = ', rho_teo)
print('rho_sim = ', rho_sim)
# experimento
job = qiskit.execute(qstc, backend = device, shots = nshots)
job_monitor(job)
qstf = StateTomographyFitter(job.result(), qstc)
rho_exp = qstf.fit(method = 'lstsq')
print('rho_exp = ', rho_exp)
F = qiskit.quantum_info.state_fidelity(rho_teo, rho_exp); print('F = ', F)
# variar th em cos(th/2)|0>+exp(i*ph)sin(th/2)|1>
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute, assemble, Aer
from qiskit.tools.visualization import plot_histogram
from math import pi
import matplotlib.pyplot as plt
q = QuantumRegister(1,'q')
c = ClassicalRegister(1,'c')
qc = QuantumCircuit(q, c)
qc.h(0)
qc.measure(0,0)
qc.x(0).c_if(c, 0)
qc.draw(output='mpl')
q = QuantumRegister(3,'q')
c = ClassicalRegister(3,'c')
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.h(q[1])
qc.h(q[2])
qc.barrier()
qc.measure(q,c)
qc.draw('mpl')
print(bin(3))
print(bin(7))
q = QuantumRegister(3,'q')
c = ClassicalRegister(3,'c')
qc = QuantumCircuit(q, c)
qc.h(0)
qc.h(1)
qc.h(2)
qc.barrier()
qc.measure(q,c)
qc.x(2).c_if(c, 3) # for the 011 case
qc.x(2).c_if(c, 7) # for the 111 case
qc.draw(output='mpl')
nq = 2
m = 2
q = QuantumRegister(nq,'q')
c = ClassicalRegister(m,'c')
qc_S = QuantumCircuit(q,c)
qc_S.h(0)
qc_S.x(1)
qc_S.draw('mpl')
cu_circ = QuantumCircuit(2)
cu_circ.cp(pi/2,0,1)
cu_circ.draw('mpl')
for _ in range(2**(m-1)):
qc_S.cp(pi/2,0,1)
qc_S.draw('mpl')
def x_measurement(qc, qubit, cbit):
"""Measure 'qubit' in the X-basis, and store the result in 'cbit'"""
qc.h(qubit)
qc.measure(qubit, cbit)
x_measurement(qc_S, q[0], c[0])
qc_S.draw('mpl')
qc_S.reset(0)
qc_S.h(0)
qc_S.draw('mpl')
qc_S.p(-pi/2,0).c_if(c,1)
qc_S.draw('mpl')
## 2^t c-U operations (with t=m-2)
for _ in range(2**(m-2)):
qc_S.cp(pi/2,0,1)
x_measurement(qc_S, q[0], c[1])
qc_S.draw('mpl')
sim = Aer.get_backend('qasm_simulator')
count0 = execute(qc_S, sim).result().get_counts()
key_new = [str(int(key,2)/2**m) for key in list(count0.keys())]
count1 = dict(zip(key_new, count0.values()))
fig, ax = plt.subplots(1,2)
plot_histogram(count0, ax=ax[0])
plot_histogram(count1, ax=ax[1])
plt.tight_layout()
nq = 3 # number of qubits
m = 3 # number of classical bits
q = QuantumRegister(nq,'q')
c = ClassicalRegister(m,'c')
qc = QuantumCircuit(q,c)
qc.h(0)
qc.x([1,2])
qc.draw('mpl')
cu_circ = QuantumCircuit(nq)
cu_circ.mcp(pi/4,[0,1],2)
cu_circ.draw('mpl')
for _ in range(2**(m-1)):
qc.mcp(pi/4,[0,1],2)
qc.draw('mpl')
x_measurement(qc, q[0], c[0])
qc.draw('mpl')
qc.reset(0)
qc.h(0)
qc.draw('mpl')
qc.p(-pi/2,0).c_if(c,1)
qc.draw('mpl')
for _ in range(2**(m-2)):
qc.mcp(pi/4,[0,1],2)
x_measurement(qc, q[0], c[1])
qc.draw('mpl')
# initialization of qubit q0
qc.reset(0)
qc.h(0)
# phase correction
qc.p(-pi/4,0).c_if(c,1)
qc.p(-pi/2,0).c_if(c,2)
qc.p(-3*pi/4,0).c_if(c,3)
# c-U operations
for _ in range(2**(m-3)):
qc.mcp(pi/4,[0,1],2)
# X measurement
qc.h(0)
qc.measure(0,2)
qc.draw('mpl')
count0 = execute(qc, sim).result().get_counts()
key_new = [str(int(key,2)/2**m) for key in list(count0.keys())]
count1 = dict(zip(key_new, count0.values()))
fig, ax = plt.subplots(1,2)
plot_histogram(count0, ax=ax[0])
plot_histogram(count1, ax=ax[1])
fig.tight_layout()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Fermionic circuit solver tests."""
import numpy as np
from qiskit import QuantumCircuit
from qiskit.test import QiskitTestCase
from qiskit_nature.second_q.operators import FermionicOp, SpinOp
from qiskit_cold_atom.fermions.fermion_circuit_solver import (
FermionCircuitSolver,
FermionicBasis,
)
from qiskit_cold_atom.fermions.fermion_gate_library import Hop
from qiskit_cold_atom.exceptions import QiskitColdAtomError
# Black import needed to decorate the quantum circuit with spin gates.
import qiskit_cold_atom.spins # pylint: disable=unused-import
class TestFermionCircuitSolver(QiskitTestCase):
"""class to test the FermionCircuitSolver class."""
def setUp(self):
super().setUp()
# Setup two solvers with different number of fermionic species
self.solver1 = FermionCircuitSolver()
self.solver2 = FermionCircuitSolver(num_species=2)
def test_basis_setter(self):
"""test max. dimension of the basis"""
self.solver1.max_dimension = 500
with self.assertRaises(QiskitColdAtomError):
self.solver1.basis = FermionicBasis(sites=12, n_particles=6)
def test_preprocess_circuit(self):
"""test the preprocessing of the circuit"""
circ = QuantumCircuit(4, 4)
circ.fload([0, 2])
circ.fhop([0.5], [0, 1, 2, 3])
with self.subTest("spin conserving circuit"):
self.solver2.preprocess_circuit(circ)
self.assertEqual(self.solver2._dim, 4)
with self.subTest("non spin conserving circuit"):
self.solver1.preprocess_circuit(circ)
self.assertEqual(self.solver1._dim, 6)
def test_get_initial_state(self):
"""test initialization of the state for the simulation"""
circ = QuantumCircuit(4, 4)
circ.fload([0, 3])
self.solver2.preprocess_circuit(circ)
init_state = self.solver2.get_initial_state(circ)
target = np.array([0, 0, 1, 0])
self.assertTrue(np.all(init_state.toarray().T == target))
def test_embed_operator(self):
"""test embedding of an operator"""
fer_op = FermionicOp({"+_0 -_1": 1.0})
spin_op = SpinOp({"X_0 Y_1": 1})
num_wires = 4
qargs = [1, 3]
qargs_wrong = [0, 1, 3]
with self.subTest("check operator type"):
with self.assertRaises(QiskitColdAtomError):
self.solver1._embed_operator(spin_op, num_wires, qargs)
with self.subTest("check operator wiring"):
with self.assertRaises(QiskitColdAtomError):
self.solver1._embed_operator(fer_op, num_wires, qargs_wrong)
with self.subTest("operator embedding"):
embedded_op = self.solver1._embed_operator(fer_op, num_wires, qargs)
target_op = FermionicOp({"+_1 -_3": 1.0}, num_spin_orbitals=4)
self.assertTrue(embedded_op.simplify() == target_op.simplify())
def test_conservation_checks(self):
"""test the checks for conservation of spin-species."""
with self.subTest("check operator type"):
circ = QuantumCircuit(4, 4)
circ.fhop([0.5], [0, 1, 2, 3])
circ.rlx(0.5, 0) # apply gate with a SpinOp generator
with self.assertRaises(QiskitColdAtomError):
self.solver1._check_conservations(circ)
with self.subTest("check compatibility with number of species"):
circ = QuantumCircuit(5, 5)
circ.fhop([0.5], [0, 1, 2, 3])
self.assertTrue(self.solver1._check_conservations(circ) == (True, True))
with self.assertRaises(QiskitColdAtomError):
self.solver2._check_conservations(circ)
with self.subTest("spin conserved"):
circ = QuantumCircuit(4, 4)
circ.fload([0, 3])
circ.fhop([0.5], [0, 1, 2, 3])
self.assertTrue(self.solver2._check_conservations(circ) == (True, True))
with self.subTest("spin not conserved"):
circ = QuantumCircuit(4, 4)
circ.fload([0, 3])
circ.fhop([0.5], [0, 1, 2, 3])
circ.frx(0.3, [0, 2]) # non spin-conserving gate
self.assertTrue(self.solver2._check_conservations(circ) == (True, False))
def test_operator_to_mat(self):
"""test matrix representation of fermionic gates"""
with self.subTest("check operator type"):
spin_op = SpinOp({"X_0 Y_1": 1.0})
with self.assertRaises(QiskitColdAtomError):
self.solver1.operator_to_mat(spin_op)
circ = QuantumCircuit(4, 4)
circ.fload([0, 3])
circ.fhop([0.5], [0, 1, 2, 3])
with self.subTest("check dimensionality of operator"):
self.solver2.preprocess_circuit(circ)
fer_op_wrong = FermionicOp({"+_0 -_1": 1.0}, num_spin_orbitals=3)
fer_op_correct = FermionicOp({"+_0 -_1": 1.0}, num_spin_orbitals=4)
with self.assertRaises(QiskitColdAtomError):
self.solver2.operator_to_mat(fer_op_wrong)
self.solver2.operator_to_mat(fer_op_correct)
with self.subTest("test matrix representation"):
self.solver2.preprocess_circuit(circ)
target = np.array(
[
[0.0, -0.5, -0.5, 0.0],
[-0.5, 0.0, 0.0, -0.5],
[-0.5, 0.0, 0.0, -0.5],
[0.0, -0.5, -0.5, 0.0],
]
)
test_op = self.solver2.operator_to_mat(Hop(num_modes=4, j=[0.5]).generator)
self.assertTrue(np.all(test_op.toarray() == target))
def test_draw_shots(self):
"""test drawing of the shots from a measurement distribution"""
circ = QuantumCircuit(4, 4)
circ.fload([0, 3])
circ.fhop([0.5], [0, 1, 2, 3])
self.solver2.preprocess_circuit(circ)
with self.subTest("check missing shot number"):
# error because the number of shots is not specified
with self.assertRaises(QiskitColdAtomError):
self.solver2.draw_shots(np.ones(4) / 4)
self.solver2.shots = 5
with self.subTest("check match of dimensions"):
# error because there is a mismatch in the dimension
with self.assertRaises(QiskitColdAtomError):
self.solver2.draw_shots(np.ones(3) / 3)
with self.subTest("formatting of measurement outcomes"):
self.solver2.seed = 40
outcomes = self.solver2.draw_shots(np.ones(4) / 4)
self.assertEqual(outcomes, ["0110", "0101", "1010", "0110", "0110"])
def test_to_operators(self):
"""test the to_operators method inherited form BaseCircuitSolver"""
test_circ = QuantumCircuit(4, 4)
test_circ.fload([0, 3])
test_circ.fhop([0.5], [0, 1, 2, 3])
test_circ.fint(1.0, [0, 1, 2, 3])
test_circ.measure_all()
with self.subTest("test ignore barriers"):
self.solver1.ignore_barriers = False
with self.assertRaises(NotImplementedError):
self.solver1.to_operators(test_circ)
self.solver1.ignore_barriers = True
with self.subTest("check for gate generators"):
qubit_circ = QuantumCircuit(1)
qubit_circ.h(0)
with self.assertRaises(QiskitColdAtomError):
self.solver1.to_operators(qubit_circ)
with self.subTest("gate after previous measurement instruction"):
meas_circ = QuantumCircuit(4, 4)
meas_circ.measure_all()
meas_circ.fhop([0.5], [0, 1, 2, 3])
with self.assertRaises(QiskitColdAtomError):
self.solver1.to_operators(meas_circ)
with self.subTest("check returned operators"):
operators = self.solver1.to_operators(test_circ)
target_ops = [
FermionicOp(
{
"+_0 -_1": -0.5,
"-_0 +_1": 0.5,
"+_2 -_3": -0.5,
"-_2 +_3": 0.5,
},
num_spin_orbitals=4,
),
FermionicOp({"+_0 -_0 +_2 -_2": 1, "+_1 -_1 +_3 -_3": 1}, num_spin_orbitals=4),
]
for op, target in zip(operators, target_ops):
self.assertTrue(op == target)
def test_call_method(self):
"""test the call method inherited form BaseCircuitSolver that simulates a circuit"""
test_circ = QuantumCircuit(4)
test_circ.fload([0, 3])
test_circ.fhop([np.pi / 4], [0, 1, 2, 3])
test_circ.fint(np.pi, [0, 1, 2, 3])
with self.subTest("running the circuit"):
self.solver2.shots = 5
self.solver2.seed = 40
simulation = self.solver2(test_circ)
self.assertEqual(simulation["memory"], ["0110", "0101", "1010", "0110", "0110"])
self.assertEqual(simulation["counts"], {"1010": 1, "0110": 3, "0101": 1})
self.assertTrue(
np.allclose(simulation["statevector"], np.array([-0.5j, -0.5, 0.5, -0.5j]))
)
self.assertTrue(
np.allclose(
simulation["unitary"],
np.array(
[
[-0.5, -0.5j, -0.5j, 0.5],
[0.5j, 0.5, -0.5, 0.5j],
[0.5j, -0.5, 0.5, 0.5j],
[0.5, -0.5j, -0.5j, -0.5],
]
),
)
)
with self.subTest("check for maximum dimension"):
self.solver2.max_dimension = 3
with self.assertRaises(QiskitColdAtomError):
simulation = self.solver2(test_circ)
self.solver2.max_dimension = 100
with self.subTest("check if shots are specified"):
self.solver2.shots = None
simulation = self.solver2(test_circ)
self.assertEqual(simulation["memory"], [])
self.assertEqual(simulation["counts"], {})
|
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
|
mathelatics
|
from IPython.display import IFrame
IFrame(src="http://www.youtube.com/embed/mMwovHK2NrE", width=1920/2, height=1080/2)
from qiskit import *
circuit = QuantumCircuit(3,3)
# QUBIT ORDERING
# q0 = State |psi> that we want to teleport
# q1 = Alice's half of the Bell pair
# q2 = Bob's half of the Bell pair, the destination of the teleportation
# ========================
# Step 0: Create the state to be teleported in qubit 0
circuit.x(0) # qubit 0 is now in state |1>, and this is the state that we want to teleport
circuit.barrier() # just a visual aid
# ========================
# Step 1: create an entangled Bell pair between Alice and Bob (qubits 1 and 2)
circuit.h(1)
circuit.cx(1,2)
circuit.barrier() # just a visual aid
# ========================
# Step 2: Alice applies a series of operations
# between the state to teleport (qubit 0) and her half of the Bell pair (qubit 1)
circuit.cx(0,1)
circuit.h(0)
circuit.barrier() # just a visual aid
# ========================
# Step 3: Alice measures both qubits 0 and 1
circuit.measure([0, 1], [0, 1]) # results stored in classical bits 0 and 1, respectively
circuit.barrier() # just a visual aid
# ========================
# Step 4: Now that Alice has measured the two qubits, their states have collapsed to 0 and 1.
# Bob can do operations conditioned on these qubits to his half of the Bell pair
# Note that while we're conditioning Bob's operation on the collapsed qubits 0 and 1, we can
# do teleportation over long distances by transmitting the classical information in classical bits 0 and 1
circuit.cx(1, 2)
circuit.cz(0, 2)
# Step 5: Done! Measure Bob's qubit to find out what state it is in
circuit.measure([2], [2])
%matplotlib inline
circuit.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit, backend=simulator, shots=1024).result()
from qiskit.visualization import plot_histogram
plot_histogram(result.get_counts(circuit))
def create_state_psi(theta):
# Create a state along the x axis on the x-y plane and then rotate it by angle theta around the z-axis
# theta = 0 => state is exactly along x
# theta = pi/2 => state is exactly along y
create_circuit = QuantumCircuit(1, name='create_state_psi')
create_circuit.h(0)
create_circuit.rz(theta, 0)
return create_circuit
def create_Bell_pair():
create_Bell_circuit = QuantumCircuit(2, name='create_Bell_pair')
create_Bell_circuit.h(0)
create_Bell_circuit.cx(0,1)
return create_Bell_circuit
def teleportation_Alice():
teleportation_Alice_circuit = QuantumCircuit(2, name='teleportation_Alice')
teleportation_Alice_circuit.cx(0,1)
teleportation_Alice_circuit.h(0)
return teleportation_Alice_circuit
def Alice_measure():
Alice_measure_circuit = QuantumCircuit(2, 2, name='Alice_measure')
Alice_measure_circuit.measure([0,1], [0,1])
return Alice_measure_circuit
def teleportation_Bob():
teleportation_Bob_circuit = QuantumCircuit(3, name='teleportation_Bob')
teleportation_Bob_circuit.cx(1,2)
teleportation_Bob_circuit.cz(0,2)
return teleportation_Bob_circuit
def build_circuit(theta):
circuit = QuantumCircuit(3, 3)
# Step 0: create the state to teleport
circuit.append(create_state_psi(theta).to_instruction(), [0])
circuit.barrier()
# Step 1: create the Bell pair between Alice and Bob's qubits
circuit.append(create_Bell_pair().to_instruction(), [1,2])
circuit.barrier()
# Step 2: Alice applies a series of operations
circuit.append(teleportation_Alice().to_instruction(), [0,1])
circuit.barrier()
# Step 3: Alice measures her two qubits
circuit.append(Alice_measure().to_instruction(), [0,1], [0,1])
circuit.barrier()
# Step 4: Bob applies operations to his qubit depending on Alice's measurement outcomes
circuit.append(teleportation_Bob().to_instruction(), [0,1,2])
circuit.barrier()
# Step 5: Done. Now measure Bob's qubit to be sure that teleportation was successful
circuit.h(2) # note that the Hadamard gate here ensures that we measure in the Hadamard basis instead of z basis
circuit.measure([0,1,2], [0,1,2])
return circuit
circuit = build_circuit(0.01)
circuit.draw(output='mpl')
circuit.decompose().draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit, backend=simulator, shots=1024).result()
counts = result.get_counts(circuit)
print(counts)
num_c2_zero = sum(counts[c2c1c0] for c2c1c0 in counts if c2c1c0[0] == '0')
import numpy as np
thetas = np.arange(0, 4*np.pi, np.pi/16)
simulator = Aer.get_backend('qasm_simulator')
percent_ones = []
for theta in thetas:
circuit = build_circuit(theta)
result = execute(circuit, backend=simulator, shots=1024).result()
counts = result.get_counts(circuit)
num_c2_ones = sum(counts[c2c1c0] for c2c1c0 in counts if c2c1c0[0] == '1')
percent_ones.append(num_c2_ones*100./1024)
import matplotlib.pyplot as plotter
plotter.plot(thetas, percent_ones)
plotter.xlabel('Initial angle, theta (radians)')
plotter.ylabel('Percentage of 1 counts')
plotter.show()
# build circuits
thetas = np.arange(0, 4*np.pi, np.pi/16)
circuits = []
for theta in thetas:
circuit = build_circuit(theta)
circuits.append(circuit)
# load account
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
qcomp = provider.get_backend('ibmq_16_melbourne')
# run the job on the backend qcomp
job = execute(circuits, backend=qcomp, shots=512, initial_layout=[6,8,7])
print(job.job_id())
from qiskit.tools.monitor import job_monitor
job_monitor(job)
simresult = execute(circuits, backend=simulator, shots=512).result()
result = job.result()
percent_ones = []
for circuit in circuits:
thiscircuit_counts = result.get_counts(circuit)
num_c2_ones = sum(thiscircuit_counts[c2c1c0] for c2c1c0 in thiscircuit_counts if c2c1c0[0] == '1')
percent_ones.append(num_c2_ones*100./512)
percent_ones_sim = []
for circuit in circuits:
thiscircuit_counts = simresult.get_counts(circuit)
num_c2_ones = sum(thiscircuit_counts[c2c1c0] for c2c1c0 in thiscircuit_counts if c2c1c0[0] == '1')
percent_ones_sim.append(num_c2_ones*100./512)
plotter.plot(thetas, percent_ones, 'r.', label='Real device')
plotter.plot(thetas, percent_ones_sim, 'k', label='Simulator')
plotter.xlabel('Initial angle, theta (radians)')
plotter.ylabel('Percentage of 1 counts')
plotter.legend()
plotter.show()
thetas = np.arange(0, 4*np.pi, np.pi/16)
circuits_classicalcontrol = []
for theta in thetas:
cr1 = ClassicalRegister(1)
cr2 = ClassicalRegister(1)
cr3 = ClassicalRegister(1)
qr = QuantumRegister(3)
circuit = QuantumCircuit(qr, cr1, cr2, cr3)
# ========================
# Step 0: Create the state to be teleported in qubit 0
circuit.h(0)
circuit.rz(theta, 0)
circuit.barrier()
# ========================
# Step 1: create an entangled Bell pair between Alice and Bob (qubits 1 and 2)
circuit.h(1)
circuit.cx(1,2)
circuit.barrier()
# ========================
# Step 2: Alice applies a series of operations
# between the state to teleport (qubit 0) and her half of the Bell pair (qubit 1)
circuit.cx(0,1)
circuit.h(0)
circuit.barrier()
# ========================
# Step 3: Alice measures both qubits 0 and 1
circuit.measure([0, 1], [0, 1]) # results stored in classical bits 0 and 1, respectively
circuit.barrier()
# ========================
# Step 4: Now that Alice has measured the two qubits, their states have collapsed to 0 and 1.
# Use the classical bits from Alice's measurements to do operations on Bob's half of the Bell pair
circuit.x(2).c_if(cr2, 1)
circuit.z(2).c_if(cr1, 1)
circuit.barrier()
# Step 5: Done! Measure Bob's qubit in the Hadamard basis to find out what state it is in
circuit.h(2)
circuit.measure([2], [2])
circuits_classicalcontrol.append(circuit)
circuits_classicalcontrol[0].draw()
simulator = Aer.get_backend('qasm_simulator')
simresult_classicalcontrol = execute(circuits_classicalcontrol, backend=simulator, shots=512).result()
percent_ones_sim = []
for ii in range(len((circuits))):
thiscircuit_counts = simresult_classicalcontrol.get_counts(ii)
num_c2_ones = sum(thiscircuit_counts[c2c1c0] for c2c1c0 in thiscircuit_counts if c2c1c0[0] == '1')
percent_ones_sim.append(num_c2_ones*100./512)
plotter.plot(thetas, percent_ones_sim, 'k', label='Simulator')
plotter.xlabel('Initial angle, theta (radians)')
plotter.ylabel('Percentage of 1 counts')
plotter.legend()
plotter.show()
qiskit.__qiskit_version__
import qiskit.tools.jupyter
%qiskit_copyright
|
https://github.com/rigetti/qiskit-rigetti
|
rigetti
|
##############################################################################
# Copyright 2021 Rigetti Computing
#
# 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 typing import Iterable, Optional, Any, Union, List, cast, Tuple
from uuid import uuid4
from pyquil import get_qc
from pyquil.api import QuantumComputer, QCSClient
from qiskit import QuantumCircuit, ClassicalRegister
from qiskit.circuit import Measure, CircuitInstruction, Clbit
from qiskit.providers import BackendV1, Options, Provider
from qiskit.providers.models import QasmBackendConfiguration
from qiskit.transpiler import CouplingMap
from ._qcs_job import RigettiQCSJob
def _prepare_readouts(circuit: QuantumCircuit) -> None:
"""
Errors if measuring into more than one readout. If only measuring one, ensures its name is 'ro'. Mutates the input
circuit.
"""
measures: List[CircuitInstruction] = [d for d in circuit.data if isinstance(d[0], Measure)]
readout_names: List[str] = list({clbit.register.name for m in measures for clbit in m.clbits})
num_readouts = len(readout_names)
if num_readouts == 0:
raise RuntimeError("Circuit has no measurements")
if num_readouts > 1:
readout_names.sort()
raise RuntimeError(
f"Multiple readout registers are unsupported on QCSBackend; found {', '.join(readout_names)}"
)
orig_readout_name = readout_names[0]
if orig_readout_name == "ro":
return
for i, reg in enumerate(circuit.cregs):
if reg.name != orig_readout_name:
continue
# rename register to "ro"
ro_reg = ClassicalRegister(size=reg.size, name="ro")
circuit.cregs[i] = ro_reg
def map_ro_reg(clbits: Iterable[Clbit]) -> List[Clbit]:
return [Clbit(ro_reg, clbit.index) for clbit in clbits if clbit.register.name == orig_readout_name]
circuit._clbits = map_ro_reg(circuit.clbits)
circuit._clbit_indices = {
Clbit(ro_reg, clbit.index): loc._replace(registers=[ro_reg])
for clbit, loc in circuit._clbit_indices.items()
if clbit.register.name == orig_readout_name
}
for instruction in circuit._data:
instruction.clbits = map_ro_reg(instruction.clbits)
break
def _prepare_circuit(circuit: QuantumCircuit) -> QuantumCircuit:
"""
Returns a prepared copy of the circuit for execution on the QCS Backend.
"""
circuit = circuit.copy()
_prepare_readouts(circuit)
return circuit
class GetQuantumProcessorException(Exception):
pass
class RigettiQCSBackend(BackendV1):
"""
Class for representing a Rigetti backend, which may target a real QPU or a simulator.
"""
def __init__(
self,
*,
compiler_timeout: float,
execution_timeout: float,
client_configuration: QCSClient,
backend_configuration: QasmBackendConfiguration,
provider: Optional[Provider],
auto_set_coupling_map: bool = True,
qc: Optional[QuantumComputer] = None,
**fields: Any,
) -> None:
"""
Args:
execution_timeout: Time limit for execution requests, in seconds.
compiler_timeout: Time limit for compiler requests, in seconds.
client_configuration: QCS client configuration.
backend_configuration: Backend configuration.
provider: Parent provider.
qc: The `QuantumComputer` this backend represents to Qiskit.
auto_set_coupling_map: When `True`, this will set the `QasmBackendConfiguration`
`coupling_map` based on the `QuantumComputer` topology if the existing
`coupling_map` is empty.
fields: Keyword arguments for the values to use to override the default options.
"""
super().__init__(backend_configuration, provider, **fields)
self._compiler_timeout = compiler_timeout
self._execution_timeout = execution_timeout
self._client_configuration = client_configuration
self._qc = qc
self._auto_set_coupling_map = auto_set_coupling_map
@classmethod
def _default_options(cls) -> Options:
return Options(shots=None)
@property
def qc(self) -> QuantumComputer:
self._load_qc_if_necessary()
return cast(QuantumComputer, self._qc)
@property
def coupling_map(self) -> CouplingMap:
self._set_coupling_map_based_on_qc_topology_if_necessary()
return CouplingMap(self.configuration().coupling_map)
def _load_qc_if_necessary(self) -> None:
configuration: QasmBackendConfiguration = self.configuration()
if self._qc is None:
try:
self._qc = get_qc(
configuration.backend_name,
compiler_timeout=self._compiler_timeout,
execution_timeout=self._execution_timeout,
client_configuration=self._client_configuration,
)
except Exception as e:
raise GetQuantumProcessorException(
f"failed to retrieve quantum processor {configuration.backend_name}"
) from e
def _set_coupling_map_based_on_qc_topology_if_necessary(self) -> None:
configuration: QasmBackendConfiguration = self.configuration()
if not configuration.coupling_map and self._auto_set_coupling_map:
configuration.coupling_map = get_coupling_map_from_qc_topology(self.qc)
def run(
self,
run_input: Union[QuantumCircuit, List[QuantumCircuit]],
**options: Any,
) -> RigettiQCSJob:
"""
Run the quantum circuit(s) using this backend.
Args:
run_input: Either a single :class:`QuantumCircuit` to run or a list of them to run in parallel.
**options: Execution options to forward to :class:`RigettiQCSJob`.
Returns:
RigettiQCSJob: The job that has been started. Wait for it by calling :func:`RigettiQCSJob.result`
"""
if not isinstance(run_input, list):
run_input = [run_input]
bindings = options.get("parameter_binds") or []
if len(bindings) > 0:
run_input = [circuit.bind_parameters(binding) for circuit in run_input for binding in bindings]
run_input = [_prepare_circuit(circuit) for circuit in run_input]
self._set_coupling_map_based_on_qc_topology_if_necessary()
return RigettiQCSJob(
job_id=str(uuid4()),
circuits=run_input,
options=options,
qc=self.qc,
backend=self,
configuration=self.configuration(),
)
def get_coupling_map_from_qc_topology(qc: QuantumComputer) -> List[Tuple[int, int]]:
return cast(List[Tuple[int, int]], qc.quantum_processor.qubit_topology().to_directed().edges())
|
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
|
import random
from qiskit.quantum_info import Statevector
secret = random.randint(0,7) # the owner is randomly picked
secret_string = format(secret, '03b') # format the owner in 3-bit string
oracle = Statevector.from_label(secret_string) # let the oracle know the owner
from qiskit.algorithms import AmplificationProblem
problem = AmplificationProblem(oracle, is_good_state=secret_string)
from qiskit.algorithms import Grover
grover_circuits = []
for iteration in range(1,3):
grover = Grover(iterations=iteration)
circuit = grover.construct_circuit(problem)
circuit.measure_all()
grover_circuits.append(circuit)
# Grover's circuit with 1 iteration
grover_circuits[0].draw()
# Grover's circuit with 2 iterations
grover_circuits[1].draw()
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
backend = "ibmq_qasm_simulator" # use the simulator
from qiskit_ibm_runtime import Sampler, Session
with Session(service=service, backend=backend):
sampler = Sampler()
job = sampler.run(circuits=grover_circuits, shots=1000)
result = job.result()
print(result)
from qiskit.tools.visualization import plot_histogram
# Extract bit string with highest probability from results as the answer
result_dict = result.quasi_dists[1].binary_probabilities()
answer = max(result_dict, key=result_dict.get)
print(f"As you can see, the quantum computer returned '{answer}' as the answer with highest probability.\n"
"And the results with 2 iterations have higher probability than the results with 1 iteration."
)
# Plot the results
plot_histogram(result.quasi_dists, legend=['1 iteration', '2 iterations'])
# Print the results and the correct answer.
print(f"Quantum answer: {answer}")
print(f"Correct answer: {secret_string}")
print('Success!' if answer == secret_string else 'Failure!')
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# Import the QuantumProgram and our configuration
import math
from pprint import pprint
from qiskit import QuantumProgram
import Qconfig
qp = QuantumProgram()
# quantum register for the first circuit
q1 = qp.create_quantum_register('q1', 4)
c1 = qp.create_classical_register('c1', 4)
# quantum register for the second circuit
q2 = qp.create_quantum_register('q2', 2)
c2 = qp.create_classical_register('c2', 2)
# making the first circuits
qc1 = qp.create_circuit('GHZ', [q1], [c1])
qc2 = qp.create_circuit('superposition', [q2], [c2])
qc1.h(q1[0])
qc1.cx(q1[0], q1[1])
qc1.cx(q1[1], q1[2])
qc1.cx(q1[2], q1[3])
for i in range(4):
qc1.measure(q1[i], c1[i])
# making the second circuits
qc2.h(q2)
for i in range(2):
qc2.measure(q2[i], c2[i])
# printing the circuits
print(qp.get_qasm('GHZ'))
print(qp.get_qasm('superposition'))
qobj = qp.compile(['GHZ','superposition'], backend='local_qasm_simulator')
qp.get_execution_list(qobj)
qp.get_execution_list(qobj, verbose=True)
qp.get_compiled_configuration(qobj, 'GHZ', )
print(qp.get_compiled_qasm(qobj, 'GHZ'))
# Coupling map
coupling_map = {0: [1, 2, 3]}
# Place the qubits on a triangle in the bow-tie
initial_layout={("q1", 0): ("q", 0), ("q1", 1): ("q", 1), ("q1", 2): ("q", 2), ("q1", 3): ("q", 3)}
qobj = qp.compile(['GHZ'], backend='local_qasm_simulator', coupling_map=coupling_map, initial_layout=initial_layout)
print(qp.get_compiled_qasm(qobj,'GHZ'))
# Define methods for making QFT circuits
def input_state(circ, q, n):
"""n-qubit input state for QFT that produces output 1."""
for j in range(n):
circ.h(q[j])
circ.u1(math.pi/float(2**(j)), q[j]).inverse()
def qft(circ, q, n):
"""n-qubit QFT on q in circ."""
for j in range(n):
for k in range(j):
circ.cu1(math.pi/float(2**(j-k)), q[j], q[k])
circ.h(q[j])
qp = QuantumProgram()
q = qp.create_quantum_register("q", 3)
c = qp.create_classical_register("c", 3)
qft3 = qp.create_circuit("qft3", [q], [c])
input_state(qft3, q, 3)
qft(qft3, q, 3)
for i in range(3):
qft3.measure(q[i], c[i])
print(qft3.qasm())
result = qp.execute(["qft3"], backend="local_qasm_simulator", shots=1024)
result.get_counts("qft3")
print(result.get_ran_qasm("qft3"))
# Coupling map for ibmqx2 "bowtie"
coupling_map = {0: [1, 2],
1: [2],
2: [],
3: [2, 4],
4: [2]}
# Place the qubits on a triangle in the bow-tie
initial_layout={("q", 0): ("q", 2), ("q", 1): ("q", 3), ("q", 2): ("q", 4)}
result2 = qp.execute(["qft3"], backend="local_qasm_simulator", coupling_map=coupling_map, initial_layout=initial_layout)
result2.get_counts("qft3")
print(result2.get_ran_qasm("qft3"))
# Place the qubits on a linear segment of the ibmqx3
coupling_map = {0: [1], 1: [2], 2: [3], 3: [14], 4: [3, 5], 6: [7, 11], 7: [10], 8: [7], 9: [8, 10], 11: [10], 12: [5, 11, 13], 13: [4, 14], 15: [0, 14]}
initial_layout={("q", 0): ("q", 0), ("q", 1): ("q", 1), ("q", 2): ("q", 2)}
result3 = qp.execute(["qft3"], backend="local_qasm_simulator", coupling_map=coupling_map, initial_layout=initial_layout)
result3.get_counts("qft3")
print(result3.get_ran_qasm("qft3"))
|
https://github.com/arthurfaria/Qiskit_certificate_prep
|
arthurfaria
|
import numpy as np
from qiskit import QuantumCircuit, assemble, Aer, execute, BasicAer
from qiskit.visualization import *
from qiskit.quantum_info import Statevector, random_statevector
from qiskit.tools.jupyter import *
from qiskit.extensions import Initialize
bell_0 = QuantumCircuit(2,2)
bell_0.h(0)
bell_0.cx(0,1)
bell_0.draw('latex')
#we define the basis
sv = Statevector.from_label("00")
#we evolve this initial state through our circuit
sv_bell_0 = sv.evolve(bell_0)
sv_bell_0.draw('latex')
bell_1 = QuantumCircuit(2,2)
bell_1.h(0)
bell_1.cx(0,1)
bell_1.z(1)
#mpl = matplotlib
#latex_source also possible, but really hard to see what is going on
bell_1.draw('mpl')
sv_bell_1 = sv.evolve(bell_1)
sv_bell_1.draw('latex_source')
bell_2 = QuantumCircuit(2,2)
bell_2.h(0)
bell_2.x(1)
bell_2.cx(0,1)
bell_2.draw('text')
sv_bell_2 = sv.evolve(bell_2)
sv_bell_2.draw('text') #text by default
bell_3 = QuantumCircuit(2,2)
bell_3.h(0)
bell_3.x(1)
bell_3.cx(0,1)
bell_3.z(1)
bell_3.draw() #text by default
sv_bell_3 = sv.evolve(bell_3)
sv_bell_3.draw()
ghz = QuantumCircuit(3)
ghz.h(0)
ghz.cx(0,1)
ghz.cx(1,2)
ghz.draw('mpl')
### drawing the statevector
sv_ghz= Statevector.from_label("000")
state_ghz = sv_ghz.evolve(ghz)
state_ghz.draw('latex')
plot_state_qsphere(bell_1)
plot_state_hinton(bell_1)
plot_state_paulivec(bell_3)
plot_state_city(bell_2)
plot_bloch_multivector(bell_2)
# It is not a separable state!!
ex_sep_state = QuantumCircuit(2)
ex_sep_state.h(0)
ex_sep_state.h(1)
ex_sv = Statevector.from_label("00")
ex_state = ex_sv.evolve(ex_sep_state)
plot_bloch_multivector(ex_state)
plot_bloch_vector([0.7,0.5,1]) #here for [x,y,z]; x=Tr[Xρ] and similar for y and z
###Part1: circuit part
qc = QuantumCircuit(3)
qc.h(0)
qc.cx(0,1)
qc.cx(1,2)
#it saves the current simulator quantum state as a statevector.
qc.save_statevector()
###Parts 2 and 3 using Aer_simulator
qobj = assemble(qc)
backend1 = Aer.get_backend('aer_simulator')
###Parts 4 and 5
result = backend1.run(qobj).result()
sv_qc0 = result.get_statevector()
sv_qc0.draw('latex')
sv_qc0.draw('qsphere')
######## PART2: statevetor_simulator
###Part1: circuit part
qc1 = QuantumCircuit(3)
qc1.h(0)
qc1.cx(0,1)
qc1.cx(1,2)
### backend part
backend2 = BasicAer.get_backend('statevector_simulator')
### result part
# by default shots = 1024
job = execute(qc1, backend2, shots=1024)
result = job.result()
#finally, we get the statevector from the result
sv_qc1 = result.get_statevector(qc1)
sv_qc1.draw('qsphere')
plot_state_city(sv_qc1)
N = 1/np.sqrt(3)
desired_state = [N,np.sqrt(1-N**2)]
#adding it to a circuit
qc_custom0 = QuantumCircuit(1)
qc_custom0.initialize(desired_state,0) #as simple as this!
qc_custom0.draw('mpl')
meas = QuantumCircuit(1,1)
meas.measure(0,0)
#we add, through the composite function, the measurement to the custom state
qc_custom = meas.compose(qc_custom0, front=True)
qc_custom.draw('mpl')
#To get histograms, we use qasm_simulator.
#We will see this in the notebook qasm_simulator_and_visualization.ipynb
backend_qasm = BasicAer.get_backend('qasm_simulator')
job0 = execute(qc_custom, backend_qasm, shots=1000)
counts = job0.result().get_counts()
plot_histogram(counts)
# random_statevector of dimension 2
psi = random_statevector(2)
#Initialize qubits in a specific state.
init_gate = Initialize(psi)
# defining a name to the state. By default is |psi\rangle
init_gate.label = "initial state"
qc_random = QuantumCircuit(1)
# random state for the first qibit
qc_random.append(init_gate, [0])
qc_random.draw('mpl')
qc_random.measure_all()
qc_random.draw('mpl')
job1 = execute(qc_random, backend_qasm, shots=1000)
counts1 = job1.result().get_counts()
plot_histogram(counts1)
decomp = qc_custom0.decompose()
decomp.draw('mpl')
|
https://github.com/jonasmaziero/computacao_quantica_qiskit_sbf_2023
|
jonasmaziero
|
from sympy import Matrix, sqrt, init_printing; init_printing(use_unicode=True)
ket0 = Matrix([[1],[0]]); ket1 = Matrix([[0],[1]]); from sympy.physics.quantum import TensorProduct as tp
ket00 = tp(ket0,ket0); ket01 = tp(ket0,ket1); ket10 = tp(ket1,ket0); ket11 = tp(ket1,ket1)
Psim = (ket01-ket10)/sqrt(2); Psim.T
X = Matrix([[0,1],[1,0]]); Z = Matrix([[1,0],[0,-1]]); (tp(Z,Z)*Psim).T, (tp(X,X)*Psim).T
A1 = Z; A2 = X; B1 = (Z+X)/sqrt(2); B2 = (Z-X)/sqrt(2); O = tp(A1,B1)+tp(A1,B2)+tp(A2,B1)-tp(A2,B2)
O, sqrt(2)*(tp(Z,Z)+tp(X,X))
from qiskit import QuantumCircuit
def qc_Psim(): # função que cria o circuito quantico para preparar o estado de Bell |Psi->
qc = QuantumCircuit(2, name=r'$|\Psi_-\rangle$')
qc.x([0,1])
qc.h(0)
qc.cx(0,1)
#qc.z(0)
#qc.x(1)
return qc
qc_Psim_ = qc_Psim()
qc_Psim_.draw('mpl')
import qiskit
from qiskit.quantum_info import Statevector
qc_Psim_ = qc_Psim()
state = Statevector(qc_Psim_)
qiskit.visualization.plot_state_city(state)
from sympy import Matrix
Psim = Matrix([[0],[1],[-1],[0]])/sqrt(2)
#Psim
from sympy.physics.quantum.dagger import Dagger
rho_Psim = Psim*Dagger(Psim)
rho_Psim
qc = QuantumCircuit(2,2)
qc_Psim_ = qc_Psim()
qc.append(qc_Psim_,[0,1])
qc.measure([0,1],[0,1])
qc.draw('mpl')
from qiskit import Aer, execute
simulator = Aer.get_backend('qasm_simulator')
nshots = 2**13
job = execute(qc, backend=simulator, shots=nshots)
counts = job.result().get_counts()
p00=0; p01=0; p10=0; p11=0
for j in (0,2):
for k in (0,2):
if '00' in counts:
p00 = counts['00']/nshots
if '01' in counts:
p01 = counts['01']/nshots
if '10' in counts:
p10 = counts['10']/nshots
if '11' in counts:
p11 = counts['11']/nshots
ZZ_avg = (p00+p11)-(p01+p10)
ZZ_avg
qc = QuantumCircuit(2,2)
qc_Psim_ = qc_Psim()
qc.append(qc_Psim_,[0,1])
qc.h([0,1])
qc.measure([0,1],[0,1])
qc.draw('mpl')
from qiskit import Aer
simulator = Aer.get_backend('qasm_simulator')
nshots = 2**13
job = execute(qc, backend=simulator, shots=nshots)
counts = job.result().get_counts()
p00=0; p01=0; p10=0; p11=0
for j in (0,2):
for k in (0,2):
if '00' in counts:
p00 = counts['00']/nshots
if '01' in counts:
p01 = counts['01']/nshots
if '10' in counts:
p10 = counts['10']/nshots
if '11' in counts:
p11 = counts['11']/nshots
XX_avg = (p00+p11)-(p01+p10)
XX_avg
O_avg = sqrt(2)*(ZZ_avg + XX_avg)
O_avg, float(O_avg)
import qiskit
qiskit.IBMQ.save_account('5a0140fc106f9f8ae43104d5751baf65c726195f8b45b1f42e161f0182b5fe79ca6dbb1405159301e1e44d40d680223ea572d9b8737205bfa6f90485f1f88123',
overwrite = True)
qiskit.IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibm_nairobi')
qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_,[0,1]); qc.measure([0,1],[0,1])
job = execute(qc, backend = device, shots = nshots); print(job.job_id())
device = provider.get_backend('ibm_nairobi'); job = device.retrieve_job('cmfbdw78vz2g008daj90')
counts = job.result().get_counts()
p00=0; p01=0; p10=0; p11=0
for j in (0,2):
for k in (0,2):
if '00' in counts:
p00 = counts['00']/nshots
if '01' in counts:
p01 = counts['01']/nshots
if '10' in counts:
p10 = counts['10']/nshots
if '11' in counts:
p11 = counts['11']/nshots
ZZ_avg_exp = (p00+p11)-(p01+p10); ZZ_avg_exp
device = provider.get_backend('ibm_nairobi')
qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_,[0,1]); qc.h([0,1]); qc.measure([0,1],[0,1])
job = execute(qc, backend = device, shots = nshots); jobid = job.job_id()
print(jobid)
device = provider.get_backend('ibm_nairobi'); job = device.retrieve_job('cmfbekafysfg008t2y4g')
counts = job.result().get_counts()
p00=0; p01=0; p10=0; p11=0
for j in (0,2):
for k in (0,2):
if '00' in counts:
p00 = counts['00']/nshots
if '01' in counts:
p01 = counts['01']/nshots
if '10' in counts:
p10 = counts['10']/nshots
if '11' in counts:
p11 = counts['11']/nshots
XX_avg_exp = (p00+p11)-(p01+p10); XX_avg_exp
O_avg_exp = sqrt(2.)*(ZZ_avg_exp + XX_avg_exp)
O_avg_exp
import numpy as np
import math
th_max = math.pi/2; npt = 100; dth = th_max/npt; th = np.arange(0,th_max+dth,dth)
Oteo = -math.sqrt(2)*(1+np.sin(th))
Odl = -2*np.ones(len(th))
from matplotlib import pyplot as plt
plt.plot(th, Oteo, label = r'$\langle O\rangle_{\Psi}^{teo}$')
plt.plot(th, Odl, label = 'LHV limit')
plt.xlabel(r'$\theta$')
plt.legend(); plt.show()
# circuito quântico para preparação do estado Psi
def qc_Psi(th):
qc = QuantumCircuit(2)
qc.u(th,0,0, 0)
qc.cx(0,1)
qc.z(0)
qc.x(1)
return qc
import math
th = math.pi/4
qc_Psi_ = qc_Psi(th)
qc_Psi_.draw('mpl')
# função para calcular as médias tipo <A\otimes B>, com A,B=+1,-1, dadas as probabilidades
def ABavg(result, nshots):
avg = 0
if '00' in result:
avg += result['00']
if '01' in result:
avg -= result['01']
if '10' in result:
avg -= result['10']
if '11' in result:
avg += result['11']
return avg/nshots # = (N(00)-N(01)-N(10)+N(11))/nshots
th_max = math.pi/2; npe = 5; dth = th_max/npe; th = np.arange(0,th_max+dth,dth)
Osim = np.zeros(len(th))
from qiskit import Aer, execute
simulator = Aer.get_backend('qasm_simulator')
nshots = 2**13
for j in range(0,len(th)):
# mede ZZ
qc = QuantumCircuit(2,2)
qc_Psi_ = qc_Psi(th[j]); qc.append(qc_Psi_, [0,1])
qc.measure([0,1],[0,1])
job = execute(qc, backend=simulator, shots=nshots)
result = job.result().get_counts()
ZZavg = ABavg(result, nshots)
# mede XX
qc = QuantumCircuit(2,2)
qc_Psi_ = qc_Psi(th[j]); qc.append(qc_Psi_, [0,1])
qc.h([0,1])
qc.measure([0,1],[0,1])
job = execute(qc, backend=simulator, shots=nshots)
result = job.result().get_counts()
XXavg = ABavg(result, nshots)
# média de O
Osim[j] = math.sqrt(2)*(ZZavg + XXavg)
Osim
import numpy as np; import math
th_max = math.pi/2; dtht = th_max/npt; tht = np.arange(0,th_max+dtht,dtht)
Oteo = -math.sqrt(2)*(1+np.sin(tht)); Odl = -2*np.ones(len(tht))
dth = th_max/npe; th = np.arange(0,th_max+dth,dth)
from matplotlib import pyplot as plt
plt.plot(tht, Oteo, label = r'$\langle O\rangle_{\Psi}^{teo}$')
plt.plot(tht, Odl, label = 'LHV limit')
plt.plot(th, Osim, '*', label = r'$\langle O\rangle_{\Psi}^{sim}$')
plt.xlabel(r'$\theta$')
plt.legend(); plt.show()
import qiskit
qiskit.IBMQ.save_account('45b1db3a3c2ecae609e6c98184250919ccd31c9ea24100440abe0821fe6312c2b05a67239806c5b0020754eb3072f924547adb621e1e3931200aee13583a776f',
overwrite = True)
qiskit.IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
th_max = math.pi/2; dth = th_max/npe; th = np.arange(0,th_max+dth,dth)
device = provider.get_backend('ibm_nairobi')
nshots = 2**13
jobs_ids_ZZ = []; jobs_ids_XX = []
for j in range(0,len(th)):
# mede ZZ
qc = QuantumCircuit(2,2); qc_Psi_ = qc_Psi(th[j]); qc.append(qc_Psi_, [0,1]); qc.measure([0,1],[0,1])
job = execute(qc, backend=device, shots=nshots)
print('ZZ',job.job_id()); jobs_ids_ZZ.append(job.job_id())
# mede XX
qc = QuantumCircuit(2,2); qc_Psi_ = qc_Psi(th[j]); qc.append(qc_Psi_, [0,1]); qc.h([0,1]); qc.measure([0,1],[0,1])
job = execute(qc, backend=device, shots=nshots)
print('XX',job.job_id()); jobs_ids_XX.append(job.job_id())
f = open("jobs_ids_ZZ.txt", "w"); f.write(str(jobs_ids_ZZ)); f.close()
f = open("jobs_ids_XX.txt", "w"); f.write(str(jobs_ids_XX)); f.close()
f = open("jobs_ids_ZZ.txt","r")
list_ids_ZZ = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",")
f.close()
f = open("jobs_ids_XX.txt","r")
list_ids_XX = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",")
f.close()
th_max = math.pi/2; dth = th_max/npe; th = np.arange(0,th_max+dth,dth)
Oexp = np.zeros(len(th))
for j in range(0,len(th)):
# média de ZZ
job = device.retrieve_job(list_ids_ZZ[j])
result = job.result().get_counts()
ZZavg = ABavg(result, nshots)
# média de XX
job = device.retrieve_job(list_ids_XX[j])
result = job.result().get_counts()
XXavg = ABavg(result, nshots)
# média de O
Oexp[j] = math.sqrt(2)*(ZZavg + XXavg)
Oexp
import numpy as np; import math
th_max = math.pi/2; dtht = th_max/npt; tht = np.arange(0,th_max+dtht,dtht)
Oteo = -math.sqrt(2)*(1+np.sin(tht)); Odl = -2*np.ones(len(tht))
dth = th_max/npe; th = np.arange(0,th_max+dth,dth)
from matplotlib import pyplot as plt
plt.plot(tht, Oteo, label = r'$\langle O\rangle_{\Psi}^{teo}$')
plt.plot(tht, Odl, label = 'LHV limit')
plt.plot(th, Osim, '*', label = r'$\langle O\rangle_{\Psi}^{sim}$')
plt.plot(th, Oexp, '*', label = r'$\langle O\rangle_{\Psi}^{exp}$')
plt.xlabel(r'$\theta$'); plt.legend(); plt.show()
def f_Oavg(O,psi):
from sympy.physics.quantum.dagger import Dagger
return Dagger(psi)*O*psi
from sympy import Matrix, symbols, cos, sin, sqrt, simplify
from sympy.physics.quantum import TensorProduct as tp
Psim = Matrix([[0],[1],[-1],[0]])/sqrt(2)
X = Matrix([[0,1],[1,0]])
Z = Matrix([[1,0],[0,-1]])
th = symbols('theta')
A1B1 = tp(Z,cos(th)*Z+sin(th)*X)
A1B1avg = f_Oavg(A1B1,Psim)
A1B2 = tp(Z,(Z-X)/sqrt(2))
A1B2avg = f_Oavg(A1B2,Psim)
A2B1 = tp(X,cos(th)*Z+sin(th)*X)
A2B1avg = f_Oavg(A2B1,Psim)
A2B2 = tp(X,(Z-X)/sqrt(2))
A2B2avg = f_Oavg(A2B2,Psim)
Oavg = A1B1avg + A1B2avg + A2B1avg - A2B2avg
A1B1avg, A1B2avg, A2B1avg, A2B2avg, simplify(Oavg)
import numpy as np; import math
th_max = math.pi/4; npt = 100; dth = th_max/npt; tht = np.arange(-th_max,th_max+dth,dth)
Oteo = -math.sqrt(2)*(1+np.sin(tht+math.pi/4))
Odl = -2*np.ones(len(tht))
from matplotlib import pyplot as plt
plt.plot(tht, Oteo, label = r'$\langle O\rangle_{\Psi}^{teo}$')
plt.plot(tht, Odl, label = 'LHV limit')
plt.xlabel(r'$\theta$')
plt.legend(); plt.show()
th_max = math.pi/4; npe = 4; dth = 2*th_max/npe; th = np.arange(-th_max,th_max+dth,dth); Osim = np.zeros(len(th))
from qiskit import *; simulator = Aer.get_backend('qasm_simulator'); nshots = 2**13
for j in range(0,len(th)):
# mede <A1B1>
qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.u(th[j],0,math.pi, 1); qc.measure([0,1],[0,1])
job = execute(qc, backend=simulator, shots=nshots); result = job.result().get_counts(); A1B1avg = ABavg(result, nshots)
# mede <A1B2>
qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.u(-math.pi/4,0,math.pi, 1); qc.measure([0,1],[0,1])
job = execute(qc, backend=simulator, shots=nshots); result = job.result().get_counts(); A1B2avg = ABavg(result, nshots)
# mede <A2B1>
qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.h(0); qc.u(th[j],0,math.pi, 1); qc.measure([0,1],[0,1])
job = execute(qc, backend=simulator, shots=nshots); result = job.result().get_counts(); A2B1avg = ABavg(result, nshots)
# mede <A2B2>
qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.h(0); qc.u(-math.pi/4,0,math.pi, 1); qc.measure([0,1],[0,1])
job = execute(qc, backend=simulator, shots=nshots); result = job.result().get_counts(); A2B2avg = ABavg(result, nshots)
# média de O
Osim[j] = A1B1avg + A1B2avg + A2B1avg - A2B2avg
Osim
import numpy as np; import math
th_max = math.pi/4; dtht = 2*th_max/npt; tht = np.arange(-th_max,th_max+dtht,dtht)
Oteo = -math.sqrt(2)*(1+np.sin(tht+math.pi/4)); Odl = -2*np.ones(len(tht))
dth = 2*th_max/npe; th = np.arange(-th_max,th_max+dth,dth)
from matplotlib import pyplot as plt
plt.plot(tht, Oteo, label = r'$\langle O\rangle_{\Psi}^{teo}$')
plt.plot(tht, Odl, label = 'LHV limit')
plt.plot(th, Osim, '*', label = r'$\langle O\rangle_{\Psi}^{sim}$')
plt.xlabel(r'$\theta$')
plt.legend(); plt.show()
import qiskit
qiskit.IBMQ.save_account('45b1db3a3c2ecae609e6c98184250919ccd31c9ea24100440abe0821fe6312c2b05a67239806c5b0020754eb3072f924547adb621e1e3931200aee13583a776f',
overwrite = True)
qiskit.IBMQ.load_account()
#provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main')
th_max = math.pi/4; npe = 4; dth = 2*th_max/npe; th = np.arange(-th_max,th_max+dth,dth)
from qiskit import *; device = provider.get_backend('ibm_nairobi'); nshots = 2**13
jobs_ids_A1B1 = []; jobs_ids_A1B2 = []; jobs_ids_A2B1 = []; jobs_ids_A2B2 = []
for j in range(0,len(th)):
# mede <A1B1>
qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.u(th[j],0,math.pi, 1)
qc.measure([0,1],[0,1])
job = execute(qc, backend=device, shots=nshots); print('A1B1:',job.job_id()); jobs_ids_A1B1.append(job.job_id())
# mede <A1B2>
qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.u(-math.pi/4,0,math.pi, 1)
qc.measure([0,1],[0,1])
job = execute(qc, backend=device, shots=nshots); print('A1B2:',job.job_id()); jobs_ids_A1B2.append(job.job_id())
# mede <A2B1>
qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.h(0); qc.u(th[j],0,math.pi, 1)
qc.measure([0,1],[0,1])
job = execute(qc, backend=device, shots=nshots); print('A2B1:',job.job_id()); jobs_ids_A2B1.append(job.job_id())
# mede <A2B2>
qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.h(0); qc.u(-math.pi/4,0,math.pi, 1)
qc.measure([0,1],[0,1])
job = execute(qc, backend=device, shots=nshots); print('A2B2:',job.job_id()); jobs_ids_A2B2.append(job.job_id())
f = open("jobs_ids_A1B1.txt", "w"); f.write(str(jobs_ids_A1B1)); f.close()
f = open("jobs_ids_A1B2.txt", "w"); f.write(str(jobs_ids_A1B2)); f.close()
f = open("jobs_ids_A2B1.txt", "w"); f.write(str(jobs_ids_A2B1)); f.close()
f = open("jobs_ids_A2B2.txt", "w"); f.write(str(jobs_ids_A2B2)); f.close()
device = provider.get_backend('ibm_nairobi')
f = open("jobs_ids_A1B1.txt","r")
list_ids_A1B1 = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(","); f.close()
f = open("jobs_ids_A1B2.txt","r")
list_ids_A1B2 = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(","); f.close()
f = open("jobs_ids_A2B1.txt","r")
list_ids_A2B1 = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(","); f.close()
f = open("jobs_ids_A2B2.txt","r")
list_ids_A2B2 = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(","); f.close()
th_max = math.pi/4; dth = 2*th_max/npe; th = np.arange(-th_max,th_max+dth,dth); Oexp = np.zeros(len(th))
for j in range(0,len(th)):
# média de A1B1
job = device.retrieve_job(list_ids_A1B1[j]); result = job.result().get_counts(); A1B1avg = ABavg(result, nshots)
# média de A1B2
job = device.retrieve_job(list_ids_A1B2[j]); result = job.result().get_counts(); A1B2avg = ABavg(result, nshots)
# média de A2B1
job = device.retrieve_job(list_ids_A2B1[j]); result = job.result().get_counts(); A2B1avg = ABavg(result, nshots)
# média de A2B2
job = device.retrieve_job(list_ids_A2B2[j]); result = job.result().get_counts(); A2B2avg = ABavg(result, nshots)
# média de O
Oexp[j] = A1B1avg + A1B2avg + A2B1avg - A2B2avg
Oexp
import numpy as np; import math
th_max = math.pi/4; dtht = 2*th_max/npt; tht = np.arange(-th_max,th_max+dtht,dtht)
Oteo = -math.sqrt(2)*(1+np.sin(tht+math.pi/4)); Odl = -2*np.ones(len(tht))
dth = 2*th_max/npe; th = np.arange(-th_max,th_max+dth,dth)
from matplotlib import pyplot as plt
plt.plot(tht, Oteo, label = r'$\langle O\rangle_{\Psi}^{teo}$')
plt.plot(tht, Odl, label = 'LHV limit')
plt.plot(th, Osim, '*', label = r'$\langle O\rangle_{\Psi}^{sim}$')
plt.plot(th, Oexp, '*', label = r'$\langle O\rangle_{\Psi}^{exp}$')
plt.xlabel(r'$\theta$'); plt.legend(); plt.show()
|
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
|
PabloMartinezAngerosa
|
from tsp_qaoa import test_solution
from qiskit.visualization import plot_histogram
import networkx as nx
import numpy as np
import json
import csv
# Array of JSON Objects
header = ['instance','p','distance', 'mean']
length_p = 3
length_instances = 2
with open('qaoa_multiple_p_distance.csv', 'w', encoding='UTF8') as f:
writer = csv.writer(f)
# write the header
writer.writerow(header)
instance_index = 0
for instance in range(length_instances):
instance_index += 1
first_p = False
UNIFORM_CONVERGENCE_P = []
UNIFORM_CONVERGENCE_SAMPLE = []
for p in range(length_p):
p = p+1
if first_p == False:
print("Vuelve a llamar a test_solution")
job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(p=p)
first_p = True
else:
job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(grafo=G, p=p)
# Sort the JSON data based on the value of the brand key
UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["mean"])
convergence_min = UNIFORM_CONVERGENCE_SAMPLE[0]
UNIFORM_CONVERGENCE_P.append({
"mean":convergence_min["mean"],
"probabilities": convergence_min["probabilities"]
})
cauchy_function_nk = UNIFORM_CONVERGENCE_P[len(UNIFORM_CONVERGENCE_P) - 1]
p_index = 0
for p_state in UNIFORM_CONVERGENCE_P:
p_index += 1
print(p_index)
mean = p_state["mean"]
print(p_state)
print(mean)
distance_p_cauchy_function_nk = np.max(np.abs(cauchy_function_nk["probabilities"] - p_state["probabilities"]))
writer.writerow([instance_index, p_index, distance_p_cauchy_function_nk, mean])
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit import ClassicalRegister, QuantumRegister
from qiskit import QuantumCircuit, execute
from qiskit.tools.visualization import plot_histogram
# set up registers and program
qr = QuantumRegister(16)
cr = ClassicalRegister(16)
qc = QuantumCircuit(qr, cr)
# rightmost eight (qu)bits have ')' = 00101001
qc.x(qr[0])
qc.x(qr[3])
qc.x(qr[5])
# second eight (qu)bits have superposition of
# '8' = 00111000
# ';' = 00111011
# these differ only on the rightmost two bits
qc.h(qr[9]) # create superposition on 9
qc.cx(qr[9],qr[8]) # spread it to 8 with a CNOT
qc.x(qr[11])
qc.x(qr[12])
qc.x(qr[13])
# measure
for j in range(16):
qc.measure(qr[j], cr[j])
from qiskit import register, available_backends, get_backend
#import Qconfig and set APIToken and API url
try:
import sys
sys.path.append("../") # go to parent dir
import Qconfig
qx_config = {
"APItoken": Qconfig.APItoken,
"url": Qconfig.config['url']}
except Exception as e:
print(e)
qx_config = {
"APItoken":"YOUR_TOKEN_HERE",
"url":"https://quantumexperience.ng.bluemix.net/api"}
#set api
register(qx_config['APItoken'], qx_config['url'])
backend = "ibmq_qasm_simulator"
shots_sim = 128
job_sim = execute(qc, backend, shots=shots_sim)
stats_sim = job_sim.result().get_counts()
plot_histogram(stats_sim)
import matplotlib.pyplot as plt
%matplotlib inline
plt.rc('font', family='monospace')
def plot_smiley (stats, shots):
for bitString in stats:
char = chr(int( bitString[0:8] ,2)) # get string of the leftmost 8 bits and convert to an ASCII character
char += chr(int( bitString[8:16] ,2)) # do the same for string of rightmost 8 bits, and add it to the previous character
prob = stats[bitString] / shots # fraction of shots for which this result occurred
# create plot with all characters on top of each other with alpha given by how often it turned up in the output
plt.annotate( char, (0.5,0.5), va="center", ha="center", color = (0,0,0, prob ), size = 300)
if (prob>0.05): # list prob and char for the dominant results (occurred for more than 5% of shots)
print(str(prob)+"\t"+char)
plt.axis('off')
plt.show()
plot_smiley(stats_sim, shots_sim)
backends = available_backends()
backend = get_backend('ibmqx5')
print('Status of ibmqx5:',backend.status)
if backend.status["operational"] is True:
print("\nThe device is operational, so we'll submit the job.")
shots_device = 1000
job_device = execute(qc, backend, shots=shots_device)
stats_device = job_device.result().get_counts()
else:
print("\nThe device is not operational. Try again later.")
plot_smiley(stats_device, shots_device)
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
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
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
# unused for this file
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("../../solutions/utils/")
import circuit_utils, zne_utils, tomography_utils
importlib.reload(circuit_utils)
importlib.reload(zne_utils) # unused for this file
importlib.reload(tomography_utils) # unused for this file
from circuit_utils import *
from zne_utils import zne_wrapper, zne_decoder
from tomography_utils import expvals_to_valid_rho
from qiskit.test.mock import FakeJakarta
backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
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_list = [1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100]
print("trotter step list: ", num_steps_list)
scale_factors = [1.0, 2.0, 3.0] # unused for this file
shots = 1 << 13
reps = 8 # unused
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
# 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())
retrieved_cal_job = cal_job
cal_results = retrieved_cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
zne_fid_list = []
zne_stddev_list = []
for num_steps in num_steps_list:
print("trotter steps: ", num_steps)
t1 = time.perf_counter()
# 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(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = t3_st_qcs
zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = False)
print("created zne_qcs (length:", len(zne_qcs), ")")
# optimization_level must be 0
# feed initial_layout here to see the picture of the circuits before casting the job
t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")")
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)
retrieved_jobs = jobs
zne_fids = []
for job in retrieved_jobs:
raw_results = job.result()
mit_results = meas_fitter.filter.apply(raw_results)
zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors)
zne_rho = expvals_to_valid_rho(num_qubits, zne_expvals)
zne_fid = state_fidelity(zne_rho, target_state)
zne_fids.append(zne_fid)
zne_fid_list.append(np.mean(zne_fids))
zne_stddev_list.append(np.std(zne_fids))
t2 = time.perf_counter()
print('zne state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(zne_fids), np.std(zne_fids)))
print("time:", t2 - t1)
print()
with open("e2d1_zne.pkl", "wb") as f:
pickle.dump({"num_steps_list": num_steps_list, "fid": zne_fid_list, "stddev": zne_stddev_list}, f)
import qiskit.tools.jupyter
%qiskit_version_table
plt.plot(num_steps_list, zne_fid_list)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_city
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
# plot using a Statevector
state = Statevector(qc)
plot_state_city(state)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test cases for the pulse Schedule transforms."""
import unittest
from typing import List, Set
import numpy as np
from qiskit import pulse
from qiskit.pulse import (
Play,
Delay,
Acquire,
Schedule,
Waveform,
Drag,
Gaussian,
GaussianSquare,
Constant,
)
from qiskit.pulse import transforms, instructions
from qiskit.pulse.channels import (
MemorySlot,
DriveChannel,
AcquireChannel,
RegisterSlot,
SnapshotChannel,
)
from qiskit.pulse.instructions import directives
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeOpenPulse2Q
class TestAlignMeasures(QiskitTestCase):
"""Test the helper function which aligns acquires."""
def setUp(self):
super().setUp()
self.backend = FakeOpenPulse2Q()
self.config = self.backend.configuration()
self.inst_map = self.backend.defaults().instruction_schedule_map
self.short_pulse = pulse.Waveform(
samples=np.array([0.02739068], dtype=np.complex128), name="p0"
)
def test_align_measures(self):
"""Test that one acquire is delayed to match the time of the later acquire."""
sched = pulse.Schedule(name="fake_experiment")
sched.insert(0, Play(self.short_pulse, self.config.drive(0)), inplace=True)
sched.insert(1, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True)
sched.insert(10, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True)
sched.insert(10, Play(self.short_pulse, self.config.measure(0)), inplace=True)
sched.insert(11, Play(self.short_pulse, self.config.measure(0)), inplace=True)
sched.insert(10, Play(self.short_pulse, self.config.measure(1)), inplace=True)
aligned = transforms.align_measures([sched])[0]
self.assertEqual(aligned.name, "fake_experiment")
ref = pulse.Schedule(name="fake_experiment")
ref.insert(0, Play(self.short_pulse, self.config.drive(0)), inplace=True)
ref.insert(10, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True)
ref.insert(10, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True)
ref.insert(19, Play(self.short_pulse, self.config.measure(0)), inplace=True)
ref.insert(20, Play(self.short_pulse, self.config.measure(0)), inplace=True)
ref.insert(10, Play(self.short_pulse, self.config.measure(1)), inplace=True)
self.assertEqual(aligned, ref)
aligned = transforms.align_measures([sched], self.inst_map, align_time=20)[0]
ref = pulse.Schedule(name="fake_experiment")
ref.insert(10, Play(self.short_pulse, self.config.drive(0)), inplace=True)
ref.insert(20, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True)
ref.insert(20, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True)
ref.insert(29, Play(self.short_pulse, self.config.measure(0)), inplace=True)
ref.insert(30, Play(self.short_pulse, self.config.measure(0)), inplace=True)
ref.insert(20, Play(self.short_pulse, self.config.measure(1)), inplace=True)
self.assertEqual(aligned, ref)
def test_align_post_u3(self):
"""Test that acquires are scheduled no sooner than the duration of the longest X gate."""
sched = pulse.Schedule(name="fake_experiment")
sched = sched.insert(0, Play(self.short_pulse, self.config.drive(0)))
sched = sched.insert(1, Acquire(5, self.config.acquire(0), MemorySlot(0)))
sched = transforms.align_measures([sched], self.inst_map)[0]
for time, inst in sched.instructions:
if isinstance(inst, Acquire):
self.assertEqual(time, 4)
sched = transforms.align_measures([sched], self.inst_map, max_calibration_duration=10)[0]
for time, inst in sched.instructions:
if isinstance(inst, Acquire):
self.assertEqual(time, 10)
def test_multi_acquire(self):
"""Test that the last acquire is aligned to if multiple acquires occur on the
same channel."""
sched = pulse.Schedule()
sched.insert(0, Play(self.short_pulse, self.config.drive(0)), inplace=True)
sched.insert(4, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True)
sched.insert(20, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True)
sched.insert(10, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True)
aligned = transforms.align_measures([sched], self.inst_map)
ref = pulse.Schedule()
ref.insert(0, Play(self.short_pulse, self.config.drive(0)), inplace=True)
ref.insert(20, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True)
ref.insert(20, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True)
ref.insert(26, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True)
self.assertEqual(aligned[0], ref)
def test_multiple_acquires(self):
"""Test that multiple acquires are also aligned."""
sched = pulse.Schedule(name="fake_experiment")
sched.insert(0, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True)
sched.insert(5, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True)
sched.insert(10, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True)
ref = pulse.Schedule()
ref.insert(10, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True)
ref.insert(15, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True)
ref.insert(10, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True)
aligned = transforms.align_measures([sched], self.inst_map)[0]
self.assertEqual(aligned, ref)
def test_align_across_schedules(self):
"""Test that acquires are aligned together across multiple schedules."""
sched1 = pulse.Schedule(name="fake_experiment")
sched1 = sched1.insert(0, Play(self.short_pulse, self.config.drive(0)))
sched1 = sched1.insert(10, Acquire(5, self.config.acquire(0), MemorySlot(0)))
sched2 = pulse.Schedule(name="fake_experiment")
sched2 = sched2.insert(3, Play(self.short_pulse, self.config.drive(0)))
sched2 = sched2.insert(25, Acquire(5, self.config.acquire(0), MemorySlot(0)))
schedules = transforms.align_measures([sched1, sched2], self.inst_map)
for time, inst in schedules[0].instructions:
if isinstance(inst, Acquire):
self.assertEqual(time, 25)
for time, inst in schedules[0].instructions:
if isinstance(inst, Acquire):
self.assertEqual(time, 25)
def test_align_all(self):
"""Test alignment of all instructions in a schedule."""
sched0 = pulse.Schedule()
sched0.insert(0, Play(self.short_pulse, self.config.drive(0)), inplace=True)
sched0.insert(10, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True)
sched1 = pulse.Schedule()
sched1.insert(25, Play(self.short_pulse, self.config.drive(0)), inplace=True)
sched1.insert(25, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True)
all_aligned = transforms.align_measures([sched0, sched1], self.inst_map, align_all=True)
ref1_aligned = pulse.Schedule()
ref1_aligned.insert(15, Play(self.short_pulse, self.config.drive(0)), inplace=True)
ref1_aligned.insert(25, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True)
self.assertEqual(all_aligned[0], ref1_aligned)
self.assertEqual(all_aligned[1], sched1)
ref1_not_aligned = pulse.Schedule()
ref1_not_aligned.insert(0, Play(self.short_pulse, self.config.drive(0)), inplace=True)
ref1_not_aligned.insert(25, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True)
all_not_aligned = transforms.align_measures(
[sched0, sched1],
self.inst_map,
align_all=False,
)
self.assertEqual(all_not_aligned[0], ref1_not_aligned)
self.assertEqual(all_not_aligned[1], sched1)
def test_measurement_at_zero(self):
"""Test that acquire at t=0 works."""
sched1 = pulse.Schedule(name="fake_experiment")
sched1 = sched1.insert(0, Play(self.short_pulse, self.config.drive(0)))
sched1 = sched1.insert(0, Acquire(5, self.config.acquire(0), MemorySlot(0)))
sched2 = pulse.Schedule(name="fake_experiment")
sched2 = sched2.insert(0, Play(self.short_pulse, self.config.drive(0)))
sched2 = sched2.insert(0, Acquire(5, self.config.acquire(0), MemorySlot(0)))
schedules = transforms.align_measures([sched1, sched2], max_calibration_duration=0)
for time, inst in schedules[0].instructions:
if isinstance(inst, Acquire):
self.assertEqual(time, 0)
for time, inst in schedules[0].instructions:
if isinstance(inst, Acquire):
self.assertEqual(time, 0)
class TestAddImplicitAcquires(QiskitTestCase):
"""Test the helper function which makes implicit acquires explicit."""
def setUp(self):
super().setUp()
self.backend = FakeOpenPulse2Q()
self.config = self.backend.configuration()
self.short_pulse = pulse.Waveform(
samples=np.array([0.02739068], dtype=np.complex128), name="p0"
)
sched = pulse.Schedule(name="fake_experiment")
sched = sched.insert(0, Play(self.short_pulse, self.config.drive(0)))
sched = sched.insert(5, Acquire(5, self.config.acquire(0), MemorySlot(0)))
sched = sched.insert(5, Acquire(5, self.config.acquire(1), MemorySlot(1)))
self.sched = sched
def test_add_implicit(self):
"""Test that implicit acquires are made explicit according to the meas map."""
sched = transforms.add_implicit_acquires(self.sched, [[0, 1]])
acquired_qubits = set()
for _, inst in sched.instructions:
if isinstance(inst, Acquire):
acquired_qubits.add(inst.acquire.index)
self.assertEqual(acquired_qubits, {0, 1})
def test_add_across_meas_map_sublists(self):
"""Test that implicit acquires in separate meas map sublists are all added."""
sched = transforms.add_implicit_acquires(self.sched, [[0, 2], [1, 3]])
acquired_qubits = set()
for _, inst in sched.instructions:
if isinstance(inst, Acquire):
acquired_qubits.add(inst.acquire.index)
self.assertEqual(acquired_qubits, {0, 1, 2, 3})
def test_dont_add_all(self):
"""Test that acquires aren't added if no qubits in the sublist aren't being acquired."""
sched = transforms.add_implicit_acquires(self.sched, [[4, 5], [0, 2], [1, 3]])
acquired_qubits = set()
for _, inst in sched.instructions:
if isinstance(inst, Acquire):
acquired_qubits.add(inst.acquire.index)
self.assertEqual(acquired_qubits, {0, 1, 2, 3})
def test_multiple_acquires(self):
"""Test for multiple acquires."""
sched = pulse.Schedule()
acq_q0 = pulse.Acquire(1200, AcquireChannel(0), MemorySlot(0))
sched += acq_q0
sched += acq_q0 << sched.duration
sched = transforms.add_implicit_acquires(sched, meas_map=[[0]])
self.assertEqual(sched.instructions, ((0, acq_q0), (2400, acq_q0)))
class TestPad(QiskitTestCase):
"""Test padding of schedule with delays."""
def test_padding_empty_schedule(self):
"""Test padding of empty schedule."""
self.assertEqual(pulse.Schedule(), transforms.pad(pulse.Schedule()))
def test_padding_schedule(self):
"""Test padding schedule."""
delay = 10
sched = (
Delay(delay, DriveChannel(0)).shift(10)
+ Delay(delay, DriveChannel(0)).shift(10)
+ Delay(delay, DriveChannel(1)).shift(10)
)
ref_sched = (
sched # pylint: disable=unsupported-binary-operation
| Delay(delay, DriveChannel(0))
| Delay(delay, DriveChannel(0)).shift(20)
| Delay(delay, DriveChannel(1))
| Delay( # pylint: disable=unsupported-binary-operation
2 * delay, DriveChannel(1)
).shift(20)
)
self.assertEqual(transforms.pad(sched), ref_sched)
def test_padding_schedule_inverse_order(self):
"""Test padding schedule is insensitive to order in which commands were added.
This test is the same as `test_adding_schedule` but the order by channel
in which commands were added to the schedule to be padded has been reversed.
"""
delay = 10
sched = (
Delay(delay, DriveChannel(1)).shift(10)
+ Delay(delay, DriveChannel(0)).shift(10)
+ Delay(delay, DriveChannel(0)).shift(10)
)
ref_sched = (
sched # pylint: disable=unsupported-binary-operation
| Delay(delay, DriveChannel(0))
| Delay(delay, DriveChannel(0)).shift(20)
| Delay(delay, DriveChannel(1))
| Delay( # pylint: disable=unsupported-binary-operation
2 * delay, DriveChannel(1)
).shift(20)
)
self.assertEqual(transforms.pad(sched), ref_sched)
def test_padding_until_less(self):
"""Test padding until time that is less than schedule duration."""
delay = 10
sched = Delay(delay, DriveChannel(0)).shift(10) + Delay(delay, DriveChannel(1))
ref_sched = sched | Delay(delay, DriveChannel(0)) | Delay(5, DriveChannel(1)).shift(10)
self.assertEqual(transforms.pad(sched, until=15), ref_sched)
def test_padding_until_greater(self):
"""Test padding until time that is greater than schedule duration."""
delay = 10
sched = Delay(delay, DriveChannel(0)).shift(10) + Delay(delay, DriveChannel(1))
ref_sched = (
sched # pylint: disable=unsupported-binary-operation
| Delay(delay, DriveChannel(0))
| Delay(30, DriveChannel(0)).shift(20)
| Delay(40, DriveChannel(1)).shift(10) # pylint: disable=unsupported-binary-operation
)
self.assertEqual(transforms.pad(sched, until=50), ref_sched)
def test_padding_supplied_channels(self):
"""Test padding of only specified channels."""
delay = 10
sched = Delay(delay, DriveChannel(0)).shift(10) + Delay(delay, DriveChannel(1))
ref_sched = sched | Delay(delay, DriveChannel(0)) | Delay(2 * delay, DriveChannel(2))
channels = [DriveChannel(0), DriveChannel(2)]
self.assertEqual(transforms.pad(sched, channels=channels), ref_sched)
def test_padding_less_than_sched_duration(self):
"""Test that the until arg is respected even for less than the input schedule duration."""
delay = 10
sched = Delay(delay, DriveChannel(0)) + Delay(delay, DriveChannel(0)).shift(20)
ref_sched = sched | pulse.Delay(5, DriveChannel(0)).shift(10)
self.assertEqual(transforms.pad(sched, until=15), ref_sched)
def test_padding_prepended_delay(self):
"""Test that there is delay before the first instruction."""
delay = 10
sched = Delay(delay, DriveChannel(0)).shift(10) + Delay(delay, DriveChannel(0))
ref_sched = (
Delay(delay, DriveChannel(0))
+ Delay(delay, DriveChannel(0))
+ Delay(delay, DriveChannel(0))
)
self.assertEqual(transforms.pad(sched, until=30, inplace=True), ref_sched)
def test_pad_no_delay_on_classical_io_channels(self):
"""Test padding does not apply to classical IO channels."""
delay = 10
sched = (
Delay(delay, MemorySlot(0)).shift(20)
+ Delay(delay, RegisterSlot(0)).shift(10)
+ Delay(delay, SnapshotChannel())
)
ref_sched = (
Delay(delay, MemorySlot(0)).shift(20)
+ Delay(delay, RegisterSlot(0)).shift(10)
+ Delay(delay, SnapshotChannel())
)
self.assertEqual(transforms.pad(sched, until=15), ref_sched)
def get_pulse_ids(schedules: List[Schedule]) -> Set[int]:
"""Returns ids of pulses used in Schedules."""
ids = set()
for schedule in schedules:
for _, inst in schedule.instructions:
ids.add(inst.pulse.id)
return ids
class TestCompressTransform(QiskitTestCase):
"""Compress function test."""
def test_with_duplicates(self):
"""Test compression of schedule."""
schedule = Schedule()
drive_channel = DriveChannel(0)
schedule += Play(Waveform([0.0, 0.1]), drive_channel)
schedule += Play(Waveform([0.0, 0.1]), drive_channel)
compressed_schedule = transforms.compress_pulses([schedule])
original_pulse_ids = get_pulse_ids([schedule])
compressed_pulse_ids = get_pulse_ids(compressed_schedule)
self.assertEqual(len(compressed_pulse_ids), 1)
self.assertEqual(len(original_pulse_ids), 2)
self.assertTrue(next(iter(compressed_pulse_ids)) in original_pulse_ids)
def test_sample_pulse_with_clipping(self):
"""Test sample pulses with clipping."""
schedule = Schedule()
drive_channel = DriveChannel(0)
schedule += Play(Waveform([0.0, 1.0]), drive_channel)
schedule += Play(Waveform([0.0, 1.001], epsilon=1e-3), drive_channel)
schedule += Play(Waveform([0.0, 1.0000000001]), drive_channel)
compressed_schedule = transforms.compress_pulses([schedule])
original_pulse_ids = get_pulse_ids([schedule])
compressed_pulse_ids = get_pulse_ids(compressed_schedule)
self.assertEqual(len(compressed_pulse_ids), 1)
self.assertEqual(len(original_pulse_ids), 3)
self.assertTrue(next(iter(compressed_pulse_ids)) in original_pulse_ids)
def test_no_duplicates(self):
"""Test with no pulse duplicates."""
schedule = Schedule()
drive_channel = DriveChannel(0)
schedule += Play(Waveform([0.0, 1.0]), drive_channel)
schedule += Play(Waveform([0.0, 0.9]), drive_channel)
schedule += Play(Waveform([0.0, 0.3]), drive_channel)
compressed_schedule = transforms.compress_pulses([schedule])
original_pulse_ids = get_pulse_ids([schedule])
compressed_pulse_ids = get_pulse_ids(compressed_schedule)
self.assertEqual(len(original_pulse_ids), len(compressed_pulse_ids))
def test_parametric_pulses_with_duplicates(self):
"""Test with parametric pulses."""
schedule = Schedule()
drive_channel = DriveChannel(0)
schedule += Play(Gaussian(duration=25, sigma=4, amp=0.5, angle=np.pi / 2), drive_channel)
schedule += Play(Gaussian(duration=25, sigma=4, amp=0.5, angle=np.pi / 2), drive_channel)
schedule += Play(GaussianSquare(duration=150, amp=0.2, sigma=8, width=140), drive_channel)
schedule += Play(GaussianSquare(duration=150, amp=0.2, sigma=8, width=140), drive_channel)
schedule += Play(Constant(duration=150, amp=0.5, angle=0.7), drive_channel)
schedule += Play(Constant(duration=150, amp=0.5, angle=0.7), drive_channel)
schedule += Play(Drag(duration=25, amp=0.4, angle=-0.3, sigma=7.8, beta=4), drive_channel)
schedule += Play(Drag(duration=25, amp=0.4, angle=-0.3, sigma=7.8, beta=4), drive_channel)
compressed_schedule = transforms.compress_pulses([schedule])
original_pulse_ids = get_pulse_ids([schedule])
compressed_pulse_ids = get_pulse_ids(compressed_schedule)
self.assertEqual(len(original_pulse_ids), 8)
self.assertEqual(len(compressed_pulse_ids), 4)
def test_parametric_pulses_with_no_duplicates(self):
"""Test parametric pulses with no duplicates."""
schedule = Schedule()
drive_channel = DriveChannel(0)
schedule += Play(Gaussian(duration=25, sigma=4, amp=0.5, angle=np.pi / 2), drive_channel)
schedule += Play(Gaussian(duration=25, sigma=4, amp=0.49, angle=np.pi / 2), drive_channel)
schedule += Play(GaussianSquare(duration=150, amp=0.2, sigma=8, width=140), drive_channel)
schedule += Play(GaussianSquare(duration=150, amp=0.19, sigma=8, width=140), drive_channel)
schedule += Play(Constant(duration=150, amp=0.5, angle=0.3), drive_channel)
schedule += Play(Constant(duration=150, amp=0.51, angle=0.3), drive_channel)
schedule += Play(Drag(duration=25, amp=0.5, angle=0.5, sigma=7.8, beta=4), drive_channel)
schedule += Play(Drag(duration=25, amp=0.5, angle=0.51, sigma=7.8, beta=4), drive_channel)
compressed_schedule = transforms.compress_pulses([schedule])
original_pulse_ids = get_pulse_ids([schedule])
compressed_pulse_ids = get_pulse_ids(compressed_schedule)
self.assertEqual(len(original_pulse_ids), len(compressed_pulse_ids))
def test_with_different_channels(self):
"""Test with different channels."""
schedule = Schedule()
schedule += Play(Waveform([0.0, 0.1]), DriveChannel(0))
schedule += Play(Waveform([0.0, 0.1]), DriveChannel(1))
compressed_schedule = transforms.compress_pulses([schedule])
original_pulse_ids = get_pulse_ids([schedule])
compressed_pulse_ids = get_pulse_ids(compressed_schedule)
self.assertEqual(len(original_pulse_ids), 2)
self.assertEqual(len(compressed_pulse_ids), 1)
def test_sample_pulses_with_tolerance(self):
"""Test sample pulses with tolerance."""
schedule = Schedule()
schedule += Play(Waveform([0.0, 0.1001], epsilon=1e-3), DriveChannel(0))
schedule += Play(Waveform([0.0, 0.1], epsilon=1e-3), DriveChannel(1))
compressed_schedule = transforms.compress_pulses([schedule])
original_pulse_ids = get_pulse_ids([schedule])
compressed_pulse_ids = get_pulse_ids(compressed_schedule)
self.assertEqual(len(original_pulse_ids), 2)
self.assertEqual(len(compressed_pulse_ids), 1)
def test_multiple_schedules(self):
"""Test multiple schedules."""
schedules = []
for _ in range(2):
schedule = Schedule()
drive_channel = DriveChannel(0)
schedule += Play(Waveform([0.0, 0.1]), drive_channel)
schedule += Play(Waveform([0.0, 0.1]), drive_channel)
schedule += Play(Waveform([0.0, 0.2]), drive_channel)
schedules.append(schedule)
compressed_schedule = transforms.compress_pulses(schedules)
original_pulse_ids = get_pulse_ids(schedules)
compressed_pulse_ids = get_pulse_ids(compressed_schedule)
self.assertEqual(len(original_pulse_ids), 6)
self.assertEqual(len(compressed_pulse_ids), 2)
class TestAlignSequential(QiskitTestCase):
"""Test sequential alignment transform."""
def test_align_sequential(self):
"""Test sequential alignment without a barrier."""
context = transforms.AlignSequential()
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
schedule = pulse.Schedule()
schedule.insert(1, instructions.Delay(3, d0), inplace=True)
schedule.insert(4, instructions.Delay(5, d1), inplace=True)
schedule.insert(12, instructions.Delay(7, d0), inplace=True)
schedule = context.align(schedule)
reference = pulse.Schedule()
# d0
reference.insert(0, instructions.Delay(3, d0), inplace=True)
reference.insert(8, instructions.Delay(7, d0), inplace=True)
# d1
reference.insert(3, instructions.Delay(5, d1), inplace=True)
self.assertEqual(schedule, reference)
def test_align_sequential_with_barrier(self):
"""Test sequential alignment with a barrier."""
context = transforms.AlignSequential()
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
schedule = pulse.Schedule()
schedule.insert(1, instructions.Delay(3, d0), inplace=True)
schedule.append(directives.RelativeBarrier(d0, d1), inplace=True)
schedule.insert(4, instructions.Delay(5, d1), inplace=True)
schedule.insert(12, instructions.Delay(7, d0), inplace=True)
schedule = context.align(schedule)
reference = pulse.Schedule()
reference.insert(0, instructions.Delay(3, d0), inplace=True)
reference.insert(3, directives.RelativeBarrier(d0, d1), inplace=True)
reference.insert(3, instructions.Delay(5, d1), inplace=True)
reference.insert(8, instructions.Delay(7, d0), inplace=True)
self.assertEqual(schedule, reference)
class TestAlignLeft(QiskitTestCase):
"""Test left alignment transform."""
def test_align_left(self):
"""Test left alignment without a barrier."""
context = transforms.AlignLeft()
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
d2 = pulse.DriveChannel(2)
schedule = pulse.Schedule()
schedule.insert(1, instructions.Delay(3, d0), inplace=True)
schedule.insert(17, instructions.Delay(11, d2), inplace=True)
sched_grouped = pulse.Schedule()
sched_grouped += instructions.Delay(5, d1)
sched_grouped += instructions.Delay(7, d0)
schedule.append(sched_grouped, inplace=True)
schedule = context.align(schedule)
reference = pulse.Schedule()
# d0
reference.insert(0, instructions.Delay(3, d0), inplace=True)
reference.insert(3, instructions.Delay(7, d0), inplace=True)
# d1
reference.insert(3, instructions.Delay(5, d1), inplace=True)
# d2
reference.insert(0, instructions.Delay(11, d2), inplace=True)
self.assertEqual(schedule, reference)
def test_align_left_with_barrier(self):
"""Test left alignment with a barrier."""
context = transforms.AlignLeft()
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
d2 = pulse.DriveChannel(2)
schedule = pulse.Schedule()
schedule.insert(1, instructions.Delay(3, d0), inplace=True)
schedule.append(directives.RelativeBarrier(d0, d1, d2), inplace=True)
schedule.insert(17, instructions.Delay(11, d2), inplace=True)
sched_grouped = pulse.Schedule()
sched_grouped += instructions.Delay(5, d1)
sched_grouped += instructions.Delay(7, d0)
schedule.append(sched_grouped, inplace=True)
schedule = transforms.remove_directives(context.align(schedule))
reference = pulse.Schedule()
# d0
reference.insert(0, instructions.Delay(3, d0), inplace=True)
reference.insert(3, instructions.Delay(7, d0), inplace=True)
# d1
reference = reference.insert(3, instructions.Delay(5, d1))
# d2
reference = reference.insert(3, instructions.Delay(11, d2))
self.assertEqual(schedule, reference)
class TestAlignRight(QiskitTestCase):
"""Test right alignment transform."""
def test_align_right(self):
"""Test right alignment without a barrier."""
context = transforms.AlignRight()
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
d2 = pulse.DriveChannel(2)
schedule = pulse.Schedule()
schedule.insert(1, instructions.Delay(3, d0), inplace=True)
schedule.insert(17, instructions.Delay(11, d2), inplace=True)
sched_grouped = pulse.Schedule()
sched_grouped.insert(2, instructions.Delay(5, d1), inplace=True)
sched_grouped += instructions.Delay(7, d0)
schedule.append(sched_grouped, inplace=True)
schedule = context.align(schedule)
reference = pulse.Schedule()
# d0
reference.insert(1, instructions.Delay(3, d0), inplace=True)
reference.insert(4, instructions.Delay(7, d0), inplace=True)
# d1
reference.insert(6, instructions.Delay(5, d1), inplace=True)
# d2
reference.insert(0, instructions.Delay(11, d2), inplace=True)
self.assertEqual(schedule, reference)
def test_align_right_with_barrier(self):
"""Test right alignment with a barrier."""
context = transforms.AlignRight()
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
d2 = pulse.DriveChannel(2)
schedule = pulse.Schedule()
schedule.insert(1, instructions.Delay(3, d0), inplace=True)
schedule.append(directives.RelativeBarrier(d0, d1, d2), inplace=True)
schedule.insert(17, instructions.Delay(11, d2), inplace=True)
sched_grouped = pulse.Schedule()
sched_grouped.insert(2, instructions.Delay(5, d1), inplace=True)
sched_grouped += instructions.Delay(7, d0)
schedule.append(sched_grouped, inplace=True)
schedule = transforms.remove_directives(context.align(schedule))
reference = pulse.Schedule()
# d0
reference.insert(0, instructions.Delay(3, d0), inplace=True)
reference.insert(7, instructions.Delay(7, d0), inplace=True)
# d1
reference.insert(9, instructions.Delay(5, d1), inplace=True)
# d2
reference.insert(3, instructions.Delay(11, d2), inplace=True)
self.assertEqual(schedule, reference)
class TestAlignEquispaced(QiskitTestCase):
"""Test equispaced alignment transform."""
def test_equispaced_with_short_duration(self):
"""Test equispaced context with duration shorter than the schedule duration."""
context = transforms.AlignEquispaced(duration=20)
d0 = pulse.DriveChannel(0)
schedule = pulse.Schedule()
for _ in range(3):
schedule.append(Delay(10, d0), inplace=True)
schedule = context.align(schedule)
reference = pulse.Schedule()
reference.insert(0, Delay(10, d0), inplace=True)
reference.insert(10, Delay(10, d0), inplace=True)
reference.insert(20, Delay(10, d0), inplace=True)
self.assertEqual(schedule, reference)
def test_equispaced_with_longer_duration(self):
"""Test equispaced context with duration longer than the schedule duration."""
context = transforms.AlignEquispaced(duration=50)
d0 = pulse.DriveChannel(0)
schedule = pulse.Schedule()
for _ in range(3):
schedule.append(Delay(10, d0), inplace=True)
schedule = context.align(schedule)
reference = pulse.Schedule()
reference.insert(0, Delay(10, d0), inplace=True)
reference.insert(20, Delay(10, d0), inplace=True)
reference.insert(40, Delay(10, d0), inplace=True)
self.assertEqual(schedule, reference)
def test_equispaced_with_multiple_channels_short_duration(self):
"""Test equispaced context with multiple channels and duration shorter than the total
duration."""
context = transforms.AlignEquispaced(duration=20)
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
schedule = pulse.Schedule()
schedule.append(Delay(10, d0), inplace=True)
schedule.append(Delay(20, d1), inplace=True)
schedule = context.align(schedule)
reference = pulse.Schedule()
reference.insert(0, Delay(10, d0), inplace=True)
reference.insert(0, Delay(20, d1), inplace=True)
self.assertEqual(schedule, reference)
def test_equispaced_with_multiple_channels_longer_duration(self):
"""Test equispaced context with multiple channels and duration longer than the total
duration."""
context = transforms.AlignEquispaced(duration=30)
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
schedule = pulse.Schedule()
schedule.append(Delay(10, d0), inplace=True)
schedule.append(Delay(20, d1), inplace=True)
schedule = context.align(schedule)
reference = pulse.Schedule()
reference.insert(0, Delay(10, d0), inplace=True)
reference.insert(10, Delay(20, d1), inplace=True)
self.assertEqual(schedule, reference)
class TestAlignFunc(QiskitTestCase):
"""Test callback alignment transform."""
@staticmethod
def _position(ind):
"""Returns 0.25, 0.5, 0.75 for ind = 1, 2, 3."""
return ind / (3 + 1)
def test_numerical_with_short_duration(self):
"""Test numerical alignment context with duration shorter than the schedule duration."""
context = transforms.AlignFunc(duration=20, func=self._position)
d0 = pulse.DriveChannel(0)
schedule = pulse.Schedule()
for _ in range(3):
schedule.append(Delay(10, d0), inplace=True)
schedule = context.align(schedule)
reference = pulse.Schedule()
reference.insert(0, Delay(10, d0), inplace=True)
reference.insert(10, Delay(10, d0), inplace=True)
reference.insert(20, Delay(10, d0), inplace=True)
self.assertEqual(schedule, reference)
def test_numerical_with_longer_duration(self):
"""Test numerical alignment context with duration longer than the schedule duration."""
context = transforms.AlignFunc(duration=80, func=self._position)
d0 = pulse.DriveChannel(0)
schedule = pulse.Schedule()
for _ in range(3):
schedule.append(Delay(10, d0), inplace=True)
schedule = context.align(schedule)
reference = pulse.Schedule()
reference.insert(15, Delay(10, d0), inplace=True)
reference.insert(35, Delay(10, d0), inplace=True)
reference.insert(55, Delay(10, d0), inplace=True)
self.assertEqual(schedule, reference)
class TestFlatten(QiskitTestCase):
"""Test flattening transform."""
def test_flatten(self):
"""Test the flatten transform."""
context_left = transforms.AlignLeft()
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
schedule = pulse.Schedule()
schedule += instructions.Delay(3, d0)
grouped = pulse.Schedule()
grouped += instructions.Delay(5, d1)
grouped += instructions.Delay(7, d0)
# include a grouped schedule
grouped = schedule + grouped
# flatten the schedule inline internal groups
flattened = transforms.flatten(grouped)
# align all the instructions to the left after flattening
flattened = context_left.align(flattened)
grouped = context_left.align(grouped)
reference = pulse.Schedule()
# d0
reference.insert(0, instructions.Delay(3, d0), inplace=True)
reference.insert(3, instructions.Delay(7, d0), inplace=True)
# d1
reference.insert(0, instructions.Delay(5, d1), inplace=True)
self.assertEqual(flattened, reference)
self.assertNotEqual(grouped, reference)
class _TestDirective(directives.Directive):
"""Pulse ``RelativeBarrier`` directive."""
def __init__(self, *channels):
"""Test directive"""
super().__init__(operands=tuple(channels))
@property
def channels(self):
return self.operands
class TestRemoveDirectives(QiskitTestCase):
"""Test removing of directives."""
def test_remove_directives(self):
"""Test that all directives are removed."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
schedule = pulse.Schedule()
schedule += _TestDirective(d0, d1)
schedule += instructions.Delay(3, d0)
schedule += _TestDirective(d0, d1)
schedule = transforms.remove_directives(schedule)
reference = pulse.Schedule()
# d0
reference += instructions.Delay(3, d0)
self.assertEqual(schedule, reference)
class TestRemoveTrivialBarriers(QiskitTestCase):
"""Test scheduling transforms."""
def test_remove_trivial_barriers(self):
"""Test that trivial barriers are properly removed."""
schedule = pulse.Schedule()
schedule += directives.RelativeBarrier()
schedule += directives.RelativeBarrier(pulse.DriveChannel(0))
schedule += directives.RelativeBarrier(pulse.DriveChannel(0), pulse.DriveChannel(1))
schedule = transforms.remove_trivial_barriers(schedule)
reference = pulse.Schedule()
reference += directives.RelativeBarrier(pulse.DriveChannel(0), pulse.DriveChannel(1))
self.assertEqual(schedule, reference)
class TestRemoveSubroutines(QiskitTestCase):
"""Test removing of subroutines."""
def test_remove_subroutines(self):
"""Test that nested subroutiens are removed."""
d0 = pulse.DriveChannel(0)
nested_routine = pulse.Schedule()
nested_routine.insert(10, pulse.Delay(10, d0), inplace=True)
subroutine = pulse.Schedule()
subroutine.insert(0, pulse.Delay(20, d0), inplace=True)
with self.assertWarns(DeprecationWarning):
subroutine.insert(20, pulse.instructions.Call(nested_routine), inplace=True)
subroutine.insert(50, pulse.Delay(10, d0), inplace=True)
main_program = pulse.Schedule()
main_program.insert(0, pulse.Delay(10, d0), inplace=True)
with self.assertWarns(DeprecationWarning):
main_program.insert(30, pulse.instructions.Call(subroutine), inplace=True)
target = transforms.inline_subroutines(main_program)
reference = pulse.Schedule()
reference.insert(0, pulse.Delay(10, d0), inplace=True)
reference.insert(30, pulse.Delay(20, d0), inplace=True)
reference.insert(60, pulse.Delay(10, d0), inplace=True)
reference.insert(80, pulse.Delay(10, d0), inplace=True)
self.assertEqual(target, reference)
def test_call_in_nested_schedule(self):
"""Test that subroutines in nested schedule."""
d0 = pulse.DriveChannel(0)
subroutine = pulse.Schedule()
subroutine.insert(10, pulse.Delay(10, d0), inplace=True)
nested_sched = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
nested_sched.insert(0, pulse.instructions.Call(subroutine), inplace=True)
main_sched = pulse.Schedule()
main_sched.insert(0, nested_sched, inplace=True)
target = transforms.inline_subroutines(main_sched)
# no call instruction
reference_nested = pulse.Schedule()
reference_nested.insert(0, subroutine, inplace=True)
reference = pulse.Schedule()
reference.insert(0, reference_nested, inplace=True)
self.assertEqual(target, reference)
def test_call_in_nested_block(self):
"""Test that subroutines in nested schedule."""
d0 = pulse.DriveChannel(0)
subroutine = pulse.ScheduleBlock()
subroutine.append(pulse.Delay(10, d0), inplace=True)
nested_block = pulse.ScheduleBlock()
with self.assertWarns(DeprecationWarning):
nested_block.append(pulse.instructions.Call(subroutine), inplace=True)
main_block = pulse.ScheduleBlock()
main_block.append(nested_block, inplace=True)
target = transforms.inline_subroutines(main_block)
# no call instruction
reference_nested = pulse.ScheduleBlock()
reference_nested.append(subroutine, inplace=True)
reference = pulse.ScheduleBlock()
reference.append(reference_nested, inplace=True)
self.assertEqual(target, reference)
if __name__ == "__main__":
unittest.main()
|
https://github.com/biswaroopmukherjee/Quantum-Waddle
|
biswaroopmukherjee
|
import numpy as np
import time
import networkx as nx
import matplotlib.pyplot as plt
import random
from qiskit import (QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer)
%matplotlib inline
from qiskit import IBMQ
from qiskit.tools.monitor import job_monitor
IBMQ.load_account()
IBMQ.providers()
provider = IBMQ.get_provider(group='open')
def counts_to_prob_1d(counts):
# Convert histogram counts to probability vector of size 1 x 2^n
states = list(counts.keys())
state_counts = list(counts.values())
nshots = sum(state_counts)
# Convert binary to integer index, reversing order as consistent w qiskit convention
states_x = [int(s[::-1],2) for s in states]
# Create array of probability values
probabilities = np.zeros(2**n)
probabilities[states_x] = state_counts
probabilities /= nshots
return probabilities
def increment_gate(circuit, qpos, qcoin):
n = len(qpos)
for i in range(n):
circuit.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla')
def decrement_gate(circuit, qpos, qcoin):
n = len(qpos)
circuit.x(qcoin[0])
for i in range(n):
if i+1 < n: circuit.x(qpos[i+1:])
circuit.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla')
if i+1 < n: circuit.x(qpos[i+1:])
def step(circuit, qpos, qcoin,cpos,simulatorType):
circuit.h(qcoin)
circuit.barrier()
increment_gate(circuit, qpos, qcoin)
circuit.barrier()
decrement_gate(circuit, qpos, qcoin)
circuit.barrier()
if simulatorType == 'classical':
circuit.measure(qpos,cpos)
def run(steps,simulatorType):
# steps = number of quantum walks steps
# simulatorType = 'sim', 'quantum' or 'classical'
if simulatorType == 'sim':
simulator = Aer.get_backend('qasm_simulator')
elif simulatorType == 'quantum':
simulator = provider.get_backend('ibmq_5_yorktown')
elif simulatorType == 'classical':
simulator = Aer.get_backend('qasm_simulator')
else:
simulator = Aer.get_backend('qasm_simulator')
qpos = QuantumRegister(n,'qc')
qcoin = QuantumRegister(1,'qanc')
cpos = ClassicalRegister(n,'cr')
circuit = QuantumCircuit(qpos, qcoin, cpos)
for i in range(steps):
step(circuit, qpos, qcoin,cpos, simulatorType)
# # Map the quantum measurement to the classical bits
circuit.measure(qpos,cpos)
# # Execute the circuit on the qasm simulator
job = execute(circuit, simulator, shots=1000)
# # monitor job
job_monitor(job)
# # Grab results from the job
result = job.result()
# # Returns counts
counts = result.get_counts(circuit)
return counts
seed = 12
random.seed(seed)
np.random.seed(seed)
def plotCircleGraph(names,propabilities,color=[0,0,1]):
G = nx.Graph()
colorarray = []
# generate array of colors
numProp = len(propabilities)
for idx in range(numProp):
colorarray.append(color+[0.5*propabilities[idx]])
# generate graph
for idx in range(numProp-1):
G.add_edge(idx, idx+1)
# add last edge
G.add_edge(0,numProp-1)
# label nodes
labels = {}
for idx in range(numProp):
labels[idx] = names[idx]
nx.draw(G,
pos=nx.circular_layout(G),
node_color=colorarray,
cmap=plt.cm.Blues,
node_size=3000,
edge_color='k',
)
pos=nx.circular_layout(G)
labels = nx.draw_networkx_labels(G,pos,labels,font_size=16,
bbox=dict(facecolor='w', alpha=1, edgecolor='w')
)
# run and plot 1D walk
steps = 3
n=2
for i in range(steps+1):
#run classical random walk
countsClassical = run(i,'classical')
propClassical = counts_to_prob_1d(countsClassical)
#run quantum simulation
countsSim = run(i,'sim')
propSim = counts_to_prob_1d(countsSim)
#run the real thing
countsQuantum = run(i,'quantum')
propQuantum = counts_to_prob_1d(countsQuantum)
names = []
formatLabel = '{0:0'+str(n)+'b}'
for idx in range(2**n):
names.append('|' + formatLabel.format(idx) +'>')
#plotting
f, axs = plt.subplots(2,3,figsize=(13,8))
margin=0.4
f.subplots_adjust(margin, margin, 1.-margin, 1.-margin)
axs[0,0].set_title('classical random walk', fontsize=14)
plt.sca(axs[0,0])
plotCircleGraph(names,propClassical,color=[1,0,0])
plt.sca(axs[1,0])
plt.bar(names,propClassical,edgecolor='black', color=[1,0,0,.4], lw=2)
plt.ylim(0,1)
plt.xticks(rotation=45)
axs[0,1].set_title('simulated quantum walk', fontsize=14)
plt.sca(axs[0,1])
plotCircleGraph(names,propSim,color=[0.3,1,0])
plt.sca(axs[1,1])
plt.bar(names,propSim,edgecolor='black', color=[0.3,1,0,.4], lw=2)
plt.ylim(0,1)
plt.xticks(rotation=45)
axs[0,2].set_title('IBM quantum walk', fontsize=14)
plt.sca(axs[0,2])
plotCircleGraph(names,propQuantum,color=[0.1,0.3,1])
plt.sca(axs[1,2])
plt.bar(names,propQuantum,edgecolor='black', color=[0.1,0.3,1,.4], lw=2)
plt.ylim(0,1)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
|
https://github.com/qiskit-community/community.qiskit.org
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, Aer, execute
def NOT(input):
q = QuantumRegister(1) # a qubit in which to encode the inout
c = ClassicalRegister(1) # a bit to store the output
qc = QuantumCircuit(q, c) # this is where the quantum program goes
# We encode '0' as the qubit state |0⟩, and '1' as |1⟩
# Since the qubit is initially |0⟩, we don't need to do anything for an input of '0'
# For an input of '1', we do an x to rotate the |0⟩ to |1⟩
if input=='1': #
qc.x( q[0] )
# Now we've encoded the input, we can do a NOT on it using x
qc.x( q[0] )
# Finally, we extract the |0⟩/|1⟩ output of the qubit and encode it in the bit c[0]
qc.measure( q[0], c[0] )
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = execute(qc,backend,shots=1,memory=True)
output = job.result().get_memory()[0]
return output
def XOR(input1,input2):
q = QuantumRegister(2) # a qubit in which to encode the inout
c = ClassicalRegister(1) # a bit to store the output
qc = QuantumCircuit(q, c) # this is where the quantum program goes
if input1=='1':
qc.x( q[0] )
if input2=='1':
qc.x( q[1] )
qc.cx(q[0],q[1]) # just needs a cnot
qc.measure(q[1],c[0]) # output from qubit 1 is measured
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = execute(qc,backend,shots=1,memory=True)
output = job.result().get_memory()[0]
return output
def AND(input1,input2):
q = QuantumRegister(3) # a qubit in which to encode the inout
c = ClassicalRegister(1) # a bit to store the output
qc = QuantumCircuit(q, c) # this is where the quantum program goes
if input1=='1':
qc.x( q[0] )
if input2=='1':
qc.x( q[1] )
qc.ccx(q[0],q[1],q[2]) # just needs a ccx controlled on qubits 0 and 1 and targeted on 2
qc.measure(q[2],c[0]) # output from qubit 2 is measured
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = execute(qc,backend,shots=1,memory=True)
output = job.result().get_memory()[0]
return output
def NAND(input1,input2):
q = QuantumRegister(3) # a qubit in which to encode the inout
c = ClassicalRegister(1) # a bit to store the output
qc = QuantumCircuit(q, c) # this is where the quantum program goes
if input1=='1':
qc.x( q[0] )
if input2=='1':
qc.x( q[1] )
# can be done with an AND followed by a NOT
qc.ccx(q[0],q[1],q[2]) # the AND just needs a ccx controlled on qubits 0 and 1 and targeted on 2
qc.x(q[2]) # the NOT is done to the qubit containing the output
qc.measure(q[2],c[0]) # output from qubit 2 is measured
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = execute(qc,backend,shots=1,memory=True)
output = job.result().get_memory()[0]
return output
def OR(input1,input2):
q = QuantumRegister(3) # a qubit in which to encode the inout
c = ClassicalRegister(1) # a bit to store the output
qc = QuantumCircuit(q, c) # this is where the quantum program goes
if input1=='1':
qc.x( q[0] )
if input2=='1':
qc.x( q[1] )
# can be done with NOTs on the inputs and output of an AND
qc.x(q[0])
qc.x(q[1])
qc.ccx(q[0],q[1],q[2]) # the AND just needs a ccx controlled on qubits 0 and 1 and targeted on 2
qc.x(q[2]) # the NOT is done to the qubit containing the output
qc.measure(q[2],c[0]) # output from qubit 2 is measured
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = execute(qc,backend,shots=1,memory=True)
output = job.result().get_memory()[0]
return output
print('\nResults for the NOT gate')
for input in ['0','1']:
print(' NOT with input',input,'gives output',NOT(input))
print('\nResults for the XOR gate')
for input1 in ['0','1']:
for input2 in ['0','1']:
print(' NOT with inputs',input1,input2,'gives output',XOR(input1,input2))
print('\nResults for the AND gate')
for input1 in ['0','1']:
for input2 in ['0','1']:
print(' NOT with inputs',input1,input2,'gives output',AND(input1,input2))
print('\nResults for the NAND gate')
for input1 in ['0','1']:
for input2 in ['0','1']:
print(' NOT with inputs',input1,input2,'gives output',NAND(input1,input2))
print('\nResults for the OR gate')
for input1 in ['0','1']:
for input2 in ['0','1']:
print(' NOT with inputs',input1,input2,'gives output',OR(input1,input2))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.timeline import draw, IQXDebugging
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial')
draw(qc, style=IQXDebugging())
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Tests for Layer1Q implementation.
"""
import unittest
from random import randint
import test.python.transpiler.aqc.fast_gradient.utils_for_testing as tut
import numpy as np
import qiskit.transpiler.synthesis.aqc.fast_gradient.layer as lr
from qiskit.transpiler.synthesis.aqc.fast_gradient.pmatrix import PMatrix
from qiskit.test import QiskitTestCase
class TestLayer1q(QiskitTestCase):
"""
Tests for Layer1Q class.
"""
max_num_qubits = 5 # maximum number of qubits in tests
num_repeats = 50 # number of repetitions in tests
def setUp(self):
super().setUp()
np.random.seed(0x0696969)
def test_layer1q_matrix(self):
"""
Tests: (1) the correctness of Layer2Q matrix construction;
(2) matrix multiplication interleaved with permutations.
"""
mat_kind = "complex"
eps = 100.0 * np.finfo(float).eps
max_rel_err = 0.0
for n in range(2, self.max_num_qubits + 1):
dim = 2**n
iden = tut.eye_int(n)
for k in range(n):
m_mat = tut.rand_matrix(dim=dim, kind=mat_kind)
t_mat, g_mat = tut.make_test_matrices2x2(n=n, k=k, kind=mat_kind)
lmat = lr.Layer1Q(num_qubits=n, k=k, g2x2=g_mat)
g2, perm, inv_perm = lmat.get_attr()
self.assertTrue(m_mat.dtype == t_mat.dtype == g_mat.dtype == g2.dtype)
self.assertTrue(np.all(g_mat == g2))
self.assertTrue(np.all(iden[perm].T == iden[inv_perm]))
g_mat = np.kron(tut.eye_int(n - 1), g_mat)
# T == P^t @ G @ P.
err = tut.relative_error(t_mat, iden[perm].T @ g_mat @ iden[perm])
self.assertLess(err, eps, "err = {:0.16f}".format(err))
max_rel_err = max(max_rel_err, err)
# Multiplication by permutation matrix of the left can be
# replaced by row permutations.
tm = t_mat @ m_mat
err1 = tut.relative_error(iden[perm].T @ g_mat @ m_mat[perm], tm)
err2 = tut.relative_error((g_mat @ m_mat[perm])[inv_perm], tm)
# Multiplication by permutation matrix of the right can be
# replaced by column permutations.
mt = m_mat @ t_mat
err3 = tut.relative_error(m_mat @ iden[perm].T @ g_mat @ iden[perm], mt)
err4 = tut.relative_error((m_mat[:, perm] @ g_mat)[:, inv_perm], mt)
self.assertTrue(
err1 < eps and err2 < eps and err3 < eps and err4 < eps,
"err1 = {:f}, err2 = {:f}, "
"err3 = {:f}, err4 = {:f}".format(err1, err2, err3, err4),
)
max_rel_err = max(max_rel_err, err1, err2, err3, err4)
def test_pmatrix_class(self):
"""
Test the class PMatrix.
"""
_eps = 100.0 * np.finfo(float).eps
mat_kind = "complex"
max_rel_err = 0.0
for n in range(2, self.max_num_qubits + 1):
dim = 2**n
tmp1 = np.ndarray((dim, dim), dtype=np.cfloat)
tmp2 = tmp1.copy()
for _ in range(self.num_repeats):
k0 = randint(0, n - 1)
k1 = randint(0, n - 1)
k2 = randint(0, n - 1)
k3 = randint(0, n - 1)
k4 = randint(0, n - 1)
t0, g0 = tut.make_test_matrices2x2(n=n, k=k0, kind=mat_kind)
t1, g1 = tut.make_test_matrices2x2(n=n, k=k1, kind=mat_kind)
t2, g2 = tut.make_test_matrices2x2(n=n, k=k2, kind=mat_kind)
t3, g3 = tut.make_test_matrices2x2(n=n, k=k3, kind=mat_kind)
t4, g4 = tut.make_test_matrices2x2(n=n, k=k4, kind=mat_kind)
c0 = lr.Layer1Q(num_qubits=n, k=k0, g2x2=g0)
c1 = lr.Layer1Q(num_qubits=n, k=k1, g2x2=g1)
c2 = lr.Layer1Q(num_qubits=n, k=k2, g2x2=g2)
c3 = lr.Layer1Q(num_qubits=n, k=k3, g2x2=g3)
c4 = lr.Layer1Q(num_qubits=n, k=k4, g2x2=g4)
m_mat = tut.rand_matrix(dim=dim, kind=mat_kind)
ttmtt = t0 @ t1 @ m_mat @ np.conj(t2).T @ np.conj(t3).T
pmat = PMatrix(n)
pmat.set_matrix(m_mat)
pmat.mul_left_q1(layer=c1, temp_mat=tmp1)
pmat.mul_left_q1(layer=c0, temp_mat=tmp1)
pmat.mul_right_q1(layer=c2, temp_mat=tmp1, dagger=True)
pmat.mul_right_q1(layer=c3, temp_mat=tmp1, dagger=True)
alt_ttmtt = pmat.finalize(temp_mat=tmp1)
err1 = tut.relative_error(alt_ttmtt, ttmtt)
self.assertLess(err1, _eps, "relative error: {:f}".format(err1))
prod = np.cfloat(np.trace(ttmtt @ t4))
alt_prod = pmat.product_q1(layer=c4, tmp1=tmp1, tmp2=tmp2)
err2 = abs(alt_prod - prod) / abs(prod)
self.assertLess(err2, _eps, "relative error: {:f}".format(err2))
max_rel_err = max(max_rel_err, err1, err2)
if __name__ == "__main__":
unittest.main()
|
https://github.com/Spintronic6889/Introduction-of-Quantum-walk-its-application-on-search-and-decision-making
|
Spintronic6889
|
!python --version
!pip install qiskit
!pip install pylatexenc
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.visualization import plot_histogram
import matplotlib.pyplot as plt
from qiskit.visualization import plot_state_city
%matplotlib inline
import matplotlib as mpl
from random import randrange
import numpy as np
import networkx as nx
import random
import math
from qiskit.tools.monitor import job_monitor
from random import randrange
pose=[]
for i in range(400):
pose.append([])
#print(pose)
#pose[-1]=1
#print(pose[-1])
pose[0]=200
for k in range(200):
rand = randrange(0,2)
if rand==0:
#print(rand)
pose[k+1]=pose[k]+1
if rand==1:
pose[k+1]=pose[k]-1
#print(pose)
yc=[]
for e in range(400):
yc.append([])
for q in range(400):
yc[q]=0
for h in range(400):
if pose[h]==q:
yc[q]=yc[q]+1
#print((yc))
#print(len(yc))
xc = np.arange(0, 400, 1)
plt.plot(yc)
plt.xlim(150, 250)
class quantom_walk:
def __init__(self):
self.__n=2
self.__steps=1
self.__theta=0
self.__phi=0
self.__qtype=1
self.__shot=5000
def main_qw(self,n,steps,qtype,theta,phi):
self.__qpos = QuantumRegister(n,'qpos')
self.__qcoin = QuantumRegister(1,'qcoin')
self.__cpos = ClassicalRegister(n,'cr')
self.__QC = QuantumCircuit(self.__qpos, self.__qcoin)
if qtype==2: self.__QC.x(self.__qcoin[0])
if qtype==3: self.__QC.u(theta, phi, 0, self.__qcoin[0])
for i in range(steps):
self.__QC.h(self.__qcoin[0])
self.__QC.barrier()
for i in range(n):
self.__QC.mct([self.__qcoin[0]]+self.__qpos[i+1:], self.__qpos[i], None, mode='noancilla')
self.__QC.barrier()
self.__QC.x(self.__qcoin[0])
for i in range(n):
if i+1 < n: self.__QC.x(self.__qpos[i+1:])
self.__QC.mct([self.__qcoin[0]]+self.__qpos[i+1:], self.__qpos[i], None, mode='noancilla')
if i+1 < n: self.__QC.x(self.__qpos[i+1:])
self.__QC.barrier()
a=n/2
p=math.floor(a)
for k in range(n):
if(k<p):
self.__QC.swap(self.__qpos[n-1-k],self.__qpos[k])
def displayh(self):
display(self.__QC.draw(output="mpl"))
def histagramh(self,shot):
self.__QC.measure_all()
job = execute(self.__QC,Aer.get_backend('aer_simulator'),shots=5000)
counts = job.result().get_counts(self.__QC)
return counts
def spacevectorh(self):
backend = Aer.get_backend('statevector_simulator')
job = execute(self.__QC, backend)
result = job.result()
outputstate = result.get_statevector(self.__QC, decimals=3)
print(outputstate)
def plotcityh(self):
backend = Aer.get_backend('statevector_simulator')
job = execute(self.__QC, backend)
result = job.result()
outputstate = result.get_statevector(self.__QC, decimals=3)
from qiskit.visualization import plot_state_city
plot_state_city(outputstate)
return outputstate
def unitaryh(self):
backend = Aer.get_backend('unitary_simulator')
job = execute(self.__QC, backend)
result = job.result()
yy=result.get_unitary(self.__QC, decimals=3)
print(yy)
def IBMQh(self):
from qiskit import IBMQ
IBMQ.save_account('d1441affe8622903745ae099f50bce72c21036f85b14600d18195c977b9efcdee621dd4a981b92d8028c03c4dc1860c82d70f501d345023471402f4f8dad0181',overwrite=True)
provider = IBMQ.load_account()
device = provider.get_backend('ibmq_quito') #we use ibmq_16_melbourne quantum device
job = execute(self.__QC, backend = device) #we pass our circuit and backend as usual
from qiskit.tools.monitor import job_monitor
job_monitor(job) #to see our status in queue
result = job.result()
counts= result.get_counts(self.__QC)
return counts
def instructionset(self):
print(self.__QC.qasm())
qw = quantom_walk()
qw.main_qw(4,4,1,1.5,4)
#qw.instructionset()
#qw.displayh()
#plot_histogram(qw.histagramh(3000), figsize=(20, 5), color=None, number_to_keep=None, sort='asc', target_string=None, legend=None, bar_labels=True, title=None, ax=None)
#qw.histagramh(3000)
#qw.spacevectorh()
#qw.unitaryh()
#qw.plotcityh()
#plot_state_city(qw.plotcityh(), figsize=(20, 10))
#plot_histogram(qw.IBMQh(), figsize=(5, 2), color=None, number_to_keep=None, sort='asc', target_string=None, legend=None, bar_labels=True, title=None, ax=None, filename=None)
#qw.IBMQh()
qw = quantom_walk()
qw.main_qw(2,2,3,1.5,1.5)
qw.displayh()
qw.main_qw(6,25,1,1.5,4)
plot_histogram(qw.histagramh(3000), figsize=(20, 5), color=None, number_to_keep=None, sort='asc', target_string=None, legend=None, bar_labels=True, title=None, ax=None)
qw.main_qw(3,4,1,1.5,4)
qw.spacevectorh()
qw.main_qw(3,15,1,1.5,4)
plot_state_city(qw.plotcityh(), figsize=(20, 10))
qw.main_qw(2,3,1,1.5,4)
qw.unitaryh()
qw.main_qw(3,2,1,1.5,4)
qw.instructionset()
qw.main_qw(2,1,1,1.5,4)
plot_histogram(qw.IBMQh(), figsize=(5, 2), color=None, number_to_keep=None, sort='asc', target_string=None, legend=None, bar_labels=True, title=None, ax=None, filename=None)
#hadamrad...qtype=1
qw = quantom_walk()
qw.main_qw(3,32,1,0,0)
plot_histogram(qw.histagramh(3000), figsize=(20, 5), color=None, number_to_keep=None, sort='asc', target_string=None, legend=None, bar_labels=True, title=None, ax=None)
#optimized ugate applied...qtype=3
qw = quantom_walk()
qw.main_qw(3,32,3,1.57,1.57)
plot_histogram(qw.histagramh(3000), figsize=(20, 5), color=None, number_to_keep=None, sort='asc', target_string=None, legend=None, bar_labels=True, title=None, ax=None)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.