repo
stringclasses 900
values | file
stringclasses 754
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/Pitt-JonesLab/clonk_transpilation
|
Pitt-JonesLab
|
import sys
sys.path.append("..")
# the following is from Qiskits two_qubit_decomp, (doesn't work as import since need to adjust parameters and return vals)
import cmath
from qiskit.quantum_info.synthesis.two_qubit_decompose import *
import scipy.linalg as la
_ipx = np.array([[0, 1j], [1j, 0]], dtype=complex)
_ipy = np.array([[0, 1], [-1, 0]], dtype=complex)
_ipz = np.array([[1j, 0], [0, -1j]], dtype=complex)
_id = np.array([[1, 0], [0, 1]], dtype=complex)
def KAKDecomp(unitary_matrix, *, fidelity=(1.0 - 1.0e-9)):
"""Perform the Weyl chamber decomposition, and optionally choose a specialized subclass.
The flip into the Weyl Chamber is described in B. Kraus and J. I. Cirac, Phys. Rev. A 63,
062309 (2001).
FIXME: There's a cleaner-seeming method based on choosing branch cuts carefully, in Andrew
M. Childs, Henry L. Haselgrove, and Michael A. Nielsen, Phys. Rev. A 68, 052311, but I
wasn't able to get that to work.
The overall decomposition scheme is taken from Drury and Love, arXiv:0806.4015 [quant-ph].
"""
pi = np.pi
pi2 = np.pi / 2
pi4 = np.pi / 4
# Make U be in SU(4)
U = np.array(unitary_matrix, dtype=complex, copy=True)
detU = la.det(U)
U *= detU ** (-0.25)
global_phase = cmath.phase(detU) / 4
Up = transform_to_magic_basis(U, reverse=True)
M2 = Up.T.dot(Up)
# M2 is a symmetric complex matrix. We need to decompose it as M2 = P D P^T where
# P ∈ SO(4), D is diagonal with unit-magnitude elements.
#
# We can't use raw `eig` directly because it isn't guaranteed to give us real or othogonal
# eigenvectors. Instead, since `M2` is complex-symmetric,
# M2 = A + iB
# for real-symmetric `A` and `B`, and as
# M2^+ @ M2 = A^2 + B^2 + i [A, B] = 1
# we must have `A` and `B` commute, and consequently they are simultaneously diagonalizable.
# Mixing them together _should_ account for any degeneracy problems, but it's not
# guaranteed, so we repeat it a little bit. The fixed seed is to make failures
# deterministic; the value is not important.
state = np.random.default_rng(2020)
for _ in range(100): # FIXME: this randomized algorithm is horrendous
M2real = state.normal() * M2.real + state.normal() * M2.imag
_, P = np.linalg.eigh(M2real)
D = P.T.dot(M2).dot(P).diagonal()
if np.allclose(P.dot(np.diag(D)).dot(P.T), M2, rtol=0, atol=1.0e-13):
break
else:
raise ValueError
d = -np.angle(D) / 2
d[3] = -d[0] - d[1] - d[2]
cs = np.mod((d[:3] + d[3]) / 2, 2 * np.pi)
# Reorder the eigenvalues to get in the Weyl chamber
cstemp = np.mod(cs, pi2)
np.minimum(cstemp, pi2 - cstemp, cstemp)
order = np.argsort(cstemp)[[1, 2, 0]]
cs = cs[order]
d[:3] = d[order]
P[:, :3] = P[:, order]
# Fix the sign of P to be in SO(4)
if np.real(la.det(P)) < 0:
P[:, -1] = -P[:, -1]
# Find K1, K2 so that U = K1.A.K2, with K being product of single-qubit unitaries
K1 = transform_to_magic_basis(Up @ P @ np.diag(np.exp(1j * d)))
K2 = transform_to_magic_basis(P.T)
K1l, K1r, phase_l = decompose_two_qubit_product_gate(K1)
K2l, K2r, phase_r = decompose_two_qubit_product_gate(K2)
global_phase += phase_l + phase_r
K1l = K1l.copy()
# Flip into Weyl chamber
if cs[0] > pi2:
cs[0] -= 3 * pi2
K1l = K1l.dot(_ipy)
K1r = K1r.dot(_ipy)
global_phase += pi2
if cs[1] > pi2:
cs[1] -= 3 * pi2
K1l = K1l.dot(_ipx)
K1r = K1r.dot(_ipx)
global_phase += pi2
conjs = 0
if cs[0] > pi4:
cs[0] = pi2 - cs[0]
K1l = K1l.dot(_ipy)
K2r = _ipy.dot(K2r)
conjs += 1
global_phase -= pi2
if cs[1] > pi4:
cs[1] = pi2 - cs[1]
K1l = K1l.dot(_ipx)
K2r = _ipx.dot(K2r)
conjs += 1
global_phase += pi2
if conjs == 1:
global_phase -= pi
if cs[2] > pi2:
cs[2] -= 3 * pi2
K1l = K1l.dot(_ipz)
K1r = K1r.dot(_ipz)
global_phase += pi2
if conjs == 1:
global_phase -= pi
if conjs == 1:
cs[2] = pi2 - cs[2]
K1l = K1l.dot(_ipz)
K2r = _ipz.dot(K2r)
global_phase += pi2
if cs[2] > pi4:
cs[2] -= pi2
K1l = K1l.dot(_ipz)
K1r = K1r.dot(_ipz)
global_phase -= pi2
a, b, c = cs[1], cs[0], cs[2]
return global_phase, (a, b, c), K1l, K1r, K2l, K2r
from qiskit.circuit import Parameter
class ParamIter:
def __iter__(self):
self.index = 0
return self
def __next__(self):
x = self.index
self.index += 1
return Parameter(f"p{x}")
# print(next(myiter))
# print(next(myiter))
from clonk.utils.riswap_gates.riswap import RiSwapGate
"""
Efficient compiler consturction of parameterized circuits
https://qiskit.org/documentation/tutorials/circuits_advanced/01_advanced_circuits.html
"""
def template_circuit(param_list, base=None):
myiter = iter(ParamIter())
if base is None:
qc = QuantumCircuit(2)
qc.u(*[next(myiter) for _ in range(3)], 0)
qc.u(*[next(myiter) for _ in range(3)], 1)
else:
qc = base.copy()
for param in param_list:
qc.append(RiSwapGate(1 / param), [0, 1])
qc.u(*[next(myiter) for _ in range(3)], 0)
qc.u(*[next(myiter) for _ in range(3)], 1)
return qc
qc = template_circuit([2])
qc.draw()
from qiskit.quantum_info import random_unitary, Operator
from qiskit import QuantumCircuit
target_qc = QuantumCircuit(2)
target_qc.append(random_unitary(dims=(2, 2)), [0, 1])
global_phase, (a, b, c), K1l, K1r, K2l, K2r = KAKDecomp(Operator(target_qc).data)
target_coordinates = (a, b, c)
print(target_coordinates)
def unitary_distance_function(A, B):
# return (1 - np.abs(np.sum(np.multiply(B,np.conj(np.transpose(A))))) / 4)
# return (1 - (np.abs(np.sum(np.multiply(B,np.conj(A)))))**2+4 / 20) # quantum volume paper
return 1 - np.abs(np.sum(np.multiply(B, np.conj(A)))) / 4
%matplotlib inline
from scipy.optimize import minimize
def sample(param_list, N=1000):
#
iter = []
current_best = []
nuop_distance = []
#
minimum_qc = None
min_distance = None
modified_template = None
for template_index in range(0, len(param_list)):
modified_params = param_list[: 1 + template_index]
template_qc = template_circuit(modified_params, base=modified_template)
initial_guess = np.random.random(len(template_qc.parameters)) * 2 * np.pi
#
qc = template_circuit(modified_params, base=modified_template)
def min_fun(x):
temp_qc = qc.assign_parameters(
{parameter: i for parameter, i in zip(qc.parameters, x)}
)
_, (a, b, c), _, _, _, _ = KAKDecomp(Operator(temp_qc).data)
temp_coordinates = (a, b, c)
return np.linalg.norm(
np.array(target_coordinates) - np.array(temp_coordinates)
)
min_result = minimize(fun=min_fun, x0=initial_guess)
# #
# for _ in range(N):
# qc = template_circuit(modified_params, base=modified_template)
# parameters = qc.parameters
# temp_qc = qc.assign_parameters({parameter:np.random.random()*2*np.pi for parameter in parameters})
# global_phase, (a, b, c), K1l, K1r, K2l, K2r = KAKDecomp(Operator(temp_qc).data)
# temp_coordinates = (a,b,c)
# temp_dist = np.linalg.norm(np.array(target_coordinates)-np.array(temp_coordinates))
# if min_distance is None or temp_dist < min_distance:
# minimum_qc = temp_qc
# min_distance = temp_dist
# #
# current_best.append(min_distance)
# nuop_distance.append(unitary_distance_function(Operator(minimum_qc).data, Operator(target_qc).data))
# #
# modified_template = template_qc.assign_parameters({parameter:i for parameter,i in zip(template_qc.parameters,min_result.x)})
min_distance = min_result.fun
print(min_distance)
modified_template = template_qc.assign_parameters(
{parameter: i for parameter, i in zip(template_qc.parameters, min_result.x)}
)
# import matplotlib.pyplot as plt
# plt.plot(range(len(current_best)), current_best, label="coords")
# plt.plot(range(len(current_best)), nuop_distance, label="nuop")
# plt.yscale('log')
return modified_template, min_result.fun
minimum_qc, min_distance = sample([2, 4, 8])
print(min_distance)
minimum_qc.draw(output="mpl")
%matplotlib inline
from scipy.optimize import minimize
def sample(param_list, N=1000):
#
iter = []
current_best = []
nuop_distance = []
#
minimum_qc = None
min_distance = None
modified_template = None
for template_index in range(0, len(param_list)):
modified_params = param_list[template_index : 1 + template_index]
template_qc = template_circuit(modified_params, base=modified_template)
initial_guess = np.random.random(len(template_qc.parameters)) * 2 * np.pi
#
qc = template_circuit(modified_params, base=modified_template)
def min_fun(x):
temp_qc = qc.assign_parameters(
{parameter: i for parameter, i in zip(qc.parameters, x)}
)
_, (a, b, c), _, _, _, _ = KAKDecomp(Operator(temp_qc).data)
temp_coordinates = (a, b, c)
return np.linalg.norm(
np.array(target_coordinates) - np.array(temp_coordinates)
)
min_result = minimize(fun=min_fun, x0=initial_guess)
# #
# for _ in range(N):
# qc = template_circuit(modified_params, base=modified_template)
# parameters = qc.parameters
# temp_qc = qc.assign_parameters({parameter:np.random.random()*2*np.pi for parameter in parameters})
# global_phase, (a, b, c), K1l, K1r, K2l, K2r = KAKDecomp(Operator(temp_qc).data)
# temp_coordinates = (a,b,c)
# temp_dist = np.linalg.norm(np.array(target_coordinates)-np.array(temp_coordinates))
# if min_distance is None or temp_dist < min_distance:
# minimum_qc = temp_qc
# min_distance = temp_dist
# #
# current_best.append(min_distance)
# nuop_distance.append(unitary_distance_function(Operator(minimum_qc).data, Operator(target_qc).data))
# #
modified_template = template_qc.assign_parameters(
{parameter: i for parameter, i in zip(template_qc.parameters, min_result.x)}
)
min_distance = min_result.fun
print(min_distance)
modified_template = template_qc.assign_parameters(
{parameter: i for parameter, i in zip(template_qc.parameters, min_result.x)}
)
# import matplotlib.pyplot as plt
# plt.plot(range(len(current_best)), current_best, label="coords")
# plt.plot(range(len(current_best)), nuop_distance, label="nuop")
# plt.yscale('log')
return modified_template, min_result.fun
minimum_qc, min_distance = sample([2, 2, 2])
print(min_distance)
minimum_qc.draw(output="mpl")
def sample(param_list, N=1000):
# want to characterize the vectors from 2,2, template
qc = template_circuit(param_list[:1])
temp_qc = qc.assign_parameters(
{parameter: np.random.random() * 2 * np.pi for parameter in qc.parameters}
)
global_phase, (a, b, c), K1l, K1r, K2l, K2r = KAKDecomp(Operator(temp_qc).data)
starting_coordinates = (a, b, c)
list_coordinates = []
for _ in range(N):
qc = template_circuit(param_list)
parameters = qc.parameters
temp_qc = qc.assign_parameters(
{parameter: np.random.random() * 2 * np.pi for parameter in parameters}
)
global_phase, (a, b, c), K1l, K1r, K2l, K2r = KAKDecomp(Operator(temp_qc).data)
temp_coordinates = (a, b, c)
list_coordinates.append(temp_coordinates)
c1, c2, c3 = weylchamber.c1c2c3(gate)
w.add_point(c1, c2, c3)
temp_vector = np.array(temp_coordinates) - np.array(starting_coordinates)
# print(temp_vector)
return list_coordinates
w = WeylChamber()
list_coordinates = sample(param_list=[3, 2])
w.plot()
# print(list_coordinates)
import scipy.spatial as ss
import numpy as np
hull = ss.ConvexHull(list_coordinates)
print("volume inside points is: ", hull.volume)
import numpy as np
import qutip
import matplotlib
import matplotlib.pylab as plt
import weylchamber
from weylchamber.visualize import WeylChamber
WeylChamber().plot()
IDENTITY = qutip.identity([2, 2])
CNOT = qutip.qip.operations.cnot()
CPHASE = qutip.qip.operations.cphase(np.pi)
BGATE = qutip.qip.operations.berkeley()
iSWAP = qutip.qip.operations.iswap()
sqrtISWAP = qutip.qip.operations.sqrtiswap()
sqrtSWAP = qutip.qip.operations.sqrtswap()
MGATE = weylchamber.canonical_gate(3 / 4, 1 / 4, 0)
w = WeylChamber()
list_of_gates = [
("Identity", IDENTITY),
("CNOT", CNOT),
("CPHASE", CPHASE),
("BGATE", BGATE),
("iSWAP", iSWAP),
("sqrtISWAP", sqrtISWAP),
("sqrtSWAP", sqrtSWAP),
("MGATE", MGATE),
]
print("Weyl Chamber Coordinates")
print("----------------------------------")
for name, gate in list_of_gates:
c1, c2, c3 = weylchamber.c1c2c3(gate)
print("%10s: \t%.2fπ %.2fπ %.2fπ" % (name, c1, c2, c3))
w.add_point(c1, c2, c3)
w.plot()
w.scatter(
*zip(
*[
weylchamber.c1c2c3(qutip.qip.operations.cphase(phase))
for phase in np.linspace(0, 2 * np.pi, 20)
]
)
)
w.plot()
print("Local Invariants")
print("----------------------------------")
for name, gate in list_of_gates:
g1, g2, g3 = weylchamber.g1g2g3(gate)
print("%10s: \t%5.2f %5.2f %5.2f" % (name, g1, g2, g3))
|
https://github.com/Pitt-JonesLab/clonk_transpilation
|
Pitt-JonesLab
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""A module for visualizing device coupling maps."""
import math
from typing import List
import numpy as np
from qiskit.exceptions import MissingOptionalLibraryError, QiskitError
from qiskit.providers.backend import BackendV2
from qiskit.tools.visualization import HAS_MATPLOTLIB, VisualizationError
from qiskit.visualization.utils import matplotlib_close_if_inline
def plot_gate_map(
backend,
figsize=None,
plot_directed=False,
label_qubits=True,
qubit_size=None,
line_width=4,
font_size=None,
qubit_color=None,
qubit_labels=None,
line_color=None,
font_color="w",
ax=None,
filename=None,
qubit_coordinates=None,
):
"""Plots the gate map of a device.
Args:
backend (BaseBackend): The backend instance that will be used to plot the device
gate map.
figsize (tuple): Output figure size (wxh) in inches.
plot_directed (bool): Plot directed coupling map.
label_qubits (bool): Label the qubits.
qubit_size (float): Size of qubit marker.
line_width (float): Width of lines.
font_size (int): Font size of qubit labels.
qubit_color (list): A list of colors for the qubits
qubit_labels (list): A list of qubit labels
line_color (list): A list of colors for each line from coupling_map.
font_color (str): The font color for the qubit labels.
ax (Axes): A Matplotlib axes instance.
filename (str): file path to save image to.
Returns:
Figure: A Matplotlib figure instance.
Raises:
QiskitError: if tried to pass a simulator, or if the backend is None,
but one of num_qubits, mpl_data, or cmap is None.
MissingOptionalLibraryError: if matplotlib not installed.
Example:
.. jupyter-execute::
:hide-code:
:hide-output:
from qiskit.test.ibmq_mock import mock_get_backend
mock_get_backend('FakeVigo')
.. jupyter-execute::
from qiskit import QuantumCircuit, execute, IBMQ
from qiskit.visualization import plot_gate_map
%matplotlib inline
provider = IBMQ.load_account()
accountProvider = IBMQ.get_provider(hub='ibm-q')
backend = accountProvider.get_backend('ibmq_vigo')
plot_gate_map(backend)
"""
if not HAS_MATPLOTLIB:
raise MissingOptionalLibraryError(
libname="Matplotlib",
name="plot_gate_map",
pip_install="pip install matplotlib",
)
if isinstance(backend, BackendV2):
pass
elif backend.configuration().simulator:
raise QiskitError("Requires a device backend, not simulator.")
qubit_coordinates_map = {}
qubit_coordinates_map[1] = [[0, 0]]
qubit_coordinates_map[5] = [[1, 0], [0, 1], [1, 1], [1, 2], [2, 1]]
qubit_coordinates_map[7] = [[0, 0], [0, 1], [0, 2], [1, 1], [2, 0], [2, 1], [2, 2]]
qubit_coordinates_map[20] = [
[0, 0],
[0, 1],
[0, 2],
[0, 3],
[0, 4],
[1, 0],
[1, 1],
[1, 2],
[1, 3],
[1, 4],
[2, 0],
[2, 1],
[2, 2],
[2, 3],
[2, 4],
[3, 0],
[3, 1],
[3, 2],
[3, 3],
[3, 4],
]
qubit_coordinates_map[15] = [
[0, 0],
[0, 1],
[0, 2],
[0, 3],
[0, 4],
[0, 5],
[0, 6],
[1, 7],
[1, 6],
[1, 5],
[1, 4],
[1, 3],
[1, 2],
[1, 1],
[1, 0],
]
qubit_coordinates_map[16] = [
[1, 0],
[1, 1],
[2, 1],
[3, 1],
[1, 2],
[3, 2],
[0, 3],
[1, 3],
[3, 3],
[4, 3],
[1, 4],
[3, 4],
[1, 5],
[2, 5],
[3, 5],
[1, 6],
]
qubit_coordinates_map[27] = [
[1, 0],
[1, 1],
[2, 1],
[3, 1],
[1, 2],
[3, 2],
[0, 3],
[1, 3],
[3, 3],
[4, 3],
[1, 4],
[3, 4],
[1, 5],
[2, 5],
[3, 5],
[1, 6],
[3, 6],
[0, 7],
[1, 7],
[3, 7],
[4, 7],
[1, 8],
[3, 8],
[1, 9],
[2, 9],
[3, 9],
[3, 10],
]
qubit_coordinates_map[28] = [
[0, 2],
[0, 3],
[0, 4],
[0, 5],
[0, 6],
[1, 2],
[1, 6],
[2, 0],
[2, 1],
[2, 2],
[2, 3],
[2, 4],
[2, 5],
[2, 6],
[2, 7],
[2, 8],
[3, 0],
[3, 4],
[3, 8],
[4, 0],
[4, 1],
[4, 2],
[4, 3],
[4, 4],
[4, 5],
[4, 6],
[4, 7],
[4, 8],
]
qubit_coordinates_map[53] = [
[0, 2],
[0, 3],
[0, 4],
[0, 5],
[0, 6],
[1, 2],
[1, 6],
[2, 0],
[2, 1],
[2, 2],
[2, 3],
[2, 4],
[2, 5],
[2, 6],
[2, 7],
[2, 8],
[3, 0],
[3, 4],
[3, 8],
[4, 0],
[4, 1],
[4, 2],
[4, 3],
[4, 4],
[4, 5],
[4, 6],
[4, 7],
[4, 8],
[5, 2],
[5, 6],
[6, 0],
[6, 1],
[6, 2],
[6, 3],
[6, 4],
[6, 5],
[6, 6],
[6, 7],
[6, 8],
[7, 0],
[7, 4],
[7, 8],
[8, 0],
[8, 1],
[8, 2],
[8, 3],
[8, 4],
[8, 5],
[8, 6],
[8, 7],
[8, 8],
[9, 2],
[9, 6],
]
qubit_coordinates_map[65] = [
[0, 0],
[0, 1],
[0, 2],
[0, 3],
[0, 4],
[0, 5],
[0, 6],
[0, 7],
[0, 8],
[0, 9],
[1, 0],
[1, 4],
[1, 8],
[2, 0],
[2, 1],
[2, 2],
[2, 3],
[2, 4],
[2, 5],
[2, 6],
[2, 7],
[2, 8],
[2, 9],
[2, 10],
[3, 2],
[3, 6],
[3, 10],
[4, 0],
[4, 1],
[4, 2],
[4, 3],
[4, 4],
[4, 5],
[4, 6],
[4, 7],
[4, 8],
[4, 9],
[4, 10],
[5, 0],
[5, 4],
[5, 8],
[6, 0],
[6, 1],
[6, 2],
[6, 3],
[6, 4],
[6, 5],
[6, 6],
[6, 7],
[6, 8],
[6, 9],
[6, 10],
[7, 2],
[7, 6],
[7, 10],
[8, 1],
[8, 2],
[8, 3],
[8, 4],
[8, 5],
[8, 6],
[8, 7],
[8, 8],
[8, 9],
[8, 10],
]
if isinstance(backend, BackendV2):
num_qubits = backend.num_qubits
coupling_map = backend.plot_coupling_map
else:
config = backend.configuration()
num_qubits = config.n_qubits
coupling_map = config.coupling_map
# don't reference dictionary if provided as a parameter
if qubit_coordinates is None:
qubit_coordinates = qubit_coordinates_map.get(num_qubits)
# try to adjust num_qubits to match the next highest hardcoded grid size
if qubit_coordinates is None:
if any([num_qubits < key for key in qubit_coordinates_map.keys()]):
num_qubits_roundup = max(qubit_coordinates_map.keys())
for key in qubit_coordinates_map.keys():
if key < num_qubits_roundup and key > num_qubits:
num_qubits_roundup = key
qubit_coordinates = qubit_coordinates_map.get(num_qubits_roundup)
return plot_coupling_map(
num_qubits,
qubit_coordinates,
coupling_map,
figsize,
plot_directed,
label_qubits,
qubit_size,
line_width,
font_size,
qubit_color,
qubit_labels,
line_color,
font_color,
ax,
filename,
)
def plot_coupling_map(
num_qubits: int,
qubit_coordinates: List[List[int]],
coupling_map: List[List[int]],
figsize=None,
plot_directed=False,
label_qubits=True,
qubit_size=None,
line_width=4,
font_size=None,
qubit_color=None,
qubit_labels=None,
line_color=None,
font_color="w",
ax=None,
filename=None,
):
"""Plots an arbitrary coupling map of qubits (embedded in a plane).
Args:
num_qubits (int): The number of qubits defined and plotted.
qubit_coordinates (List[List[int]]): A list of two-element lists, with entries of each nested
list being the planar coordinates in a 0-based square grid where each qubit is located.
coupling_map (List[List[int]]): A list of two-element lists, with entries of each nested
list being the qubit numbers of the bonds to be plotted.
figsize (tuple): Output figure size (wxh) in inches.
plot_directed (bool): Plot directed coupling map.
label_qubits (bool): Label the qubits.
qubit_size (float): Size of qubit marker.
line_width (float): Width of lines.
font_size (int): Font size of qubit labels.
qubit_color (list): A list of colors for the qubits
qubit_labels (list): A list of qubit labels
line_color (list): A list of colors for each line from coupling_map.
font_color (str): The font color for the qubit labels.
ax (Axes): A Matplotlib axes instance.
filename (str): file path to save image to.
Returns:
Figure: A Matplotlib figure instance.
Raises:
MissingOptionalLibraryError: if matplotlib not installed.
QiskitError: If length of qubit labels does not match number of qubits.
Example:
.. jupyter-execute::
from qiskit.visualization import plot_coupling_map
%matplotlib inline
num_qubits = 8
coupling_map = [[0, 1], [1, 2], [2, 3], [3, 5], [4, 5], [5, 6], [2, 4], [6, 7]]
qubit_coordinates = [[0, 1], [1, 1], [1, 0], [1, 2], [2, 0], [2, 2], [2, 1], [3, 1]]
plot_coupling_map(num_qubits, coupling_map, qubit_coordinates)
"""
if not HAS_MATPLOTLIB:
raise MissingOptionalLibraryError(
libname="Matplotlib",
name="plot_coupling_map",
pip_install="pip install matplotlib",
)
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
input_axes = False
if ax:
input_axes = True
if font_size is None:
font_size = 12
if qubit_size is None:
qubit_size = 24
if num_qubits > 20:
qubit_size = 28
font_size = 10
if qubit_labels is None:
qubit_labels = list(range(num_qubits))
else:
if len(qubit_labels) != num_qubits:
raise QiskitError("Length of qubit labels does not equal number of qubits.")
if qubit_coordinates is not None:
grid_data = qubit_coordinates
else:
if not input_axes:
fig, ax = plt.subplots(figsize=(5, 5))
ax.axis("off")
if filename:
fig.savefig(filename)
return fig
x_max = max(d[1] for d in grid_data)
y_max = max(d[0] for d in grid_data)
max_dim = max(x_max, y_max)
if figsize is None:
if num_qubits == 1 or (x_max / max_dim > 0.33 and y_max / max_dim > 0.33):
figsize = (5, 5)
else:
figsize = (9, 3)
if ax is None:
fig, ax = plt.subplots(figsize=figsize)
ax.axis("off")
# set coloring
if qubit_color is None:
qubit_color = ["#648fff"] * num_qubits
if line_color is None:
line_color = ["#648fff"] * len(coupling_map) if coupling_map else []
# Add lines for couplings
if num_qubits != 1:
for ind, edge in enumerate(coupling_map):
is_symmetric = False
if edge[::-1] in coupling_map:
is_symmetric = True
y_start = grid_data[edge[0]][0]
x_start = grid_data[edge[0]][1]
y_end = grid_data[edge[1]][0]
x_end = grid_data[edge[1]][1]
if is_symmetric:
if y_start == y_end:
x_end = (x_end - x_start) / 2 + x_start
elif x_start == x_end:
y_end = (y_end - y_start) / 2 + y_start
else:
x_end = (x_end - x_start) / 2 + x_start
y_end = (y_end - y_start) / 2 + y_start
ax.add_artist(
plt.Line2D(
[x_start, x_end],
[-y_start, -y_end],
color=line_color[ind],
linewidth=line_width,
zorder=0,
)
)
if plot_directed:
dx = x_end - x_start
dy = y_end - y_start
if is_symmetric:
x_arrow = x_start + dx * 0.95
y_arrow = -y_start - dy * 0.95
dx_arrow = dx * 0.01
dy_arrow = -dy * 0.01
head_width = 0.15
else:
x_arrow = x_start + dx * 0.5
y_arrow = -y_start - dy * 0.5
dx_arrow = dx * 0.2
dy_arrow = -dy * 0.2
head_width = 0.2
ax.add_patch(
mpatches.FancyArrow(
x_arrow,
y_arrow,
dx_arrow,
dy_arrow,
head_width=head_width,
length_includes_head=True,
edgecolor=None,
linewidth=0,
facecolor=line_color[ind],
zorder=1,
)
)
# Add circles for qubits
for var, idx in enumerate(grid_data):
# add check if num_qubits had been rounded up
if var >= num_qubits:
break
_idx = [idx[1], -idx[0]]
ax.add_artist(
mpatches.Ellipse(
_idx,
qubit_size / 48,
qubit_size / 48, # This is here so that the changes
color=qubit_color[var],
zorder=1,
)
) # to how qubits are plotted does
if label_qubits: # not affect qubit size kwarg.
ax.text(
*_idx,
s=qubit_labels[var],
horizontalalignment="center",
verticalalignment="center",
color=font_color,
size=font_size,
weight="bold",
)
ax.set_xlim([-1, x_max + 1])
ax.set_ylim([-(y_max + 1), 1])
ax.set_aspect("equal")
if not input_axes:
matplotlib_close_if_inline(fig)
if filename:
fig.savefig(filename)
return fig
return None
def plot_circuit_layout(circuit, backend, view="virtual", qubit_coordinates=None):
"""Plot the layout of a circuit transpiled for a given target backend.
Args:
circuit (QuantumCircuit): Input quantum circuit.
backend (BaseBackend): Target backend.
view (str): Layout view: either 'virtual' or 'physical'.
Returns:
Figure: A matplotlib figure showing layout.
Raises:
QiskitError: Invalid view type given.
VisualizationError: Circuit has no layout attribute.
Example:
.. jupyter-execute::
:hide-code:
:hide-output:
from qiskit.test.ibmq_mock import mock_get_backend
mock_get_backend('FakeVigo')
.. jupyter-execute::
import numpy as np
from qiskit import QuantumCircuit, IBMQ, transpile
from qiskit.visualization import plot_histogram, plot_gate_map, plot_circuit_layout
from qiskit.tools.monitor import job_monitor
import matplotlib.pyplot as plt
%matplotlib inline
IBMQ.load_account()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
for idx in range(1,3):
ghz.cx(0,idx)
ghz.measure(range(3), range(3))
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_vigo')
new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3)
plot_circuit_layout(new_circ_lv3, backend)
"""
if circuit._layout is None:
raise QiskitError("Circuit has no layout. Perhaps it has not been transpiled.")
if isinstance(backend, BackendV2):
num_qubits = backend.num_qubits
else:
num_qubits = backend.configuration().n_qubits
qubits = []
qubit_labels = [None] * num_qubits
bit_locations = {
bit: {"register": register, "index": index}
for register in circuit._layout.get_registers()
for index, bit in enumerate(register)
}
for index, qubit in enumerate(circuit._layout.get_virtual_bits()):
if qubit not in bit_locations:
bit_locations[qubit] = {"register": None, "index": index}
if view == "virtual":
for key, val in circuit._layout.get_virtual_bits().items():
bit_register = bit_locations[key]["register"]
if bit_register is None or bit_register.name != "ancilla":
qubits.append(val)
qubit_labels[val] = bit_locations[key]["index"]
elif view == "physical":
for key, val in circuit._layout.get_physical_bits().items():
bit_register = bit_locations[val]["register"]
if bit_register is None or bit_register.name != "ancilla":
qubits.append(key)
qubit_labels[key] = key
else:
raise VisualizationError("Layout view must be 'virtual' or 'physical'.")
qcolors = ["#648fff"] * num_qubits
for k in qubits:
qcolors[k] = "k"
if isinstance(backend, BackendV2):
cmap = backend.plot_coupling_map
else:
cmap = backend.configuration().coupling_map
lcolors = ["#648fff"] * len(cmap)
for idx, edge in enumerate(cmap):
if edge[0] in qubits and edge[1] in qubits:
lcolors[idx] = "k"
fig = plot_gate_map(
backend,
qubit_color=qcolors,
qubit_labels=qubit_labels,
line_color=lcolors,
qubit_coordinates=qubit_coordinates,
)
return fig
def plot_error_map(backend, figsize=(12, 9), show_title=True):
"""Plots the error map of a given backend.
Args:
backend (IBMQBackend): Given backend.
figsize (tuple): Figure size in inches.
show_title (bool): Show the title or not.
Returns:
Figure: A matplotlib figure showing error map.
Raises:
VisualizationError: Input is not IBMQ backend.
VisualizationError: The backend does not provide gate errors for the 'sx' gate.
MissingOptionalLibraryError: If seaborn is not installed
Example:
.. jupyter-execute::
:hide-code:
:hide-output:
from qiskit.test.ibmq_mock import mock_get_backend
mock_get_backend('FakeVigo')
.. jupyter-execute::
from qiskit import QuantumCircuit, execute, IBMQ
from qiskit.visualization import plot_error_map
%matplotlib inline
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_vigo')
plot_error_map(backend)
"""
try:
import seaborn as sns
except ImportError as ex:
raise MissingOptionalLibraryError(
libname="seaborn",
name="plot_error_map",
pip_install="pip install seaborn",
) from ex
if not HAS_MATPLOTLIB:
raise MissingOptionalLibraryError(
libname="Matplotlib",
name="plot_error_map",
pip_install="pip install matplotlib",
)
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import gridspec, ticker
color_map = sns.cubehelix_palette(reverse=True, as_cmap=True)
props = backend.properties().to_dict()
config = backend.configuration().to_dict()
num_qubits = config["n_qubits"]
# sx error rates
single_gate_errors = [0] * num_qubits
for gate in props["gates"]:
if gate["gate"] == "sx":
_qubit = gate["qubits"][0]
for param in gate["parameters"]:
if param["name"] == "gate_error":
single_gate_errors[_qubit] = param["value"]
break
else:
raise VisualizationError(
f"Backend '{backend}' did not supply an error for the 'sx' gate."
)
# Convert to percent
single_gate_errors = 100 * np.asarray(single_gate_errors)
avg_1q_err = np.mean(single_gate_errors)
single_norm = matplotlib.colors.Normalize(
vmin=min(single_gate_errors), vmax=max(single_gate_errors)
)
q_colors = [color_map(single_norm(err)) for err in single_gate_errors]
cmap = config["coupling_map"]
directed = False
line_colors = []
if cmap:
directed = False
if num_qubits < 20:
for edge in cmap:
if [edge[1], edge[0]] not in cmap:
directed = True
break
cx_errors = []
for line in cmap:
for item in props["gates"]:
if item["qubits"] == line:
cx_errors.append(item["parameters"][0]["value"])
break
else:
continue
# Convert to percent
cx_errors = 100 * np.asarray(cx_errors)
avg_cx_err = np.mean(cx_errors)
cx_norm = matplotlib.colors.Normalize(vmin=min(cx_errors), vmax=max(cx_errors))
line_colors = [color_map(cx_norm(err)) for err in cx_errors]
# Measurement errors
read_err = []
for qubit in range(num_qubits):
for item in props["qubits"][qubit]:
if item["name"] == "readout_error":
read_err.append(item["value"])
read_err = 100 * np.asarray(read_err)
avg_read_err = np.mean(read_err)
max_read_err = np.max(read_err)
fig = plt.figure(figsize=figsize)
gridspec.GridSpec(nrows=2, ncols=3)
grid_spec = gridspec.GridSpec(
12,
12,
height_ratios=[1] * 11 + [0.5],
width_ratios=[2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2],
)
left_ax = plt.subplot(grid_spec[2:10, :1])
main_ax = plt.subplot(grid_spec[:11, 1:11])
right_ax = plt.subplot(grid_spec[2:10, 11:])
bleft_ax = plt.subplot(grid_spec[-1, :5])
if cmap:
bright_ax = plt.subplot(grid_spec[-1, 7:])
qubit_size = 28
if num_qubits <= 5:
qubit_size = 20
plot_gate_map(
backend,
qubit_color=q_colors,
line_color=line_colors,
qubit_size=qubit_size,
line_width=5,
plot_directed=directed,
ax=main_ax,
)
main_ax.axis("off")
main_ax.set_aspect(1)
if cmap:
single_cb = matplotlib.colorbar.ColorbarBase(
bleft_ax, cmap=color_map, norm=single_norm, orientation="horizontal"
)
tick_locator = ticker.MaxNLocator(nbins=5)
single_cb.locator = tick_locator
single_cb.update_ticks()
single_cb.update_ticks()
bleft_ax.set_title(f"H error rate (%) [Avg. = {round(avg_1q_err, 3)}]")
if cmap is None:
bleft_ax.axis("off")
bleft_ax.set_title(f"H error rate (%) = {round(avg_1q_err, 3)}")
if cmap:
cx_cb = matplotlib.colorbar.ColorbarBase(
bright_ax, cmap=color_map, norm=cx_norm, orientation="horizontal"
)
tick_locator = ticker.MaxNLocator(nbins=5)
cx_cb.locator = tick_locator
cx_cb.update_ticks()
bright_ax.set_title(f"CNOT error rate (%) [Avg. = {round(avg_cx_err, 3)}]")
if num_qubits < 10:
num_left = num_qubits
num_right = 0
else:
num_left = math.ceil(num_qubits / 2)
num_right = num_qubits - num_left
left_ax.barh(range(num_left), read_err[:num_left], align="center", color="#DDBBBA")
left_ax.axvline(avg_read_err, linestyle="--", color="#212121")
left_ax.set_yticks(range(num_left))
left_ax.set_xticks([0, round(avg_read_err, 2), round(max_read_err, 2)])
left_ax.set_yticklabels([str(kk) for kk in range(num_left)], fontsize=12)
left_ax.invert_yaxis()
left_ax.set_title("Readout Error (%)", fontsize=12)
for spine in left_ax.spines.values():
spine.set_visible(False)
if num_right:
right_ax.barh(
range(num_left, num_qubits),
read_err[num_left:],
align="center",
color="#DDBBBA",
)
right_ax.axvline(avg_read_err, linestyle="--", color="#212121")
right_ax.set_yticks(range(num_left, num_qubits))
right_ax.set_xticks([0, round(avg_read_err, 2), round(max_read_err, 2)])
right_ax.set_yticklabels(
[str(kk) for kk in range(num_left, num_qubits)], fontsize=12
)
right_ax.invert_yaxis()
right_ax.invert_xaxis()
right_ax.yaxis.set_label_position("right")
right_ax.yaxis.tick_right()
right_ax.set_title("Readout Error (%)", fontsize=12)
else:
right_ax.axis("off")
for spine in right_ax.spines.values():
spine.set_visible(False)
if show_title:
fig.suptitle(f"{backend.name()} Error Map", fontsize=24, y=0.9)
matplotlib_close_if_inline(fig)
return fig
|
https://github.com/Pitt-JonesLab/clonk_transpilation
|
Pitt-JonesLab
|
# from cirq import cphase
import numpy as np
import qiskit.circuit.library.standard_gates as g
import qiskit.circuit.quantumcircuit as qc
from qiskit.circuit.equivalence import EquivalenceLibrary
from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary
from qiskit.circuit.library.standard_gates.equivalence_library import (
StandardEquivalenceLibrary,
)
SessionEquivalenceLibrary = EquivalenceLibrary(base=StandardEquivalenceLibrary)
# https://github.com/Qiskit/qiskit-terra/blob/main/qiskit/circuit/library/standard_gates/equivalence_library.py
from qiskit.quantum_info.operators import Operator
circuit = qc.QuantumCircuit(2, name="rootswap")
cx = Operator(
[
[1, 0, 0, 0],
[0, 0.5 * (1 + 1j), 0.5 * (1 - 1j), 0],
[0, 0.5 * (1 - 1j), 0.5 * (1 + 1j), 0],
[0, 0, 0, 1],
]
)
circuit.unitary(cx, [0, 1])
rootSwap = circuit.to_gate()
# define rootiswap
circuit = qc.QuantumCircuit(2, name="rootiswap")
cx = Operator(
[
[1, 0, 0, 0],
[0, 1 / np.sqrt(2), 1j / np.sqrt(2), 0],
[0, 1j / np.sqrt(2), 1 / np.sqrt(2), 0],
[0, 0, 0, 1],
]
)
circuit.unitary(cx, [0, 1])
rootiSwap = circuit.to_gate()
def iswap(alpha):
return np.matrix(
[
[1, 0, 0, 0],
[0, np.cos(np.pi * alpha / 2), 1j * np.sin(np.pi * alpha / 2), 0],
[0, 1j * np.sin(np.pi * alpha / 2), np.cos(np.pi * alpha / 2), 0],
[0, 0, 0, 1],
]
)
# class rootiswap_gate(qe.UnitaryGate):
# def __init__(self):
# super().__init__(
# data=np.array(
# [
# [1, 0, 0, 0],
# [0, 1 / np.sqrt(2), 1j / np.sqrt(2), 0],
# [0, 1j / np.sqrt(2), 1 / np.sqrt(2), 0],
# [0, 0, 0, 1],
# ]
# ),
# label=r"rootiswap",
# )
# SWAP out of rootSWAP
_rootSwapEquiv = qc.QuantumCircuit(2)
_rootSwapEquiv.append(rootSwap, [0, 1])
_rootSwapEquiv.append(rootSwap, [0, 1])
SessionEquivalenceLibrary.add_equivalence(g.SwapGate(), _rootSwapEquiv)
# CX out of rootSWAP
_cxEquiv = qc.QuantumCircuit(2)
_cxEquiv.ry(np.pi / 2, 1)
_cxEquiv.append(rootSwap, [0, 1])
_cxEquiv.z(0)
_cxEquiv.append(rootSwap, [0, 1])
_cxEquiv.rz(-np.pi / 2, 0)
_cxEquiv.rz(-np.pi / 2, 1)
_cxEquiv.ry(-np.pi / 2, 1)
SessionEquivalenceLibrary.add_equivalence(g.CXGate(), _cxEquiv)
# rootSWAP out of CX
_rootSwapEquiv = qc.QuantumCircuit(2)
_rootSwapEquiv.cx(0, 1)
_rootSwapEquiv.h(0)
_rootSwapEquiv.rz(np.pi / 4, 0)
_rootSwapEquiv.rz(-np.pi / 4, 1)
_rootSwapEquiv.h(0)
_rootSwapEquiv.h(1)
_rootSwapEquiv.cx(0, 1)
_rootSwapEquiv.h(0)
_rootSwapEquiv.h(1)
_rootSwapEquiv.rz(-np.pi / 4, 0)
_rootSwapEquiv.h(0)
_rootSwapEquiv.cx(0, 1)
_rootSwapEquiv.rz(-np.pi / 2, 0)
_rootSwapEquiv.rz(np.pi / 2, 1)
SessionEquivalenceLibrary.add_equivalence(rootSwap, _rootSwapEquiv)
# add decomp rule for CZ out of Cphase
_czEquiv = qc.QuantumCircuit(2)
_czEquiv.append(g.CPhaseGate(np.pi), [0, 1])
SessionEquivalenceLibrary.add_equivalence(g.CZGate(), _czEquiv)
|
https://github.com/Pitt-JonesLab/clonk_transpilation
|
Pitt-JonesLab
|
import sys
sys.path.append("../..")
from qiskit.quantum_info.random import random_unitary, random_clifford
from qiskit import QuantumCircuit
from clonk.utils.transpiler_passes.pass_manager_v2 import level_0_pass_manager
from clonk.backend_utils import FakeAllToAll
from clonk.utils.riswap_gates.riswap import RiSwapGate
from clonk.utils.transpiler_passes.weyl_decompose import RootiSwapWeylDecomposition
from qiskit.transpiler.passes import CountOps
from qiskit.transpiler import PassManager
from qiskit.circuit.library import CXGate
N = 2000
basis_gate = RiSwapGate(0.5)
pm0 = PassManager()
pm0.append(RootiSwapWeylDecomposition(basis_gate=basis_gate))
pm0.append(CountOps())
res = 0
for _ in range(N):
qc = QuantumCircuit(2)
qc.append(random_clifford(2), [0, 1])
# random_unitary(dim=4)
pm0.run(qc)
res += pm0.property_set["count_ops"]["riswap"]
print(res / N)
N = 2000
basis_gate = CXGate()
pm0 = PassManager()
pm0.append(RootiSwapWeylDecomposition(basis_gate=basis_gate))
pm0.append(CountOps())
res = 0
for _ in range(N):
qc = QuantumCircuit(2)
qc.append(random_clifford(2), [0, 1])
# random_unitary(dim=4)
pm0.run(qc)
res += (
pm0.property_set["count_ops"]["cx"]
if "cx" in pm0.property_set["count_ops"].keys()
else 0
)
print(res / N)
from qiskit.circuit.library import CPhaseGate
import numpy as np
basis_gate = CXGate()
pm0 = PassManager()
pm0.append(RootiSwapWeylDecomposition(basis_gate=basis_gate))
pm0.append(CountOps())
qc = QuantumCircuit(2)
qc.append(CPhaseGate(np.pi / 2), [0, 1])
# random_unitary(dim=4)
transp = pm0.run(qc)
transp.draw(output="mpl")
from qiskit import transpile
transp = transpile(qc, basis_gates=["rz", "sx", "cx"], optimization_level=3)
print(transp.draw(output="latex_source"))
from qiskit.circuit.library import CPhaseGate
import numpy as np
basis_gate = RiSwapGate(0.5)
pm0 = PassManager()
pm0.append(RootiSwapWeylDecomposition(basis_gate=basis_gate))
pm0.append(CountOps())
qc = QuantumCircuit(2)
qc.append(CPhaseGate(np.pi / 2), [0, 1])
# random_unitary(dim=4)
transp = pm0.run(qc)
print(transp.draw(output="latex"))
|
https://github.com/Pitt-JonesLab/clonk_transpilation
|
Pitt-JonesLab
|
%reload_ext autoreload
%autoreload 2
import sys
sys.path.append("../..")
from clonk.backend_utils import FakeHatlab
backend_hatlab = FakeHatlab(dimension=1, router_as_qubits=False)
from clonk.utils.transpiler_passes import level_0_pass_manager
pm_hypercube = level_0_pass_manager(
backend_hatlab,
basis_gate="riswap",
routing="basic",
decompose_swaps=False,
decompose_1q=False,
)
from qiskit import QuantumCircuit
circuit = QuantumCircuit(20)
circuit.cx(1, 4)
circuit.cx(3, 2)
circuit.cx(6, 8)
# circuit.draw()
transp = pm_hypercube.run(circuit)
transp.draw(output="mpl")
from qiskit.converters import circuit_to_dag
from qiskit.visualization import dag_drawer
dag = circuit_to_dag(transp)
dag_drawer(dag)
|
https://github.com/Pitt-JonesLab/clonk_transpilation
|
Pitt-JonesLab
|
from typing import Optional
from qiskit.circuit.gate import Gate
from qiskit.circuit.parameterexpression import ParameterValueType
import numpy as np
class RiSwapGate(Gate):
r"""RiSWAP gate.
**Circuit Symbol:**
.. parsed-literal::
q_0: ─⨂─
R(alpha)
q_1: ─⨂─
"""
def __init__(self, alpha: ParameterValueType, label: Optional[str] = None):
"""Create new iSwap gate."""
super().__init__("riswap", 2, [alpha], label=label)
def __array__(self, dtype=None):
"""Return a numpy.array for the RiSWAP gate."""
alpha = self.params[0]
return np.array(
[
[1, 0, 0, 0],
[0, np.cos(np.pi * alpha / 2), 1j * np.sin(np.pi * alpha / 2), 0],
[0, 1j * np.sin(np.pi * alpha / 2), np.cos(np.pi * alpha / 2), 0],
[0, 0, 0, 1],
],
dtype=dtype,
)
# from Qiskits two_qubit_decomp #FIXME moving functions around still this won't need to be copied once SQiSwap inside of that same pass
import cmath
from qiskit.quantum_info.synthesis.two_qubit_decompose import *
import scipy.linalg as la
_ipx = np.array([[0, 1j], [1j, 0]], dtype=complex)
_ipy = np.array([[0, 1], [-1, 0]], dtype=complex)
_ipz = np.array([[1j, 0], [0, -1j]], dtype=complex)
_id = np.array([[1, 0], [0, 1]], dtype=complex)
def KAKDecomp(unitary_matrix, *, fidelity=(1.0 - 1.0e-9)):
"""Perform the Weyl chamber decomposition, and optionally choose a specialized subclass.
The flip into the Weyl Chamber is described in B. Kraus and J. I. Cirac, Phys. Rev. A 63,
062309 (2001).
FIXME: There's a cleaner-seeming method based on choosing branch cuts carefully, in Andrew
M. Childs, Henry L. Haselgrove, and Michael A. Nielsen, Phys. Rev. A 68, 052311, but I
wasn't able to get that to work.
The overall decomposition scheme is taken from Drury and Love, arXiv:0806.4015 [quant-ph].
"""
pi = np.pi
pi2 = np.pi / 2
pi4 = np.pi / 4
# Make U be in SU(4)
U = np.array(unitary_matrix, dtype=complex, copy=True)
detU = la.det(U)
U *= detU ** (-0.25)
global_phase = cmath.phase(detU) / 4
Up = transform_to_magic_basis(U, reverse=True)
M2 = Up.T.dot(Up)
# M2 is a symmetric complex matrix. We need to decompose it as M2 = P D P^T where
# P ∈ SO(4), D is diagonal with unit-magnitude elements.
#
# We can't use raw `eig` directly because it isn't guaranteed to give us real or othogonal
# eigenvectors. Instead, since `M2` is complex-symmetric,
# M2 = A + iB
# for real-symmetric `A` and `B`, and as
# M2^+ @ M2 = A^2 + B^2 + i [A, B] = 1
# we must have `A` and `B` commute, and consequently they are simultaneously diagonalizable.
# Mixing them together _should_ account for any degeneracy problems, but it's not
# guaranteed, so we repeat it a little bit. The fixed seed is to make failures
# deterministic; the value is not important.
state = np.random.default_rng(2020)
for _ in range(100): # FIXME: this randomized algorithm is horrendous
M2real = state.normal() * M2.real + state.normal() * M2.imag
_, P = np.linalg.eigh(M2real)
D = P.T.dot(M2).dot(P).diagonal()
if np.allclose(P.dot(np.diag(D)).dot(P.T), M2, rtol=0, atol=1.0e-13):
break
else:
raise ValueError
d = -np.angle(D) / 2
d[3] = -d[0] - d[1] - d[2]
cs = np.mod((d[:3] + d[3]) / 2, 2 * np.pi)
# Reorder the eigenvalues to get in the Weyl chamber
cstemp = np.mod(cs, pi2)
np.minimum(cstemp, pi2 - cstemp, cstemp)
order = np.argsort(cstemp)[[1, 2, 0]]
cs = cs[order]
d[:3] = d[order]
P[:, :3] = P[:, order]
# Fix the sign of P to be in SO(4)
if np.real(la.det(P)) < 0:
P[:, -1] = -P[:, -1]
# Find K1, K2 so that U = K1.A.K2, with K being product of single-qubit unitaries
K1 = transform_to_magic_basis(Up @ P @ np.diag(np.exp(1j * d)))
K2 = transform_to_magic_basis(P.T)
K1l, K1r, phase_l = decompose_two_qubit_product_gate(K1)
K2l, K2r, phase_r = decompose_two_qubit_product_gate(K2)
global_phase += phase_l + phase_r
K1l = K1l.copy()
# Flip into Weyl chamber
if cs[0] > pi2:
cs[0] -= 3 * pi2
K1l = K1l.dot(_ipy)
K1r = K1r.dot(_ipy)
global_phase += pi2
if cs[1] > pi2:
cs[1] -= 3 * pi2
K1l = K1l.dot(_ipx)
K1r = K1r.dot(_ipx)
global_phase += pi2
conjs = 0
if cs[0] > pi4:
cs[0] = pi2 - cs[0]
K1l = K1l.dot(_ipy)
K2r = _ipy.dot(K2r)
conjs += 1
global_phase -= pi2
if cs[1] > pi4:
cs[1] = pi2 - cs[1]
K1l = K1l.dot(_ipx)
K2r = _ipx.dot(K2r)
conjs += 1
global_phase += pi2
if conjs == 1:
global_phase -= pi
if cs[2] > pi2:
cs[2] -= 3 * pi2
K1l = K1l.dot(_ipz)
K1r = K1r.dot(_ipz)
global_phase += pi2
if conjs == 1:
global_phase -= pi
if conjs == 1:
cs[2] = pi2 - cs[2]
K1l = K1l.dot(_ipz)
K2r = _ipz.dot(K2r)
global_phase += pi2
if cs[2] > pi4:
cs[2] -= pi2
K1l = K1l.dot(_ipz)
K1r = K1r.dot(_ipz)
global_phase -= pi2
a, b, c = cs[1], cs[0], cs[2]
return global_phase, (a, b, c), K1l, K1r, K2l, K2r
# Reference: https://arxiv.org/pdf/2105.06074.pdf
from qiskit.circuit.library import RZGate, RXGate, RYGate, IGate
from qiskit.extensions.unitary import UnitaryGate
from qiskit import QuantumCircuit
from qiskit.quantum_info import Operator
# from clonk.utils.riswap_gates.riswap import RiSwapGate
def decomp(U):
"""Decompose U into single qubit gates and the SQiSW gates"""
qc = QuantumCircuit(2)
_, (x, y, z), A1, A2, B1, B2 = KAKDecomp(U)
if np.abs(z) <= x - y:
C1, C2 = interleavingSingleQubitRotations(x, y, z)
V = RiSwapGate(0.5).to_matrix() @ np.kron(C1, C2) @ RiSwapGate(0.5).to_matrix()
_, (x, y, z), D1, D2, E1, E2 = KAKDecomp(V)
qc.append(UnitaryGate(np.matrix(E1).H @ B1), [1])
qc.append(UnitaryGate(np.matrix(E2).H @ B2), [0])
qc.append(RiSwapGate(0.5), [0, 1])
qc.append(UnitaryGate(C1), [1])
qc.append(UnitaryGate(C2), [0])
qc.append(RiSwapGate(0.5), [0, 1])
qc.append(UnitaryGate(A1 @ np.matrix(D1).H), [1])
qc.append(UnitaryGate(A2 @ np.matrix(D2).H), [0])
else:
(x, y, z), F1, F2, G1, G2, H1, H2 = canonicalize(x, y, z)
C1, C2 = interleavingSingleQubitRotations(x, y, z)
V = RiSwapGate(0.5).to_matrix() @ np.kron(C1, C2) @ RiSwapGate(0.5).to_matrix()
_, (x, y, z), D1, D2, E1, E2 = KAKDecomp(V)
qc.append(UnitaryGate(H1 @ B1), [1])
qc.append(UnitaryGate(H2 @ B2), [0])
qc.append(RiSwapGate(0.5), [0, 1])
qc.append(UnitaryGate(np.matrix(E1).H @ G1), [1])
qc.append(UnitaryGate(np.matrix(E2).H @ G2), [0])
qc.append(RiSwapGate(0.5), [0, 1])
qc.append(UnitaryGate(C1), [1])
qc.append(UnitaryGate(C2), [0])
qc.append(RiSwapGate(0.5), [0, 1])
qc.append(UnitaryGate(A1 @ F1 @ np.matrix(D1).H), [1])
qc.append(UnitaryGate(A2 @ F2 @ np.matrix(D2).H), [0])
return qc
def interleavingSingleQubitRotations(x, y, z):
"""Output the single qubit rotations given the interaction coefficients (x,y,z) \in W' when sandiwched by two SQiSW gates"""
C = np.sin(x + y - z) * np.sin(x - y + z) * np.sin(-x - y - z) * np.sin(-x + y + z)
alpha = np.arccos(np.cos(2 * x) - np.cos(2 * y) + np.cos(2 * z) + 2 * np.sqrt(C))
beta = np.arccos(np.cos(2 * x) - np.cos(2 * y) + np.cos(2 * z) - 2 * np.sqrt(C))
_num = 4 * (np.cos(x) ** 2) * (np.cos(z) ** 2) * (np.cos(y) ** 2)
_den = _num + np.cos(2 * x) + np.cos(2 * y) * np.cos(2 * z)
gamma = np.arccos(np.sign(z) * np.sqrt(_num / _den))
return (
RZGate(gamma).to_matrix()
@ RXGate(alpha).to_matrix()
@ RZGate(gamma).to_matrix(),
RXGate(beta).to_matrix(),
)
def canonicalize(x, y, z):
"""Decompose an arbitrary gate into one SQISW and one L(x,y',z) where (x',y',z') \in W' and output the coefficients (x',y',z') and the interleaving single qubit rotations"""
A1 = IGate().to_matrix()
A2 = IGate().to_matrix()
B1 = RYGate(-np.pi / 2).to_matrix()
B2 = RYGate(np.pi / 2).to_matrix()
C1 = RYGate(np.pi / 2).to_matrix()
C2 = RYGate(-np.pi / 2).to_matrix()
s = np.sign(z)
z = np.abs(z)
if x > np.pi / 8:
y = y - np.pi / 8
z = z - np.pi / 8
B1 = RZGate(np.pi / 2).to_matrix() @ B1
B2 = RZGate(-np.pi / 2).to_matrix() @ B2
C1 = C1 @ RZGate(-np.pi / 2).to_matrix()
C2 = C2 @ RZGate(np.pi / 2).to_matrix()
else:
x = x + np.pi / 8
z = z - np.pi / 8
if np.abs(y) < np.abs(z):
# XXX typo in alibaba here (?)
z = -z
A1 = RXGate(np.pi / 2).to_matrix()
A2 = RXGate(-np.pi / 2).to_matrix()
B1 = RXGate(-np.pi / 2).to_matrix() @ B1
B2 = RXGate(np.pi / 2).to_matrix() @ B2
if s < 0:
z = -z
A1 = RZGate(np.pi).to_matrix() @ A1 @ RZGate(np.pi).to_matrix()
B1 = RZGate(np.pi).to_matrix() @ B1 @ RZGate(np.pi).to_matrix()
C1 = RZGate(np.pi).to_matrix() @ C1 @ RZGate(np.pi).to_matrix()
return (x, y, z), A1, A2, B1, B2, C1, C2
# qc = QuantumCircuit(2)
# qc.swap(0,1)
# new_qc = decomp(Operator(qc).data)
# Operator(new_qc).equiv(qc)
new_qc.decompose().draw(output="mpl")
from qiskit.transpiler import PassManager
pm = PassManager()
from qiskit.transpiler.passes import (
BasisTranslator,
UnrollCustomDefinitions,
Optimize1qGates,
Optimize1qGatesDecomposition,
Optimize1qGatesSimpleCommutation,
)
from qiskit.transpiler import PassManager
from qiskit.circuit.equivalence_library import StandardEquivalenceLibrary as _sel
from elim_small_ import ElimSmallRZ
pass_ = [
UnrollCustomDefinitions(_sel, ["u3", "riswap"]),
Optimize1qGatesDecomposition(basis=["rz", "sx", "riswap"]),
Optimize1qGatesDecomposition(basis=["rz", "sx", "x", "riswap"]),
]
pm = PassManager(pass_)
new_circ = pm.run(new_qc)
new_circ.draw(output="mpl")
Operator(new_circ).equiv(CXGate())
import sys
sys.path.append("../..")
# qc.draw(output='mpl')
from qiskit import transpile
b = transpile(qc, basis_gates=basis)
b.draw(output="mpl")
from qiskit.circuit.library.basis_change import QFT
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc = QFT(4).decompose()
# qc.cz(0,1)
from clonk.utils.riswap_gates.riswap import RiSwapGate
from qiskit.circuit.library.standard_gates import CXGate
basis = ["u3", "cx"]
basis_gate = CXGate()
# basis = ["u3", "riswap"]
# basis_gate = RiSwapGate(0.5)
from clonk.utils.riswap_gates.equivalence_library import (
SessionEquivalenceLibrary as _sel,
)
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import (
Collect2qBlocks,
ConsolidateBlocks,
ResourceEstimation,
)
from clonk.utils.transpiler_passes.weyl_decompose import RootiSwapWeylDecomposition
pm = PassManager()
# pm.append(BasisTranslator(equivalence_library=_sel, target_basis=basis))
pm.append(Collect2qBlocks())
pm.append(ConsolidateBlocks(kak_basis_gate=basis_gate, force_consolidate=True))
pm.append(RootiSwapWeylDecomposition(basis_gate=basis_gate))
pm.append(ResourceEstimation())
a = pm.run(qc)
print(pm.property_set["count_ops"])
a.draw(output="mpl")
|
https://github.com/Pitt-JonesLab/clonk_transpilation
|
Pitt-JonesLab
|
import numpy as np
from scipy.linalg import expm
from qiskit.circuit.library import *
S = expm(
-1j
* np.pi
* (XGate().to_matrix() + YGate().to_matrix() + ZGate().to_matrix())
/ np.sqrt(33)
)
from qiskit.extensions.unitary import UnitaryGate
from qiskit import QuantumCircuit
S_gate = UnitaryGate(S)
qc = QuantumCircuit(1)
qc.append(S_gate, [0])
qc.draw(output="mpl")
from qiskit.transpiler.passes import (
BasisTranslator,
UnrollCustomDefinitions,
Optimize1qGates,
)
from qiskit.transpiler import PassManager
from qiskit.circuit.equivalence_library import StandardEquivalenceLibrary as _sel
pass_ = [UnrollCustomDefinitions(_sel, ["u3"]), BasisTranslator(_sel, ["rz", "sx"])]
pm = PassManager(pass_)
new_circ = pm.run(qc)
new_circ.draw(output="mpl")
# verify correctness
from qiskit.quantum_info.operators import Operator
Operator(new_circ).equiv(qc)
from qiskit.quantum_info.synthesis.one_qubit_decompose import OneQubitEulerDecomposer
decomposer = OneQubitEulerDecomposer("ZSXX")
euler_circ = decomposer(S)
euler_circ.draw(output="mpl")
# verify correctness
Operator(new_circ).equiv(qc)
from qiskit.quantum_info.synthesis.one_qubit_decompose import OneQubitEulerDecomposer
decomposer = OneQubitEulerDecomposer("ZXZ")
euler_decomp = decomposer(S)
euler_decomp.draw(output="mpl")
alpha, gamma, delta = [gate[0].params[0] for gate in euler_decomp]
new_circ2 = QuantumCircuit(1)
new_circ2.rz(alpha - np.pi / 2, 0)
new_circ2.sx(0)
new_circ2.rz(np.pi - gamma, 0)
new_circ2.sx(0)
new_circ2.rz(delta - np.pi / 2, 0)
new_circ2.draw(output="mpl")
# verify correctness
Operator(new_circ).equiv(qc)
|
https://github.com/Pitt-JonesLab/clonk_transpilation
|
Pitt-JonesLab
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Weyl decomposition of two-qubit gates in terms of echoed cross-resonance
gates."""
import cmath
import numpy as np
import scipy.linalg as la
from qiskit import QuantumCircuit
from qiskit.circuit.library import IGate, RXGate, RYGate, RZGate
from qiskit.converters import circuit_to_dag
from qiskit.dagcircuit import DAGCircuit
from qiskit.extensions.unitary import UnitaryGate
from qiskit.quantum_info.synthesis.two_qubit_decompose import *
from qiskit.transpiler.basepasses import TransformationPass
from qiskit.transpiler.exceptions import TranspilerError
from clonk.utils.qiskit_patch.two_qubit_decompose import TwoQubitBasisDecomposer
from clonk.utils.riswap_gates.equivalence_library import SessionEquivalenceLibrary
# from qiskit.circuit.library.standard_gates import *
from clonk.utils.riswap_gates.riswap import RiSwapGate, fSim
_sel = SessionEquivalenceLibrary
class RootiSwapWeylDecomposition(TransformationPass):
"""Rewrite two-qubit gates using the Weyl decomposition.
This transpiler pass rewrites two-qubit gates in terms of root iswap
gates according to the Weyl decomposition. A two-qubit gate will be
replaced with at most 3 root i swap gates.
"""
def __init__(self, basis_gate=False):
"""RootiSwapWeylDecomposition pass.
Args:
instruction_schedule_map (InstructionScheduleMap): the mapping from circuit
:class:`~.circuit.Instruction` names and arguments to :class:`.Schedule`\\ s.
"""
super().__init__()
# self.requires = [
# BasisTranslator(_sel, ["u3", "cu3", "cp", "swap", "riswap", "id"])
# ]
# self.decompose_swaps = decompose_swaps
self.basis_gate = basis_gate
# @staticmethod
# def _improper_orthogonal_decomp(x, y, z):
# alpha = np.arccos(
# np.cos(2 * z) - np.cos(2 * y) + np.sqrt((np.cos(4 * z) + np.cos(4 * y)) / 2)
# )
# beta = np.arccos(
# np.cos(2 * z) - np.cos(2 * y) - np.sqrt((np.cos(4 * z) + np.cos(4 * y)) / 2)
# )
# gamma = 0
# psi = -np.arccos(np.sqrt((1 + np.tan(y - z)) / 2))
# phi = np.arccos(np.sqrt((1 + np.tan(y + z)) / 2))
# def_Lxyz = QuantumCircuit(2)
# # ISwap
# if np.isclose(x, y) and np.isclose(z, 0):
# def_Lxyz.append(RiSwapGate(0.5), [0, 1])
# def_Lxyz.rz(2 * x, 0)
# def_Lxyz.rz(-2 * x + np.pi, 1)
# def_Lxyz.append(RiSwapGate(0.5), [0, 1])
# def_Lxyz.rz(-np.pi, 1)
# return def_Lxyz
# # CPhase
# if np.isclose(y, 0) and np.isclose(z, 0):
# def_Lxyz.rz(np.arcsin(np.tan(x)), 1)
# def_Lxyz.rx(-np.pi / 2, 1)
# def_Lxyz.append(RiSwapGate(0.5), [0, 1])
# def_Lxyz.z(1)
# def_Lxyz.ry(2 * np.arcsin(np.sqrt(2) * np.sin(x)), 1)
# def_Lxyz.append(RiSwapGate(0.5), [0, 1])
# def_Lxyz.rx(-np.pi / 2, 1)
# def_Lxyz.rz(np.arcsin(np.tan(x)) - np.pi, 1)
# return def_Lxyz
# # Canonicalized SWAP
# elif np.isclose(x, np.pi / 4) and y + np.abs(z) <= np.pi / 4:
# def_Lxyz.rx(phi + psi, 0)
# def_Lxyz.rz(np.pi / 2, 1)
# def_Lxyz.rx(phi - psi, 1)
# def_Lxyz.append(RiSwapGate(0.5), [0, 1])
# def_Lxyz.rx(alpha, 0)
# def_Lxyz.rx(beta, 1)
# def_Lxyz.append(RiSwapGate(0.5), [0, 1])
# def_Lxyz.rx(phi + psi, 0)
# def_Lxyz.rx(phi - psi, 1)
# def_Lxyz.rz(-np.pi / 2, 1)
# return def_Lxyz
# else:
# raise NotImplementedError
# @staticmethod
# def cphase_decomp(unitary):
# # assuming unitary is a CPhase, is true per self.requires pass
# # TODO function structure needs to be reoganized to use canonicalize function
# x, y, z = weyl_coordinates(Operator(unitary).data)
# def_CPhase = RootiSwapWeylDecomposition._improper_orthogonal_decomp(x, y, z)
# return def_CPhase
# # Note this is the way suggested by alibaba paper, but google has a swap->riswap(1/2) decomp rule that uses less 1Q gates
# @staticmethod
# def swap_decomp(unitary):
# # FIXME: green, blue, maroon rules
# def_swap = QuantumCircuit(2)
# def_swap.z(0)
# def_swap.rx(np.pi / 2, 0)
# def_swap.z(0)
# def_swap.rx(-np.pi / 2, 1)
# x, y, z = weyl_coordinates(Operator(unitary).data)
# def_swap += RootiSwapWeylDecomposition._improper_orthogonal_decomp(
# x, y - np.pi / 4, z - np.pi / 4
# )
# def_swap.z(0)
# def_swap.rx(-np.pi / 2, 0)
# def_swap.rz(np.pi / 2, 0)
# def_swap.ry(-np.pi / 2, 0)
# def_swap.z(0)
# def_swap.rx(np.pi / 2, 1)
# def_swap.rz(-np.pi / 2, 1)
# def_swap.ry(np.pi / 2, 1)
# def_swap.append(RiSwapGate(0.5), [0, 1])
# def_swap.z(0)
# def_swap.ry(np.pi / 2, 0)
# def_swap.rz(-np.pi / 2, 0)
# def_swap.z(0)
# def_swap.ry(-np.pi / 2, 1)
# def_swap.rz(np.pi / 2, 1)
# return def_swap
# reference: https://arxiv.org/pdf/2105.06074.pdf
# from Qiskits two_qubit_decomp #FIXME moving functions around still this won't need to be copied once SQiSwap inside of that same pass
def KAKDecomp(self, unitary_matrix, *, fidelity=(1.0 - 1.0e-9)):
_ipx = np.array([[0, 1j], [1j, 0]], dtype=complex)
_ipy = np.array([[0, 1], [-1, 0]], dtype=complex)
_ipz = np.array([[1j, 0], [0, -1j]], dtype=complex)
_id = np.array([[1, 0], [0, 1]], dtype=complex)
"""Perform the Weyl chamber decomposition, and optionally choose a
specialized subclass.
The flip into the Weyl Chamber is described in B. Kraus and J. I. Cirac, Phys. Rev. A 63,
062309 (2001).
FIXME: There's a cleaner-seeming method based on choosing branch cuts carefully, in Andrew
M. Childs, Henry L. Haselgrove, and Michael A. Nielsen, Phys. Rev. A 68, 052311, but I
wasn't able to get that to work.
The overall decomposition scheme is taken from Drury and Love, arXiv:0806.4015 [quant-ph].
"""
pi = np.pi
pi2 = np.pi / 2
pi4 = np.pi / 4
# Make U be in SU(4)
U = np.array(unitary_matrix, dtype=complex, copy=True)
detU = la.det(U)
U *= detU ** (-0.25)
global_phase = cmath.phase(detU) / 4
Up = transform_to_magic_basis(U, reverse=True)
M2 = Up.T.dot(Up)
# M2 is a symmetric complex matrix. We need to decompose it as M2 = P D P^T where
# P ∈ SO(4), D is diagonal with unit-magnitude elements.
#
# We can't use raw `eig` directly because it isn't guaranteed to give us real or othogonal
# eigenvectors. Instead, since `M2` is complex-symmetric,
# M2 = A + iB
# for real-symmetric `A` and `B`, and as
# M2^+ @ M2 = A^2 + B^2 + i [A, B] = 1
# we must have `A` and `B` commute, and consequently they are simultaneously diagonalizable.
# Mixing them together _should_ account for any degeneracy problems, but it's not
# guaranteed, so we repeat it a little bit. The fixed seed is to make failures
# deterministic; the value is not important.
state = np.random.default_rng(2020)
for _ in range(100): # FIXME: this randomized algorithm is horrendous
M2real = state.normal() * M2.real + state.normal() * M2.imag
_, P = np.linalg.eigh(M2real)
D = P.T.dot(M2).dot(P).diagonal()
if np.allclose(P.dot(np.diag(D)).dot(P.T), M2, rtol=0, atol=1.0e-13):
break
else:
raise ValueError
d = -np.angle(D) / 2
d[3] = -d[0] - d[1] - d[2]
cs = np.mod((d[:3] + d[3]) / 2, 2 * np.pi)
# Reorder the eigenvalues to get in the Weyl chamber
cstemp = np.mod(cs, pi2)
np.minimum(cstemp, pi2 - cstemp, cstemp)
order = np.argsort(cstemp)[[1, 2, 0]]
cs = cs[order]
d[:3] = d[order]
P[:, :3] = P[:, order]
# Fix the sign of P to be in SO(4)
if np.real(la.det(P)) < 0:
P[:, -1] = -P[:, -1]
# Find K1, K2 so that U = K1.A.K2, with K being product of single-qubit unitaries
K1 = transform_to_magic_basis(Up @ P @ np.diag(np.exp(1j * d)))
K2 = transform_to_magic_basis(P.T)
K1l, K1r, phase_l = decompose_two_qubit_product_gate(K1)
K2l, K2r, phase_r = decompose_two_qubit_product_gate(K2)
global_phase += phase_l + phase_r
K1l = K1l.copy()
# Flip into Weyl chamber
if cs[0] > pi2:
cs[0] -= 3 * pi2
K1l = K1l.dot(_ipy)
K1r = K1r.dot(_ipy)
global_phase += pi2
if cs[1] > pi2:
cs[1] -= 3 * pi2
K1l = K1l.dot(_ipx)
K1r = K1r.dot(_ipx)
global_phase += pi2
conjs = 0
if cs[0] > pi4:
cs[0] = pi2 - cs[0]
K1l = K1l.dot(_ipy)
K2r = _ipy.dot(K2r)
conjs += 1
global_phase -= pi2
if cs[1] > pi4:
cs[1] = pi2 - cs[1]
K1l = K1l.dot(_ipx)
K2r = _ipx.dot(K2r)
conjs += 1
global_phase += pi2
if conjs == 1:
global_phase -= pi
if cs[2] > pi2:
cs[2] -= 3 * pi2
K1l = K1l.dot(_ipz)
K1r = K1r.dot(_ipz)
global_phase += pi2
if conjs == 1:
global_phase -= pi
if conjs == 1:
cs[2] = pi2 - cs[2]
K1l = K1l.dot(_ipz)
K2r = _ipz.dot(K2r)
global_phase += pi2
if cs[2] > pi4:
cs[2] -= pi2
K1l = K1l.dot(_ipz)
K1r = K1r.dot(_ipz)
global_phase -= pi2
a, b, c = cs[1], cs[0], cs[2]
return global_phase, (a, b, c), K1l, K1r, K2l, K2r
# Reference: https://quantumai.google/reference/python/cirq/transformers/decompose_two_qubit_interaction_into_four_fsim_gates
def SYCDecomposer(self, U):
qc = QuantumCircuit(2)
# totally ignorning 1Q gates because we are just using this method for counting 2Q gate durations
qc.append(fSim(np.pi / 2, np.pi / 6), [0, 1])
qc.append(fSim(np.pi / 2, np.pi / 6), [0, 1])
qc.append(fSim(np.pi / 2, np.pi / 6), [0, 1])
qc.append(fSim(np.pi / 2, np.pi / 6), [0, 1])
return qc
# Reference: https://arxiv.org/pdf/2105.06074.pdf
def riswapWeylDecomp(self, U):
"""Decompose U into single qubit gates and the SQiSW gates."""
qc = QuantumCircuit(2)
_, (x, y, z), A1, A2, B1, B2 = self.KAKDecomp(U)
if np.abs(z) <= x - y:
C1, C2 = self.interleavingSingleQubitRotations(x, y, z)
V = (
RiSwapGate(0.5).to_matrix()
@ np.kron(C1, C2)
@ RiSwapGate(0.5).to_matrix()
)
_, (x, y, z), D1, D2, E1, E2 = self.KAKDecomp(V)
qc.append(UnitaryGate(np.matrix(E1).H @ B1), [1])
qc.append(UnitaryGate(np.matrix(E2).H @ B2), [0])
qc.append(RiSwapGate(0.5), [0, 1])
qc.append(UnitaryGate(C1), [1])
qc.append(UnitaryGate(C2), [0])
qc.append(RiSwapGate(0.5), [0, 1])
qc.append(UnitaryGate(A1 @ np.matrix(D1).H), [1])
qc.append(UnitaryGate(A2 @ np.matrix(D2).H), [0])
else:
(x, y, z), F1, F2, G1, G2, H1, H2 = self.canonicalize(x, y, z)
C1, C2 = self.interleavingSingleQubitRotations(x, y, z)
V = (
RiSwapGate(0.5).to_matrix()
@ np.kron(C1, C2)
@ RiSwapGate(0.5).to_matrix()
)
_, (x, y, z), D1, D2, E1, E2 = self.KAKDecomp(V)
qc.append(UnitaryGate(H1 @ B1), [1])
qc.append(UnitaryGate(H2 @ B2), [0])
qc.append(RiSwapGate(0.5), [0, 1])
qc.append(UnitaryGate(np.matrix(E1).H @ G1), [1])
qc.append(UnitaryGate(np.matrix(E2).H @ G2), [0])
qc.append(RiSwapGate(0.5), [0, 1])
qc.append(UnitaryGate(C1), [1])
qc.append(UnitaryGate(C2), [0])
qc.append(RiSwapGate(0.5), [0, 1])
qc.append(UnitaryGate(A1 @ F1 @ np.matrix(D1).H), [1])
qc.append(UnitaryGate(A2 @ F2 @ np.matrix(D2).H), [0])
return qc.decompose()
def interleavingSingleQubitRotations(self, x, y, z):
"""Output the single qubit rotations given the interaction coefficients
(x,y,z) \in W' when sandiwched by two SQiSW gates."""
C = (
np.sin(x + y - z)
* np.sin(x - y + z)
* np.sin(-x - y - z)
* np.sin(-x + y + z)
)
alpha = np.arccos(
np.cos(2 * x) - np.cos(2 * y) + np.cos(2 * z) + 2 * np.sqrt(C)
)
beta = np.arccos(np.cos(2 * x) - np.cos(2 * y) + np.cos(2 * z) - 2 * np.sqrt(C))
_num = 4 * (np.cos(x) ** 2) * (np.cos(z) ** 2) * (np.cos(y) ** 2)
_den = _num + np.cos(2 * x) + np.cos(2 * y) * np.cos(2 * z)
gamma = np.arccos(np.sign(z) * np.sqrt(_num / _den))
return (
RZGate(gamma).to_matrix()
@ RXGate(alpha).to_matrix()
@ RZGate(gamma).to_matrix(),
RXGate(beta).to_matrix(),
)
def canonicalize(self, x, y, z):
"""Decompose an arbitrary gate into one SQISW and one L(x,y',z) where
(x',y',z') \in W' and output the coefficients (x',y',z') and the
interleaving single qubit rotations."""
A1 = IGate().to_matrix()
A2 = IGate().to_matrix()
B1 = RYGate(-np.pi / 2).to_matrix()
B2 = RYGate(np.pi / 2).to_matrix()
C1 = RYGate(np.pi / 2).to_matrix()
C2 = RYGate(-np.pi / 2).to_matrix()
s = np.sign(z)
z = np.abs(z)
if x > np.pi / 8:
y = y - np.pi / 8
z = z - np.pi / 8
B1 = RZGate(np.pi / 2).to_matrix() @ B1
B2 = RZGate(-np.pi / 2).to_matrix() @ B2
C1 = C1 @ RZGate(-np.pi / 2).to_matrix()
C2 = C2 @ RZGate(np.pi / 2).to_matrix()
else:
x = x + np.pi / 8
z = z - np.pi / 8
if np.abs(y) < np.abs(z):
# XXX typo in alibaba here (?)
z = -z
A1 = RXGate(np.pi / 2).to_matrix()
A2 = RXGate(-np.pi / 2).to_matrix()
B1 = RXGate(-np.pi / 2).to_matrix() @ B1
B2 = RXGate(np.pi / 2).to_matrix() @ B2
if s < 0:
z = -z
A1 = RZGate(np.pi).to_matrix() @ A1 @ RZGate(np.pi).to_matrix()
B1 = RZGate(np.pi).to_matrix() @ B1 @ RZGate(np.pi).to_matrix()
C1 = RZGate(np.pi).to_matrix() @ C1 @ RZGate(np.pi).to_matrix()
return (x, y, z), A1, A2, B1, B2, C1, C2
def run(self, dag: DAGCircuit):
"""Run the RootiSwapWeylDecomposition pass on `dag`.
Rewrites two-qubit gates in an arbitrary circuit in terms of echoed cross-resonance
gates by computing the Weyl decomposition of the corresponding unitary. Modifies the
input dag.
Args:
dag (DAGCircuit): DAG to rewrite.
Returns:
DAGCircuit: The modified dag.
Raises:
TranspilerError: If the circuit cannot be rewritten.
"""
# pylint: disable=cyclic-import
from qiskit.quantum_info import Operator
if len(dag.qregs) > 1:
raise TranspilerError(
"RootiSwapWeylDecomposition expects a single qreg input DAG,"
f"but input DAG had qregs: {dag.qregs}."
)
# trivial_layout = Layout.generate_trivial_layout(*dag.qregs.values())
if isinstance(self.basis_gate, RiSwapGate):
self.decomposer = self.riswapWeylDecomp
elif isinstance(self.basis_gate, fSim):
self.decomposer = self.SYCDecomposer
else:
self.decomposer = TwoQubitBasisDecomposer(self.basis_gate)
# add something which caches the result to SWAP so we don't have to do it every time
swap_sub = None
cnot_sub = None
for node in dag.two_qubit_ops():
# denote 2 different decomp rules, either for swap gates, or for U gates in CPhase basis
# if node.name == "riswap":
# continue
# FIXME need to convert unitary to a special unitary first to preserve 1Qs?
unitary = Operator(node.op).data
if node.name == "swap":
if swap_sub is None:
swap_sub = circuit_to_dag(self.decomposer(unitary))
dag.substitute_node_with_dag(node, swap_sub)
continue
if node.name == "cx":
if cnot_sub is None:
cnot_sub = circuit_to_dag(self.decomposer(unitary))
dag.substitute_node_with_dag(node, cnot_sub)
continue
# special_unitary = unitary
dag_sub = circuit_to_dag(self.decomposer(unitary))
dag.substitute_node_with_dag(node, dag_sub)
# if node.name == "swap":
# if self.decompose_swaps:
# dag_weyl = circuit_to_dag(self.swap_decomp(unitary))
# dag.substitute_node_with_dag(node, dag_weyl)
# elif node.name == "cp":
# dag_weyl = circuit_to_dag(self.cphase_decomp(unitary))
# dag.substitute_node_with_dag(node, dag_weyl)
# # FIXME
# # FIXME
# # FIXME
# # I need to double check the x,y,z coordinates -> why is CX and CPhase both (np.pi/4 ,0 ,0)
# # that tells me I need to write CX in CPhase basis first to preverse 1Q gates
# # but CU is 2 CPhase gates and yet still a (np.pi/4, 0, 0)- how do I preserve 1Q gates?
# elif node.name == "cu3":
# dag_weyl = circuit_to_dag(self.cphase_decomp(unitary))
# dag.substitute_node_with_dag(node, dag_weyl)
return dag
|
https://github.com/annabsouza/qft-qiskit
|
annabsouza
|
import numpy as np
from numpy import pi
from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ
from qiskit.providers.ibmq import least_busy
from qiskit.tools.monitor import job_monitor
from qiskit.visualization import plot_histogram, plot_bloch_multivector
qc = QuantumCircuit(3)
#Qiskit's least significant bit has the lowest index (0), thus the circuit will be mirrored through the horizontal
qc.h(2)
#Next, we want to turn this an extra quarter turn if qubit 1 is in the state |1>
qc.cp(pi/2, 1, 2) # CROT from qubit 1 to qubit 2
#And another eighth turn if the least significant qubit (0) is |1>
qc.cp(pi/4, 0, 2) # CROT from qubit 2 to qubit 0
qc.h(1)
qc.cp(pi/2, 0, 1) # CROT from qubit 0 to qubit 1
qc.h(0)
qc.swap(0,2)
qc.draw()
def qft_rotations(circuit, n):
if n == 0: # Exit function if circuit is empty
return circuit
n -= 1 # Indexes start from 0
circuit.h(n) # Apply the H-gate to the most significant qubit
for qubit in range(n):
# For each less significant qubit, we need to do a
# smaller-angled controlled rotation:
circuit.cp(pi/2**(n-qubit), qubit, n)
# At the end of our function, we call the same function again on
# the next qubits (we reduced n by one earlier in the function)
qft_rotations(circuit, n)
def swap_registers(circuit, n):
for qubit in range(n//2):
circuit.swap(qubit, n-qubit-1)
return circuit
def qft(circuit, n):
"""QFT on the first n qubits in circuit"""
qft_rotations(circuit, n)
swap_registers(circuit, n)
return circuit
qc1 = QuantumCircuit(4)
qft(qc1,4)
qc1.draw()
# Create the circuit
qc = QuantumCircuit(3)
# Encode the state 5
qc.x(0) # since we need '1' at first qubit and at last qubit
qc.x(2)
qc.draw()
# And let's check the qubit's states using the aer simulator:
sim = Aer.get_backend("aer_simulator")
qc_init = qc.copy() # making a copy so that we can work on the original one
qc_init.save_statevector()
statevector = sim.run(qc_init).result().get_statevector()
plot_bloch_multivector(statevector)
# we can see the state below as '101'
qft(qc,3)
qc.draw()
qc.save_statevector()
statevector = sim.run(qc).result().get_statevector()
plot_bloch_multivector(statevector)
def inverse_qft(circuit, n):
"""Does the inverse QFT on the first n qubits in circuit"""
# First we create a QFT circuit of the correct size:
qft_circ = qft(QuantumCircuit(n), n)
# Then we take the inverse of this circuit
invqft_circ = qft_circ.inverse()
# And add it to the first n qubits in our existing circuit
circuit.append(invqft_circ, circuit.qubits[:n])
return circuit.decompose() # .decompose() allows us to see the individual gates
nqubits = 3
number = 5
qc = QuantumCircuit(nqubits)
for qubit in range(nqubits):
qc.h(qubit)
qc.p(number*pi/4,0)
qc.p(number*pi/2,1)
qc.p(number*pi,2)
qc.draw()
qc_init = qc.copy()
qc_init.save_statevector()
sim = Aer.get_backend("aer_simulator")
statevector = sim.run(qc_init).result().get_statevector()
plot_bloch_multivector(statevector)
qc = inverse_qft(qc, nqubits)
qc.measure_all()
qc.draw()
# Load our saved IBMQ accounts and get the least busy backend device with less than or equal to nqubits
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= nqubits
and not x.configuration().simulator
and x.status().operational==True))
print("least busy backend: ", backend)
shots = 2048
transpiled_qc = transpile(qc, backend, optimization_level=3)
job = backend.run(transpiled_qc, shots=shots)
job_monitor(job)
counts = job.result().get_counts()
plot_histogram(counts)
|
https://github.com/nunofernandes-plight/Qiskit_Textbook_Worstation
|
nunofernandes-plight
|
from qiskit import QuantumCircuit, execute, Aer
from qiskit.visualization import plot_histogram, plot_bloch_vector
from math import sqrt, pi
qc = QuantumCircuit(1) # Create a quantum circuit with one qubit
qc = QuantumCircuit(1) # Create a quantum circuit with one qubit
initial_state = [0,1] # Define initial_state as |1>
qc.initialize(initial_state, 0) # Apply initialisation operation to the 0th qubit
qc.draw() # Let's view our circuit
backend = Aer.get_backend('statevector_simulator') # Tell Qiskit how to simulate our circuit
qc = QuantumCircuit(1) # Create a quantum circuit with one qubit
initial_state = [0,1] # Define initial_state as |1>
qc.initialize(initial_state, 0) # Apply initialisation operation to the 0th qubit
result = execute(qc,backend).result() # Do the simulation, returning the result
output_state = result.get_statevector()
print(output_state) # Display the output state vector
qc.measure_all()
qc.draw()
result = execute(qc,backend).result()
counts = result.get_counts()
plot_histogram(counts)
initial_state = [1/sqrt(2), 1j/sqrt(2)] # Define state |q_0>
qc = QuantumCircuit(1) # Must redefine qc
qc.initialize(initial_state, 0) # Initialise the 0th qubit in the state `initial_state`
state = execute(qc,backend).result().get_statevector() # Execute the circuit
print(state) # Print the result
results = execute(qc,backend).result().get_counts()
plot_histogram(results)
vector = [1,1]
qc.initialize(vector, 0)
qc = QuantumCircuit(1) # We are redefining qc
initial_state = [0.+1.j/sqrt(2),1/sqrt(2)+0.j]
qc.initialize(initial_state, 0)
qc.draw()
state = execute(qc, backend).result().get_statevector()
print("Qubit State = " + str(state))
qc.measure_all()
qc.draw()
state = execute(qc, backend).result().get_statevector()
print("State of Measured Qubit = " + str(state))
from qiskit_textbook.widgets import plot_bloch_vector_spherical
coords = [pi/2,0,1] # [Theta, Phi, Radius]
plot_bloch_vector_spherical(coords) # Bloch Vector with spherical coordinates
import qiskit
qiskit.__qiskit_version__
|
https://github.com/nunofernandes-plight/Qiskit_Textbook_Worstation
|
nunofernandes-plight
|
!pip install qiskit
import qiskit
import matplotlib as plt
import numpy as np
import pandas as pd
import math
from qiskit import(
QuantumCircuit,
execute,
Aer)
from qiskit.visualization import plot_histogram
# Use Aer's qasm_simulator
simulator = Aer.get_backend('qasm_simulator')
# Create a Quantum Circuit acting on the q register
circuit = QuantumCircuit(2, 2)
# Add a H gate on qubit 0
circuit.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1
circuit.cx(0, 1)
# Map the quantum measurement to the classical bits
circuit.measure([0,1], [0,1])
# Execute the circuit on the qasm simulator
job = execute(circuit, simulator, shots=1000)
# Grab results from the job
result = job.result()
# Returns counts
counts = result.get_counts(circuit)
print("\nTotal count for 00 and 11 are:",counts)
# Draw the circuit
circuit.draw()
!pip install ./qiskit-textbook-src
from qiskit import (qiskit_texbook)
from qiskit_textbook.widgets import binary_widget
binary_widget(nbits=5)
n = 10
n_q = n
n_b = n
qc_output = QuantumCircuit(n_q,n_b)
for j in range(n):
qc_output.measure(j,j)
qc_output.draw()
counts = execute(qc_output,Aer.get_backend('qasm_simulator')).result().get_counts()
plot_histogram(counts)
qc_encode = QuantumCircuit(n)
qc_encode.x(9)
qc_encode.draw()
qc = qc_encode + qc_output
qc.draw()
counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts()
plot_histogram(counts)
qc_encode = QuantumCircuit(n)
qc_encode.x(2)
qc_encode.x(3)
qc_encode.x(5)
qc_encode.draw()
qc_cnot = QuantumCircuit(2)
qc_cnot.cx(0,1)
qc_cnot.draw()
qc = QuantumCircuit(2,2)
qc.x(0)
qc.cx(0,1)
qc.measure(0,0)
qc.measure(1,1)
qc.draw()
qc = QuantumCircuit(2,2)
qc.x(1)
qc.cx(1,0)
qc.measure(0,0)
qc.measure(1,1)
qc.draw()
qc = QuantumCircuit(2,2)
qc.x(0)
qc.cx(1,0)
qc.measure(0,1)
qc.measure(1,0)
qc.draw()
qc = QuantumCircuit(2,2)
qc.x(1)
qc.cx(0,1)
qc.measure(1,0)
qc.measure(0,1)
qc.draw()
qc = QuantumCircuit(2,2)
qc.x(1)
qc.cx(0,1)
qc.measure(0,0)
qc.measure(1,1)
qc.draw()
qc_half_adder = QuantumCircuit(4,2)
# encode inputs in qubits 0 and 1
qc_half_adder.x(0) # For a=0, remove this line. For a=1, leave it.
qc_half_adder.x(1) # For b=0, remove this line. For b=1, leave it.
qc_half_adder.barrier()
# use cnots to write the XOR of the inputs on qubit 2
qc_half_adder.cx(0,2)
qc_half_adder.cx(1,2)
qc_half_adder.barrier()
# extract outputs
qc_half_adder.measure(2,0) # extract XOR value
qc_half_adder.measure(3,1)
qc_half_adder.draw()
qc_half_adder = QuantumCircuit(4,2)
# encode inputs in qubits 0 and 1
qc_half_adder.x(0) # For a=0, remove the this line. For a=1, leave it.
qc_half_adder.x(1) # For b=0, remove the this line. For b=1, leave it.
qc_half_adder.barrier()
# use cnots to write the XOR of the inputs on qubit 2
qc_half_adder.cx(0,2)
qc_half_adder.cx(1,2)
# use ccx to write the AND of the inputs on qubit 3
qc_half_adder.ccx(0,1,3)
qc_half_adder.barrier()
# extract outputs
qc_half_adder.measure(2,0) # extract XOR value
qc_half_adder.measure(3,1) # extract AND value
qc_half_adder.draw()
counts = execute(qc_half_adder,Aer.get_backend('qasm_simulator')).result().get_counts()
plot_histogram(counts)
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
a= 1 + 1
a
#print(a)
a = 1
b = 0.5
a + b
an_integer = 42 # Just an integer
a_float = 0.1 # A non-integer number, up to a fixed precision
a_boolean = True # A value that can be True or False
a_string = '''just enclose text between two 's, or two "s, or do what we did for this string''' # Text
none_of_the_above = None # The absence of any actual value or variable type
a_list = [0,1,2,3]
a_list = [ 42, 0.5, True, [0,1], None, 'Banana' ]
a_list[0]
a_tuple = ( 42, 0.5, True, [0,1], None, 'Banana' )
a_tuple[0]
a_list[5] = 'apple'
print(a_list)
a_tuple[5] = 'apple'
a_list.append( 3.14 )
print(a_list)
a_dict = { 1:'This is the value, for the key 1', 'This is the key for a value 1':1, False:':)', (0,1):256 }
a_dict['This is the key for a value 1']
a_dict['new key'] = 'new_value'
for j in range(5):
print(j)
for j in a_list:
print(j)
for key in a_dict:
value = a_dict[key]
print('key =',key)
print('value =',value)
print()
if 'strawberry' in a_list:
print('We have a strawberry!')
elif a_list[5]=='apple':
print('We have an apple!')
else:
print('Not much fruit here!')
import numpy
numpy.sin( numpy.pi/2 )
import numpy as np
np.sin( np.pi/2 )
from numpy import *
sin( pi/2 )
def do_some_maths ( Input1, Input2 ):
the_answer = Input1 + Input2
return the_answer
x = do_some_maths(1,72)
print(x)
def add_sausages ( input_list ):
if 'sausages' not in input_list:
input_list.append('sausages')
print('List before the function')
print(a_list)
add_sausages(a_list) # function called without an output
print('\nList after the function')
print(a_list)
import random
for j in range(5):
print('* Results from sample',j+1)
print('\n Random number from 0 to 1:', random.random() )
print("\n Random choice from our list:", random.choice( a_list ) )
print('\n')
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
a= 1 + 1
a
#print(a)
a = 1
b = 0.5
a + b
an_integer = 42 # Just an integer
a_float = 0.1 # A non-integer number, up to a fixed precision
a_boolean = True # A value that can be True or False
a_string = '''just enclose text between two 's, or two "s, or do what we did for this string''' # Text
none_of_the_above = None # The absence of any actual value or variable type
a_list = [0,1,2,3]
a_list = [ 42, 0.5, True, [0,1], None, 'Banana' ]
a_list[0]
a_tuple = ( 42, 0.5, True, [0,1], None, 'Banana' )
a_tuple[0]
a_list[5] = 'apple'
print(a_list)
a_tuple[5] = 'apple'
a_list.append( 3.14 )
print(a_list)
a_dict = { 1:'This is the value, for the key 1', 'This is the key for a value 1':1, False:':)', (0,1):256 }
a_dict['This is the key for a value 1']
a_dict['new key'] = 'new_value'
for j in range(5):
print(j)
for j in a_list:
print(j)
for key in a_dict:
value = a_dict[key]
print('key =',key)
print('value =',value)
print()
if 'strawberry' in a_list:
print('We have a strawberry!')
elif a_list[5]=='apple':
print('We have an apple!')
else:
print('Not much fruit here!')
import numpy
numpy.sin( numpy.pi/2 )
import numpy as np
np.sin( np.pi/2 )
from numpy import *
sin( pi/2 )
def do_some_maths ( Input1, Input2 ):
the_answer = Input1 + Input2
return the_answer
x = do_some_maths(1,72)
print(x)
def add_sausages ( input_list ):
if 'sausages' not in input_list:
input_list.append('sausages')
print('List before the function')
print(a_list)
add_sausages(a_list) # function called without an output
print('\nList after the function')
print(a_list)
import random
for j in range(5):
print('* Results from sample',j+1)
print('\n Random number from 0 to 1:', random.random() )
print("\n Random choice from our list:", random.choice( a_list ) )
print('\n')
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
# initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
nQubits = 2 # number of physical qubits used to represent s
s = 3 # the hidden integer
# make sure that a can be represented with nqubits
s = s % 2**(nQubits)
# Creating registers
# qubits for querying the oracle and finding the hidden integer
qr = QuantumRegister(nQubits)
# bits for recording the measurement on qr
cr = ClassicalRegister(nQubits)
bvCircuit = QuantumCircuit(qr, cr)
barriers = True
# Apply Hadamard gates before querying the oracle
for i in range(nQubits):
bvCircuit.h(qr[i])
# Apply barrier
if barriers:
bvCircuit.barrier()
# Apply the inner-product oracle
for i in range(nQubits):
if (s & (1 << i)):
bvCircuit.z(qr[i])
else:
bvCircuit.iden(qr[i])
# Apply barrier
if barriers:
bvCircuit.barrier()
#Apply Hadamard gates after querying the oracle
for i in range(nQubits):
bvCircuit.h(qr[i])
# Apply barrier
if barriers:
bvCircuit.barrier()
# Measurement
bvCircuit.measure(qr, cr)
bvCircuit.draw(output='mpl')
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(bvCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# Load our saved IBMQ accounts and get the least busy backend device with less than or equal to 5 qubits
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')provider.backends()
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 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
job = execute(bvCircuit, backend=backend, shots=shots)
job_monitor(job, interval = 2)
# Get the results from the computation
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
import qiskit
qiskit.__qiskit_version__
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
import numpy as np
from qiskit import *
%matplotlib inline
# 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()
circ.draw(output='mpl')
# Import Aer
from qiskit import Aer
# Run the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
# Create a Quantum Program for execution
job = execute(circ, backend)
result = job.result()
outputstate = result.get_statevector(circ, decimals=3)
print(outputstate)
from qiskit.visualization import plot_state_city
plot_state_city(outputstate)
# Run the quantum circuit on a unitary simulator backend
backend = Aer.get_backend('unitary_simulator')
job = execute(circ, backend)
result = job.result()
# Show the results
print(result.get_unitary(circ, decimals=3))
# Create a Quantum Circuit
meas = QuantumCircuit(3, 3)
meas.barrier(range(3))
# map the quantum measurement to the classical bits
meas.measure(range(3),range(3))
# The Qiskit circuit object supports composition using
# the addition operator.
qc = circ+meas
#drawing the circuit
qc.draw()
# Use Aer's qasm_simulator
backend_sim = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator.
# We've set the number of repeats of the circuit
# to be 1024, which is the default.
job_sim = execute(qc, backend_sim, shots=1024)
# Grab the results from the job.
result_sim = job_sim.result()
counts = result_sim.get_counts(qc)
print(counts)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
from qiskit import IBMQ
#IBMQ.save_account('APIKEY')
IBMQ.load_account()
IBMQ.providers()
provider = IBMQ.get_provider(group='open')
provider.backends()
simulator_backend = provider.get_backend('ibmq_qasm_simulator')
job_cloud = execute(qc, backend=simulator_backend)
result_cloud = job_cloud.result()
counts_cloud = result_cloud.get_counts(qc)
plot_histogram(counts_cloud)
#example of backend filtering, you can modify the filters or ask just for the least_busy device
from qiskit.providers.ibmq import least_busy
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
#here we ask for the backend properties
backend.configuration()
from qiskit.tools.monitor import job_monitor
job_exp = execute(qc, backend=backend)
job_monitor(job_exp)
result_exp = job_exp.result()
counts_exp = result_exp.get_counts(qc)
plot_histogram([counts_exp,counts], legend=['Device', 'Simulator'])
#uncomment the line below in case you are not able to specify 'latex' in the draw method
#!pip install pylatexenc
#!pip install pillow
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import BasicAer
qr0 = QuantumRegister(1,name='qb') # qb for "qubit", but the name is optional
cr0 = ClassicalRegister(1,name='b') # b for "bit", but the name is optional
qc0 = QuantumCircuit(qr0,cr0)
qc0.draw(output='latex')
from qiskit.tools.visualization import plot_bloch_vector
import math
theta = math.pi/2 # You can try to change the parameters theta and phi
phi = math.pi/4 # to see how the vector moves on the sphere
plot_bloch_vector([math.cos(phi)*math.sin(theta),math.sin(phi)*math.sin(theta),math.cos(theta)]) # Entries of the
# input vector are
# coordinates [x,y,z]
qc0.measure(qr0,cr0)
#Select the output method to use for drawing the circuit. Valid choices are text, latex, latex_source, or mpl. By default the ‘text’ drawer is used unless a user config file has an alternative backend set as the default.
#If the output kwarg is set, that backend will always be used over the default in a user config file.
qc0.draw('latex')
#backend_sim = Aer.get_backend('qasm_simulator') already defined above
job = execute(qc0, backend_sim, shots=1024)
result = job.result()
counts = result.get_counts()
print(counts)
qc1 = QuantumCircuit(qr0,cr0)
qc1.x(0) # A X gate targeting the first (and only) qubit in register qr0
qc1.measure(qr0,cr0)
qc1.draw(output='mpl')
job1 = execute(qc1, backend_sim, shots=1024)
result1 = job1.result()
counts1 = result1.get_counts()
print(counts1)
from qiskit.tools.visualization import plot_bloch_multivector
vec_backend = Aer.get_backend('statevector_simulator')
result_vec0 = execute(qc0, vec_backend).result()
result_vec1 = execute(qc1, vec_backend).result()
psi0 = result_vec0.get_statevector()
psi1 = result_vec1.get_statevector()
plot_bloch_multivector(psi0)
plot_bloch_multivector(psi1)
qc2 = QuantumCircuit(qr0,cr0)
qc2.h(0)
qc2.measure(qr0,cr0)
qc2.draw(output='mpl')
job2 = execute(qc2, backend_sim, shots=1024)
result2 = job2.result()
counts2 = result2.get_counts()
print(counts2)
result_vec2 = execute(qc2, vec_backend).result()
psi2 = result_vec2.get_statevector()
plot_bloch_multivector(psi2)
qc3 = QuantumCircuit(qr0,cr0)
qc3.h(0)
qc3.s(0) # Use sdg instead of s for the adjoint
qc3.measure(qr0,cr0)
qc3.draw(output='mpl')
job3 = execute(qc3, backend_sim, shots=1024)
result3 = job3.result()
counts3 = result3.get_counts()
print(counts3)
result_vec3 = execute(qc3, vec_backend).result()
psi3 = result_vec3.get_statevector()
plot_bloch_multivector(psi3)
qc4 = QuantumCircuit(qr0,cr0)
qc4.h(0)
qc4.t(0) # Use tdg instead of t for the adjoint
qc4.measure(qr0,cr0)
qc4.draw(output='mpl')
job4 = execute(qc4, backend_sim, shots=1024)
result4 = job4.result()
counts4 = result4.get_counts()
print(counts4)
result_vec4 = execute(qc4, vec_backend).result()
psi4 = result_vec4.get_statevector()
plot_bloch_multivector(psi4)
qc4b = QuantumCircuit(qr0)
qc4b.tdg(0)
qc4b.draw('mpl')
backend_unit = BasicAer.get_backend('unitary_simulator')
job = execute(qc4b, backend_unit)
job.result().get_unitary(qc4b, decimals=3)
lmbd = 1.2 # Change this value to rotate the output vector on the equator of the Bloch sphere
qc5 = QuantumCircuit(qr0,cr0)
qc5.h(0)
qc5.u1(lmbd,0)
qc5.measure(qr0,cr0)
qc5.draw(output='mpl')
result_vec5 = execute(qc5, vec_backend).result()
psi5 = result_vec5.get_statevector()
plot_bloch_multivector(psi5)
qc6 = QuantumCircuit(qr0,cr0)
qc6.u2(0,math.pi, 0)
qc6.measure(qr0,cr0)
result_vec6 = execute(qc6, vec_backend).result()
psi6 = result_vec6.get_statevector()
plot_bloch_multivector(psi6)
theta = math.pi
phi = math.pi
lmb = math.pi
qc7 = QuantumCircuit(qr0,cr0)
qc7.u3(theta,phi, lmb, 0)
qc7.measure(qr0,cr0)
result_vec7 = execute(qc7, vec_backend).result()
psi7 = result_vec7.get_statevector()
plot_bloch_multivector(psi7)
qr = QuantumRegister(2,name='qr') # we need a 2-qubit register now
cr = ClassicalRegister(2,name='cr')
cnot_example = QuantumCircuit(qr,cr)
cnot_example.x(0)
cnot_example.cx(0,1) # First entry is control, the second is the target
cnot_example.measure(qr,cr)
cnot_example.draw(output='mpl')
job_cnot = execute(cnot_example, backend_sim, shots=1024)
result_cnot = job_cnot.result()
counts_cnot = result_cnot.get_counts()
print(counts_cnot)
cnot_reversed = QuantumCircuit(qr,cr)
cnot_reversed.x(0)
# This part uses cx(qr[1],qr[0]) but is equivalent to cx(qr[0],qr[1])
cnot_reversed.h(0)
cnot_reversed.h(1)
cnot_reversed.cx(1,0)
cnot_reversed.h(0)
cnot_reversed.h(1)
#
cnot_reversed.measure(qr,cr)
cnot_reversed.draw(output='mpl')
job_cnot_rev = execute(cnot_reversed, backend_sim, shots=1024)
result_cnot_rev = job_cnot_rev.result()
counts_cnot_rev = result_cnot_rev.get_counts()
print(counts_cnot_rev)
bell_phi_p = QuantumCircuit(qr,cr)
bell_phi_p.h(0)
bell_phi_p.cx(0,1)
bell_phi_p.measure(qr,cr)
bell_phi_p.draw(output='mpl')
job_bell_phi_p = execute(bell_phi_p, backend_sim, shots=1024)
result_bell_phi_p = job_bell_phi_p.result()
counts_bell_phi_p = result_bell_phi_p.get_counts()
print(counts_bell_phi_p)
cz_example = QuantumCircuit(qr)
cz_example.cz(0,1)
cz_example.draw(output='mpl')
job_cz = execute(cz_example, backend_unit)
job_cz.result().get_unitary(cz_example, decimals=3)
cz_from_cnot = QuantumCircuit(qr)
#notice here a more verbose way of writing gates and assign them to qubits
cz_from_cnot.h(qr[1])
cz_from_cnot.cx(qr[0],qr[1])
cz_from_cnot.h(qr[1])
cz_from_cnot.draw(output='mpl')
swap_test = QuantumCircuit(qr)
swap_test.swap(qr[0],qr[1])
swap_test.draw(output='mpl')
swap_from_cnot = QuantumCircuit(qr)
swap_from_cnot.cx(qr[0],qr[1])
swap_from_cnot.cx(qr[1],qr[0])
swap_from_cnot.cx(qr[0],qr[1])
swap_from_cnot.draw(output='mpl')
qr_many = QuantumRegister(5)
control_example = QuantumCircuit(qr_many)
control_example.cy(qr_many[0],qr_many[1])
control_example.ch(qr_many[1],qr_many[2])
control_example.crz(0.2,qr_many[2],qr_many[3])
control_example.cu3(0.5, 0, 0, qr_many[3],qr_many[4])
control_example.draw(output='mpl')
qrthree = QuantumRegister(3)
toffoli_example = QuantumCircuit(qrthree)
toffoli_example.ccx(0,1,2)
toffoli_example.draw(output='mpl')
toffoli_from_cnot = QuantumCircuit(qrthree)
toffoli_from_cnot.h(qrthree[2])
toffoli_from_cnot.cx(qrthree[1],qrthree[2])
toffoli_from_cnot.tdg(qrthree[2])
toffoli_from_cnot.cx(qrthree[0],qrthree[2])
toffoli_from_cnot.t(qrthree[2])
toffoli_from_cnot.cx(qrthree[1],qrthree[2])
toffoli_from_cnot.tdg(qrthree[2])
toffoli_from_cnot.cx(qrthree[0],qrthree[2])
toffoli_from_cnot.tdg(qrthree[1])
toffoli_from_cnot.t(qrthree[2])
toffoli_from_cnot.h(qrthree[2])
toffoli_from_cnot.cx(qrthree[0],qrthree[1])
toffoli_from_cnot.tdg(qrthree[1])
toffoli_from_cnot.cx(qrthree[0],qrthree[1])
toffoli_from_cnot.s(qrthree[1])
toffoli_from_cnot.t(qrthree[0])
toffoli_from_cnot.draw(output='mpl')
# Initializing a three-qubit quantum state
import math
desired_vector = [
1 / math.sqrt(16) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(16) * complex(1, 1),
0,
0,
1 / math.sqrt(8) * complex(1, 2),
1 / math.sqrt(16) * complex(1, 0),
0]
q = QuantumRegister(3)
qc = QuantumCircuit(q)
qc.initialize(desired_vector, [q[0],q[1],q[2]])
qc.draw(output='latex')
backend = BasicAer.get_backend('statevector_simulator')
job = execute(qc, backend)
qc_state = job.result().get_statevector(qc)
qc_state
state_fidelity(desired_vector,qc_state)
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
# initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
# Creating registers
# n qubits for querying the oracle and one qubit for storing the answer
qr = QuantumRegister(2,name='qr')
crsingle = ClassicalRegister(1)
deutsch = QuantumCircuit(qr,crsingle)
deutsch.x(qr[1])
deutsch.h(qr[1])
deutsch.draw(output='latex')
deutsch.h(qr[0])
deutsch.draw(output='mpl')
deutsch.cx(qr[0],qr[1])
deutsch.h(qr[0])
deutsch.measure(qr[0],crsingle[0])
deutsch.draw(output='mpl')
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(deutsch, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# set the length of the $n$-bit string.
n = 2
# set the oracle, b for balanced, c for constant
oracle = "b"
# if the oracle is balanced, set the hidden bitstring, b
if oracle == "b":
b = 3 # np.random.randint(1,2**n) uncomment for a random value
# if the oracle is constant, set c = 0 or 1 randomly.
if oracle == "c":
c = np.random.randint(2)
# Creating registers
# n qubits for querying the oracle and one qubit for storing the answer
qr = QuantumRegister(n+1)
cr = ClassicalRegister(n)
djCircuit = QuantumCircuit(qr, cr)
barriers = True
# Since all qubits are initialized to |0>, we need to flip the second register qubit to the the |1> state
djCircuit.x(qr[n])
# Apply barrier
if barriers:
djCircuit.barrier()
# Apply Hadamard gates to all qubits
djCircuit.h(qr)
# Apply barrier
if barriers:
djCircuit.barrier()
# Query the oracle
if oracle == "c": # if the oracle is constant, return c
if c == 1:
djCircuit.x(qr[n])
else:
djCircuit.iden(qr[n])
else: # otherwise, the oracle is balanced and it returns the inner product of the input with b (non-zero bitstring)
for i in range(n):
if (b & (1 << i)):
djCircuit.cx(qr[i], qr[n])
# Apply barrier
if barriers:
djCircuit.barrier()
# Apply Hadamard gates to the first register after querying the oracle
for i in range(n):
djCircuit.h(qr[i])
# Measure the first register
for i in range(n):
djCircuit.measure(qr[i], cr[i])
djCircuit.draw(output='mpl')
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(djCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# Load our saved IBMQ accounts and get the least busy backend device with less than or equal to 5 qubits
#IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 and
not x.configuration().simulator and x.status().operational==True))
# 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
job = execute(djCircuit, backend=backend, shots=shots)
job_monitor(job, interval = 2)
# Get the results of the computation
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
N = 4
qrQFT = QuantumRegister(N,'qftr')
QFT = QuantumCircuit(qrQFT)
for i in range(N):
QFT.h(qrQFT[i])
for k in range(i+1,N):
l = k-i+1
QFT.cu1(2*math.pi/(2**l),qrQFT[k],qrQFT[i])
QFT.draw(output='mpl')
import qiskit
qiskit.__qiskit_version__
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
# initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
nQubits = 2 # number of physical qubits used to represent s
s = 3 # the hidden integer
# make sure that a can be represented with nqubits
s = s % 2**(nQubits)
# Creating registers
# qubits for querying the oracle and finding the hidden integer
qr = QuantumRegister(nQubits)
# bits for recording the measurement on qr
cr = ClassicalRegister(nQubits)
bvCircuit = QuantumCircuit(qr, cr)
barriers = True
# Apply Hadamard gates before querying the oracle
for i in range(nQubits):
bvCircuit.h(qr[i])
# Apply barrier
if barriers:
bvCircuit.barrier()
# Apply the inner-product oracle
for i in range(nQubits):
if (s & (1 << i)):
bvCircuit.z(qr[i])
else:
bvCircuit.iden(qr[i])
# Apply barrier
if barriers:
bvCircuit.barrier()
#Apply Hadamard gates after querying the oracle
for i in range(nQubits):
bvCircuit.h(qr[i])
# Apply barrier
if barriers:
bvCircuit.barrier()
# Measurement
bvCircuit.measure(qr, cr)
bvCircuit.draw(output='mpl')
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(bvCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# Load our saved IBMQ accounts and get the least busy backend device with less than or equal to 5 qubits
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 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
job = execute(bvCircuit, backend=backend, shots=shots)
job_monitor(job, interval = 2)
# Get the results from the computation
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
import qiskit
qiskit.__qiskit_version__
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
import numpy as np
from qiskit import *
%matplotlib inline
# 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()
circ.draw(output='mpl')
# Import Aer
from qiskit import Aer
# Run the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
# Create a Quantum Program for execution
job = execute(circ, backend)
result = job.result()
outputstate = result.get_statevector(circ, decimals=3)
print(outputstate)
from qiskit.visualization import plot_state_city
plot_state_city(outputstate)
# Run the quantum circuit on a unitary simulator backend
backend = Aer.get_backend('unitary_simulator')
job = execute(circ, backend)
result = job.result()
# Show the results
print(result.get_unitary(circ, decimals=3))
# Create a Quantum Circuit
meas = QuantumCircuit(3, 3)
meas.barrier(range(3))
# map the quantum measurement to the classical bits
meas.measure(range(3),range(3))
# The Qiskit circuit object supports composition using
# the addition operator.
qc = circ+meas
#drawing the circuit
qc.draw()
# Use Aer's qasm_simulator
backend_sim = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator.
# We've set the number of repeats of the circuit
# to be 1024, which is the default.
job_sim = execute(qc, backend_sim, shots=1024)
# Grab the results from the job.
result_sim = job_sim.result()
counts = result_sim.get_counts(qc)
print(counts)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
from qiskit import IBMQ
#IBMQ.save_account('APIKEY')
IBMQ.load_account()
IBMQ.providers()
provider = IBMQ.get_provider(group='open')
provider.backends()
simulator_backend = provider.get_backend('ibmq_qasm_simulator')
job_cloud = execute(qc, backend=simulator_backend)
result_cloud = job_cloud.result()
counts_cloud = result_cloud.get_counts(qc)
plot_histogram(counts_cloud)
#example of backend filtering, you can modify the filters or ask just for the least_busy device
from qiskit.providers.ibmq import least_busy
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
#here we ask for the backend properties
backend.configuration()
from qiskit.tools.monitor import job_monitor
job_exp = execute(qc, backend=backend)
job_monitor(job_exp)
result_exp = job_exp.result()
counts_exp = result_exp.get_counts(qc)
plot_histogram([counts_exp,counts], legend=['Device', 'Simulator'])
#uncomment the line below in case you are not able to specify 'latex' in the draw method
#!pip install pylatexenc
#!pip install pillow
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import BasicAer
qr0 = QuantumRegister(1,name='qb') # qb for "qubit", but the name is optional
cr0 = ClassicalRegister(1,name='b') # b for "bit", but the name is optional
qc0 = QuantumCircuit(qr0,cr0)
qc0.draw(output='latex')
from qiskit.tools.visualization import plot_bloch_vector
import math
theta = math.pi/2 # You can try to change the parameters theta and phi
phi = math.pi/4 # to see how the vector moves on the sphere
plot_bloch_vector([math.cos(phi)*math.sin(theta),math.sin(phi)*math.sin(theta),math.cos(theta)]) # Entries of the
# input vector are
# coordinates [x,y,z]
qc0.measure(qr0,cr0)
#Select the output method to use for drawing the circuit. Valid choices are text, latex, latex_source, or mpl. By default the ‘text’ drawer is used unless a user config file has an alternative backend set as the default.
#If the output kwarg is set, that backend will always be used over the default in a user config file.
qc0.draw('latex')
#backend_sim = Aer.get_backend('qasm_simulator') already defined above
job = execute(qc0, backend_sim, shots=1024)
result = job.result()
counts = result.get_counts()
print(counts)
qc1 = QuantumCircuit(qr0,cr0)
qc1.x(0) # A X gate targeting the first (and only) qubit in register qr0
qc1.measure(qr0,cr0)
qc1.draw(output='mpl')
job1 = execute(qc1, backend_sim, shots=1024)
result1 = job1.result()
counts1 = result1.get_counts()
print(counts1)
from qiskit.tools.visualization import plot_bloch_multivector
vec_backend = Aer.get_backend('statevector_simulator')
result_vec0 = execute(qc0, vec_backend).result()
result_vec1 = execute(qc1, vec_backend).result()
psi0 = result_vec0.get_statevector()
psi1 = result_vec1.get_statevector()
plot_bloch_multivector(psi0)
plot_bloch_multivector(psi1)
qc2 = QuantumCircuit(qr0,cr0)
qc2.h(0)
qc2.measure(qr0,cr0)
qc2.draw(output='mpl')
job2 = execute(qc2, backend_sim, shots=1024)
result2 = job2.result()
counts2 = result2.get_counts()
print(counts2)
result_vec2 = execute(qc2, vec_backend).result()
psi2 = result_vec2.get_statevector()
plot_bloch_multivector(psi2)
qc3 = QuantumCircuit(qr0,cr0)
qc3.h(0)
qc3.s(0) # Use sdg instead of s for the adjoint
qc3.measure(qr0,cr0)
qc3.draw(output='mpl')
job3 = execute(qc3, backend_sim, shots=1024)
result3 = job3.result()
counts3 = result3.get_counts()
print(counts3)
result_vec3 = execute(qc3, vec_backend).result()
psi3 = result_vec3.get_statevector()
plot_bloch_multivector(psi3)
qc4 = QuantumCircuit(qr0,cr0)
qc4.h(0)
qc4.t(0) # Use tdg instead of t for the adjoint
qc4.measure(qr0,cr0)
qc4.draw(output='mpl')
job4 = execute(qc4, backend_sim, shots=1024)
result4 = job4.result()
counts4 = result4.get_counts()
print(counts4)
result_vec4 = execute(qc4, vec_backend).result()
psi4 = result_vec4.get_statevector()
plot_bloch_multivector(psi4)
qc4b = QuantumCircuit(qr0)
qc4b.tdg(0)
qc4b.draw('mpl')
backend_unit = BasicAer.get_backend('unitary_simulator')
job = execute(qc4b, backend_unit)
job.result().get_unitary(qc4b, decimals=3)
lmbd = 1.2 # Change this value to rotate the output vector on the equator of the Bloch sphere
qc5 = QuantumCircuit(qr0,cr0)
qc5.h(0)
qc5.u1(lmbd,0)
qc5.measure(qr0,cr0)
qc5.draw(output='mpl')
result_vec5 = execute(qc5, vec_backend).result()
psi5 = result_vec5.get_statevector()
plot_bloch_multivector(psi5)
qc6 = QuantumCircuit(qr0,cr0)
qc6.u2(0,math.pi, 0)
qc6.measure(qr0,cr0)
result_vec6 = execute(qc6, vec_backend).result()
psi6 = result_vec6.get_statevector()
plot_bloch_multivector(psi6)
theta = math.pi
phi = math.pi
lmb = math.pi
qc7 = QuantumCircuit(qr0,cr0)
qc7.u3(theta,phi, lmb, 0)
qc7.measure(qr0,cr0)
result_vec7 = execute(qc7, vec_backend).result()
psi7 = result_vec7.get_statevector()
plot_bloch_multivector(psi7)
qr = QuantumRegister(2,name='qr') # we need a 2-qubit register now
cr = ClassicalRegister(2,name='cr')
cnot_example = QuantumCircuit(qr,cr)
cnot_example.x(0)
cnot_example.cx(0,1) # First entry is control, the second is the target
cnot_example.measure(qr,cr)
cnot_example.draw(output='mpl')
job_cnot = execute(cnot_example, backend_sim, shots=1024)
result_cnot = job_cnot.result()
counts_cnot = result_cnot.get_counts()
print(counts_cnot)
cnot_reversed = QuantumCircuit(qr,cr)
cnot_reversed.x(0)
# This part uses cx(qr[1],qr[0]) but is equivalent to cx(qr[0],qr[1])
cnot_reversed.h(0)
cnot_reversed.h(1)
cnot_reversed.cx(1,0)
cnot_reversed.h(0)
cnot_reversed.h(1)
#
cnot_reversed.measure(qr,cr)
cnot_reversed.draw(output='mpl')
job_cnot_rev = execute(cnot_reversed, backend_sim, shots=1024)
result_cnot_rev = job_cnot_rev.result()
counts_cnot_rev = result_cnot_rev.get_counts()
print(counts_cnot_rev)
bell_phi_p = QuantumCircuit(qr,cr)
bell_phi_p.h(0)
bell_phi_p.cx(0,1)
bell_phi_p.measure(qr,cr)
bell_phi_p.draw(output='mpl')
job_bell_phi_p = execute(bell_phi_p, backend_sim, shots=1024)
result_bell_phi_p = job_bell_phi_p.result()
counts_bell_phi_p = result_bell_phi_p.get_counts()
print(counts_bell_phi_p)
cz_example = QuantumCircuit(qr)
cz_example.cz(0,1)
cz_example.draw(output='mpl')
job_cz = execute(cz_example, backend_unit)
job_cz.result().get_unitary(cz_example, decimals=3)
cz_from_cnot = QuantumCircuit(qr)
#notice here a more verbose way of writing gates and assign them to qubits
cz_from_cnot.h(qr[1])
cz_from_cnot.cx(qr[0],qr[1])
cz_from_cnot.h(qr[1])
cz_from_cnot.draw(output='mpl')
swap_test = QuantumCircuit(qr)
swap_test.swap(qr[0],qr[1])
swap_test.draw(output='mpl')
swap_from_cnot = QuantumCircuit(qr)
swap_from_cnot.cx(qr[0],qr[1])
swap_from_cnot.cx(qr[1],qr[0])
swap_from_cnot.cx(qr[0],qr[1])
swap_from_cnot.draw(output='mpl')
qr_many = QuantumRegister(5)
control_example = QuantumCircuit(qr_many)
control_example.cy(qr_many[0],qr_many[1])
control_example.ch(qr_many[1],qr_many[2])
control_example.crz(0.2,qr_many[2],qr_many[3])
control_example.cu3(0.5, 0, 0, qr_many[3],qr_many[4])
control_example.draw(output='mpl')
qrthree = QuantumRegister(3)
toffoli_example = QuantumCircuit(qrthree)
toffoli_example.ccx(0,1,2)
toffoli_example.draw(output='mpl')
toffoli_from_cnot = QuantumCircuit(qrthree)
toffoli_from_cnot.h(qrthree[2])
toffoli_from_cnot.cx(qrthree[1],qrthree[2])
toffoli_from_cnot.tdg(qrthree[2])
toffoli_from_cnot.cx(qrthree[0],qrthree[2])
toffoli_from_cnot.t(qrthree[2])
toffoli_from_cnot.cx(qrthree[1],qrthree[2])
toffoli_from_cnot.tdg(qrthree[2])
toffoli_from_cnot.cx(qrthree[0],qrthree[2])
toffoli_from_cnot.tdg(qrthree[1])
toffoli_from_cnot.t(qrthree[2])
toffoli_from_cnot.h(qrthree[2])
toffoli_from_cnot.cx(qrthree[0],qrthree[1])
toffoli_from_cnot.tdg(qrthree[1])
toffoli_from_cnot.cx(qrthree[0],qrthree[1])
toffoli_from_cnot.s(qrthree[1])
toffoli_from_cnot.t(qrthree[0])
toffoli_from_cnot.draw(output='mpl')
# Initializing a three-qubit quantum state
import math
desired_vector = [
1 / math.sqrt(16) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(16) * complex(1, 1),
0,
0,
1 / math.sqrt(8) * complex(1, 2),
1 / math.sqrt(16) * complex(1, 0),
0]
q = QuantumRegister(3)
qc = QuantumCircuit(q)
qc.initialize(desired_vector, [q[0],q[1],q[2]])
qc.draw(output='latex')
backend = BasicAer.get_backend('statevector_simulator')
job = execute(qc, backend)
qc_state = job.result().get_statevector(qc)
qc_state
state_fidelity(desired_vector,qc_state)
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
# initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
# Creating registers
# n qubits for querying the oracle and one qubit for storing the answer
qr = QuantumRegister(2,name='qr')
crsingle = ClassicalRegister(1)
deutsch = QuantumCircuit(qr,crsingle)
deutsch.x(qr[1])
deutsch.h(qr[1])
deutsch.draw(output='latex')
deutsch.h(qr[0])
deutsch.draw(output='mpl')
deutsch.cx(qr[0],qr[1])
deutsch.h(qr[0])
deutsch.measure(qr[0],crsingle[0])
deutsch.draw(output='mpl')
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(deutsch, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# set the length of the $n$-bit string.
n = 2
# set the oracle, b for balanced, c for constant
oracle = "b"
# if the oracle is balanced, set the hidden bitstring, b
if oracle == "b":
b = 3 # np.random.randint(1,2**n) uncomment for a random value
# if the oracle is constant, set c = 0 or 1 randomly.
if oracle == "c":
c = np.random.randint(2)
# Creating registers
# n qubits for querying the oracle and one qubit for storing the answer
qr = QuantumRegister(n+1)
cr = ClassicalRegister(n)
djCircuit = QuantumCircuit(qr, cr)
barriers = True
# Since all qubits are initialized to |0>, we need to flip the second register qubit to the the |1> state
djCircuit.x(qr[n])
# Apply barrier
if barriers:
djCircuit.barrier()
# Apply Hadamard gates to all qubits
djCircuit.h(qr)
# Apply barrier
if barriers:
djCircuit.barrier()
# Query the oracle
if oracle == "c": # if the oracle is constant, return c
if c == 1:
djCircuit.x(qr[n])
else:
djCircuit.iden(qr[n])
else: # otherwise, the oracle is balanced and it returns the inner product of the input with b (non-zero bitstring)
for i in range(n):
if (b & (1 << i)):
djCircuit.cx(qr[i], qr[n])
# Apply barrier
if barriers:
djCircuit.barrier()
# Apply Hadamard gates to the first register after querying the oracle
for i in range(n):
djCircuit.h(qr[i])
# Measure the first register
for i in range(n):
djCircuit.measure(qr[i], cr[i])
djCircuit.draw(output='mpl')
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(djCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# Load our saved IBMQ accounts and get the least busy backend device with less than or equal to 5 qubits
#IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 and
not x.configuration().simulator and x.status().operational==True))
# 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
job = execute(djCircuit, backend=backend, shots=shots)
job_monitor(job, interval = 2)
# Get the results of the computation
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
N = 4
qrQFT = QuantumRegister(N,'qftr')
QFT = QuantumCircuit(qrQFT)
for i in range(N):
QFT.h(qrQFT[i])
for k in range(i+1,N):
l = k-i+1
QFT.cu1(2*math.pi/(2**l),qrQFT[k],qrQFT[i])
QFT.draw(output='mpl')
import qiskit
qiskit.__qiskit_version__
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
# initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
# Creating registers
# n qubits for querying the oracle and one qubit for storing the answer
qr = QuantumRegister(2,name='qr')
crsingle = ClassicalRegister(1)
deutsch = QuantumCircuit(qr,crsingle)
deutsch.x(qr[1])
deutsch.h(qr[1])
deutsch.draw(output='latex')
deutsch.h(qr[0])
deutsch.draw(output='mpl')
deutsch.cx(qr[0],qr[1])
deutsch.h(qr[0])
deutsch.measure(qr[0],crsingle[0])
deutsch.draw(output='mpl')
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(deutsch, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# set the length of the $n$-bit string.
n = 2
# set the oracle, b for balanced, c for constant
oracle = "b"
# if the oracle is balanced, set the hidden bitstring, b
if oracle == "b":
b = 3 # np.random.randint(1,2**n) uncomment for a random value
# if the oracle is constant, set c = 0 or 1 randomly.
if oracle == "c":
c = np.random.randint(2)
# Creating registers
# n qubits for querying the oracle and one qubit for storing the answer
qr = QuantumRegister(n+1)
cr = ClassicalRegister(n)
djCircuit = QuantumCircuit(qr, cr)
barriers = True
# Since all qubits are initialized to |0>, we need to flip the second register qubit to the the |1> state
djCircuit.x(qr[n])
# Apply barrier
if barriers:
djCircuit.barrier()
# Apply Hadamard gates to all qubits
djCircuit.h(qr)
# Apply barrier
if barriers:
djCircuit.barrier()
# Query the oracle
if oracle == "c": # if the oracle is constant, return c
if c == 1:
djCircuit.x(qr[n])
else:
djCircuit.iden(qr[n])
else: # otherwise, the oracle is balanced and it returns the inner product of the input with b (non-zero bitstring)
for i in range(n):
if (b & (1 << i)):
djCircuit.cx(qr[i], qr[n])
# Apply barrier
if barriers:
djCircuit.barrier()
# Apply Hadamard gates to the first register after querying the oracle
for i in range(n):
djCircuit.h(qr[i])
# Measure the first register
for i in range(n):
djCircuit.measure(qr[i], cr[i])
djCircuit.draw(output='mpl')
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(djCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# Load our saved IBMQ accounts and get the least busy backend device with less than or equal to 5 qubits
#IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 and
not x.configuration().simulator and x.status().operational==True))
# 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
job = execute(djCircuit, backend=backend, shots=shots)
job_monitor(job, interval = 2)
# Get the results of the computation
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
N = 4
qrQFT = QuantumRegister(N,'qftr')
QFT = QuantumCircuit(qrQFT)
for i in range(N):
QFT.h(qrQFT[i])
for k in range(i+1,N):
l = k-i+1
QFT.cu1(2*math.pi/(2**l),qrQFT[k],qrQFT[i])
QFT.draw(output='mpl')
import qiskit
qiskit.__qiskit_version__
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
# qiskit packages
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer, IBMQ, execute
# visualization packages
from qiskit.tools.visualization import plot_histogram, qx_color_scheme, plot_state_city, plot_bloch_multivector, plot_state_paulivec, plot_state_hinton, plot_state_qsphere
backend = Aer.get_backend('qasm_simulator') # select the qasm simulator
# to use a real processor uncomment the following lines:
#IBMQ.load_accounts()
#from qiskit.providers.ibmq import least_busy
#backend = least_busy(IBMQ.backends(simulator=False))
#print("the best backend is " + backend.name())
# Create the registers
q2 = QuantumRegister(2)
c2 = ClassicalRegister(2)
# Create the Bell's State
bell = QuantumCircuit(q2, c2)
bell.h(q2[0])
bell.cx(q2[0], q2[1])
# Measure the qubits in the standard base (Z)
measureZZ = QuantumCircuit(q2, c2)
measureZZ.measure(q2[0], c2[0])
measureZZ.measure(q2[1], c2[1])
bellZZ = bell+measureZZ
# Measure the qubits in the superposition base (X)
measureXX = QuantumCircuit(q2, c2)
measureXX.h(q2)
measureXX.measure(q2, c2)
bellXX = bell+measureXX
bellZZ.draw(output='mpl')
circuits = [bellZZ,bellXX]
job = execute(circuits, backend)
result = job.result()
#plot_histogram(result.get_counts(bellZZ))
legend = ['bellZZ', 'bellXX']
plot_histogram([result.get_counts(bellZZ), result.get_counts(bellXX)], legend=legend, sort='desc', figsize=(15,12),
color=['orange', 'black'], bar_labels=False)
# Create a circuit that measures the qubits in 0 and one that flips and measures them in 1:
mixed1 = QuantumCircuit(q2, c2)
mixed2 = QuantumCircuit(q2, c2)
mixed2.x(q2)
mixed1.measure(q2[0], c2[0])
mixed1.measure(q2[1], c2[1])
mixed2.measure(q2[0], c2[0])
mixed2.measure(q2[1], c2[1])
mixed1.draw(output='mpl')
mixed2.draw(output='mpl')
mixed_state = [mixed1,mixed2]
job = execute(mixed_state, backend)
result = job.result()
counts1 = result.get_counts(mixed_state[0])
counts2 = result.get_counts(mixed_state[1])
from collections import Counter
ground = Counter(counts1)
excited = Counter(counts2)
plot_histogram(ground+excited)
backend = Aer.get_backend('') # select the appropriate backend
# Create registers
q2 = QuantumRegister(2)
c2 = ClassicalRegister(2)
# Create the Bell's State
bell = QuantumCircuit(q2, c2)
bell.h(q2[0])
bell.cx(q2[0], q2[1])
# Run the job to see the matrix that creates the entanglement
circuit = bell
job = execute(circuit, backend)
result = job.result()
print(result.get_unitary(bell, decimals=3))
backend = Aer.get_backend('') # select the appropriate simulator
# Create registers
q2 = QuantumRegister(2)
c2 = ClassicalRegister(2)
# Create the mixed state
mix1 = QuantumCircuit(q2, c2)
mix2 = QuantumCircuit(q2, c2)
mix1.iden(q2)
mix2.x(q2)
# Execute the circuits to obtain the matrices
mixed_state = [mix1,mix2]
job = execute(mixed_state, backend)
result = job.result()
print(result.get_unitary(mixed_state[0], decimals=3),'\n \n',result.get_unitary(mixed_state[1],decimals=3))
backend= Aer.get_backend('qasm_simulator')
q2 = QuantumRegister(2)
c2 = ClassicalRegister(2)
# Create Bell's State
env = QuantumCircuit(q2, c2)
env.h(q2[0])
env.cx(q2[0], q2[1])
# Apply the X gates
env.x(q2[0])
env.iden(q2[1])
env.iden(q2[0])
env.x(q2[1])
meas = QuantumCircuit(q2, c2)
meas.measure(q2[0], c2[0])
meas.measure(q2[1], c2[1])
env = env+meas
env.draw(output='mpl')
circuit = env
job = execute(circuit, backend)
result = job.result()
plot_histogram(result.get_counts(env))
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
# useful additional packages
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# importing Qiskit
from qiskit import Aer, IBMQ
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
import qiskit as qk
#from qiskit.wrapper.jupyter import *
# import basic plot tools
from qiskit.tools.visualization import circuit_drawer, plot_histogram
#IBMQ.save_account('APItoken')
# Load our saved IBMQ accounts
IBMQ.load_account()
n = 2 # n is the length of the first register
# Let's choose ranomly the type of oracle. The probability that it is balanced is 50% and that is constant is 50%
# In order to do so we will use a function from numpy module
oracleType, oracleValue = np.random.randint(2), np.random.randint(2)
if oracleType == 0:
print("The oracle is constant ", oracleValue)
else:
print("The oracle is balanced")
a = np.random.randint(1,2**n) # let's save an hidden value for the balanced function.
# create quantum and classical registers all initialized at zero
# 2 qubits for oracle interrogation, and the other one is to save the result
qr = QuantumRegister(n+1)
# we only need the classical register for the measurement of the first quantum circuit
cr = ClassicalRegister(n)
circuitName = "DeutschJozsa"
djCircuit = QuantumCircuit(qr, cr)
# Superpose the first register.
for i in range(n):
djCircuit.h(qr[i])
# Invert the second register and apply H.
djCircuit.x(qr[n])
djCircuit.h(qr[n])
# Let's visualize a barrier of the oracle (this is only for stylistical purpose)
djCircuit.barrier()
if oracleType == 0:#The function is constant
if oracleValue == 1:
djCircuit.x(qr[n])
else:
djCircuit.iden(qr[n])
else: # The function is balanced, in that case the oracle applies a CNOT on the qubit i controlling the qubit n
for i in range(n):
if (a & (1 << i)):
djCircuit.cx(qr[i], qr[n])
# End of the oracle, let's close the barrier
djCircuit.barrier()
# Apply H to each qubit
for i in range(n):
djCircuit.h(qr[i])
# Measure
djCircuit.barrier()
for i in range(n):
djCircuit.measure(qr[i], cr[i])
#draw the circuit
circuit_drawer(djCircuit)
backend = Aer.get_backend('qasm_simulator')
shots = 1024
job = qk.execute(djCircuit, backend=backend, shots=shots)
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
from qiskit.tools.monitor import job_monitor
backend = IBMQ.get_backend('ibmq_16_melbourne')
shots = 1024
job = qk.execute(djCircuit, backend=backend, shots=shots)
job_monitor(job, interval=5)
results = job.result()
answer = results.get_counts()
threshold = int(0.03 * shots) # set a threshold for significant measurements
filteredAnswer = {k: v for k,v in answer.items() if v >= threshold} # filter for an optimal visualization of the results
removedCounts = np.sum([ v for k,v in answer.items() if v < threshold ]) #
filteredAnswer['other_bitstring'] = removedCounts #
plot_histogram(answer)
print(answer)
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
import qiskit
qiskit.__qiskit_version__
# useful additional packages
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# importing Qiskit
from qiskit import BasicAer, IBMQ
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.compiler import transpile
from qiskit.tools.monitor import job_monitor
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
#IBMQ.save_account('API-TOKEN')
# Load our saved IBMQ accounts
IBMQ.load_accounts()
n = 13 # the length of the first register for querying the oracle
# Choose a type of oracle at random. With probability half it is constant,
# and with the same probability it is balanced
oracleType, oracleValue = np.random.randint(2), np.random.randint(2)
if oracleType == 0:
print("The oracle returns a constant value ", oracleValue)
else:
print("The oracle returns a balanced function")
a = np.random.randint(1,2**n) # this is a hidden parameter for balanced oracle.
# Creating registers
# n qubits for querying the oracle and one qubit for storing the answer
qr = QuantumRegister(n+1) #all qubits are initialized to zero
# for recording the measurement on the first register
cr = ClassicalRegister(n)
circuitName = "DeutschJozsa"
djCircuit = QuantumCircuit(qr, cr)
# Create the superposition of all input queries in the first register by applying the Hadamard gate to each qubit.
for i in range(n):
djCircuit.h(qr[i])
# Flip the second register and apply the Hadamard gate.
djCircuit.x(qr[n])
djCircuit.h(qr[n])
# Apply barrier to mark the beginning of the oracle
djCircuit.barrier()
if oracleType == 0:#If the oracleType is "0", the oracle returns oracleValue for all input.
if oracleValue == 1:
djCircuit.x(qr[n])
else:
djCircuit.iden(qr[n])
else: # Otherwise, it returns the inner product of the input with a (non-zero bitstring)
for i in range(n):
if (a & (1 << i)):
djCircuit.cx(qr[i], qr[n])
# Apply barrier to mark the end of the oracle
djCircuit.barrier()
# Apply Hadamard gates after querying the oracle
for i in range(n):
djCircuit.h(qr[i])
# Measurement
djCircuit.barrier()
for i in range(n):
djCircuit.measure(qr[i], cr[i])
#draw the circuit
djCircuit.draw(output='mpl',scale=0.5)
backend = BasicAer.get_backend('qasm_simulator')
shots = 1000
job = execute(djCircuit, backend=backend, shots=shots)
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
backend = IBMQ.get_backend('ibmq_16_melbourne')
djCompiled = transpile(djCircuit, backend=backend, optimization_level=1)
djCompiled.draw(output='mpl',scale=0.5)
job = execute(djCompiled, backend=backend, shots=1024)
job_monitor(job)
results = job.result()
answer = results.get_counts()
threshold = int(0.01 * shots) # the threshold of plotting significant measurements
filteredAnswer = {k: v for k,v in answer.items() if v >= threshold} # filter the answer for better view of plots
removedCounts = np.sum([ v for k,v in answer.items() if v < threshold ]) # number of counts removed
filteredAnswer['other_bitstrings'] = removedCounts # the removed counts are assigned to a new index
plot_histogram(filteredAnswer)
print(filteredAnswer)
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
# qiskit-ibmq-provider has been deprecated.
# Please see the Migration Guides in https://ibm.biz/provider_migration_guide for more detail.
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Estimator, Session, Options
# Loading your IBM Quantum account(s)
service = QiskitRuntimeService(channel="ibm_quantum")
# Invoke a primitive. For more details see https://qiskit.org/documentation/partners/qiskit_ibm_runtime/tutorials.html
# result = Sampler("ibmq_qasm_simulator").run(circuits).result()
# Built-in modules
import math
# Imports from Qiskit
from qiskit import QuantumCircuit
from qiskit.circuit.library import GroverOperator, MCMT, ZGate
from qiskit.visualization import plot_distribution
# Imports from Qiskit Runtime
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Session
# Add your token below
service = QiskitRuntimeService(channel="ibm_quantum")
from qiskit import IBMQ
IBMQ.save_account('33b329939cf6fe545c64afb41b84e0993a774c578c2d3e3a07b2ed8644261511d4712974c684ae3050ca82dd8f4ca161930bb344995de7934be32214bdb17079')
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
#initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
def phase_oracle(circuit, register):
circuit.cz(qr[2],qr[0])
circuit.cz(qr[2],qr[1])
def n_controlled_Z(circuit, controls, target):
"""Implement a Z gate with multiple controls"""
if (len(controls) > 2):
raise ValueError('The controlled Z with more than 2 controls is not implemented')
elif (len(controls) == 1):
circuit.h(target)
circuit.cx(controls[0], target)
circuit.h(target)
elif (len(controls) == 2):
circuit.h(target)
circuit.ccx(controls[0], controls[1], target)
circuit.h(target)
def inversion_about_average(circuit, register, n, barriers):
"""Apply inversion about the average step of Grover's algorithm."""
circuit.h(register)
circuit.x(register)
if barriers:
circuit.barrier()
n_controlled_Z(circuit, [register[j] for j in range(n-1)], register[n-1])
if barriers:
circuit.barrier()
circuit.x(register)
circuit.h(register)
barriers = True
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
groverCircuit = QuantumCircuit(qr,cr)
groverCircuit.h(qr)
if barriers:
groverCircuit.barrier()
phase_oracle(groverCircuit, qr)
if barriers:
groverCircuit.barrier()
inversion_about_average(groverCircuit, qr, 3, barriers)
if barriers:
groverCircuit.barrier()
groverCircuit.measure(qr,cr)
groverCircuit.draw(output="mpl")
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(groverCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# Load our saved IBMQ accounts and get the least busy backend device with less than or equal to 5 qubits
IBMQ.load_account()
IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 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
job = execute(groverCircuit, backend=backend, shots=shots)
job_monitor(job, interval = 2)
# Get the results from the computation
results = job.result()
answer = results.get_counts(groverCircuit)
plot_histogram(answer)
import qiskit
qiskit.__qiskit_version__
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
import pylab
import numpy as np
from qiskit import BasicAer
from qiskit.tools.visualization import plot_histogram
from qiskit.aqua import QuantumInstance
from qiskit.aqua import run_algorithm
from qiskit.aqua.algorithms import Grover
from qiskit.aqua.components.oracles import LogicalExpressionOracle, TruthTableOracle
input_3sat_instance = '''
c example DIMACS-CNF 3-SAT
p cnf 3 5
-1 -2 -3 0
1 -2 3 0
1 2 -3 0
1 -2 -3 0
-1 2 3 0
'''
oracle = LogicalExpressionOracle(input_3sat_instance)
grover = Grover(oracle)
backend = BasicAer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1024)
result = grover.run(quantum_instance)
print(result['result'])
plot_histogram(result['measurement'])
params = {
'problem': {
'name': 'search',
},
'algorithm': {
'name': 'Grover'
},
'oracle': {
'name': 'LogicalExpressionOracle',
'expression': input_3sat_instance
},
'backend': {
'shots': 1000,
},
}
result_dict = run_algorithm(params, backend=backend)
plot_histogram(result_dict['measurement'])
expression = '(w ^ x) & ~(y ^ z) & (x & y & z)'
oracle = LogicalExpressionOracle(expression)
grover = Grover(oracle)
result = grover.run(QuantumInstance(BasicAer.get_backend('qasm_simulator'), shots=1024))
plot_histogram(result['measurement'])
truthtable = '1000000000000001'
oracle = TruthTableOracle(truthtable)
grover = Grover(oracle)
result = grover.run(QuantumInstance(BasicAer.get_backend('qasm_simulator'), shots=1024))
plot_histogram(result['measurement'])
#solution
from hide_toggle import hide_toggle
hide_toggle(for_next=True)
sat_cnf = '''
c prova.cnf
c
p cnf 2 2
1 -2 0
-1 2 0
'''
print(sat_cnf)
oracle_2 = LogicalExpressionOracle(sat_cnf)
my_grover = Grover(oracle_2)
backend = BasicAer.get_backend('qasm_simulator')
quantum_grover = QuantumInstance(backend, shots=1024)
result = grover.run(quantum_grover)
print(result['result'])
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
from hide_toggle import hide_toggle
#usage:
#1 create a cell with: hide_toggle(for_next=True)
#2 put the commented solution in the next cell
import qiskit as qk
import numpy as np
from scipy.linalg import expm
import matplotlib.pyplot as plt
import math
# definition of single qubit operators
sx = np.array([[0.0, 1.0],[1.0, 0.0]])
sy = np.array([[0.0, -1.0*1j],[1.0*1j, 0.0]])
sz = np.array([[1.0, 0.0],[0.0, -1.0]])
idt = np.array([[1.0, 0.0],[0.0, 1.0]])
psi0 = np.array([1.0, 0.0])
thetas = np.linspace(0,4*math.pi,200)
avg_sx_tot = np.zeros(len(thetas))
for i in range(len(thetas)):
psi_theta = expm(-1j*0.5*thetas[i]*(sx+sz)/math.sqrt(2)).dot(psi0)
avg_sx_tot[i] = np.real(psi_theta.conjugate().transpose().dot(sx.dot(psi_theta)))
plt.plot(thetas,avg_sx_tot)
plt.xlabel(r'$\theta$')
plt.ylabel(r'$\langle\sigma_x\rangle_\theta$')
plt.show()
#solution
hide_toggle(for_next=True)
avg_sx_zx = np.zeros(len(thetas))
avg_sx_xz = np.zeros(len(thetas))
for i in range(len(thetas)):
psi_theta_zx = expm(-1j*0.5*thetas[i]*(sz)/math.sqrt(2)).dot(expm(-1j*0.5*thetas[i]*(sx)/math.sqrt(2)).dot(psi0))
psi_theta_xz = expm(-1j*0.5*thetas[i]*(sx)/math.sqrt(2)).dot(expm(-1j*0.5*thetas[i]*(sz)/math.sqrt(2)).dot(psi0))
avg_sx_zx[i] = np.real(psi_theta_zx.conjugate().transpose().dot(sx.dot(psi_theta_zx)))
avg_sx_xz[i] = np.real(psi_theta_xz.conjugate().transpose().dot(sx.dot(psi_theta_xz)))
plt.plot(thetas,avg_sx_tot)
plt.plot(thetas,avg_sx_zx)
plt.plot(thetas,avg_sx_xz)
plt.xlabel(r'$\theta$')
plt.ylabel(r'$\langle\sigma_x\rangle_\theta$')
plt.legend(['Around x = z', 'x first', 'z first'],loc=1)
plt.show()
# Try this with e.g. ntrot = 1, 5, 10, 50.
# You can also try to do sx and sz slices in the reverse order: both choices will become good approximations for large n
ntrot = 8
avg_sx_n = np.zeros(len(thetas))
for i in range(len(thetas)):
rot = expm(-1j*0.5*thetas[i]*(sx)/(ntrot*math.sqrt(2))).dot(expm(-1j*0.5*thetas[i]*(sz)/(ntrot*math.sqrt(2))))
for j in range(ntrot-1):
rot = expm(-1j*0.5*thetas[i]*(sx)/(ntrot*math.sqrt(2))).dot(expm(-1j*0.5*thetas[i]*(sz)/(ntrot*math.sqrt(2)))).dot(rot)
psi_theta_n = rot.dot(psi0)
avg_sx_n[i] = np.real(psi_theta_n.conjugate().transpose().dot(sx.dot(psi_theta_n)))
plt.plot(thetas,avg_sx_tot)
plt.plot(thetas,avg_sx_n,'--')
plt.xlabel(r'$\theta$')
plt.ylabel(r'$\langle\sigma_x\rangle_\theta$')
plt.legend(['Exact', 'ntrot = ' + str(ntrot)],loc=1)
plt.show()
#solution
hide_toggle(for_next=True)
# commutation function
def comm_check(a,b):
aa = np.kron(a,a)
bb = np.kron(b,b)
return (np.dot(aa,bb) - np.dot(bb,aa))
comm_check(sx,sy)
delta = 0.1
qr = qk.QuantumRegister(2,name='qr')
zz_example = qk.QuantumCircuit(qr)
zz_example.cx(qr[0],qr[1])
zz_example.u1(2*delta,qr[1])
zz_example.cx(qr[0],qr[1])
zz_example.draw(output='mpl')
#solution
J = 1
c_times = np.linspace(0,0.5*math.pi/abs(J),1000)
q_times = np.linspace(0,0.5*math.pi/abs(J),10)
### Classical simulation of the Heisenberg dimer model
psi0 = np.kron( np.array([0,1]), np.array([1,0]) )
H = J * ( np.kron(sx,sx) + np.kron(sy,sy) + np.kron(sz,sz) )
sz1_t = np.zeros(len(c_times))
sz2_t = np.zeros(len(c_times))
sz1 = np.kron(sz,idt)
sz2 = np.kron(idt,sz)
for i in range(len(c_times)):
t = c_times[i]
psi_t = expm(-1j*H*t).dot(psi0)
sz1_t[i] = np.real(psi_t.conjugate().transpose().dot(sz1.dot(psi_t)))
sz2_t[i] = np.real(psi_t.conjugate().transpose().dot(sz2.dot(psi_t)))
### Digital quantum simulation of the Heisenberg dimer model using qiskit
nshots = 1024
sz1q_t = np.zeros(len(q_times))
sz2q_t = np.zeros(len(q_times))
#Solution: try to write the circuit and the quantum evolution,
#hints: start with:
#for k in range(len(q_times)):
#delta =
#define QuantumRegister, ClassicalRegister and QuantumCircuit (Heis2)
#define initial state
#define each part of the circuit: ZZ, YY, XX
#measurement
# Post processing of outcomes to get sz expectation values
#sz1q = 0
#sz2q = 0
#for key,value in counts.items():
#if key == '00':
#sz1q += value
#sz2q += value
#elif key == '01':
#sz1q -= value
#sz2q += value
#elif key == '10':
#sz1q += value
#sz2q -= value
#elif key == '11':
#sz1q -= value
#sz2q -= value
#sz1q_t[k] = sz1q/nshots
#sz2q_t[k] = sz2q/nshots
# Run the quantum algorithm and colect the result, counts
hide_toggle(for_next=True)
for k in range(len(q_times)):
delta = J*q_times[k]
qr = qk.QuantumRegister(2,name='qr')
cr = qk.ClassicalRegister(2,name='cr')
Heis2 = qk.QuantumCircuit(qr,cr)
# Initial state preparation
Heis2.x(qr[0])
# ZZ
Heis2.cx(qr[0],qr[1])
Heis2.u1(-2*delta,qr[1])
Heis2.cx(qr[0],qr[1])
# YY
Heis2.u3(math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis2.u3(math.pi/2, -math.pi/2, math.pi/2, qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u1(-2*delta,qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis2.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[1])
# XX
Heis2.u3(-math.pi/2, 0.0, 0.0, qr[0])
Heis2.u3(-math.pi/2, 0.0, 0.0, qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u1(-2*delta,qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u3(math.pi/2, 0.0, 0.0, qr[0])
Heis2.u3(math.pi/2, 0.0, 0.0, qr[1])
# measure
Heis2.measure(qr,cr)
# Run the quantum algorithm
backend = qk.BasicAer.get_backend('qasm_simulator')
job = qk.execute(Heis2, backend, shots=nshots)
result = job.result()
counts = result.get_counts()
# Post processing of outcomes to get sz expectation values
sz1q = 0
sz2q = 0
for key,value in counts.items():
if key == '00':
sz1q += value
sz2q += value
elif key == '01':
sz1q -= value
sz2q += value
elif key == '10':
sz1q += value
sz2q -= value
elif key == '11':
sz1q -= value
sz2q -= value
sz1q_t[k] = sz1q/nshots
sz2q_t[k] = sz2q/nshots
plt.plot(abs(J)*c_times,0.5*sz1_t,'b--')
plt.plot(abs(J)*c_times,0.5*sz2_t,'c')
plt.plot(abs(J)*q_times,0.5*sz1q_t,'rd')
plt.plot(abs(J)*q_times,0.5*sz2q_t,'ko')
plt.legend(['sz1','sz2','sz1q','sz2q'])
plt.xlabel(r'$\delta = |J|t$')
plt.show()
# WARNING: all these cells can take a few minutes to run!
ntrotter = 5
J12 = 1
J23 = 1
c_times = np.linspace(0,math.pi/abs(J12),1000)
q_times = np.linspace(0,math.pi/abs(J12),20)
### Classical simulation of the Heisenberg trimer model
psi0 = np.kron( np.kron( np.array([0,1]), np.array([1,0]) ) , np.array([1,0]) )
# SOLUTION:
#sxsx12 = np.kron(sx, np.kron(sx,idt))
#sysy12 =
#szsz12 =
#sxsx23 =
#sysy23 =
#szsz23 =
#H12 = J12 * ( sxsx12 + sysy12 + szsz12 )
#H23 =
#H = H12 + H23
hide_toggle(for_next=True)
sxsx12 = np.kron(sx, np.kron(sx,idt))
sysy12 = np.kron(sy, np.kron(sy,idt))
szsz12 = np.kron(sz, np.kron(sz,idt))
sxsx23 = np.kron(idt, np.kron(sx,sx))
sysy23 = np.kron(idt, np.kron(sy,sy))
szsz23 = np.kron(idt, np.kron(sz,sz))
H12 = J12 * ( sxsx12 + sysy12 + szsz12 )
H23 = J23 * ( sxsx23 + sysy23 + szsz23 )
H = H12 + H23
sz1_t = np.zeros(len(c_times))
sz2_t = np.zeros(len(c_times))
sz3_t = np.zeros(len(c_times))
sz1 = np.kron(sz, np.kron(idt,idt))
sz2 = np.kron(idt, np.kron(sz,idt))
sz3 = np.kron(idt, np.kron(idt,sz))
#SOLUTION:
#for i in range(len(c_times)):
#t = c_times[i]
#psi_t =
#sz1_t[i] =
#sz2_t[i] =
#sz3_t[i] =
hide_toggle(for_next=True)
for i in range(len(c_times)):
t = c_times[i]
psi_t = expm(-1j*H*t).dot(psi0)
sz1_t[i] = np.real(psi_t.conjugate().transpose().dot(sz1.dot(psi_t)))
sz2_t[i] = np.real(psi_t.conjugate().transpose().dot(sz2.dot(psi_t)))
sz3_t[i] = np.real(psi_t.conjugate().transpose().dot(sz3.dot(psi_t)))
### Classical simulation of the Heisenberg trimer model WITH SUZUKI TROTTER DIGITALIZATION
sz1st_t = np.zeros(len(c_times))
sz2st_t = np.zeros(len(c_times))
sz3st_t = np.zeros(len(c_times))
for i in range(len(c_times)):
t = c_times[i]
Ust = expm(-1j*H23*t/ntrotter).dot(expm(-1j*H12*t/ntrotter))
for j in range(ntrotter-1):
Ust = expm(-1j*H23*t/ntrotter).dot(expm(-1j*H12*t/ntrotter)).dot(Ust)
psi_t = Ust.dot(psi0)
sz1st_t[i] = np.real(psi_t.conjugate().transpose().dot(sz1.dot(psi_t)))
sz2st_t[i] = np.real(psi_t.conjugate().transpose().dot(sz2.dot(psi_t)))
sz3st_t[i] = np.real(psi_t.conjugate().transpose().dot(sz3.dot(psi_t)))
### Digital quantum simulation of the Heisenberg model using qiskit
hide_toggle(for_next=True)
### Digital quantum simulation of the Heisenberg model using qiskit
nshots = 1024
sz1q_t = np.zeros(len(q_times))
sz2q_t = np.zeros(len(q_times))
sz3q_t = np.zeros(len(q_times))
for k in range(len(q_times)):
delta12n = J12*q_times[k]/ntrotter
delta23n = J23*q_times[k]/ntrotter
qr = qk.QuantumRegister(3,name='qr')
cr = qk.ClassicalRegister(3,name='cr')
Heis3 = qk.QuantumCircuit(qr,cr)
# Initial state preparation
Heis3.x(qr[0])
for n in range(ntrotter):
# 1-2 bond mapped on qubits 0 and 1 in the quantum register
# ZZ
Heis3.cx(qr[0],qr[1])
Heis3.u1(-2*delta12n,qr[1])
Heis3.cx(qr[0],qr[1])
# YY
Heis3.u3(math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis3.u3(math.pi/2, -math.pi/2, math.pi/2, qr[1])
Heis3.cx(qr[0],qr[1])
Heis3.u1(-2*delta12n,qr[1])
Heis3.cx(qr[0],qr[1])
Heis3.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis3.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[1])
# XX
Heis3.u3(-math.pi/2, 0.0, 0.0, qr[0])
Heis3.u3(-math.pi/2, 0.0, 0.0, qr[1])
Heis3.cx(qr[0],qr[1])
Heis3.u1(-2*delta12n,qr[1])
Heis3.cx(qr[0],qr[1])
Heis3.u3(math.pi/2, 0.0, 0.0, qr[0])
Heis3.u3(math.pi/2, 0.0, 0.0, qr[1])
# 2-3 bond mapped on qubits 1 and 2 in the quantum register
# ZZ
Heis3.cx(qr[1],qr[2])
Heis3.u1(-2*delta12n,qr[2])
Heis3.cx(qr[1],qr[2])
# YY
Heis3.u3(math.pi/2, -math.pi/2, math.pi/2, qr[1])
Heis3.u3(math.pi/2, -math.pi/2, math.pi/2, qr[2])
Heis3.cx(qr[1],qr[2])
Heis3.u1(-2*delta12n,qr[2])
Heis3.cx(qr[1],qr[2])
Heis3.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[1])
Heis3.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[2])
# XX
Heis3.u3(-math.pi/2, 0.0, 0.0, qr[1])
Heis3.u3(-math.pi/2, 0.0, 0.0, qr[2])
Heis3.cx(qr[1],qr[2])
Heis3.u1(-2*delta12n,qr[2])
Heis3.cx(qr[1],qr[2])
Heis3.u3(math.pi/2, 0.0, 0.0, qr[1])
Heis3.u3(math.pi/2, 0.0, 0.0, qr[2])
# measure
Heis3.measure(qr,cr)
# Run the quantum algorithm
backend = qk.BasicAer.get_backend('qasm_simulator')
job = qk.execute(Heis3, backend, shots=nshots)
result = job.result()
counts = result.get_counts()
# Post processing of outcomes to get sz expectation values
sz1q = 0
sz2q = 0
sz3q = 0
for key,value in counts.items():
if key == '000':
sz1q += value
sz2q += value
sz3q += value
elif key == '001':
sz1q -= value
sz2q += value
sz3q += value
elif key == '010':
sz1q += value
sz2q -= value
sz3q += value
elif key == '011':
sz1q -= value
sz2q -= value
sz3q += value
elif key == '100':
sz1q += value
sz2q += value
sz3q -= value
elif key == '101':
sz1q -= value
sz2q += value
sz3q -= value
elif key == '110':
sz1q += value
sz2q -= value
sz3q -= value
elif key == '111':
sz1q -= value
sz2q -= value
sz3q -= value
sz1q_t[k] = sz1q/nshots
sz2q_t[k] = sz2q/nshots
sz3q_t[k] = sz3q/nshots
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(abs(J12)*c_times,0.5*sz1_t,'b', label='sz1 full')
ax.plot(abs(J12)*c_times,0.5*sz2_t,'r', label='sz2 full')
ax.plot(abs(J12)*c_times,0.5*sz3_t,'g', label='sz3 full')
ax.plot(abs(J12)*c_times,0.5*sz1st_t,'b--',label='sz1 n = ' + str(ntrotter) + ' (classical)')
ax.plot(abs(J12)*c_times,0.5*sz2st_t,'r--', label='sz2 n = ' + str(ntrotter) + ' (classical)')
ax.plot(abs(J12)*c_times,0.5*sz3st_t,'g--', label='sz3 n = ' + str(ntrotter) + ' (classical)')
ax.plot(abs(J12)*q_times,0.5*sz1q_t,'b*',label='sz1 n = ' + str(ntrotter) + ' (quantum)')
ax.plot(abs(J12)*q_times,0.5*sz2q_t,'ro', label='sz2 n = ' + str(ntrotter) + ' (quantum)')
ax.plot(abs(J12)*q_times,0.5*sz3q_t,'gd', label='sz3 n = ' + str(ntrotter) + ' (quantum)')
chartBox = ax.get_position()
ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*1, chartBox.height])
ax.legend(loc='upper center', bbox_to_anchor=(1.3, 0.8), shadow=True, ncol=1)
plt.xlabel(r'$\delta_{12} = |J_{12}|t$')
plt.show()
Heis3.count_ops()
import Qconfig
from qiskit.tools.monitor import job_monitor
qk.IBMQ.enable_account(Qconfig.APItoken, **Qconfig.config)
delta = 0.5*math.pi
qr = qk.QuantumRegister(2,name='qr')
cr = qk.ClassicalRegister(2,name='cr')
Heis2 = qk.QuantumCircuit(qr,cr)
# Initial state preparation
Heis2.x(qr[0])
# ZZ
Heis2.cx(qr[0],qr[1])
Heis2.u1(-2*delta,qr[1])
Heis2.cx(qr[0],qr[1])
# YY
Heis2.u3(math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis2.u3(math.pi/2, -math.pi/2, math.pi/2, qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u1(-2*delta,qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis2.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[1])
# XX
Heis2.u3(-math.pi/2, 0.0, 0.0, qr[0])
Heis2.u3(-math.pi/2, 0.0, 0.0, qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u1(-2*delta,qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u3(math.pi/2, 0.0, 0.0, qr[0])
Heis2.u3(math.pi/2, 0.0, 0.0, qr[1])
# measure
Heis2.measure(qr,cr)
my_backend = qk.IBMQ.get_backend('ibmqx4')
job = qk.execute(Heis2, backend=my_backend, shots=1024)
job_monitor(job, interval=5)
result = job.result()
counts = result.get_counts()
print(counts)
plot_histogram(counts)
my_backend.configuration().coupling_map # In the output, the first entry in a pair [a,b] is a control, second is the
# corresponding target for a CNOT
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
from qiskit import QuantumCircuit, Aer, execute, IBMQ
from qiskit.utils import QuantumInstance
import numpy as np
from qiskit.algorithms import Shor
IBMQ.enable_account('ENTER API TOKEN HERE') # Enter your API token here
provider = IBMQ.get_provider(hub='ibm-q')
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1000)
my_shor = Shor(quantum_instance)
result_dict = my_shor.factor(15)
print(result_dict)
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
from hide_toggle import hide_toggle
#usage:
#1 create a cell with: hide_toggle(for_next=True)
#2 put the commented solution in the next cell
#import latex
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, BasicAer
import numpy as np
%matplotlib inline
#define a 2 qubit register and QuantumCircuit
hide_toggle(for_next=True)
# 2 bit registry creation.
#qr = QuantumRegister(2, 'qr')
# Circuit creation
#qc = QuantumCircuit(qr)
#solution:
#had_tr = QuantumCircuit(qr)
hide_toggle(for_next=True)
# Circuit creation of the Hadamard Transform
#had_tr = QuantumCircuit(qr)
#had_tr.h(qr[0])
#had_tr.h(qr[1])
#had_tr.barrier()
#qc = had_tr
#qc.draw(output='mpl')
#run the circuit on statevector_simulator, save result to state_superposition variable
hide_toggle(for_next=True)
# execute the quantum circuit on simulator
#backend = BasicAer.get_backend('statevector_simulator')
#job = execute(qc, backend)
#state_superposition = job.result().get_statevector(qc)
#print(state_superposition)
from qiskit.tools.visualization import plot_bloch_multivector
rho_superposition= np.outer(state_superposition, state_superposition.conj())
plot_bloch_multivector(rho_superposition)
print("\n\n\n\n===== Welcome! =====\n\n")
print(" ~~ Let's take this test ~~ ")
print("\n\n")
print("Select the winner among:")
print("a) Hearts")
print("b) Pictures")
print("c) Flowers")
print("d) Spades")
chosen = 0
while (chosen==0):
# scelta = getpass.getpass("make your choise. (a, b, c, d, e or f)\n")
scelta = input("Choose your card (a, b, c, d)\n")
if scelta == "a":
bit = "|00>"
print("Choice: a) Hearts")
if scelta == "b":
bit = "|01>"
print("Choice: b) Pictures")
if scelta == "c":
bit = "|10>"
print("Choice: c) Flowers")
if scelta == "d":
bit = "|11>"
print("Choice: d) Spades")
if scelta in ["a","b","c","d"]:
chosen = 1
print ("Linked to:", bit)
else:
print("wrong selection, retry")
#create the circuit orac
#orac = QuantumCircuit(qr)
hide_toggle(for_next=True)
#orac = QuantumCircuit(qr)
#orac.h(qr[1])
#orac.cx(qr[0],qr[1])
#orac.h(qr[1])
#orac.barrier()
#orac.draw(output='mpl')
# The Qiskit circuit object supports concatenating circuits with the addition operator.
qc = had_tr + orac
qc.draw(output='mpl')
orac = QuantumCircuit(qr)
if scelta == "a": # |00>
orac.x(qr[0])
orac.x(qr[1])
orac.h(qr[1])
orac.cx(qr[0],qr[1])
orac.h(qr[1])
orac.x(qr[0])
orac.x(qr[1])
orac.barrier()
if scelta == "b": # |01>
orac.x(qr[1])
orac.h(qr[1])
orac.cx(qr[0],qr[1])
orac.h(qr[1])
orac.x(qr[1])
orac.barrier()
if scelta == "c": # |10>
orac.x(qr[0])
orac.h(qr[1])
orac.cx(qr[0],qr[1])
orac.h(qr[1])
orac.x(qr[0])
orac.barrier()
if scelta == "d": # |11>
orac.h(qr[1])
orac.cx(qr[0],qr[1])
orac.h(qr[1])
orac.barrier()
orac.draw(output='mpl')
qc = had_tr
qc.draw(output='mpl')
backend = BasicAer.get_backend('statevector_simulator')
job = execute(qc, backend)
state = job.result().get_statevector(qc)
state
qc = had_tr + orac
qc.draw(output='mpl')
job = execute(qc, backend)
state = job.result().get_statevector(qc)
state
cphase = QuantumCircuit(qr)
cphase.x(qr[0])
cphase.x(qr[1])
cphase.h(qr[1])
cphase.cx(qr[0],qr[1])
cphase.h(qr[1])
cphase.x(qr[0])
cphase.x(qr[1])
cphase.barrier()
qc = cphase
qc.draw(output='mpl')
qc = had_tr + orac + had_tr + cphase + had_tr
qc.draw(output='mpl')
#solution:
#add classical bit register and meas, draw the circuit
hide_toggle(for_next=True)
# Create a Classical Register with 2 bits.
#cr = ClassicalRegister(2, 'cr')
# Create a Quantum Circuit
#meas = QuantumCircuit(qr, cr)
# add measurement operators
#meas.measure(qr,cr)
#qc = had_tr + orac + had_tr + cphase + had_tr + meas
#drawing the circuit
#qc.draw(output='mpl')
#solution:
#from qiskit import BasicAer
#...
#...
#print("Results : ", counts)
hide_toggle(for_next=True)
# Import Aer
#from qiskit import BasicAer
# Use Aer's qasm_simulator
#backend_sim = BasicAer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator.
# We've set the number of repeats of the circuit
# to be 1024, which is the default.
#job = execute(qc, backend_sim)
# Grab the results from the job.
#result = job.result()
#counts = result.get_counts(qc)
#print("Results : ", counts)
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)
#1
from qiskit import IBMQ
#IBMQ.delete_accounts()
#IBMQ.save_account('API_TOKEN')
#2
provider = IBMQ.load_account()
#3
#solution:
hide_toggle(for_next=True)
#3
#print("Available backends:")
#provider.backends()
#from qiskit.tools.monitor import job_monitor, backend_monitor, backend_overview
#from qiskit.providers.ibmq import least_busy
#backend = least_busy(provider.backends(filters=lambda x: not x.configuration().simulator))
#backend.name()
#shots = 1024 # Number of shots to run the program (experiment); maximum is 8192 shots.
#max_credits = 3 # Maximum number of credits to spend on executions.
#job_exp = execute(qc, backend=backend, shots=shots, max_credits=max_credits)
#job_monitor(job_exp)
#result_real = job_exp.result()
#counts_real = result_real.get_counts(qc)
plot_histogram(counts_real)
#formulate the classical solution
hide_toggle(for_next=True)
#counter=0
#for i in ["a","b","c","d"]:
#counter=counter+1
#if i == scelta:
#print("winner found after ", counter)
import webbrowser
url_1target = 'https://www.nature.com/articles/s41467-017-01904-7/tables/1'
url_2target = 'https://www.nature.com/articles/s41467-017-01904-7/tables/2'
webbrowser.open(url_1target)
webbrowser.open(url_2target)
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
#initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
def phase_oracle(circuit, register):
circuit.cz(qr[2],qr[0])
circuit.cz(qr[2],qr[1])
def n_controlled_Z(circuit, controls, target):
"""Implement a Z gate with multiple controls"""
if (len(controls) > 2):
raise ValueError('The controlled Z with more than 2 controls is not implemented')
elif (len(controls) == 1):
circuit.h(target)
circuit.cx(controls[0], target)
circuit.h(target)
elif (len(controls) == 2):
circuit.h(target)
circuit.ccx(controls[0], controls[1], target)
circuit.h(target)
def inversion_about_average(circuit, register, n, barriers):
"""Apply inversion about the average step of Grover's algorithm."""
circuit.h(register)
circuit.x(register)
if barriers:
circuit.barrier()
n_controlled_Z(circuit, [register[j] for j in range(n-1)], register[n-1])
if barriers:
circuit.barrier()
circuit.x(register)
circuit.h(register)
barriers = True
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
groverCircuit = QuantumCircuit(qr,cr)
groverCircuit.h(qr)
if barriers:
groverCircuit.barrier()
phase_oracle(groverCircuit, qr)
if barriers:
groverCircuit.barrier()
inversion_about_average(groverCircuit, qr, 3, barriers)
if barriers:
groverCircuit.barrier()
groverCircuit.measure(qr,cr)
groverCircuit.draw(output="mpl")
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(groverCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# Load our saved IBMQ accounts and get the least busy backend device with less than or equal to 5 qubits
IBMQ.load_account()
IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 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
job = execute(groverCircuit, backend=backend, shots=shots)
job_monitor(job, interval = 2)
# Get the results from the computation
results = job.result()
answer = results.get_counts(groverCircuit)
plot_histogram(answer)
import qiskit
qiskit.__qiskit_version__
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
import pylab
import numpy as np
from qiskit import BasicAer
from qiskit.tools.visualization import plot_histogram
from qiskit.aqua import QuantumInstance
from qiskit.aqua import run_algorithm
from qiskit.aqua.algorithms import Grover
from qiskit.aqua.components.oracles import LogicalExpressionOracle, TruthTableOracle
input_3sat_instance = '''
c example DIMACS-CNF 3-SAT
p cnf 3 5
-1 -2 -3 0
1 -2 3 0
1 2 -3 0
1 -2 -3 0
-1 2 3 0
'''
oracle = LogicalExpressionOracle(input_3sat_instance)
grover = Grover(oracle)
backend = BasicAer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1024)
result = grover.run(quantum_instance)
print(result['result'])
plot_histogram(result['measurement'])
params = {
'problem': {
'name': 'search',
},
'algorithm': {
'name': 'Grover'
},
'oracle': {
'name': 'LogicalExpressionOracle',
'expression': input_3sat_instance
},
'backend': {
'shots': 1000,
},
}
result_dict = run_algorithm(params, backend=backend)
plot_histogram(result_dict['measurement'])
expression = '(w ^ x) & ~(y ^ z) & (x & y & z)'
oracle = LogicalExpressionOracle(expression)
grover = Grover(oracle)
result = grover.run(QuantumInstance(BasicAer.get_backend('qasm_simulator'), shots=1024))
plot_histogram(result['measurement'])
truthtable = '1000000000000001'
oracle = TruthTableOracle(truthtable)
grover = Grover(oracle)
result = grover.run(QuantumInstance(BasicAer.get_backend('qasm_simulator'), shots=1024))
plot_histogram(result['measurement'])
#solution
from hide_toggle import hide_toggle
hide_toggle(for_next=True)
sat_cnf = '''
c prova.cnf
c
p cnf 2 2
1 -2 0
-1 2 0
'''
#print(sat_cnf)
#oracle_2 = LogicalExpressionOracle(sat_cnf)
#my_grover = Grover(oracle_2)
#backend = BasicAer.get_backend('qasm_simulator')
#quantum_grover = QuantumInstance(backend, shots=1024)
#result = grover.run(quantum_grover)
#print(result['result'])
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
from hide_toggle import hide_toggle
#usage:
#1 create a cell with: hide_toggle(for_next=True)
#2 put the commented solution in the next cell
import qiskit as qk
import numpy as np
from scipy.linalg import expm
import matplotlib.pyplot as plt
import math
# definition of single qubit operators
sx = np.array([[0.0, 1.0],[1.0, 0.0]])
sy = np.array([[0.0, -1.0*1j],[1.0*1j, 0.0]])
sz = np.array([[1.0, 0.0],[0.0, -1.0]])
idt = np.array([[1.0, 0.0],[0.0, 1.0]])
psi0 = np.array([1.0, 0.0])
thetas = np.linspace(0,4*math.pi,200)
avg_sx_tot = np.zeros(len(thetas))
for i in range(len(thetas)):
psi_theta = expm(-1j*0.5*thetas[i]*(sx+sz)/math.sqrt(2)).dot(psi0)
avg_sx_tot[i] = np.real(psi_theta.conjugate().transpose().dot(sx.dot(psi_theta)))
plt.plot(thetas,avg_sx_tot)
plt.xlabel(r'$\theta$')
plt.ylabel(r'$\langle\sigma_x\rangle_\theta$')
plt.show()
#solution
hide_toggle(for_next=True)
#avg_sx_zx = np.zeros(len(thetas))
#avg_sx_xz = np.zeros(len(thetas))
#for i in range(len(thetas)):
# psi_theta_zx = expm(-1j*0.5*thetas[i]*(sz)/math.sqrt(2)).dot(expm(-1j*0.5*thetas[i]*(sx)/math.sqrt(2)).dot(psi0))
# psi_theta_xz = expm(-1j*0.5*thetas[i]*(sx)/math.sqrt(2)).dot(expm(-1j*0.5*thetas[i]*(sz)/math.sqrt(2)).dot(psi0))
# avg_sx_zx[i] = np.real(psi_theta_zx.conjugate().transpose().dot(sx.dot(psi_theta_zx)))
#avg_sx_xz[i] = np.real(psi_theta_xz.conjugate().transpose().dot(sx.dot(psi_theta_xz)))
#plt.plot(thetas,avg_sx_tot)
#plt.plot(thetas,avg_sx_zx)
#plt.plot(thetas,avg_sx_xz)
#plt.xlabel(r'$\theta$')
#plt.ylabel(r'$\langle\sigma_x\rangle_\theta$')
#plt.legend(['Around x = z', 'x first', 'z first'],loc=1)
#plt.show()
# Try this with e.g. ntrot = 1, 5, 10, 50.
# You can also try to do sx and sz slices in the reverse order: both choices will become good approximations for large n
ntrot = 10
avg_sx_n = np.zeros(len(thetas))
for i in range(len(thetas)):
rot = expm(-1j*0.5*thetas[i]*(sx)/(ntrot*math.sqrt(2))).dot(expm(-1j*0.5*thetas[i]*(sz)/(ntrot*math.sqrt(2))))
for j in range(ntrot-1):
rot = expm(-1j*0.5*thetas[i]*(sx)/(ntrot*math.sqrt(2))).dot(expm(-1j*0.5*thetas[i]*(sz)/(ntrot*math.sqrt(2)))).dot(rot)
psi_theta_n = rot.dot(psi0)
avg_sx_n[i] = np.real(psi_theta_n.conjugate().transpose().dot(sx.dot(psi_theta_n)))
plt.plot(thetas,avg_sx_tot)
plt.plot(thetas,avg_sx_n,'--')
plt.xlabel(r'$\theta$')
plt.ylabel(r'$\langle\sigma_x\rangle_\theta$')
plt.legend(['Exact', 'ntrot = ' + str(ntrot)],loc=1)
plt.show()
#solution
hide_toggle(for_next=True)
# commutation function
#def comm_check(a,b):
# aa = np.dot(a,a)
# bb = np.dot(b,b)
# return (np.dot(aa,bb) - np.dot(bb,aa))
#comm_check(sx,sy)
delta = 0.1
qr = qk.QuantumRegister(2,name='qr')
zz_example = qk.QuantumCircuit(qr)
zz_example.cx(qr[0],qr[1])
zz_example.u1(2*delta,qr[1])
zz_example.cx(qr[0],qr[1])
zz_example.draw(output='mpl')
#solution
J = 1
c_times = np.linspace(0,0.5*math.pi/abs(J),1000)
q_times = np.linspace(0,0.5*math.pi/abs(J),10)
### Classical simulation of the Heisenberg dimer model
psi0 = np.kron( np.array([0,1]), np.array([1,0]) )
H = J * ( np.kron(sx,sx) + np.kron(sy,sy) + np.kron(sz,sz) )
sz1_t = np.zeros(len(c_times))
sz2_t = np.zeros(len(c_times))
sz1 = np.kron(sz,idt)
sz2 = np.kron(idt,sz)
for i in range(len(c_times)):
t = c_times[i]
psi_t = expm(-1j*H*t).dot(psi0)
sz1_t[i] = np.real(psi_t.conjugate().transpose().dot(sz1.dot(psi_t)))
sz2_t[i] = np.real(psi_t.conjugate().transpose().dot(sz2.dot(psi_t)))
### Digital quantum simulation of the Heisenberg dimer model using qiskit
nshots = 1024
sz1q_t = np.zeros(len(q_times))
sz2q_t = np.zeros(len(q_times))
#Solution: try to write the circuit and the quantum evolution,
#hints: start with:
#for k in range(len(q_times)):
#delta =
#define QuantumRegister, ClassicalRegister and QuantumCircuit (Heis2)
#define initial state
#define each part of the circuit: ZZ, YY, XX
#measurement
# Post processing of outcomes to get sz expectation values
#sz1q = 0
#sz2q = 0
#for key,value in counts.items():
#if key == '00':
#sz1q += value
#sz2q += value
#elif key == '01':
#sz1q -= value
#sz2q += value
#elif key == '10':
#sz1q += value
#sz2q -= value
#elif key == '11':
#sz1q -= value
#sz2q -= value
#sz1q_t[k] = sz1q/nshots
#sz2q_t[k] = sz2q/nshots
# Run the quantum algorithm and colect the result, counts
hide_toggle(for_next=True)
#for k in range(len(q_times)):
#delta = J*q_times[k]
#qr = qk.QuantumRegister(2,name='qr')
#cr = qk.ClassicalRegister(2,name='cr')
#Heis2 = qk.QuantumCircuit(qr,cr)
# Initial state preparation
#Heis2.x(qr[0])
# ZZ
#Heis2.cx(qr[0],qr[1])
#Heis2.u1(-2*delta,qr[1])
#Heis2.cx(qr[0],qr[1])
# YY
#Heis2.u3(math.pi/2, -math.pi/2, math.pi/2, qr[0])
#Heis2.u3(math.pi/2, -math.pi/2, math.pi/2, qr[1])
#Heis2.cx(qr[0],qr[1])
#Heis2.u1(-2*delta,qr[1])
#Heis2.cx(qr[0],qr[1])
#Heis2.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[0])
#Heis2.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[1])
# XX
#Heis2.u3(-math.pi/2, 0.0, 0.0, qr[0])
#Heis2.u3(-math.pi/2, 0.0, 0.0, qr[1])
#Heis2.cx(qr[0],qr[1])
#Heis2.u1(-2*delta,qr[1])
#Heis2.cx(qr[0],qr[1])
#Heis2.u3(math.pi/2, 0.0, 0.0, qr[0])
#Heis2.u3(math.pi/2, 0.0, 0.0, qr[1])
# measure
#Heis2.measure(qr,cr)
# Post processing of outcomes to get sz expectation values
#sz1q = 0
#sz2q = 0
#for key,value in counts.items():
#if key == '00':
#sz1q += value
#sz2q += value
#elif key == '01':
#sz1q -= value
#sz2q += value
#elif key == '10':
#sz1q += value
#sz2q -= value
#elif key == '11':
#sz1q -= value
#sz2q -= value
#sz1q_t[k] = sz1q/nshots
#sz2q_t[k] = sz2q/nshots
# Run the quantum algorithm
#backend = qk.BasicAer.get_backend('qasm_simulator')
#job = qk.execute(Heis2, backend, shots=nshots)
#result = job.result()
#counts = result.get_counts()
plt.plot(abs(J)*c_times,0.5*sz1_t,'b--')
plt.plot(abs(J)*c_times,0.5*sz2_t,'c')
plt.plot(abs(J)*q_times,0.5*sz1q_t,'rd')
plt.plot(abs(J)*q_times,0.5*sz2q_t,'ko')
plt.legend(['sz1','sz2','sz1q','sz2q'])
plt.xlabel(r'$\delta = |J|t$')
plt.show()
# WARNING: all these cells can take a few minutes to run!
ntrotter = 5
J12 = 1
J23 = 1
c_times = np.linspace(0,math.pi/abs(J12),1000)
q_times = np.linspace(0,math.pi/abs(J12),20)
### Classical simulation of the Heisenberg trimer model
psi0 = np.kron( np.kron( np.array([0,1]), np.array([1,0]) ) , np.array([1,0]) )
# SOLUTION:
#sxsx12 = np.kron(sx, np.kron(sx,idt))
#sysy12 =
#szsz12 =
#sxsx23 =
#sysy23 =
#szsz23 =
#H12 = J12 * ( sxsx12 + sysy12 + szsz12 )
#H23 =
#H = H12 + H23
hide_toggle(for_next=True)
#sxsx12 = np.kron(sx, np.kron(sx,idt))
#sysy12 = np.kron(sy, np.kron(sy,idt))
#szsz12 = np.kron(sz, np.kron(sz,idt))
#sxsx23 = np.kron(idt, np.kron(sx,sx))
#sysy23 = np.kron(idt, np.kron(sy,sy))
#szsz23 = np.kron(idt, np.kron(sz,sz))
#H12 = J12 * ( sxsx12 + sysy12 + szsz12 )
#H23 = J23 * ( sxsx23 + sysy23 + szsz23 )
#H = H12 + H23
sz1_t = np.zeros(len(c_times))
sz2_t = np.zeros(len(c_times))
sz3_t = np.zeros(len(c_times))
sz1 = np.kron(sz, np.kron(idt,idt))
sz2 = np.kron(idt, np.kron(sz,idt))
sz3 = np.kron(idt, np.kron(idt,sz))
#SOLUTION:
#for i in range(len(c_times)):
#t = c_times[i]
#psi_t =
#sz1_t[i] =
#sz2_t[i] =
#sz3_t[i] =
hide_toggle(for_next=True)
#for i in range(len(c_times)):
#t = c_times[i]
#psi_t = expm(-1j*H*t).dot(psi0)
#sz1_t[i] = np.real(psi_t.conjugate().transpose().dot(sz1.dot(psi_t)))
#sz2_t[i] = np.real(psi_t.conjugate().transpose().dot(sz2.dot(psi_t)))
#sz3_t[i] = np.real(psi_t.conjugate().transpose().dot(sz3.dot(psi_t)))
### Classical simulation of the Heisenberg trimer model WITH SUZUKI TROTTER DIGITALIZATION
sz1st_t = np.zeros(len(c_times))
sz2st_t = np.zeros(len(c_times))
sz3st_t = np.zeros(len(c_times))
for i in range(len(c_times)):
t = c_times[i]
Ust = expm(-1j*H23*t/ntrotter).dot(expm(-1j*H12*t/ntrotter))
for j in range(ntrotter-1):
Ust = expm(-1j*H23*t/ntrotter).dot(expm(-1j*H12*t/ntrotter)).dot(Ust)
psi_t = Ust.dot(psi0)
sz1st_t[i] = np.real(psi_t.conjugate().transpose().dot(sz1.dot(psi_t)))
sz2st_t[i] = np.real(psi_t.conjugate().transpose().dot(sz2.dot(psi_t)))
sz3st_t[i] = np.real(psi_t.conjugate().transpose().dot(sz3.dot(psi_t)))
### Digital quantum simulation of the Heisenberg model using qiskit
hide_toggle(for_next=True)
### Digital quantum simulation of the Heisenberg model using qiskit
nshots = 1024
sz1q_t = np.zeros(len(q_times))
sz2q_t = np.zeros(len(q_times))
sz3q_t = np.zeros(len(q_times))
for k in range(len(q_times)):
delta12n = J12*q_times[k]/ntrotter
delta23n = J23*q_times[k]/ntrotter
qr = qk.QuantumRegister(3,name='qr')
cr = qk.ClassicalRegister(3,name='cr')
Heis3 = qk.QuantumCircuit(qr,cr)
# Initial state preparation
Heis3.x(qr[0])
for n in range(ntrotter):
# 1-2 bond mapped on qubits 0 and 1 in the quantum register
# ZZ
Heis3.cx(qr[0],qr[1])
Heis3.u1(-2*delta12n,qr[1])
Heis3.cx(qr[0],qr[1])
# YY
Heis3.u3(math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis3.u3(math.pi/2, -math.pi/2, math.pi/2, qr[1])
Heis3.cx(qr[0],qr[1])
Heis3.u1(-2*delta12n,qr[1])
Heis3.cx(qr[0],qr[1])
Heis3.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis3.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[1])
# XX
Heis3.u3(-math.pi/2, 0.0, 0.0, qr[0])
Heis3.u3(-math.pi/2, 0.0, 0.0, qr[1])
Heis3.cx(qr[0],qr[1])
Heis3.u1(-2*delta12n,qr[1])
Heis3.cx(qr[0],qr[1])
Heis3.u3(math.pi/2, 0.0, 0.0, qr[0])
Heis3.u3(math.pi/2, 0.0, 0.0, qr[1])
# 2-3 bond mapped on qubits 1 and 2 in the quantum register
# ZZ
Heis3.cx(qr[1],qr[2])
Heis3.u1(-2*delta12n,qr[2])
Heis3.cx(qr[1],qr[2])
# YY
Heis3.u3(math.pi/2, -math.pi/2, math.pi/2, qr[1])
Heis3.u3(math.pi/2, -math.pi/2, math.pi/2, qr[2])
Heis3.cx(qr[1],qr[2])
Heis3.u1(-2*delta12n,qr[2])
Heis3.cx(qr[1],qr[2])
Heis3.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[1])
Heis3.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[2])
# XX
Heis3.u3(-math.pi/2, 0.0, 0.0, qr[1])
Heis3.u3(-math.pi/2, 0.0, 0.0, qr[2])
Heis3.cx(qr[1],qr[2])
Heis3.u1(-2*delta12n,qr[2])
Heis3.cx(qr[1],qr[2])
Heis3.u3(math.pi/2, 0.0, 0.0, qr[1])
Heis3.u3(math.pi/2, 0.0, 0.0, qr[2])
# measure
Heis3.measure(qr,cr)
# Run the quantum algorithm
backend = qk.BasicAer.get_backend('qasm_simulator')
job = qk.execute(Heis3, backend, shots=nshots)
result = job.result()
counts = result.get_counts()
# Post processing of outcomes to get sz expectation values
sz1q = 0
sz2q = 0
sz3q = 0
for key,value in counts.items():
if key == '000':
sz1q += value
sz2q += value
sz3q += value
elif key == '001':
sz1q -= value
sz2q += value
sz3q += value
elif key == '010':
sz1q += value
sz2q -= value
sz3q += value
elif key == '011':
sz1q -= value
sz2q -= value
sz3q += value
elif key == '100':
sz1q += value
sz2q += value
sz3q -= value
elif key == '101':
sz1q -= value
sz2q += value
sz3q -= value
elif key == '110':
sz1q += value
sz2q -= value
sz3q -= value
elif key == '111':
sz1q -= value
sz2q -= value
sz3q -= value
sz1q_t[k] = sz1q/nshots
sz2q_t[k] = sz2q/nshots
sz3q_t[k] = sz3q/nshots
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(abs(J12)*c_times,0.5*sz1_t,'b', label='sz1 full')
ax.plot(abs(J12)*c_times,0.5*sz2_t,'r', label='sz2 full')
ax.plot(abs(J12)*c_times,0.5*sz3_t,'g', label='sz3 full')
ax.plot(abs(J12)*c_times,0.5*sz1st_t,'b--',label='sz1 n = ' + str(ntrotter) + ' (classical)')
ax.plot(abs(J12)*c_times,0.5*sz2st_t,'r--', label='sz2 n = ' + str(ntrotter) + ' (classical)')
ax.plot(abs(J12)*c_times,0.5*sz3st_t,'g--', label='sz3 n = ' + str(ntrotter) + ' (classical)')
ax.plot(abs(J12)*q_times,0.5*sz1q_t,'b*',label='sz1 n = ' + str(ntrotter) + ' (quantum)')
ax.plot(abs(J12)*q_times,0.5*sz2q_t,'ro', label='sz2 n = ' + str(ntrotter) + ' (quantum)')
ax.plot(abs(J12)*q_times,0.5*sz3q_t,'gd', label='sz3 n = ' + str(ntrotter) + ' (quantum)')
chartBox = ax.get_position()
ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*1, chartBox.height])
ax.legend(loc='upper center', bbox_to_anchor=(1.3, 0.8), shadow=True, ncol=1)
plt.xlabel(r'$\delta_{12} = |J_{12}|t$')
plt.show()
import Qconfig
from qiskit.tools.monitor import job_monitor
qk.IBMQ.enable_account(Qconfig.APItoken, **Qconfig.config)
delta = 0.5*math.pi
qr = qk.QuantumRegister(2,name='qr')
cr = qk.ClassicalRegister(2,name='cr')
Heis2 = qk.QuantumCircuit(qr,cr)
# Initial state preparation
Heis2.x(qr[0])
# ZZ
Heis2.cx(qr[0],qr[1])
Heis2.u1(-2*delta,qr[1])
Heis2.cx(qr[0],qr[1])
# YY
Heis2.u3(math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis2.u3(math.pi/2, -math.pi/2, math.pi/2, qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u1(-2*delta,qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis2.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[1])
# XX
Heis2.u3(-math.pi/2, 0.0, 0.0, qr[0])
Heis2.u3(-math.pi/2, 0.0, 0.0, qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u1(-2*delta,qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u3(math.pi/2, 0.0, 0.0, qr[0])
Heis2.u3(math.pi/2, 0.0, 0.0, qr[1])
# measure
Heis2.measure(qr,cr)
my_backend = qk.IBMQ.get_backend('ibmqx4')
job = qk.execute(Heis2, backend=my_backend, shots=1024)
job_monitor(job, interval=5)
result = job.result()
counts = result.get_counts()
print(counts)
plot_histogram(counts)
my_backend.configuration().coupling_map # In the output, the first entry in a pair [a,b] is a control, second is the
# corresponding target for a CNOT
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
from IPython.display import IFrame
IFrame("https://www.youtube.com/embed/hOlOY7NyMfs?start=75&end=126",560,315)
# Example of Brute force period finding algorithm
def find_period_classical(x, N):
n = 1
t = x
while t != 1:
t *= x
t %= N
n += 1
return n
N = 4
qrQFT = QuantumRegister(N,'qftr')
QFT = QuantumCircuit(qrQFT)
for i in range(N):
QFT.h(qrQFT[i])
for k in range(i+1,N):
l = k-i+1
QFT.cu1(2*math.pi/(2**l),qrQFT[k],qrQFT[i])
QFT.draw(output='mpl')
import logging
logger = logging.getLogger()
logger.setLevel(logging.CRITICAL)
from qiskit import IBMQ
IBMQ.load_account()
import qiskit
qiskit.__version__
qiskit.__qiskit_version__
from qiskit.aqua.algorithms.quantum_algorithm import QuantumAlgorithm
from qiskit.aqua.algorithms import Shor
from qiskit import Aer
from qiskit.tools.visualization import plot_histogram
backend = Aer.get_backend("qasm_simulator")
logger.setLevel(logging.CRITICAL)
shor = Shor(15,11)
result = shor.run(backend)
result
circuit = shor.construct_circuit(measurement=True)
print(qiskit.aqua.utils.summarize_circuits(circuit))
circuit.draw()
cloud_backend = IBMQ.get_provider(group='open').get_backend('ibmq_qasm_simulator')
cloud_backend
execution = qiskit.execute(circuit,cloud_backend)
plot_histogram(execution.result().get_counts())
print('i(M/r)= 10000000=', int('10000000',2), ' M=', pow(2,8), ' r/i=', pow(2,8)/int('10000000',2), ' (i=1)')
logger.setLevel(logging.DEBUG)
counts = execution.result().get_counts()
for output_desired in list(counts.keys()):
# Get the x_value from the final state qubits
success = shor._get_factors(output_desired, int(2 * shor._n))
if success:
logger.info('Found factors {} from measurement {}.\n'.format(
shor._ret['results'][output_desired], output_desired
))
else:
logger.info('Cannot find factors from measurement {} because {}\n'.format(
output_desired, shor._ret['results'][output_desired]
))
logger.setLevel(logging.CRITICAL)
shor = Shor(15,7)
result = shor.run(backend)
result
circuit = shor.construct_circuit(measurement=True)
print(qiskit.aqua.utils.summarize_circuits(circuit))
circuit.draw()
execution = qiskit.execute(circuit,backend)
plot_histogram(execution.result().get_counts())
print('i(M/r)= 01000000=', int('01000000',2), ' M=', pow(2,8), ' r/i=', pow(2,8)/int('01000000',2), ' (i=1)')
print('i(M/r)= 10000000=', int('10000000',2), ' M=', pow(2,8), ' r/i=', pow(2,8)/int('10000000',2), ' (i=2)')
print('i(M/r)= 11000000=', int('11000000',2), ' M=', pow(2,8), ' r/i=', pow(2,8)/int('11000000',2), ' (i=3)')
logger.setLevel(logging.DEBUG)
counts = execution.result().get_counts()
for output_desired in list(counts.keys()):
# Get the x_value from the final state qubits
success = shor._get_factors(output_desired, int(2 * shor._n))
if success:
logger.info('Found factors {} from measurement {}.\n'.format(
shor._ret['results'][output_desired], output_desired
))
else:
logger.info('Cannot find factors from measurement {} because {}\n'.format(
output_desired, shor._ret['results'][output_desired]
))
|
https://github.com/ichen17/Learning-Qiskit
|
ichen17
|
from qiskit import *
from qiskit.tools.visualization import plot_histogram
%matplotlib inline
secretnumber = '11100011'
circuit = QuantumCircuit(len(secretnumber)+1,len(secretnumber))
circuit.h(range(len(secretnumber)))
circuit.x(len(secretnumber))
circuit.h(len(secretnumber))
circuit.barrier()
for ii, yesno in enumerate(reversed(secretnumber)):
if yesno == '1':
circuit.cx(ii,len(secretnumber))
circuit.barrier()
circuit.h(range(len(secretnumber)))
circuit.barrier()
circuit.measure(range(len(secretnumber)),range(len(secretnumber)))
circuit.draw(output = 'mpl')
|
https://github.com/ichen17/Learning-Qiskit
|
ichen17
|
from qiskit import *
from qiskit.tools.jupyter import *
from qiskit import pulse
from qiskit import IBMQ
from qiskit.ignis.mitigation.measurement import (complete_meas_cal, tensored_meas_cal,
CompleteMeasFitter, TensoredMeasFitter)
IBMQ.save_account("26595118309e0ea848015d3f7458b040ec723a9c11afd2d777038533a5a2b8079312af1e3713e370053f85bf7dd5d77f72993b0f04c2cd561e4c31f5a40c910c")
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science')
backend = provider.get_backend('ibmq_rome')
backend_config = backend.configuration()
assert backend_config.open_pulse, "Backend doesn't support Pulse"
dt = backend_config.dt
print(f"Sampling time: {dt*1e9} ns")
backend_defaults = backend.defaults()
import numpy as np
# unit conversion factors -> all backend properties returned in SI (Hz, sec, etc)
GHz = 1.0e9 # Gigahertz
MHz = 1.0e6 # Megahertz
us = 1.0e-6 # Microseconds
ns = 1.0e-9 # Nanoseconds
# We will find the qubit frequency for the following qubit.
#qubit = 0
frequencies_GHzs = []
for qubit in range(5):
# The sweep will be centered around the estimated qubit frequency.
center_frequency_Hz = backend_defaults.qubit_freq_est[qubit] # The default frequency is given in Hz
# warning: this will change in a future release
print(f"Qubit {qubit} has an estimated frequency of {center_frequency_Hz / GHz} GHz.")
# scale factor to remove factors of 10 from the data
scale_factor = 1e-14
# We will sweep 40 MHz around the estimated frequency
frequency_span_Hz = 40 * MHz
# in steps of 1 MHz.
frequency_step_Hz = 1 * MHz
# We will sweep 20 MHz above and 20 MHz below the estimated frequency
frequency_min = center_frequency_Hz - frequency_span_Hz / 2
frequency_max = center_frequency_Hz + frequency_span_Hz / 2
# Construct an np array of the frequencies for our experiment
frequencies_GHz = np.arange(frequency_min / GHz,
frequency_max / GHz,
frequency_step_Hz / GHz)
frequencies_GHzs.append(frequencies_GHz)
print(f"The sweep will go from {frequency_min / GHz} GHz to {frequency_max / GHz} GHz in steps of {frequency_step_Hz / MHz} MHz.")
def get_closest_multiple_of_16(num):
return int(num + 8 ) - (int(num + 8 ) % 16)
from qiskit import pulse # This is where we access all of our Pulse features!
from qiskit.pulse import Play
# This Pulse module helps us build sampled pulses for common pulse shapes
from qiskit.pulse import library as pulse_lib
# Drive pulse parameters (us = microseconds)
#drive_sigma_us = 0.004444
# This determines the actual width of the gaussian
#0.0075
drive_sigma_us = 0.009
drive_samples_us = drive_sigma_us*8 # This is a truncating parameter, because gaussians don't have
# a natural finite length
drive_sigma = get_closest_multiple_of_16(drive_sigma_us * us /dt) # The width of the gaussian in units of dt
drive_samples = get_closest_multiple_of_16(drive_samples_us * us /dt) # The truncating parameter in units of dt
drive_amp = 0.05
# Drive pulse samples
drive_pulse = pulse_lib.gaussian(duration=drive_samples,
sigma=drive_sigma,
amp=drive_amp,
name='freq_sweep_excitation_pulse')
drive_pulse = pulse_lib.gaussian(duration=drive_samples,
sigma=drive_sigma,
amp=drive_amp,
name='freq_sweep_excitation_pulse')
drive_sigma
meas_map_idx = None
for i, measure_group in enumerate(backend_config.meas_map):
if qubit in measure_group:
meas_map_idx = i
break
assert meas_map_idx is not None, f"Couldn't find qubit {qubit} in the meas_map!"
inst_sched_map = backend_defaults.instruction_schedule_map
measure = inst_sched_map.get('measure', qubits=backend_config.meas_map[meas_map_idx])
drive = []
meas = []
acq = []
for qubit in range(5):
drive_chan = pulse.DriveChannel(qubit)
drive.append(drive_chan)
meas_chan = pulse.MeasureChannel(qubit)
meas.append(meas_chan)
acq_chan = pulse.AcquireChannel(qubit)
acq.append(acq_chan)
schedule = pulse.Schedule(name='Frequency sweep')
schedule_frequencies = []
for i, j in enumerate(drive):
schedule += Play(drive_pulse, j)
# The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration
# Create the frequency settings for the sweep (MUST BE IN HZ)
frequencies_Hz = frequencies_GHzs[i]*GHz
schedule_frequencies += [{j: freq} for freq in frequencies_Hz]
schedule += measure << schedule.duration
schedule.draw(label=True)
from qiskit import assemble
num_shots_per_frequency = 1024
frequency_sweep_program = assemble(schedule,
backend=backend,
meas_level=1,
meas_return='avg',
shots=num_shots_per_frequency,
schedule_los=schedule_frequencies)
job = backend.run(frequency_sweep_program)
from qiskit import pulse
with pulse.build(name='Pulse') as arb:
pulse.play(drive_pulse,
pulse.DriveChannel(0))
arb.draw()
from qiskit.tools.monitor import job_monitor
job_monitor(job)
frequency_sweep_results = job.result(timeout=120)
scale_factor = 1e-7
import matplotlib.pyplot as plt
qubit = 0
sweep_values_total = []
for j in range(5):
sweep_values = []
#for i in range(len(frequency_sweep_results.results)):
for i in range(41*j,41*(j+1)):
# Get the results from the ith experiment
res = frequency_sweep_results.get_memory(i)*scale_factor
# Get the results for `qubit` from this experiment
sweep_values.append(res[j])
#frequency_q= list(frequency_for_qubits[j])*7
print(len(sweep_values))
sweep_values_total.append(sweep_values)
plt.scatter(frequencies_GHzs[j], np.real(sweep_values), color='black') # plot real part of sweep values
plt.xlim([min(frequencies_GHzs[j]), max(frequencies_GHzs[j])])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured signal [a.u.]")
plt.show()
from scipy.optimize import curve_fit
def fit_function(x_values, y_values, function, init_params):
fitparams, conv = curve_fit(function, x_values, y_values, init_params)
y_fit = function(x_values, *fitparams)
return fitparams, y_fit
Q_freq=[]
for i in range(5):
fit_params, y_fit = fit_function(frequencies_GHzs[i],
np.real(np.real(sweep_values_total[i])),
lambda x, A, q_freq, B, C: (A / np.pi) * (B / ((x - q_freq)**2 + B**2)) + C,
[0.02, frequencies_GHzs[i][20], 0.002, -2.17] # initial parameters for curve_fit
)
plt.scatter(frequencies_GHzs[i], np.real(sweep_values_total[i]), color='black')
plt.plot(frequencies_GHzs[i], y_fit, color='red')
plt.xlim([min(frequencies_GHzs[i]), max(frequencies_GHzs[i])])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured Signal [a.u.]")
plt.show()
Q_freq.append(fit_params[1])
Q_freq
num_rabi_points = 50
# Drive amplitude values to iterate over: 50 amplitudes evenly spaced from 0 to 0.75
drive_amp_min = 0
drive_amp_max = 0.20
drive_amps = np.linspace(drive_amp_min, drive_amp_max, num_rabi_points)
rabi_schedules = []
for drive_amp in drive_amps:
rabi_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_amp,
sigma=drive_sigma, name=f"Rabi drive amplitude = {drive_amp}")
this_schedule = pulse.Schedule(name=f"Rabi drive amplitude = {drive_amp}")
this_schedule += Play(rabi_pulse, drive[0])
# Reuse the measure instruction from the frequency sweep experiment
this_schedule += measure << this_schedule.duration
rabi_schedules.append(this_schedule)
rabi_schedules[-1].draw(label=True)
num_shots_per_point = 1024
rabi_experiment_program = assemble(rabi_schedules,
backend=backend,
meas_level=1,
meas_return='avg',
shots=num_shots_per_point,
schedule_los=[{drive_chan: Q_freq[0]*GHz}]
* num_rabi_points)
print(job.job_id())
job = backend.run(rabi_experiment_program)
job_monitor(job)
rabi_results = job.result(timeout=120)
def baseline_remove(values):
return np.array(values) - np.mean(values)
rabi_values = []
for i in range(num_rabi_points):
# Get the results for `qubit` from the ith experiment
rabi_values.append(rabi_results.get_memory(i)[qubit]*scale_factor)
rabi_values = np.real(baseline_remove(rabi_values))
plt.xlabel("Drive amp [a.u.]")
plt.ylabel("Measured signal [a.u.]")
plt.scatter(drive_amps, rabi_values, color='black') # plot real part of Rabi values
plt.show()
fit_params, y_fit = fit_function(drive_amps,
rabi_values,
lambda x, A, B, drive_period, phi: (A*np.cos(2*np.pi*x/drive_period - phi) + B),
[2, 0, 0.2, 0])
plt.scatter(drive_amps, rabi_values, color='black')
plt.plot(drive_amps, y_fit, color='red')
drive_period = fit_params[2] # get period of rabi oscillation
plt.axvline(drive_period/4*3, color='red', linestyle='--')
plt.axvline(drive_period, color='red', linestyle='--')
#plt.annotate("", xy=(drive_period, 0), xytext=(drive_period/2,0), arrowprops=dict(arrowstyle="<->", color='red'))
#plt.annotate("$\pi$", xy=(drive_period/2-0.03, 0.1), color='red')
plt.xlabel("Drive amp [a.u.]", fontsize=15)
plt.ylabel("Measured signal [a.u.]", fontsize=15)
plt.show()
print(fit_params)
fit_params[2]
pi_half_amp = abs(drive_period / 4)
pi_amp= abs(drive_period / 2)
print(f"Square root x (amp.)= {pi_half_amp}")
print(f"Square root x (amp.)= {pi_amp}")
time_max_us = 1.5
time_step_us = 0.025
times_us = np.arange(0.025, time_max_us, time_step_us)
# Convert to units of dt
delay_times_dt = times_us * us / dt
# Drive parameters
# The drive amplitude for pi/2 is simply half the amplitude of the pi pulse
drive_amp = pi_amp / 2
# x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees
x90_pulse = pulse_lib.gaussian(duration=drive_samples,
amp=drive_amp,
sigma=drive_sigma,
name='x90_pulse')
ramsey_schedules = []
for delay in delay_times_dt:
this_schedule = pulse.Schedule(name=f"Ramsey delay = {delay * dt / us} us")
this_schedule |= Play(x90_pulse, drive[0])
this_schedule |= Play(x90_pulse, drive[0]) << int(this_schedule.duration + delay)
this_schedule |= measure << int(this_schedule.duration)
ramsey_schedules.append(this_schedule)
ramsey_schedules[0].draw(label=True)
num_shots = 256
detuning_MHz = -1
ramsey_frequency = round(Q_freq[0]*GHz + detuning_MHz * MHz, 6) # need ramsey freq in Hz
ramsey_program = assemble(ramsey_schedules,
backend=backend,
meas_level=1,
meas_return='avg',
shots=num_shots,
schedule_los=[{drive_chan: ramsey_frequency}]*len(ramsey_schedules)
)
job = backend.run(ramsey_program)
# print(job.job_id())
job_monitor(job)
ramsey_results = job.result(timeout=120)
ramsey_values = []
for i in range(len(times_us)):
ramsey_values.append(ramsey_results.get_memory(i)[0]*scale_factor)
plt.scatter(times_us, np.real(ramsey_values), color='black')
plt.xlim(0, np.max(times_us))
plt.title("Ramsey Experiment", fontsize=15)
plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15)
plt.ylabel('Measured Signal [a.u.]', fontsize=15)
plt.show()
fit_params, y_fit = fit_function(times_us, np.real(ramsey_values),
lambda x, A, del_f_MHz, C, B: (
A* np.cos(2*np.pi*del_f_MHz*x - 0.56) + B*x**(C)
),
[0.15588132, 0.0554278, -0.04492174, 2.21367894]
)
# Off-resonance component
_, del_f_MHz, _, _, = fit_params # freq is MHz since times in us
plt.scatter(times_us, np.real(ramsey_values), color='black')
plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.2f} MHz")
plt.xlim(0, np.max(times_us))
plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15)
plt.ylabel('Measured Signal [a.u.]', fontsize=15)
plt.title('Ramsey Experiment', fontsize=15)
plt.legend()
plt.show()
fit_params
precise_qubit_freq = Q_freq[0]*GHz + (del_f_MHz - detuning_MHz) * MHz # get new freq in Hz
print(f"Our updated qubit frequency is now {round(precise_qubit_freq/GHz, 6)} GHz. "
f"It used to be {round(Q_freq[0]*GHz / GHz, 6)} GHz")
ramsey_results.get_memory(0)
pi_half_pulse = pulse_lib.gaussian(duration=drive_samples,
amp=pi_half_amp,
sigma=drive_sigma,
name='Square root x')
from qiskit import pulse
with pulse.build(name='Square root x') as xrx:
pulse.play(pi_half_pulse,
pulse.DriveChannel(0))
xrx.draw()
def X_circuit1(n=20,qubit=0):
Xcircuit = []
for i in range(n):
xcircuit_z_q0 = QuantumCircuit(5,1)
xcircuit_x_q0 = QuantumCircuit(5,1)
xcircuit_y_q0 = QuantumCircuit(5,1)
for j in range(i):
xcircuit_z_q0.sx(qubit)
xcircuit_z_q0.sx(qubit)
xcircuit_z_q0.barrier()
xcircuit_z_q0.sx(qubit)
xcircuit_z_q0.sx(qubit)
xcircuit_z_q0.barrier()
xcircuit_x_q0.sx(qubit)
xcircuit_x_q0.sx(qubit)
xcircuit_x_q0.barrier()
xcircuit_x_q0.sx(qubit)
xcircuit_x_q0.sx(qubit)
xcircuit_x_q0.barrier()
xcircuit_y_q0.sx(qubit)
xcircuit_y_q0.sx(qubit)
xcircuit_y_q0.barrier()
xcircuit_y_q0.sx(qubit)
xcircuit_y_q0.sx(qubit)
xcircuit_y_q0.barrier()
xcircuit_x_q0.h(qubit)
xcircuit_y_q0.sdg(qubit)
xcircuit_y_q0.h(qubit)
xcircuit_z_q0.measure(qubit,0)
xcircuit_x_q0.measure(qubit,0)
xcircuit_y_q0.measure(qubit,0)
xcircuit_z_q0.add_calibration('sx', [0], xrx)
xcircuit_x_q0.add_calibration('sx', [0], xrx)
xcircuit_y_q0.add_calibration('sx', [0], xrx)
xcircuit_z_q0 = transpile(xcircuit_z_q0, backend)
xcircuit_x_q0 = transpile(xcircuit_x_q0, backend)
xcircuit_y_q0 = transpile(xcircuit_y_q0, backend)
Xcircuit.append(xcircuit_z_q0)
Xcircuit.append(xcircuit_x_q0)
Xcircuit.append(xcircuit_y_q0)
return Xcircuit
q=0
qr = QuantumRegister(5)
qubit_list = [q]
meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list, qr=qr, circlabel='mcal')
circuit_x = X_circuit1(20,0)
reps=2
all_jobs = []
all_jobs_mit = []
for ii in range(reps):
# Run QPT on backend
shots = 8192
il = [0,1,2,3,4]
#job_backend = execute(stabilizer_circuits, Aer.get_backend('qasm_simulator'), shots=shots, initial_layout=il,basis_gates=basis_gates,noise_model=noise_model)
job_backend = execute(circuit_x, backend, shots=shots, initial_layout=il)
#job_mit_backend = execute(meas_cal_circuits, Aer.get_backend('qasm_simulator'), shots=shots, initial_layout=il,basis_gates=basis_gates,noise_model=noise_model)
job_mit_backend = execute(meas_calibs, backend, shots=shots, initial_layout=il)
print('Job IDs ({}/{}): \n measurement calibration: {}\n stabilizer measurements: {}'.format(
ii+1, reps, job_mit_backend.job_id(), job_backend.job_id()))
all_jobs.append(job_backend)
all_jobs_mit.append(job_mit_backend)
for job in all_jobs:
job_monitor(job)
try:
if job.error_message() is not None:
print(job.error_message())
except:
pass
cal_results = all_jobs_mit[1].result()
results = all_jobs[1].result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, qubit_list=qubit_list, circlabel='mcal')
print(meas_fitter.cal_matrix)
meas_fitter.plot_calibration()
from qiskit.tools.visualization import *
import matplotlib.pyplot as plt
import math
import numpy as np
Result_nomit = results.get_counts(0)
mitigated_counts = meas_fitter.filter.apply(results).get_counts(0)
plot_histogram([Result_nomit, mitigated_counts], legend=['raw', 'mitigated'])
(0.719/0.990)**(1/80)
|
https://github.com/ichen17/Learning-Qiskit
|
ichen17
|
# initialization
import numpy as np
import matplotlib
# importing Qiskit
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ, BasicAer, assemble, transpile
from qiskit.quantum_info import Statevector
# import basic plot tools
from qiskit.visualization import plot_bloch_multivector,plot_bloch_vector, plot_histogram
style = {'backgroundcolor': 'lightyellow'} # Style of the circuits
# set the length of the n-bit input string.
n = 3
# set the length of the n-bit input string.
n = 3
const_oracle = QuantumCircuit(n+1)
output = np.random.randint(2)
if output == 1:
const_oracle.x(n)
const_oracle.draw(output='mpl', style=style)
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
balanced_oracle.draw(output='mpl', style=style)
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
balanced_oracle.draw(output='mpl', style=style)
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Show oracle
balanced_oracle.draw(output='mpl', style=style)
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
dj_circuit.draw(output='mpl', style=style)
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit += balanced_oracle
dj_circuit.draw(output='mpl', style=style)
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit += balanced_oracle
# Repeat H-gates
for qubit in range(n):
dj_circuit.h(qubit)
dj_circuit.barrier()
# Measure
for i in range(n):
dj_circuit.measure(i, i)
# Display circuit
dj_circuit.draw(output='mpl', style=style)
# use local simulator
aer_sim = Aer.get_backend('aer_simulator')
qobj = assemble(dj_circuit, aer_sim)
results = aer_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
def dj_oracle(case, n):
# We need to make a QuantumCircuit object to return
# This circuit has n+1 qubits: the size of the input,
# plus one output qubit
oracle_qc = QuantumCircuit(n+1)
# First, let's deal with the case in which oracle is balanced
if case == "balanced":
# First generate a random number that tells us which CNOTs to
# wrap in X-gates:
b = np.random.randint(1,2**n)
print(b)
print(str(n))
b=7
# Next, format 'b' as a binary string of length 'n', padded with zeros:
b_str = format(b, '0'+str(n)+'b')
print(b_str)
# Next, we place the first X-gates. Each digit in our binary string
# corresponds to a qubit, if the digit is 0, we do nothing, if it's 1
# we apply an X-gate to that qubit:
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Do the controlled-NOT gates for each qubit, using the output qubit
# as the target:
for qubit in range(n):
oracle_qc.cx(qubit, n)
# Next, place the final X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Case in which oracle is constant
if case == "constant":
# First decide what the fixed output of the oracle will be
# (either always 0 or always 1)
output = np.random.randint(2)
if output == 1:
oracle_qc.x(n)
oracle_gate = oracle_qc.to_gate()
oracle_gate.name = "Oracle" # To show when we display the circuit
return oracle_gate
def dj_algorithm(oracle, n):
dj_circuit = QuantumCircuit(n+1, n)
# Set up the output qubit:
dj_circuit.x(n)
dj_circuit.h(n)
# And set up the input register:
for qubit in range(n):
dj_circuit.h(qubit)
# Let's append the oracle gate to our circuit:
dj_circuit.append(oracle, range(n+1))
# Finally, perform the H-gates again and measure:
for qubit in range(n):
dj_circuit.h(qubit)
for i in range(n):
dj_circuit.measure(i, i)
return dj_circuit
n = 4
oracle_gate = dj_oracle('balanced', n)
dj_circuit = dj_algorithm(oracle_gate, n)
dj_circuit.draw(output='mpl', style=style)
transpiled_dj_circuit = transpile(dj_circuit, aer_sim)
qobj = assemble(transpiled_dj_circuit)
results = aer_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/ichen17/Learning-Qiskit
|
ichen17
|
pip install pylatexenc
!pip install qiskit
from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.providers.ibmq import least_busy
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_histogram
# Create a Quantum Register called "qr" with 2 qubits.
qr = QuantumRegister(2,'qr')
# Create a Classical Register called "cr" with 2 bits.
cr = ClassicalRegister(2,'cr')
qc = QuantumCircuit(qr,cr)
# Add the H gate in the Qubit 1, putting this qubit in superposition.
qc.h(qr[1])
# Add the CX gate on control qubit 1 and target qubit 0, putting the qubits in a Bell state i.e entanglement
qc.cx(qr[1], qr[0])
# Add a Measure gate to see the state.
qc.measure(qr[0],cr[0])
qc.measure(qr[1],cr[1])
# Compile and execute the Quantum Program in the ibmqx5
qc.draw(output='mpl')
qasm_simulator = Aer.get_backend('qasm_simulator')
shots = 1024
result = results = execute(qc, backend=qasm_simulator, shots=shots).result()
Ans=result.get_counts()
plot_histogram(Ans)
|
https://github.com/ichen17/Learning-Qiskit
|
ichen17
|
# Importing Packages
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, transpile, assemble, QuantumRegister, ClassicalRegister
from qiskit.visualization import plot_histogram
from qiskit_textbook.tools import simon_oracle
bb = input("Enter the input string:\n")
### Using in-built "simon_oracle" from QISKIT
# importing Qiskit
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, transpile, assemble
# import basic plot tools
from qiskit.visualization import plot_histogram
from qiskit_textbook.tools import simon_oracle
n = len(bb)
simon_circuit = QuantumCircuit(n*2, n)
# Apply Hadamard gates before querying the oracle
simon_circuit.h(range(n))
# Apply barrier for visual separation
simon_circuit.barrier()
simon_circuit += simon_oracle(bb)
# Apply barrier for visual separation
simon_circuit.barrier()
# Apply Hadamard gates to the input register
simon_circuit.h(range(n))
# Measure qubits
simon_circuit.measure(range(n), range(n))
simon_circuit.draw(output="mpl")
# use local simulator
aer_sim = Aer.get_backend('aer_simulator')
shots = 500
qobj = assemble(simon_circuit, shots=shots)
results = aer_sim.run(qobj).result()
counts = results.get_counts()
print(counts)
plot_histogram(counts)
# Calculate the dot product of the results
def bdotz(b, z):
accum = 0
for i in range(len(b)):
accum += int(b[i]) * int(z[i])
return (accum % 2)
for z in counts:
print( '{}.{} = {} (mod 2)'.format(b, z, bdotz(b,z)) )
b = input("Enter a binary string:\n")
# Actual b = 011
b_rev = b[::-1]
flagbit = b_rev.find('1')
n=len(b)
q1=QuantumRegister(n,'q1')
q2=QuantumRegister(n,'q2')
c1=ClassicalRegister(n)
qc = QuantumCircuit(q1,q2,c1)
qc.barrier()
qc.h(q1)
qc.barrier()
for i in range(n):
qc.cx(q1[i],q2[i])
qc.barrier()
if flagbit != -1:
# print("test1")
for ind, bit in enumerate(b_rev):
# print("test2")
if bit == "1":
# print("test3")
qc.cx(flagbit, q2[ind])
qc.barrier()
qc.h(q1)
qc.barrier()
qc.measure(q1,c1)
qc.draw("mpl")
aer_sim = Aer.get_backend('aer_simulator')
shots = 500
qobj = assemble(qc, shots=shots)
results = aer_sim.run(qobj).result()
counts = results.get_counts()
print(counts)
plot_histogram(counts)
# Actual b = 011
b="1"
b_rev = "1"
flagbit = b_rev.find('1')
n=len(b)
q1=QuantumRegister(n,'q1')
q2=QuantumRegister(n,'q2')
c1=ClassicalRegister(n)
qc = QuantumCircuit(q1,q2,c1)
qc.barrier()
qc.h(q1)
qc.barrier()
for i in range(n):
qc.cx(q1[i],q2[i])
qc.barrier()
if flagbit != -1:
# print("test1")
for ind, bit in enumerate(b_rev):
# print("test2")
if bit == "1":
# print("test3")
qc.cx(flagbit, q2[ind])
qc.barrier()
qc.h(q1)
qc.barrier()
# qc.measure(q1,c1)
# qc.draw("mpl")
# Simulate the unitary
usim = Aer.get_backend('aer_simulator')
qc.save_unitary()
qobj = assemble(qc)
unitary = usim.run(qobj).result().get_unitary()
# Display the results:
array_to_latex(unitary, prefix="\\text{Circuit = } ")
|
https://github.com/ichen17/Learning-Qiskit
|
ichen17
|
from qiskit import *
import numpy as np
from qiskit.visualization import plot_histogram
qb_Alice = QuantumRegister(1, name='qr') # Alice's qubit
qb_Bob = QuantumRegister(1, name='qr1') # Bob's qubit
Superdense_Code = QuantumCircuit(qb_Alice, qb_Bob)
def buid_Bell_pair(qc,q1,q2): #To build up the a bell pair state
qc.h(q1) #Applying the Hadamard gate on qubit for alice
qc.cx(q1,q2) #Applying the Cnot gate with the control qubit Alice's and target qubit bob's
def operation_from_Alice(qc,q1,classical_info):
if classical_info =='00': #The classical information Alice want to send
return
elif classical_info =='01':#The classical information Alice want to send
qc.z(q1)
elif classical_info =='10':#The classical information Alice want to send
qc.x(q1)
else: #'11': #The classical information Alice want to send
qc.x(q1)
qc.z(q1)
def Bell_decoding(qc,q1,q2): # In this step, Bob get the qubit operated by Alice and another qubit of Bell pair state.
qc.cx(q1,q2) # Bob applies the CNOT gate with the control qubit Alice's and target qubit bob's
qc.h(q1) # Applying the Hadamard gate on qubit for Alice's qubit
classical_info='01' # The classical information Alice wants to send
buid_Bell_pair(Superdense_Code, 0, 1)
Superdense_Code.barrier()
operation_from_Alice(Superdense_Code,0,classical_info)
Superdense_Code.barrier()
Bell_decoding(Superdense_Code,0,1)
Superdense_Code.measure_all() #measure all of qubits
Superdense_Code.draw(output = "mpl")
backend = Aer.get_backend('qasm_simulator')
job_sim = execute(Superdense_Code, backend, shots=10)
sim_result = job_sim.result()
measurement_result = sim_result.get_counts(Superdense_Code)
print(measurement_result)
plot_histogram(measurement_result)
|
https://github.com/ichen17/Learning-Qiskit
|
ichen17
|
from qiskit import *
import numpy as np
from random import random
from qiskit.extensions import Initialize
from qiskit.visualization import plot_histogram, plot_bloch_multivector
## SETUP
# Protocol uses 3 qubits and 1 classical bit in a register
qr = QuantumRegister(3, name="q") # Protocol uses 4 qubits
cr1 = ClassicalRegister(1, name="cr1") # and 2 classical bit
#cr2 = ClassicalRegister(1, name="cr2")
bit_flip_circuit = QuantumCircuit(qr,cr1)
def encoding(qc, q0, q1, q2):
"""Creates encoding process using qubits q0 & q1 & q2"""
qc.cx(q0,q1) # CNOT with q1 as control and q0 as target
qc.cx(q0,q2) # CNOT with q2 as control and q0 as target
# initialization instruction to create
# |ψ⟩ from the state |0⟩:
p = 0.25 # p stands for the probability of fliping the state of the qubit
psi = [np.sqrt(p), np.sqrt(1-p)]
init_gate = Initialize(psi) # initialize the superposition state
init_gate.label = "init"
def measure(qc, q0, cr):
"""Measures qubit q0 """
qc.barrier()
qc.measure(q0,cr)
def decoding(qc, q0, q1, q2):
"""Creates decoding process using qubits q0 & q1 & q2"""
qc.cx(q0,q1) # CNOT with q1 as control and q0 as target
qc.cx(q0,q2) # CNOT with q2 as control and q0 as target
qc.ccx(q2,q1,q0) # Apply a Toffoli gate |011> <-> |111>
encoding(bit_flip_circuit, 0, 1, 2)
# step 2. error simulation
#bit_flip_circuit.append(Er,[0,1,2,3])
#error_simulation(bit_flip_circuit, 0, 1, 2, p)
bit_flip_circuit.barrier()
bit_flip_circuit.ry(np.pi/3,0)# Here rotate the spin around x axis by pi/3 so that the state will become 1/2|0>+sqrt(3)/2|1>
bit_flip_circuit.ry(np.pi/3,1)# Here rotate the spin around x axis by pi/3 so that the state will become 1/2|0>+sqrt(3)/2|1>
bit_flip_circuit.ry(np.pi/3,2)# Here rotate the spin around x axis by pi/3 so that the state will become 1/2|0>+sqrt(3)/2|1>
bit_flip_circuit.barrier()
# step 3. decoding
decoding(bit_flip_circuit, 0, 1, 2)
# step 4. measurement
measure(bit_flip_circuit, 0, 0)
# View the circuit:
%matplotlib inline
bit_flip_circuit.draw(output='mpl')
backend = BasicAer.get_backend('qasm_simulator')
counts = execute(bit_flip_circuit, backend, shots=1024).result().get_counts() # No. of measurement shots = 1024
plot_histogram(counts)
|
https://github.com/ichen17/Learning-Qiskit
|
ichen17
|
from qiskit import *
import numpy as np
from random import random
from qiskit.extensions import Initialize
from qiskit.visualization import plot_histogram, plot_bloch_multivector
import qiskit.providers.aer.noise as noise
# Protocol uses 3 qubits and 1 classical bit in a register
qr = QuantumRegister(3, name="q") # Protocol uses 4 qubits
cr1 = ClassicalRegister(1, name="cr1") # and 2 classical bit
#cr2 = ClassicalRegister(1, name="cr2")
bit_flip_circuit = QuantumCircuit(qr,cr1)
def encoding(qc, q0, q1, q2):
"""Creates encoding process using qubits q0 & q1 & q2"""
qc.cx(q0,q1) # CNOT with q1 as control and q0 as target
qc.cx(q0,q2) # CNOT with q2 as control and q0 as target
def measure(qc, q0, cr):
"""Measures qubit q0 """
qc.barrier()
qc.measure(q0,cr)
def decoding(qc, q0, q1, q2):
"""Creates decoding process using qubits q0 & q1 & q2"""
qc.cx(q0,q1) # CNOT with q1 as control and q0 as target
qc.cx(q0,q2) # CNOT with q2 as control and q0 as target
qc.ccx(q2,q1,q0) # Apply a Toffoli gate |011> <-> |111>
prob_1 = 0.25 # 1-qubit gate
#prob_2 = 0.01 # 2-qubit gate
# Depolarizing quantum errors
error_1 = noise.phase_amplitude_damping_error(prob_1, 0.1, 1)
#error_1 = noise.amplitude_damping_error(prob_1, 1)
#error_2 = noise.depolarizing_error(prob_2, 2)
# Add errors to noise model
noise_model = noise.NoiseModel()
noise_model.add_all_qubit_quantum_error(error_1, ['id'])
#noise_model.add_all_qubit_quantum_error(error_2, ['cx'])
# Get basis gates from noise model
basis_gates = noise_model.basis_gates
encoding(bit_flip_circuit, 0, 1, 2)
# step 2. error simulation
#bit_flip_circuit.append(Er,[0,1,2,3])
#error_simulation(bit_flip_circuit, 0, 1, 2, p)
bit_flip_circuit.barrier()
bit_flip_circuit.i(0)
bit_flip_circuit.i(1)
bit_flip_circuit.i(2)
bit_flip_circuit.barrier()
# step 3. decoding
decoding(bit_flip_circuit, 0, 1, 2)
# step 4. measurement
measure(bit_flip_circuit, 0, 0)
# View the circuit:
%matplotlib inline
bit_flip_circuit.draw(output='mpl')
result = execute(bit_flip_circuit, Aer.get_backend('qasm_simulator'),
basis_gates=basis_gates,
noise_model=noise_model).result()
counts = result.get_counts(0)
plot_histogram(counts)
nocor = QuantumCircuit(1,1)
nocor.i(0)
measure(nocor, 0, 0)
nocor.draw(output='mpl')
result = execute(nocor, Aer.get_backend('qasm_simulator'),
basis_gates=basis_gates,
noise_model=noise_model).result()
counts = result.get_counts(0)
plot_histogram(counts)
|
https://github.com/ichen17/Learning-Qiskit
|
ichen17
|
# Import libraries for use
from qiskit import *
import numpy as np
from random import random
from qiskit.extensions import Initialize
from qiskit.visualization import plot_histogram, plot_bloch_multivector
from qiskit_textbook.tools import random_state, array_to_latex
## SETUP
# Protocol uses 4 qubits and 1 classical bit in a register
qr = QuantumRegister(4, name="q") # Protocol uses 4 qubits
cr = ClassicalRegister(1, name="cr") # and 1 classical bit cr
sign_flip_circuit = QuantumCircuit(qr, cr)
def encoding(qc, q0, q1, q2):
"""Creates encoding process using qubits q0 & q1 & q2"""
qc.cx(q0,q1) # CNOT with q1 as control and q0 as target (Use q1 to control q0.)
qc.cx(q0,q2) # CNOT with q2 as control and q0 as target
# initialization instruction to create
# |ψ⟩ from the state |0⟩:
p = 1 # p stands for the probability of sign-fliping the state of the qubit
psi = [np.sqrt(1-p), np.sqrt(p)]
init_gate = Initialize(psi) # initialize the superposition state
init_gate.label = "init"
def error_simulation(qc, q0, q1, q2, q3):
"""Creates error simulation using qubits q0 & q1 & q2 & q3"""
qc.append(init_gate, [3]) # create the superposition state for |q3>
measure(qc, 3, 0) # measure the state on |q3>
qc.z(q0).c_if(cr, 1) # apply z gate on q0 if |1> was measured by |q3>
qc.append(init_gate, [3])
measure(qc, 3, 0)
qc.z(q1).c_if(cr, 1) # apply z gate on q1 if |1> was measured by |q3>
qc.append(init_gate, [3])
measure(qc, 3, 0)
qc.z(q2).c_if(cr, 1) # apply z gate on q2 if |1> was measured by |q3>
def measure(qc, q0, cr):
"""Measures qubit q0 """
qc.barrier()
qc.measure(q0,cr)
def decoding(qc, q0, q1, q2):
"""Creates decoding process using qubits q0 & q1 & q2"""
qc.cx(q0,q1) # CNOT with q1 as control and q0 as target
qc.cx(q0,q2) # CNOT with q2 as control and q0 as target
qc.ccx(q2,q1,q0) # Apply a Toffoli gate |011> <-> |111>
# Let's apply the process above to our circuit:
# step 0. input |0> -> |+>
sign_flip_circuit.h(0)
# step 1. encoding
encoding(sign_flip_circuit, 0, 1, 2)
sign_flip_circuit.h(0)
sign_flip_circuit.h(1)
sign_flip_circuit.h(2)
# step 2. error simulation
error_simulation(sign_flip_circuit, 0, 1, 2, p)
sign_flip_circuit.barrier()
# step 3. decoding
sign_flip_circuit.h(0)
sign_flip_circuit.h(1)
sign_flip_circuit.h(2)
decoding(sign_flip_circuit, 0, 1, 2)
# step 4. measurement
sign_flip_circuit.h(0)
measure(sign_flip_circuit, 0, 0)
# View the circuit:
%matplotlib inline
sign_flip_circuit.draw(output='mpl')
backend = BasicAer.get_backend('qasm_simulator')
counts = execute(sign_flip_circuit, backend, shots=1024).result().get_counts() # No. of measurement shots = 1024
plot_histogram(counts)
|
https://github.com/ichen17/Learning-Qiskit
|
ichen17
|
# Import libraries for use
from qiskit import *
import numpy as np
from random import random
from qiskit.extensions import Initialize
from qiskit.visualization import plot_histogram, plot_bloch_multivector
from qiskit_textbook.tools import random_state, array_to_latex
## SETUP
# Protocol uses 4 qubits and 1 classical bit in a register
qr = QuantumRegister(4, name="q") # Protocol uses 4 qubits
cr = ClassicalRegister(1, name="cr") # and 1 classical bit cr
bit_flip_circuit = QuantumCircuit(qr, cr)
def encoding(qc, q0, q1, q2):
"""Creates encoding process using qubits q0 & q1 & q2"""
qc.cx(q0,q1) # CNOT with q1 as control and q0 as target (Use q1 to control q0.)
qc.cx(q0,q2) # CNOT with q2 as control and q0 as target
# initialization instruction to create
# |ψ⟩ from the state |0⟩:
p = 0.25 # p stands for the probability of fliping the state of the qubit
psi = [np.sqrt(1-p), np.sqrt(p)]
init_gate = Initialize(psi) # initialize the superposition state
init_gate.label = "init"
def error_simulation(qc, q0, q1, q2, q3):
"""Creates error simulation using qubits q0 & q1 & q2 & q3"""
qc.append(init_gate, [3]) # create the superposition state for |q3>
measure(qc, 3, 0) # measure the state on |q3>
qc.x(q0).c_if(cr, 1) # apply x gate on q0 if |1> was measured by |q3>
qc.append(init_gate, [3])
measure(qc, 3, 0)
qc.x(q1).c_if(cr, 1) # apply x gate on q1 if |1> was measured by |q3>
qc.append(init_gate, [3])
measure(qc, 3, 0)
qc.x(q2).c_if(cr, 1) # apply x gate on q2 if |1> was measured by |q3>
def measure(qc, q0, cr):
"""Measures qubit q0 """
qc.barrier()
qc.measure(q0,cr)
def decoding(qc, q0, q1, q2):
"""Creates decoding process using qubits q0 & q1 & q2"""
qc.cx(q0,q1) # CNOT with q1 as control and q0 as target
qc.cx(q0,q2) # CNOT with q2 as control and q0 as target
qc.ccx(q2,q1,q0) # Apply a Toffoli gate |011> <-> |111>
# Let's apply the process above to our circuit:
# step 1. encoding
encoding(bit_flip_circuit, 0, 1, 2)
# step 2. error simulation
error_simulation(bit_flip_circuit, 0, 1, 2, p)
bit_flip_circuit.barrier()
# step 3. decoding
decoding(bit_flip_circuit, 0, 1, 2)
# step 4. measurement
measure(bit_flip_circuit, 0, 0)
# View the circuit:
%matplotlib inline
bit_flip_circuit.draw(output='mpl')
backend = BasicAer.get_backend('qasm_simulator')
counts = execute(bit_flip_circuit, backend, shots=1024).result().get_counts() # No. of measurement shots = 1024
plot_histogram(counts)
## SETUP
# Protocol uses 4 qubits and 1 classical bit in a register
qr = QuantumRegister(4, name="q") # Protocol uses 4 qubits
cr = ClassicalRegister(1, name="cr") # and 1 classical bit cr
bit_flip_random_circuit = QuantumCircuit(qr, cr)
# Create random 1-qubit state
psi_random = random_state(1)
# Display it nicely
array_to_latex(psi_random, pretext="|\\psi\\rangle =")
# Show it on a Bloch sphere
plot_bloch_multivector(psi_random)
# initialization instruction to create
# |ψ⟩ from the state |0⟩:
#(Initialize is technically not a gate since it contains a reset operation.)
init_gate_random = Initialize(psi_random)
init_gate_random.label = "init_random"
#Since all quantum gates are reversible,
#we can find the inverse of these gates using:
inverse_init_gate_random = init_gate_random.gates_to_uncompute()
# Let's apply the process above to our circuit:
## STEP 0
# First, let's initialize Alice's q0
bit_flip_random_circuit.append(init_gate_random, [0])
bit_flip_random_circuit.barrier()
# step 1. encoding
encoding(bit_flip_random_circuit, 0, 1, 2)
# step 2. error simulation
error_simulation(bit_flip_random_circuit, 0, 1, 2, p)
bit_flip_random_circuit.barrier()
# step 3. decoding
decoding(bit_flip_random_circuit, 0, 1, 2)
## STEP 4
# reverse the initialization process
bit_flip_random_circuit.append(inverse_init_gate_random, [0])
# step 5. measurement
measure(bit_flip_random_circuit, 0, 0)
# View the circuit:
%matplotlib inline
bit_flip_random_circuit.draw(output='mpl')
backend = BasicAer.get_backend('qasm_simulator')
counts = execute(bit_flip_random_circuit, backend, shots=1024).result().get_counts() # No. of measurement shots = 1024
plot_histogram(counts)
|
https://github.com/josejad42/quantum_algorithms_and_protocols
|
josejad42
|
pip install qiskit
pip install qiskit_aer
from qiskit import QuantumCircuit
def deustch_func(value):
c = QuantumCircuit(2)
if value in [2,3]:
c.cx(0,1)
if value in [3,4]:
c.x(1)
return c
num = 2
deustch_func(num).draw()
def deustch_algorithm(func):
n = func.num_qubits - 1
qc = QuantumCircuit(n+1,n)
qc.x(n)
qc.h(range(n+1))
qc.barrier()
qc.compose(func, inplace=True)
qc.barrier()
qc.h(range(n))
qc.measure(range(n),range(n))
return qc
deustch_algorithm(deustch_func(2)).draw()
from qiskit_aer import AerSimulator
def execute_deutsch(function):
qc = deustch_algorithm(function)
result = AerSimulator().run(qc,shots=1,memory=True).result()
measurements = result.get_memory()
if measurements[0] == '0':
return "constant"
return "balanced"
f = deustch_func(2)
display(f.draw())
execute_deutsch(f)
|
https://github.com/josejad42/quantum_algorithms_and_protocols
|
josejad42
|
!pip install qiskit qiskit-aer pylatexenc --quiet
import numpy as np
from qiskit import QuantumCircuit
qc = QuantumCircuit(3,2) # QuantumCircuit(num. bits quânticos, num. bits clássicos)
qc.x(0)
qc.ccx(0,1,2)
qc.y(0)
qc.barrier()
qc.h(1)
qc.h(2)
qc.measure(1,0) # É possível medir epecificamente um qubit: measure(qubit,bit clássico)
qc.measure(2,1)
qc.draw('mpl')
qc = QuantumCircuit(3) # Não passamos nenhum bit clássico
qc.x(0)
qc.ccx(0,1,2)
qc.y(0)
qc.barrier()
qc.h(1)
qc.h(2)
qc.measure_all() # É possível medir todos os qubits de uma vez
qc.draw('mpl')
qc = QuantumCircuit(3)
#matrizes de pauli
qc.x(0)
qc.y(1)
qc.z(2)
#rotações parametrizadas - r_ (ângulo, posicão)
qc.rx(30,0)
qc.ry(45,1)
qc.rz(np.pi/2,2)
#hadamard gate
qc.h(0)
#outras portas
qc.s(1)
qc.t(2)
qc.draw('mpl')
qc = QuantumCircuit(4)
#rotações controladas - cr_ (angulo, controle, alvo)
qc.crz(30,0,1)
qc.cry(np.pi,1,0)
#porta CNOT - cx(controle, alvo)
qc.cx(0,1)
#porta Tofolli - ccx (controles, alvo)
qc.ccx(0,1,2)
#CNOT multicontrolada - mcx([lista de controles], alvo)
qc.mcx([0,1,2],3)
qc.draw('mpl')
circuit = QuantumCircuit(2)
matrix = [[0, 0, 0, 1],
[0, 0, 1, 0],
[1, 0, 0, 0],
[0, 1, 0, 0]]
circuit.unitary(matrix, [0 ,1]) # unitary([[matriz]], [lista de bits])
circuit.draw('mpl')
from qiskit.circuit.library import UnitaryGate
circuit = QuantumCircuit(3)
matrix = [[0, 0, 0, 1],
[0, 0, 1, 0],
[1, 0, 0, 0],
[0, 1, 0, 0]]
gate = UnitaryGate(matrix)
cGate = gate.control(1)
circuit.append(cGate, [0, 1, 2]) # append(operador, [controles, alvos])
circuit.draw('mpl')
c = QuantumCircuit(3)
c.x(0)
c.x(1)
c.h(2)
c.ccx(0,1,2)
gate = c.to_gate(label='Death Note')
c.draw('mpl')
qc = QuantumCircuit(4)
qc.append(gate, [0,1,2])
qc.draw('mpl')
qc = QuantumCircuit(6)
cGate = gate.control(3)
qc.x(0)
qc.x(1)
qc.x(2)
qc.append(cGate, [0,1,2,3,4,5])
qc.draw('mpl')
from qiskit_aer import Aer
from qiskit.visualization import plot_histogram
from qiskit import transpile
sim = Aer.get_backend('aer_simulator')
qc.measure_all()
qc = transpile(qc, basis_gates=['u', 'cx']) # o simulador nao consegue trabalhar com a caixa-preta,
# precisamos decompor o circuito em operadores mais simples
# não precisaríamos da transpilação se o circuito fosse simples
counts = sim.run(qc).result().get_counts()
plot_histogram(counts)
#Circuito após a transpilação
#qc.draw('mpl')
|
https://github.com/josejad42/quantum_algorithms_and_protocols
|
josejad42
|
pip install qiskit pylatexenc qiskit-aer --quiet
from qiskit import QuantumCircuit, Aer, transpile
from qiskit.visualization import plot_histogram, plot_bloch_multivector
from numpy.random import randint
from qiskit.visualization import visualize_transition
import numpy as np
import matplotlib.pyplot as plt
qc = QuantumCircuit(1, 1)
# Alice prepara o qubit no estado |-> (1 na base de Hadamard)
qc.x(0)
qc.h(0)
qc.s(0)
qc.barrier()
# Alice envia o qubit para Bob
# Bob mede o qubit na base X
qc.sdg(0)
qc.h(0)
qc.measure(0, 0)
# Backend
display(qc.draw('mpl'))
aer_sim = Aer.get_backend('aer_simulator')
job = aer_sim.run(qc)
plot_h1 = plot_histogram(job.result().get_counts())
plot_h1
qc = QuantumCircuit(1, 1)
# Alice prepara o qubit no estado |-> (1 na base de Hadamard)
qc.x(0)
qc.h(0)
qc.barrier()
# Alice envia o qubit para Bob
# Bob mede o qubit na base X
qc.h(0)
qc.measure(0, 0)
# Backend
display(qc.draw('mpl'))
aer_sim = Aer.get_backend('aer_simulator')
job = aer_sim.run(qc)
plot_h1 = plot_histogram(job.result().get_counts())
plot_h1
qc = QuantumCircuit(1,1)
# Alice prepara o qubit no estado |-> e envia para Bob
qc.x(0)
qc.h(0)
# Eve intersepta e tenta ler o qubit
qc.barrier()
qc.measure(0, 0)
qc.barrier()
# Eve manda a mensagem para Bob
# Bob mede o qubit na base X
qc.h(0)
qc.measure(0,0)
# Backend
display(qc.draw('mpl'))
aer_sim = Aer.get_backend('aer_simulator')
job = aer_sim.run(qc)
plot_h2 = plot_histogram(job.result().get_counts())
plot_h2
n = 100
alice_bits = randint(2, size=n)
print(alice_bits)
#Lista representando a base escolhida para encodar cada bit de alice_bits.
#0 significa preparar na base Z e 1 significa preparar na base X
alice_bases = randint(2, size=n)
print(alice_bases)
#Função que cria uma lista de QuantumCircuits
#Cada um representa um bit da mensagem de Alice
def encode_message(bits, bases):
message = []
for i in range(n):
qc = QuantumCircuit(1,1)
if bases[i] == 0: # Prepara qubit na base Z
if bits[i] == 0:
pass
else:
qc.x(0)
else: # Prepara qubit na base X
if bits[i] == 0:
qc.h(0)
else:
qc.x(0)
qc.h(0)
qc.barrier()
message.append(qc)
return message
#Estamos agora codificando a mensagem de Alice
message = encode_message(alice_bits, alice_bases)
#Exemplo para o primeiro bit
print('bit = %i' % alice_bits[0])
print('basis = %i' % alice_bases[0])
message[0].draw('mpl')
#Array representando a base escolhida para medir cada bit de alice_bits.
bob_bases = randint(2, size=n)
print(bob_bases)
#Função que mede cada qubit da mensagem
def measure_message(message, bases):
backend = Aer.get_backend('aer_simulator')
measurements = []
for q in range(n):
if bases[q] == 0: # mede na base Z
message[q].measure(0,0)
if bases[q] == 1: # mede na base X
message[q].h(0)
message[q].measure(0,0)
aer_sim = Aer.get_backend('aer_simulator')
result = aer_sim.run(message[q], shots=1, memory=True).result()
measured_bit = int(result.get_memory()[0])
measurements.append(measured_bit)
return measurements
#Estamos agora medindo cada qubit da mensagem de Alice
bob_results = measure_message(message, bob_bases)
print(bob_results)
#primeiro bit
message[0].draw('mpl')
#segundo bit
message[1].draw('mpl')
#Função que retorna apenas os qubits em que as bases foram iguais
def remove_garbage(a_bases, b_bases, bits):
good_bits = []
for q in range(n):
if a_bases[q] == b_bases[q]:
# If both used the same basis, add
# this to the list of 'good' bits
good_bits.append(bits[q])
return good_bits
#Chave da Alice
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
print(alice_key)
#Chave do Bob
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
print(bob_key)
def sample_bits(bits, selection):
sample = []
for i in selection:
#usamos o np.mod para garantir que o bit
i = np.mod(i, len(bits))
# pop(i) remove o elemento da lista
sample.append(bits.pop(i))
return sample
sample_size = 15
bit_selection = randint(n, size=sample_size)
bob_sample = sample_bits(bob_key, bit_selection)
print(" bob_sample = " + str(bob_sample))
alice_sample = sample_bits(alice_key, bit_selection)
print("alice_sample = "+ str(alice_sample))
#Verificamos se o protocolo funcionou corretamente sem interferências
bob_sample == alice_sample
np.random.seed()
n = 100
# PASSO 1
alice_bits = randint(2, size=n)
# PASSO 2
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
# PASSO 3
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
# PASSO 4
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
# PASSO 5
sample_size = 15
bit_selection = randint(n, size=sample_size)
bob_sample = sample_bits(bob_key, bit_selection)
print(" bob_sample = " + str(bob_sample))
alice_sample = sample_bits(alice_key, bit_selection)
print("alice_sample = "+ str(alice_sample))
# PASSO 1
np.random.seed(seed=3)
alice_bits = randint(2, size=n)
print(alice_bits)
# PASSO 1
np.random.seed(seed=3)
alice_bits = randint(2, size=n)
# PASSO 2
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
print(alice_bases)
message[0].draw('mpl')
# PASSO 1
np.random.seed(seed=3)
alice_bits = randint(2, size=n)
# PASSO 2
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
# Interceptação
eve_bases = randint(2, size=n)
intercepted_message = measure_message(message, eve_bases)
print(intercepted_message)
message[0].draw('mpl')
# PASSO 1
np.random.seed(seed=3)
alice_bits = randint(2, size=n)
# PASSO 2
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Interceptação
eve_bases = randint(2, size=n)
intercepted_message = measure_message(message, eve_bases)
# PASSO 3
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
message[0].draw('mpl')
# PASSO 1
np.random.seed(seed=3)
alice_bits = randint(2, size=n)
# PASSO 2
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Interceptação
eve_bases = randint(2, size=n)
intercepted_message = measure_message(message, eve_bases)
# PASSO 3
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
# PASSO 4
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
# PASSO 1
np.random.seed(seed=3)
alice_bits = randint(2, size=n)
# PASSO 2
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
# Interceptação!
eve_bases = randint(2, size=n)
intercepted_message = measure_message(message, eve_bases)
# PASSO 3
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
# PASSO 4
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
# PASSO 5
sample_size = 15
bit_selection = randint(n, size=sample_size)
bob_sample = sample_bits(bob_key, bit_selection)
print(" bob_sample = " + str(bob_sample))
alice_sample = sample_bits(alice_key, bit_selection)
print("alice_sample = "+ str(alice_sample))
#Ao comparar as seleções arbitrárias de qubits de Alice e Bob
#Percebemos que elas não são iguais
bob_sample == alice_sample
|
https://github.com/levchCode/RSA-breaker
|
levchCode
|
#
# This is a toy RSA encryption breaker using Shor's algorithm (params: a = 2, N = 85)
# To use your custom alphabet, please change alphabet var
#
from qiskit import QuantumProgram
from fractions import gcd
from math import pi
qp = QuantumProgram()
qr = qp.create_quantum_register('qr', 8)
cr = qp.create_classical_register('cr', 4)
qc = qp.create_circuit('Shor',[qr],[cr])
def Oracle():
qc.cx(qr[2], qr[6])
qc.cx(qr[3], qr[7])
def findPQ(a, N):
qc.h(qr[0])
qc.h(qr[1])
qc.h(qr[2])
qc.h(qr[3])
Oracle()
qc.h(qr[0])
qc.cu1(pi/2, qr[0], qr[1])
qc.h(qr[1])
qc.cu1(pi/4, qr[0], qr[2])
qc.cu1(pi/2, qr[1], qr[2])
qc.h(qr[2])
qc.cu1(pi/8, qr[0], qr[3])
qc.cu1(pi/4, qr[1], qr[3])
qc.cu1(pi/2, qr[2], qr[3])
qc.h(qr[3])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
qc.measure(qr[2], cr[2])
qc.measure(qr[3], cr[3])
result = qp.execute(['Shor'])#, backend='ibmqx_qasm_simulator', shots=1024, wait=5, timeout=1200)
res = result.get_counts('Shor')
mult_list = []
for k in res.keys():
p = int(k, 2)
if p % 2 == 0:
k1 = a**(p/2) - 1
k2 = a**(p/2) + 1
mult_list.append((gcd(k1, N), gcd(k2, N)))
else:
print("Period is odd, skipping")
print("mult_list: {}".format(mult_list))
return mult_list
def decrypt(public_key, message):
m_list = findPQ(2, public_key[1])
#alphabet84 = " !(),-./0123456789:?АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"
#alphabet50 = " !(),-.0123456789:?АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"
alphabet = " !(),-./0123456789:?АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"
message = [alphabet.find(i) for i in message]
for m in m_list:
fi = (m[0]-1)*(m[1]-1)
if(fi == 0):
print("N = N * 1, skipping")
else:
d = 0
while True:
rem = (d*public_key[0]) % fi
if rem == 1:
break
else:
d = d + 1
text = ''
for i in message:
text += alphabet[i**d % public_key[1]]
print("The message is: {}".format(text))
if __name__ == '__main__':
decrypt((11, 85), "Ы97 3хД7УЙ НЖ3 Жл2Ж, Н9ще7 НЖ?32Ж Дхнх9лЖ,д")
|
https://github.com/stevvwen/QAlgoImplementation
|
stevvwen
|
# initialization
import numpy as np
import matplotlib
# importing Qiskit
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ, BasicAer, assemble, transpile
from qiskit.quantum_info import Statevector
# import basic plot tools
from qiskit.visualization import plot_bloch_multivector,plot_bloch_vector, plot_histogram
style = {'backgroundcolor': 'lightyellow'} # Style of the circuits
# set the length of the n-bit input string.
n = 3
# set the length of the n-bit input string.
n = 3
const_oracle = QuantumCircuit(n+1)
output = np.random.randint(2)
if output == 1:
const_oracle.x(n)
const_oracle.draw(output='mpl', style=style)
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
balanced_oracle.draw(output='mpl', style=style)
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
balanced_oracle.draw(output='mpl', style=style)
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Show oracle
balanced_oracle.draw(output='mpl', style=style)
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
dj_circuit.draw(output='mpl', style=style)
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit += balanced_oracle
dj_circuit.draw(output='mpl', style=style)
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit += balanced_oracle
# Repeat H-gates
for qubit in range(n):
dj_circuit.h(qubit)
dj_circuit.barrier()
# Measure
for i in range(n):
dj_circuit.measure(i, i)
# Display circuit
dj_circuit.draw(output='mpl', style=style)
# use local simulator
aer_sim = Aer.get_backend('aer_simulator')
qobj = assemble(dj_circuit, aer_sim)
results = aer_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
def dj_oracle(case, n):
# We need to make a QuantumCircuit object to return
# This circuit has n+1 qubits: the size of the input,
# plus one output qubit
oracle_qc = QuantumCircuit(n+1)
# First, let's deal with the case in which oracle is balanced
if case == "balanced":
# First generate a random number that tells us which CNOTs to
# wrap in X-gates:
b = np.random.randint(1,2**n)
print(b)
print(str(n))
b=7
# Next, format 'b' as a binary string of length 'n', padded with zeros:
b_str = format(b, '0'+str(n)+'b')
print(b_str)
# Next, we place the first X-gates. Each digit in our binary string
# corresponds to a qubit, if the digit is 0, we do nothing, if it's 1
# we apply an X-gate to that qubit:
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Do the controlled-NOT gates for each qubit, using the output qubit
# as the target:
for qubit in range(n):
oracle_qc.cx(qubit, n)
# Next, place the final X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Case in which oracle is constant
if case == "constant":
# First decide what the fixed output of the oracle will be
# (either always 0 or always 1)
output = np.random.randint(2)
if output == 1:
oracle_qc.x(n)
oracle_gate = oracle_qc.to_gate()
oracle_gate.name = "Oracle" # To show when we display the circuit
return oracle_gate
def dj_algorithm(oracle, n):
dj_circuit = QuantumCircuit(n+1, n)
# Set up the output qubit:
dj_circuit.x(n)
dj_circuit.h(n)
# And set up the input register:
for qubit in range(n):
dj_circuit.h(qubit)
# Let's append the oracle gate to our circuit:
dj_circuit.append(oracle, range(n+1))
# Finally, perform the H-gates again and measure:
for qubit in range(n):
dj_circuit.h(qubit)
for i in range(n):
dj_circuit.measure(i, i)
return dj_circuit
n = 4
oracle_gate = dj_oracle('balanced', n)
dj_circuit = dj_algorithm(oracle_gate, n)
dj_circuit.draw(output='mpl', style=style)
transpiled_dj_circuit = transpile(dj_circuit, aer_sim)
qobj = assemble(transpiled_dj_circuit)
results = aer_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/stevvwen/QAlgoImplementation
|
stevvwen
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit.providers.aer import QasmSimulator
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
qc= QuantumCircuit(2, 1)
qc.h(0)
qc.cx(0, 1)
qc.h(0)
qc.measure(0, 0)
qc.draw()
# use local simulator
aer_sim = Aer.get_backend('aer_simulator')
qobj = assemble(qc, aer_sim)
results = aer_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/stevvwen/QAlgoImplementation
|
stevvwen
|
# 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/henotrix/quantum-practice
|
henotrix
|
from qiskit import *
from oracle_generation import generate_oracle
get_bin = lambda x, n: format(x, 'b').zfill(n)
def gen_circuits(min,max,size):
circuits = []
secrets = []
ORACLE_SIZE = size
for i in range(min,max+1):
cur_str = get_bin(i,ORACLE_SIZE-1)
(circuit, secret) = generate_oracle(ORACLE_SIZE,False,3,cur_str)
circuits.append(circuit)
secrets.append(secret)
return (circuits, secrets)
|
https://github.com/LohitPotnuru/GroverAlgorithm_Qiskit
|
LohitPotnuru
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit.providers.aer import QasmSimulator
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
from qiskit.circuit.library.standard_gates import XGate, HGate
from operator import *
n = 3
N = 8 #2**n
index_colour_table = {}
colour_hash_map = {}
index_colour_table = {'000':"yellow", '001':"red", '010':"blue", '011':"red", '100':"green", '101':"blue", '110':"orange", '111':"red"}
colour_hash_map = {"yellow":'100', "red":'011', "blue":'000', "green":'001', "orange":'010'}
def database_oracle(index_colour_table, colour_hash_map):
circ_database = QuantumCircuit(n + n)
for i in range(N):
circ_data = QuantumCircuit(n)
idx = bin(i)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion
colour = index_colour_table[idx]
colour_hash = colour_hash_map[colour][::-1]
for j in range(n):
if colour_hash[j] == '1':
circ_data.x(j)
# qiskit maps the rightmost bit as the 0th qubit -> qn, ..., q0
# we therefore reverse the index string -> q0, ..., qn
data_gate = circ_data.to_gate(label=colour).control(num_ctrl_qubits=n, ctrl_state=idx, label="index-"+colour)
circ_database.append(data_gate, list(range(n+n)))
return circ_database
# drawing the database oracle circuit
print("Database Encoding")
database_oracle(index_colour_table, colour_hash_map).draw()
circ_data = QuantumCircuit(n)
m = 4
idx = bin(m)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion
colour = index_colour_table[idx]
colour_hash = colour_hash_map[colour][::-1]
for j in range(n):
if colour_hash[j] == '1':
circ_data.x(j)
print("Internal colour encoding for the colour green (as an example)");
circ_data.draw()
def oracle_grover(database, data_entry):
circ_grover = QuantumCircuit(n + n + 1)
circ_grover.append(database, list(range(n+n)))
target_reflection_gate = XGate().control(num_ctrl_qubits=n, ctrl_state=colour_hash_map[data_entry], label="Reflection of " + "\"" + data_entry + "\" Target")
# control() missing 1 required positional argument: 'self' .... if only 'XGate' used instead of 'XGate()'
# The “missing 1 required positional argument: 'self'” error is raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class.
circ_grover.append(target_reflection_gate, list(range(n, n+n+1)))
circ_grover.append(database, list(range(n+n)))
return circ_grover
print("Grover Oracle (target example: orange)")
oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), "orange").decompose().draw()
def mcz_gate(num_qubits):
num_controls = num_qubits - 1
mcz_gate = QuantumCircuit(num_qubits)
target_mcz = QuantumCircuit(1)
target_mcz.z(0)
target_mcz = target_mcz.to_gate(label="Z_Gate").control(num_ctrl_qubits=num_controls, ctrl_state=None, label="MCZ")
mcz_gate.append(target_mcz, list(range(num_qubits)))
return mcz_gate.reverse_bits()
print("Multi-controlled Z (MCZ) Gate")
mcz_gate(n).decompose().draw()
def diffusion_operator(num_qubits):
circ_diffusion = QuantumCircuit(num_qubits)
qubits_list = list(range(num_qubits))
# Layer of H^n gates
circ_diffusion.h(qubits_list)
# Layer of X^n gates
circ_diffusion.x(qubits_list)
# Layer of Multi-controlled Z (MCZ) Gate
circ_diffusion = circ_diffusion.compose(mcz_gate(num_qubits), qubits_list)
# Layer of X^n gates
circ_diffusion.x(qubits_list)
# Layer of H^n gates
circ_diffusion.h(qubits_list)
return circ_diffusion
print("Diffusion Circuit")
diffusion_operator(n).draw()
# Putting it all together ... !!!
item = "green"
print("Searching for the index of the colour", item)
circuit = QuantumCircuit(n + n + 1, n)
circuit.x(n + n)
circuit.barrier()
circuit.h(list(range(n)))
circuit.h(n+n)
circuit.barrier()
unitary_oracle = oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), item).to_gate(label="Oracle Operator")
unitary_diffuser = diffusion_operator(n).to_gate(label="Diffusion Operator")
M = countOf(index_colour_table.values(), item)
Q = int(np.pi * np.sqrt(N/M) / 4)
for i in range(Q):
circuit.append(unitary_oracle, list(range(n + n + 1)))
circuit.append(unitary_diffuser, list(range(n)))
circuit.barrier()
circuit.measure(list(range(n)), list(range(n)))
circuit.draw()
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = backend_sim.run(transpile(circuit, backend_sim), shots=1024)
result_sim = job_sim.result()
counts = result_sim.get_counts(circuit)
if M==1:
print("Index of the colour", item, "is the index with most probable outcome")
else:
print("Indices of the colour", item, "are the indices the most probable outcomes")
from qiskit.visualization import plot_histogram
plot_histogram(counts)
|
https://github.com/pedrotelez/QuantumHelloWorld
|
pedrotelez
|
# Importing Qiskit
from qiskit import *
# Init 2 qubits and 2 classical bits
number_of_qubits = 2 # qubits
number_of_classical_bits = 2 # classical bits
Qr = QuantumRegister(number_of_qubits) # quantum register
Cr = ClassicalRegister(number_of_classical_bits) # classical register
# Building the circuit
circuit = QuantumCircuit(Qr, Cr)
# Adding gates to the circuit
circuit.h(Qr[0]) # Hadamard gate on Qubit 0
circuit.cx(Qr[0], Qr[1]) # CNOT gate on control Qubit 0 and target Qubit 1
# Measure the qubits [0, 1] and store the result in classical bits [0, 1]
circuit.measure(Qr, Cr)
# Draw the circuit
circuit.draw(output='mpl')
# the hello world of quantum computing
# 2 qubits, 2 classical bits
# Hadamard gate on Qubit 0
# CNOT gate on control Qubit 0 and target Qubit 1
# Measure the qubits [0, 1] and store the result in classical bits [0, 1]
# Hadamard gate means that the qubit is in superposition, so it has a 50% chance of being 0 or 1
# CNOT gate means that the qubit 1 is entangled with qubit 0, so if qubit 0 is 0, qubit 1 is 0, and if qubit 0 is 1, qubit 1 is 1
# Simulating the circuit in the local simulator
simulator = Aer.get_backend('qasm_simulator') # simulator
result = execute(circuit, backend=simulator).result() # execute the circuit on the simulator
# Plot the result
from qiskit.visualization import plot_histogram
plot_histogram(result.get_counts(circuit)) # plot the result
|
https://github.com/pedrotelez/QuantumHelloWorld
|
pedrotelez
|
from qiskit import QuantumCircuit, execute, Aer, BasicAer
from qiskit.visualization import plot_state_qsphere, plot_histogram, plot_bloch_multivector
from qiskit.quantum_info import Statevector
import numpy as np
# numero de qubits do circuito
n = 4
# inicializando o circuito
qft = QuantumCircuit(n, n, name = "QFT")
for i in range(n-1, -1, -1):
#começa do último bit que só tem uma porta H
qft.h(i)
fase = 0
for j in range(i):
#conecta as portas de fase nos bits anteriores
fase +=1
qft.cp(np.pi/(2**fase), i - j -1, i)
#para melhorar a visualização
qft.barrier()
for i in range(int(n/2)):
#Operação de swap
qft.swap(i, n-1-i)
qft.draw('mpl')
sv = Statevector.from_label("1010")
plot_bloch_multivector(sv)
qft_sv = sv.evolve(qft) #aplica a QFT nos qubits
plot_bloch_multivector(qft_sv)
|
https://github.com/0xCAB0/shor_algorithm
|
0xCAB0
|
from qiskit import QuantumCircuit, Aer, execute, IBMQ
from qiskit.utils import QuantumInstance
import numpy as np
from qiskit.algorithms import Shor
IBMQ.enable_account('ENTER API TOKEN HERE') # Enter your API token here
provider = IBMQ.get_provider(hub='ibm-q')
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1000)
my_shor = Shor(quantum_instance)
result_dict = my_shor.factor(15)
print(result_dict)
|
https://github.com/samabwhite/Grover-Search-Implementation
|
samabwhite
|
from qiskit import QuantumCircuit
from qiskit.tools.visualization import circuit_drawer
import numpy as np
from matplotlib import pyplot as plt
n=5
qc = QuantumCircuit(n)
qc.x(1)
qc.ccx(0, 1, 3)
qc.ccx(2, 3, 4)
qc.ccx(0, 1, 3)
qc.x(1)
qc.draw('mpl')
def phase_oracle(n, name = 'Uf'):
qc = QuantumCircuit(n, name = name)
qc.x(1)
qc.ccx(0, 1, 3)
qc.ccx(2, 3, 4)
qc.ccx(0, 1, 3)
qc.x(1)
return qc
n=5
qc = QuantumCircuit(n)
for i in range(n-2):
qc.x(i)
qc.ccx(0, 1, 3)
qc.ccx(2, 3, 4)
qc.ccx(0, 1, 3)
for i in range(n-2):
qc.x(i)
qc.draw('mpl')
def diffuser(n, name= 'V'):
qc = QuantumCircuit(n, name =name)
for qb in range(n-2): # First layer of Hadamards in diffuser
qc.h(qb)
for i in range(n-2):
qc.x(i)
qc.ccx(0, 1, 3)
qc.ccx(2, 3, 4)
qc.ccx(0, 1, 3)
for i in range(n-2):
qc.x(i)
for qb in range(n-2): # Second layer of Hadamards in diffuser
qc.h(qb)
return qc
n=5
gr = QuantumCircuit(n, n-2)
mu = 1 #number of solutions
r = int(np.floor(np.pi/4*np.sqrt(2**(n-2)/mu))) #determine r
print('r = ',r)
gr.h(range(n-2)) #step1: apply Hadamard gates on all working qubits
#put ancilla in state |->
gr.x(n-1)
gr.h(n-1)
#step 2: apply r rounds of the phase oracle and the diffuser
for j in range(r):
gr.append(phase_oracle(n), range(n))
gr.append(diffuser(n), range(n))
gr.measure(range(n-2), range(n-2)) #step 3: measure all qubits
gr.draw('mpl')
from qiskit import BasicAer, Aer, execute, IBMQ
from qiskit.visualization import plot_histogram
simulator = Aer.get_backend('qasm_simulator')
result = execute(gr, backend = simulator, shots = 1024).result()
counts = result.get_counts()
plot_histogram(counts)
from qiskit import IBMQ
IBMQ.save_account('e19ab1a54fb68a1937a725b48b02eafb8af0db9189107e78762686e5bf12dff5642e1597470d966ea9d2e121cc86f4a0f08bea5d5e760de66c7be7be04fd2974')
IBMQ.load_account()
provider = IBMQ.get_provider(hub = 'ibm-q')
device = provider.get_backend('ibmq_qasm_simulator')
job = execute(gr, backend=device, shots=1024)
print(job.job_id())
from qiskit.tools.monitor import job_monitor
job_monitor(job)
device_result = job.result()
plot_histogram(device_result.get_counts(gr))
|
https://github.com/nagarx/Quantum-KNN-Classifier-using-Qiskit
|
nagarx
|
from qiskit import QuantumCircuit, QuantumRegister
def swap_test(N):
'''
`N`: Number of qubits of the quantum registers.
'''
a = QuantumRegister(N, 'a')
b = QuantumRegister(N, 'b')
d = QuantumRegister(1, 'd')
# Quantum Circuit
qc_swap = QuantumCircuit(name = ' SWAP \nTest')
qc_swap.add_register(a)
qc_swap.add_register(b)
qc_swap.add_register(d)
qc_swap.h(d)
for i in range(N):
qc_swap.cswap(d, a[i], b[i])
qc_swap.h(d)
return qc_swap
|
https://github.com/nagarx/Quantum-KNN-Classifier-using-Qiskit
|
nagarx
|
# Classical computing modules
import numpy as np
import pandas as pd
import seaborn as sns
from statistics import mode
# Dataset
from sklearn import datasets, preprocessing
from sklearn.model_selection import train_test_split
# Quantum computing modules
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute
from qiskit.visualization import plot_histogram
from qiskit.quantum_info import Statevector
# Load the dataset
iris = datasets.load_iris()
feature_labels = iris.feature_names
class_labels = iris.target_names
# Extract the data
X = iris.data
y = np.array([iris.target])
M = 4
# Print the features and classes
print("Features: ", feature_labels)
print("Classes: ", class_labels)
df = pd.DataFrame(data = np.concatenate((X, y.T), axis = 1), columns = feature_labels[0:M] + ["Species"])
sns.pairplot(df, hue = 'Species')
min_max_scaler = preprocessing.MinMaxScaler(feature_range=(0, 1))
min_max_scaler.fit(X)
X_normalized = min_max_scaler.transform(X)
df2 = pd.DataFrame(data = np.concatenate((X_normalized, y.T), axis = 1), columns = feature_labels[0:M] + ["Species"])
sns.pairplot(df2, hue = 'Species')
N_train = 100 # Training dataset size
X_train, X_test, y_train, y_test = train_test_split(X_normalized, y[0], train_size=N_train)
# Select a sample test sample for classification
test_index = int(np.random.rand()*len(X_test))
phi_test = X_test[test_index]
# Create the encoded feature vector
for i in range(M):
phi_i = [np.sqrt(phi_test[i]), np.sqrt(1- phi_test[i])]
if i == 0:
phi = phi_i
else:
phi = np.kron(phi_i, phi)
# Validate the statevector
print('Valid statevector: ', Statevector(phi).is_valid())
N = int(np.ceil(np.log2(N_train)))
psi = np.zeros(2**(M + N)) # Task 9
for i in range(N_train):
# Encode |i>
i_vec = np.zeros(2**N)
i_vec[i] = 1
# Encode |x>
x = X_train[i, :]
for j in range(M):
dummy = [np.sqrt(x[j]), np.sqrt(1- x[j])]
if j == 0:
x_vec = dummy
else:
x_vec = np.kron(dummy, x_vec)
psi_i = np.kron(x_vec, i_vec)
# Task 9
psi += psi_i
psi /= np.sqrt(N_train)
# Check the validity of the statevector
assert Statevector(psi).is_valid(), "The statevector is not square-normalized."
index_reg = QuantumRegister(N, 'i')
train_reg = QuantumRegister(M, 'train')
test_reg = QuantumRegister(M, 'test')
p = QuantumRegister(1, 'similarity')
# Create the quantum circuit
qknn = QuantumCircuit()
# Add registers to the circuit
qknn.add_register(index_reg)
qknn.add_register(train_reg)
qknn.add_register(test_reg)
qknn.add_register(p)
# Draw the quantum circuit
qknn.draw('mpl')
# Initialize the training register
qknn.initialize(psi, index_reg[0:N] + train_reg[0:M])
# Initialize the test register
qknn.initialize(phi, test_reg)
# Draw qknn
qknn.draw('mpl')
from modules import swap_test
# Apply the Quantum SWAP Test module to the quantum circuit
qknn.append(swap_test(M), train_reg[0:M] + test_reg[0:M] + [p[0]])
# Draw qknn
qknn.draw('mpl')
# Create the classical register
meas_reg_len = N + 1
meas_reg = ClassicalRegister(meas_reg_len, 'meas')
qknn.add_register(meas_reg)
# Measure the qubits
qknn.measure(index_reg[0::] + p[0::], meas_reg)
# Draw qknn
qknn.draw('mpl', fold = -1)
backend = Aer.get_backend('qasm_simulator')
counts_knn = execute(qknn, backend, shots = 15000).result().get_counts()
result_arr = np.zeros((N_train, 3))
for count in counts_knn:
i_dec = int(count[1::], 2)
phase = int(count[0], 2)
if phase == 0:
result_arr[i_dec, 0] += counts_knn[count]
else:
result_arr[i_dec, 1] += counts_knn[count]
for i in range(N_train):
prob_1 = result_arr[i][1]/(result_arr[i][0] + result_arr[i][1])
result_arr[i][2] = 1 - 2*prob_1
# Find the indexes of minimum distance
k = 10
k_min_dist_arr = result_arr[:, 2].argsort()[::-1][:k]
# Determine the class of the test sample
y_pred = mode(y_train[k_min_dist_arr])
y_exp = y_test[test_index]
print('Predicted class of the test sample is {}.'.format(y_pred))
print('Expected class of the test sample is {}.'.format(y_exp))
def q_knn_module(test_index, psi, k=10):
phi_test = X_test[test_index]
# Create the encoded feature vector
for i in range(M):
phi_i = [np.sqrt(phi_test[i]), np.sqrt(1- phi_test[i])]
if i == 0:
phi = phi_i
else:
phi = np.kron(phi, phi_i)
# Create the quantum circuit
qknn = QuantumCircuit()
# Add registers to circuit
qknn.add_register(index_reg)
qknn.add_register(train_reg)
qknn.add_register(test_reg)
qknn.add_register(p)
# Initialize train reg
qknn.initialize(psi, index_reg[0:N] + train_reg[0:M])
# Initialize test reg
qknn.initialize(phi, test_reg)
# Apply the swap test module to the quantum circuit
qknn.append(swap_test(M), train_reg[0:M] + test_reg[0:M] + [p[0]])
# Create the classical register
meas_reg_len = N+1
meas_reg = ClassicalRegister(meas_reg_len, 'meas')
qknn.add_register(meas_reg)
# Measure the qubits
qknn.measure(index_reg[0::] + p[0::], meas_reg)
# Circuit execution
backend = Aer.get_backend('qasm_simulator')
counts_knn = execute(qknn, backend, shots = 10000).result().get_counts()
# Decoding the results
result_arr = np.zeros((N_train, 3))
for count in counts_knn:
i_dec = int(count[1::], 2)
phase = int(count[0], 2)
if phase == 0:
result_arr[i_dec, 0] += counts_knn[count]
else:
result_arr[i_dec, 1] += counts_knn[count]
# Computing similarity
for i in range(N_train):
prob_1 = result_arr[i][1]/(result_arr[i][0] + result_arr[i][1])
result_arr[i][2] = 1 - 2*prob_1
# Find the indices of minimum distance
k_min_dist_arr = result_arr[:, 2].argsort()[::-1][:k]
# Determine the class of the test sample
y_pred = mode(y_train[k_min_dist_arr])
y_exp = y_test[test_index]
return y_pred, y_exp
y_pred_arr = []
y_exp_arr = []
for test_indx in range(len(X_test)):
y_pred, y_exp = q_knn_module(test_indx, psi)
y_pred_arr.append(y_pred)
y_exp_arr.append(y_exp)
t = 0
f = 0
for i in range(len(X_test)):
if y_pred_arr[i] == y_exp_arr[i]:
t += 1
else:
f += 1
print('Model accuracy is {}%.'.format(t/(t+f) *100))
|
https://github.com/varunpalakodeti20/Grover-Algo
|
varunpalakodeti20
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit.providers.aer import QasmSimulator
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
from qiskit.circuit.library.standard_gates import XGate, HGate
from operator import *
n = 3
N = 8 #2**n
index_colour_table = {}
colour_hash_map = {}
index_colour_table = {'000':"yellow", '001':"red", '010':"blue", '011':"red", '100':"green", '101':"blue", '110':"orange", '111':"red"}
colour_hash_map = {"yellow":'100', "red":'011', "blue":'000', "green":'001', "orange":'010'}
def database_oracle(index_colour_table, colour_hash_map):
circ_database = QuantumCircuit(n + n)
for i in range(N):
circ_data = QuantumCircuit(n)
idx = bin(i)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion
colour = index_colour_table[idx]
colour_hash = colour_hash_map[colour][::-1]
for j in range(n):
if colour_hash[j] == '1':
circ_data.x(j)
# qiskit maps the rightmost bit as the 0th qubit -> qn, ..., q0
# we therefore reverse the index string -> q0, ..., qn
data_gate = circ_data.to_gate(label=colour).control(num_ctrl_qubits=n, ctrl_state=idx, label="index-"+colour)
circ_database.append(data_gate, list(range(n+n)))
return circ_database
# drawing the database oracle circuit
print("Database Encoding")
database_oracle(index_colour_table, colour_hash_map).draw()
circ_data = QuantumCircuit(n)
m = 4
idx = bin(m)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion
colour = index_colour_table[idx]
colour_hash = colour_hash_map[colour][::-1]
for j in range(n):
if colour_hash[j] == '1':
circ_data.x(j)
print("Internal colour encoding for the colour green (as an example)");
circ_data.draw()
def oracle_grover(database, data_entry):
circ_grover = QuantumCircuit(n + n + 1)
circ_grover.append(database, list(range(n+n)))
target_reflection_gate = XGate().control(num_ctrl_qubits=n, ctrl_state=colour_hash_map[data_entry], label="Reflection of " + "\"" + data_entry + "\" Target")
# control() missing 1 required positional argument: 'self' .... if only 'XGate' used instead of 'XGate()'
# The “missing 1 required positional argument: 'self'” error is raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class.
circ_grover.append(target_reflection_gate, list(range(n, n+n+1)))
circ_grover.append(database, list(range(n+n)))
return circ_grover
print("Grover Oracle (target example: orange)")
oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), "orange").decompose().draw()
def mcz_gate(num_qubits):
num_controls = num_qubits - 1
mcz_gate = QuantumCircuit(num_qubits)
target_mcz = QuantumCircuit(1)
target_mcz.z(0)
target_mcz = target_mcz.to_gate(label="Z_Gate").control(num_ctrl_qubits=num_controls, ctrl_state=None, label="MCZ")
mcz_gate.append(target_mcz, list(range(num_qubits)))
return mcz_gate.reverse_bits()
print("Multi-controlled Z (MCZ) Gate")
mcz_gate(n).decompose().draw()
def diffusion_operator(num_qubits):
circ_diffusion = QuantumCircuit(num_qubits)
qubits_list = list(range(num_qubits))
# Layer of H^n gates
circ_diffusion.h(qubits_list)
# Layer of X^n gates
circ_diffusion.x(qubits_list)
# Layer of Multi-controlled Z (MCZ) Gate
circ_diffusion = circ_diffusion.compose(mcz_gate(num_qubits), qubits_list)
# Layer of X^n gates
circ_diffusion.x(qubits_list)
# Layer of H^n gates
circ_diffusion.h(qubits_list)
return circ_diffusion
print("Diffusion Circuit")
diffusion_operator(n).draw()
# Putting it all together ... !!!
item = "green"
print("Searching for the index of the colour", item)
circuit = QuantumCircuit(n + n + 1, n)
circuit.x(n + n)
circuit.barrier()
circuit.h(list(range(n)))
circuit.h(n+n)
circuit.barrier()
unitary_oracle = oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), item).to_gate(label="Oracle Operator")
unitary_diffuser = diffusion_operator(n).to_gate(label="Diffusion Operator")
M = countOf(index_colour_table.values(), item)
Q = int(np.pi * np.sqrt(N/M) / 4)
for i in range(Q):
circuit.append(unitary_oracle, list(range(n + n + 1)))
circuit.append(unitary_diffuser, list(range(n)))
circuit.barrier()
circuit.measure(list(range(n)), list(range(n)))
circuit.draw()
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = backend_sim.run(transpile(circuit, backend_sim), shots=1024)
result_sim = job_sim.result()
counts = result_sim.get_counts(circuit)
if M==1:
print("Index of the colour", item, "is the index with most probable outcome")
else:
print("Indices of the colour", item, "are the indices the most probable outcomes")
from qiskit.visualization import plot_histogram
plot_histogram(counts)
|
https://github.com/Sinestro38/Shors-Algorithm
|
Sinestro38
|
import matplotlib.pyplot as plt
import numpy as np
from qiskit import QuantumCircuit, Aer, transpile, assemble
from qiskit.visualization import plot_histogram
from math import gcd
from numpy.random import randint
import pandas as pd
from fractions import Fraction
print("Imports Successful")
def c_amod15(a, power):
"""Controlled multiplication by a mod 15"""
if a not in [2,7,8,11,13]:
raise ValueError("'a' must be 2,7,8,11 or 13")
U = QuantumCircuit(4) p
for iteration in range(power):
if a in [2,13]:
U.swap(0,1)
U.swap(1,2)
U.swap(2,3)
if a in [7,8]:
U.swap(2,3)
U.swap(1,2)
U.swap(0,1)
if a == 11:
U.swap(1,3)
U.swap(0,2)
if a in [7,11,13]:
for q in range(4):
U.x(q)
U = U.to_gate()
U.name = "%i^%i mod 15" % (a, power)
c_U = U.control()
return c_U
def qft_dagger(n):
"""n-qubit QFTdagger the first n qubits in circ"""
qc = QuantumCircuit(n)
# 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(-np.pi/float(2**(j-m)), m, j)
qc.h(j)
qc.name = "QFT†"
return qc
# Specify variables
n_count = 8 # number of counting qubits
a = 7
# Create QuantumCircuit with n_count counting qubits
# plus 4 qubits for U to act on
qc = QuantumCircuit(n_count + 4, n_count)
# Initialize counting qubits
# in state |+>
for q in range(n_count):
qc.h(q)
# And auxiliary register in state |1>
qc.x(3+n_count)
# Do controlled-U operations
for q in range(n_count):
qc.append(c_amod15(a, 2**q), # second one is power of 2
[q] + [i+n_count for i in range(4)]) # i+n_count will be 0+8, 1+8, 2+8, 3+8 where n_count = 8
# Do inverse-QFT
qc.append(qft_dagger(n_count), range(n_count))
# Measure circuit
qc.measure(range(n_count), range(n_count))
qc.draw(fold=-1) # -1 means 'do not fold'
aer_sim = Aer.get_backend('aer_simulator')
t_qc = transpile(qc, aer_sim)
qobj = assemble(t_qc)
results = aer_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts)
rows, measured_phases = [], []
for output in counts:
decimal = int(output, 2) # Convert (base 2) string to decimal
phase = decimal/(2**n_count) # Find corresponding eigenvalue
measured_phases.append(phase)
# Add these values to the rows in our table:
rows.append([f"{output}(bin) = {decimal:>3}(dec)",
f"{decimal}/{2**n_count} = {phase:.2f}"])
# Print the rows in a table
headers=["Register Output", "Phase"]
df = pd.DataFrame(rows, columns=headers)
print(df)
rows = []
for phase in measured_phases:
frac = Fraction(phase).limit_denominator(15)
rows.append([phase, f"{frac.numerator}/{frac.denominator}", frac.denominator])
# Print as a table
headers=["Phase", "Fraction", "Guess for r"]
df = pd.DataFrame(rows, columns=headers)
print(df)
def qpe_amod15(a):
n_count = 8
qc = QuantumCircuit(4+n_count, n_count)
for q in range(n_count):
qc.h(q) # Initialize counting qubits in state |+>
qc.x(3+n_count) # And auxiliary register in state |1>
for q in range(n_count): # Do controlled-U operations
qc.append(c_amod15(a, 2**q),
[q] + [i+n_count for i in range(4)])
qc.append(qft_dagger(n_count), range(n_count)) # Do inverse-QFT
qc.measure(range(n_count), range(n_count))
# Simulate Results
aer_sim = Aer.get_backend('aer_simulator')
# Setting memory=True below allows us to see a list of each sequential reading
t_qc = transpile(qc, aer_sim)
qobj = assemble(t_qc, shots=1)
result = aer_sim.run(qobj, memory=True).result()
readings = result.get_memory()
print("Register Reading: " + readings[0])
phase = int(readings[0],2)/(2**n_count)
print("Corresponding Phase: %f" % phase)
return phase
N = 15
a = 7
factor_found = False
attempt = 0
while not factor_found:
attempt += 1
print("\nAttempt %i:" % attempt)
phase = qpe_amod15(a) # Phase = s/r
frac = Fraction(phase).limit_denominator(N) # Denominator should (hopefully!) tell us r
r = frac.denominator
print("Result: r = %i" % r)
if phase != 0:
# Guesses for factors are gcd(x^{r/2} ±1 , 15)
guesses = [gcd(a**(r//2)-1, N), gcd(a**(r//2)+1, N)]
print("Guessed Factors: %i and %i" % (guesses[0], guesses[1]))
for guess in guesses:
if guess not in [1,N] and (N % guess) == 0: # Check to see if guess is a factor
print("*** Non-trivial factor found: %i ***" % guess)
factor_found = True
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
from qiskit_chemistry import FermionicOperator, QMolecule
from qiskit_chemistry.aqua_extensions.components.initial_states import HartreeFock
from qiskit_chemistry.aqua_extensions.components.variational_forms import UCCSD
from qiskit_chemistry import QMolecule as qm
from qiskit_aqua.components.optimizers import COBYLA
from qiskit_aqua import Operator
from qiskit_aqua.algorithms import VQE, ExactEigensolver
from qiskit import Aer
from scipy import linalg as la
import numpy as np
import yaml as yml
from yaml import SafeLoader as Loader
import os
import Load_Hamiltonians as lh
#################### WALK ROOT DIR ############################
root_dir = 'IntegralData/vqe-data-master/Li2_cc-pVTZ/4_ORBITALS'
data_file_list = []
data_file_list_oe = []
for dirName, subdirList, fileList in os.walk(root_dir):
print('Found directory: %s' % dirName)
for fname in sorted(fileList):
if fname.endswith('.yaml'):
data_file_list.append(fname)
#I added an x in front of the 10s for distance to force the sorting, else it sees 13 as 1
#If any distance is in the 100s (unlikely) then add a 'y' in front of dist in file name
###############################################################
############# Output Files to Plot stuff ###############
Fout = open('Li2_ExactEnergies_wMP2_4-orbitals_060319.dat',"w")
#Fout = open('Li2_ExactEnergiesG&FE_wMP2_4-orbitals_052919.dat',"w")
###########################################################
#Variables that can be assigned outside of Loop
map_type = str('jordan_wigner')
truncation_threshold = 0.01
################# IBM BACKEND #####################
backend1 = Aer.get_backend('statevector_simulator')
backend2 = Aer.get_backend('qasm_simulator')
###################################################
output_data = []
#Looping over all of the yaml files in a particular directory and saving the energies from VQE and Exact
ind = 0
for key, file in enumerate(data_file_list):
NW_data_file = str(os.path.join(root_dir,file))
print(NW_data_file)
try:
doc = open(NW_data_file, 'r')
data = yml.load(doc, Loader)
finally:
doc.close()
#Import all the data from a yaml file
n_spatial_orbitals = data['integral_sets'][0]['n_orbitals']
nuclear_repulsion_energy = data['integral_sets'][0]['coulomb_repulsion']['value']
n_orbitals = 2 * n_spatial_orbitals
n_particles = data['integral_sets'][0]['n_electrons']
dist = 2 * data['integral_sets'][0]['geometry']['atoms'][1]['coords'][2]
print('Bond distance is {}'.format(dist))
if map_type == 'parity':
# For two-qubit reduction
n_qubits = n_orbitals - 2
else:
n_qubits = n_orbitals
# Populating the QMolecule class with the data to make calculations easier
qm.num_orbitals = n_spatial_orbitals
qm.num_alpha = n_particles // 2
qm.num_beta = n_particles // 2
qm.core_orbitals = 0
qm.nuclear_repulsion_energy = nuclear_repulsion_energy
qm.hf_energy = data['integral_sets'][0]['scf_energy']['value']
#Importing the integrals
one_electron_import = data['integral_sets'][0]['hamiltonian']['one_electron_integrals']['values']
two_electron_import = data['integral_sets'][0]['hamiltonian']['two_electron_integrals']['values']
#Getting spatial integrals and spin integrals to construct Hamiltonian
one_electron_spatial_integrals, two_electron_spatial_integrals = lh.get_spatial_integrals(one_electron_import,
two_electron_import,
n_spatial_orbitals)
one_electron_spatial_integrals, two_electron_spatial_integrals = lh.trunctate_spatial_integrals(
one_electron_spatial_integrals, two_electron_spatial_integrals, .001)
h1, h2 = lh.convert_to_spin_index(one_electron_spatial_integrals, two_electron_spatial_integrals,
n_spatial_orbitals, truncation_threshold)
#For the MP2 Calculation
qm.mo_eri_ints = two_electron_spatial_integrals
#Constructing the fermion operator and qubit operator from integrals data
fop = FermionicOperator(h1, h2)
qop_paulis = fop.mapping(map_type)
qop = Operator(paulis=qop_paulis.paulis)
################### EXACT RESULT ##################################
exact_eigensolver = ExactEigensolver(qop, k=12)
ret = exact_eigensolver.run()
print('The electronic energy is: {:.12f}'.format(ret['eigvals'][0].real))
print('The total FCI energy is: {:.12f}'.format(ret['eigvals'][0].real + nuclear_repulsion_energy))
exact_energy = ret['eigvals'][0].real + nuclear_repulsion_energy
exact_energy_fe = ret['eigvals'][1].real + nuclear_repulsion_energy
# qop.to_matrix()
# #print(qop)
# eigval, eigvec = np.linalg.eigh(qop.matrix.toarray())
# exact_energy = eigval[0].real + nuclear_repulsion_energy
# exact_energy_fe = eigval[1].real + nuclear_repulsion_energy
# print('{} is the groundstate energy and {} is the first excited state'.format(eigval[0].real,eigval[1].real))
###################################################################
# my_info = [dist, exact_energy,eigval[1].real + nuclear_repulsion_energy, eigval[2].real + nuclear_repulsion_energy, eigval[3].real\
# + nuclear_repulsion_energy, eigval[4].real + nuclear_repulsion_energy, eigval[5].real + nuclear_repulsion_energy, \
# eigval[6].real + nuclear_repulsion_energy, eigval[7].real + nuclear_repulsion_energy, eigval[8].real + nuclear_repulsion_energy, eigval[9].real + nuclear_repulsion_energy, \
# eigval[10].real + nuclear_repulsion_energy, eigval[11].real + nuclear_repulsion_energy]
my_info = [dist, ret['eigvals'][0].real + nuclear_repulsion_energy, exact_energy,ret['eigvals'][1].real + nuclear_repulsion_energy, ret['eigvals'][2].real + nuclear_repulsion_energy, ret['eigvals'][3].real\
+ nuclear_repulsion_energy, ret['eigvals'][4].real + nuclear_repulsion_energy, ret['eigvals'][5].real + nuclear_repulsion_energy, \
ret['eigvals'][6].real + nuclear_repulsion_energy, ret['eigvals'][7].real + nuclear_repulsion_energy, ret['eigvals'][8].real + nuclear_repulsion_energy, ret['eigvals'][9].real + nuclear_repulsion_energy, \
ret['eigvals'][10].real + nuclear_repulsion_energy, ret['eigvals'][11].real + nuclear_repulsion_energy]
output_data.append(my_info)
my_info_to_str = " ".join(str(e) for e in my_info)
Fout.write(my_info_to_str + "\n")
print(output_data)
Fout.close()
# output_data[:,0] = np.sort(output_data[:,0],axis=0)
# print(output_data)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
from qiskit_chemistry import FermionicOperator, QMolecule
from qiskit_chemistry.aqua_extensions.components.initial_states import HartreeFock
from qiskit_chemistry.aqua_extensions.components.variational_forms import UCCSD
from qiskit_chemistry import QMolecule as qm
from qiskit_aqua.components.optimizers import COBYLA
from qiskit_aqua import Operator
from qiskit_aqua.algorithms import VQE, ExactEigensolver
from qiskit import Aer
from scipy import linalg as la
import numpy as np
import yaml as yml
from yaml import SafeLoader as Loader
import os
import Load_Hamiltonians as lh
##Carefully upgrade terra to see if qasm/state-vector simulator perform quicker.##
#################### WALK ROOT DIR ############################
root_dir = 'IntegralData/vqe-data-master/Li2_cc-pVTZ/4_ORBITALS'
data_file_list = []
data_file_list_oe = []
for dirName, subdirList, fileList in os.walk(root_dir):
print('Found directory: %s' % dirName)
for fname in sorted(fileList):
if fname.endswith('.yaml'):
data_file_list.append(fname)
if fname.endswith('.FOCK'):
data_file_list_oe.append(fname)
#This 'del' is four the 4-orbital case since the OEs are missing for the distance 13...
#This should be resolved for the future
del data_file_list[-1]
#I added an x in front of the 10s for distance to force the sorting, else it sees 13 as 1
#If any distance is in the 100s (unlikely) then add a 'y' in front of dist in file name
###############################################################
############# Output Files to Plot stuff ###############
print(data_file_list)
Fout = open('Li2_ExactEnergies_wMP2_4-orbitals_061219.dat',"w")
Fout_op = open('Li2_OptimalParams_wMP2_4-orbitals_061219.dat',"w")
#Fout = open('Li2_ExactEnergiesG&FE_wMP2_4-orbitals_052919.dat',"w")
###########################################################
#Variables that can be assigned outside of Loop
map_type = str('jordan_wigner')
truncation_threshold = 0.01
################# IBM BACKEND #####################
backend1 = Aer.get_backend('statevector_simulator')
backend2 = Aer.get_backend('qasm_simulator')
###################################################
output_data = []
#Looping over all of the yaml files in a particular directory and saving the energies from VQE and Exact
ind = 0
for file1, file2 in zip(data_file_list, data_file_list_oe):
NW_data_file = str(os.path.join(root_dir,file1))
OE_data_file = str(os.path.join(root_dir+'/DOWNFOLDED_ORBITAL_ENERGIES',file2))
try:
doc = open(NW_data_file, 'r')
doc_oe = open(OE_data_file,'r')
data = yml.load(doc, Loader)
content_oe = doc_oe.readlines()
finally:
doc.close()
doc_oe.close()
#Import all the data from a yaml file
print('Getting data')
n_spatial_orbitals = data['integral_sets'][0]['n_orbitals']
nuclear_repulsion_energy = data['integral_sets'][0]['coulomb_repulsion']['value']
n_orbitals = 2 * n_spatial_orbitals
n_particles = data['integral_sets'][0]['n_electrons']
dist = 2 * data['integral_sets'][0]['geometry']['atoms'][1]['coords'][2]
print('Bond distance is {}'.format(dist))
if map_type == 'parity':
# For two-qubit reduction
n_qubits = n_orbitals - 2
else:
n_qubits = n_orbitals
# Populating the QMolecule class with the data to make calculations easier
qm.num_orbitals = n_spatial_orbitals
qm.num_alpha = n_particles // 2
qm.num_beta = n_particles // 2
qm.core_orbitals = 0
qm.nuclear_repulsion_energy = nuclear_repulsion_energy
qm.hf_energy = data['integral_sets'][0]['scf_energy']['value']
###################Get Orbital Energies from FOCK file########################
orbital_energies = []
found = False
count = 0
for line in content_oe:
if 'Eigenvalues:' in line.split()[0]:
found = True
if found and len(line.split()) > 1:
orbital_energies.append(float(line.split()[1]))
count += 1
if count >= n_spatial_orbitals:
break
qm.orbital_energies = orbital_energies
print('OEs:\n',orbital_energies)
##############################################################################
#Importing the integrals
one_electron_import = data['integral_sets'][0]['hamiltonian']['one_electron_integrals']['values']
two_electron_import = data['integral_sets'][0]['hamiltonian']['two_electron_integrals']['values']
#Getting spatial integrals and spin integrals to construct Hamiltonian
one_electron_spatial_integrals, two_electron_spatial_integrals = lh.get_spatial_integrals(one_electron_import,
two_electron_import,
n_spatial_orbitals)
one_electron_spatial_integrals, two_electron_spatial_integrals = lh.trunctate_spatial_integrals(
one_electron_spatial_integrals, two_electron_spatial_integrals, .001)
h1, h2 = lh.convert_to_spin_index(one_electron_spatial_integrals, two_electron_spatial_integrals,
n_spatial_orbitals, truncation_threshold)
#For the MP2 Calculation
qm.mo_eri_ints = two_electron_spatial_integrals
#Constructing the fermion operator and qubit operator from integrals data
fop = FermionicOperator(h1, h2)
qop_paulis = fop.mapping(map_type)
qop = Operator(paulis=qop_paulis.paulis)
#Get Variational form and intial state
init_state = HartreeFock(n_qubits, n_orbitals, n_particles, map_type, two_qubit_reduction=False)
var_op = UCCSD(n_qubits, 1, n_orbitals, n_particles, active_occupied=None, active_unoccupied=None, initial_state=init_state, qubit_mapping=map_type, mp2_reduction=True)
######################## VQE RESULT ###############################
# setup a classical optimizer for VQE
max_eval = 200
optimizer = COBYLA(maxiter=max_eval, disp=True, tol=1e-3)
#Choosing initial params based on previous iteration
if ind == 0:
# initial_params = var_op._mp2_coeff
initial_params = None
ind += 1
elif len(vqe_params) == var_op.num_parameters:
initial_params = vqe_params
else:
initial_params = None
print('Doing VQE')
algorithm = VQE(qop_paulis,var_op,optimizer,'paulis', initial_point=initial_params, )
#VQE_Circ = algorithm.construct_circuit(dumpy_params, backend1)
#print('The VQE circuit:\n',VQE_Circ)
result = algorithm.run(backend1)
vqe_energy = result['energy'] + nuclear_repulsion_energy
vqe_params = result['opt_params']
# print('The VQE energy is: ',vqe_energy)
# print('The optimized params are {}.'.format(vqe_params))
###################################################################
################### EXACT RESULT ##################################
exact_eigensolver = ExactEigensolver(qop, k=2)
ret = exact_eigensolver.run()
print('The electronic energy is: {:.12f}'.format(ret['eigvals'][0].real))
print('The total FCI energy is: {:.12f}'.format(ret['eigvals'][0].real + nuclear_repulsion_energy))
exact_energy = ret['eigvals'][0].real + nuclear_repulsion_energy
exact_energy_fe = ret['eigvals'][1].real + nuclear_repulsion_energy
qop.to_matrix()
#print(qop)
# eigval, eigvec = np.linalg.eigh(qop.matrix.toarray())
# exact_energy = eigval[0].real + nuclear_repulsion_energy
# exact_energy_fe = eigval[1].real + nuclear_repulsion_energy
# print('{} is the groundstate energy and {} is the first excited state'.format(eigval[0].real,eigval[1].real))
# print('Groundstate: \n', eigv[:,0])
# print('First excited state: \n', eigv[:, 0])
###################################################################
# The outputs to plot
my_info = [dist,exact_energy,vqe_energy]
param_info = [dist,vqe_params]
# my_info = [dist, exact_energy,eigval[1].real + nuclear_repulsion_energy, eigval[2].real + nuclear_repulsion_energy, eigval[3].real\
# + nuclear_repulsion_energy, eigval[4].real + nuclear_repulsion_energy, eigval[5].real + nuclear_repulsion_energy, \
# eigval[6].real + nuclear_repulsion_energy, eigval[7].real + nuclear_repulsion_energy, eigval[8].real + nuclear_repulsion_energy, eigval[9].real + nuclear_repulsion_energy, \
# eigval[10].real + nuclear_repulsion_energy, eigval[11].real + nuclear_repulsion_energy]
output_data.append(my_info)
my_info_to_str = " ".join(str(e) for e in my_info)
params_to_str = " ".join(str(e) for e in param_info)
Fout.write(my_info_to_str + "\n")
Fout_op.write(params_to_str + "\n")
print(output_data)
Fout.close()
Fout_op.close()
# output_data[:,0] = np.sort(output_data[:,0],axis=0)
# print(output_data)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
from qiskit_chemistry import FermionicOperator, QMolecule
from qiskit_chemistry.aqua_extensions.components.initial_states import HartreeFock
from qiskit_chemistry.aqua_extensions.components.variational_forms import UCCSD
from qiskit_chemistry import QMolecule as qm
from qiskit_aqua.components.optimizers import COBYLA
from qiskit_aqua import Operator
from qiskit_aqua.algorithms import VQE, ExactEigensolver
from qiskit import Aer
from scipy import linalg as la
import numpy as np
import yaml as yml
from yaml import SafeLoader as Loader
import os
import Load_Hamiltonians as lh
##Carefully upgrade terra to see if qasm/state-vector simulator perform quicker.##
#################### WALK ROOT DIR ############################
#root_dir = 'IntegralData/vqe-data-master/Li2_cc-pVTZ/4_ORBITALS'
root_dir = 'IntegralData/H2_MEKENA'
data_file_list = []
for dirName, subdirList, fileList in os.walk(root_dir):
print('Found directory: %s' % dirName)
for fname in sorted(fileList):
if fname.endswith('.yaml'):
data_file_list.append(fname)
#This 'del' is four the 4-orbital case since the OEs are missing for the distance 13...
#This should be resolved for the future
#del data_file_list[-1]
# print(data_file_list)
# print(data_file_list_oe)
#I added an x in front of the 10s for distance to force the sorting, else it sees 13 as 1
#If any distance is in the 100s (unlikely) then add a 'y' in front of dist in file name
###############################################################
############# Output Files to Plot stuff ###############
print(data_file_list)
Fout = open('H2_VQEEnergies_noMP2_4-orbitals_071519.dat',"w")
Fout_op = open('H2_OptimalParams_noMP2_4-orbitals_071519.dat',"w")
#Fout = open('Li2_ExactEnergiesG&FE_wMP2_4-orbitals_052919.dat',"w")
###########################################################
#Variables that can be assigned outside of Loop
map_type = str('jordan_wigner')
truncation_threshold = 0.01
################# IBM BACKEND #####################
backend1 = Aer.get_backend('statevector_simulator')
backend2 = Aer.get_backend('qasm_simulator')
###################################################
output_data = []
#Looping over all of the yaml files in a particular directory and saving the energies from VQE and Exact
ind = 0
for key, file in enumerate(data_file_list):
NW_data_file = str(os.path.join(root_dir,file))
print('First File', NW_data_file)
try:
doc = open(NW_data_file, 'r')
data = yml.load(doc, Loader)
finally:
doc.close()
#Import all the data from a yaml file
print('Getting data')
n_spatial_orbitals = data['integral_sets'][0]['n_orbitals']
print('{} spatial orbitals'.format(n_spatial_orbitals))
nuclear_repulsion_energy = data['integral_sets'][0]['coulomb_repulsion']['value']
print('{} Coloumb repulsion'.format(nuclear_repulsion_energy))
n_orbitals = 2 * n_spatial_orbitals
n_particles = data['integral_sets'][0]['n_electrons']
print('{} particles'.format(n_particles))
dist = 2 * data['integral_sets'][0]['geometry']['atoms'][1]['coords'][2]
print('Bond distance is {}'.format(dist))
if map_type == 'parity':
# For two-qubit reduction
n_qubits = n_orbitals - 2
else:
n_qubits = n_orbitals
# Populating the QMolecule class with the data to make calculations easier
qm.num_orbitals = n_spatial_orbitals
qm.num_alpha = n_particles // 2
qm.num_beta = n_particles // 2
qm.core_orbitals = 0
qm.nuclear_repulsion_energy = nuclear_repulsion_energy
qm.hf_energy = data['integral_sets'][0]['scf_energy']['value']
#Importing the integrals
one_electron_import = data['integral_sets'][0]['hamiltonian']['one_electron_integrals']['values']
two_electron_import = data['integral_sets'][0]['hamiltonian']['two_electron_integrals']['values']
#Getting spatial integrals and spin integrals to construct Hamiltonian
one_electron_spatial_integrals, two_electron_spatial_integrals = lh.get_spatial_integrals(one_electron_import,
two_electron_import,
n_spatial_orbitals)
one_electron_spatial_integrals, two_electron_spatial_integrals = lh.trunctate_spatial_integrals(
one_electron_spatial_integrals, two_electron_spatial_integrals, .001)
h1, h2 = lh.convert_to_spin_index(one_electron_spatial_integrals, two_electron_spatial_integrals,
n_spatial_orbitals, truncation_threshold)
#For the MP2 Calculation
qm.mo_eri_ints = two_electron_spatial_integrals
#Constructing the fermion operator and qubit operator from integrals data
fop = FermionicOperator(h1, h2)
qop_paulis = fop.mapping(map_type)
print(qop_paulis)
qop = Operator(paulis=qop_paulis.paulis)
#Get Variational form and intial state
# init_state = HartreeFock(n_qubits, n_orbitals, n_particles, map_type, two_qubit_reduction=False)
# var_op = UCCSD(n_qubits, 1, n_orbitals, n_particles, active_occupied=None, active_unoccupied=None, initial_state=init_state, qubit_mapping=map_type, mp2_reduction=False)
#
# ######################## VQE RESULT ###############################
# # setup a classical optimizer for VQE
# max_eval = 200
# optimizer = COBYLA(maxiter=max_eval, disp=True, tol=1e-2)
#
# #Choosing initial params based on previous iteration
# if ind == 0:
# # initial_params = var_op._mp2_coeff
# initial_params = None
# ind += 1
# elif len(vqe_params) == var_op.num_parameters:
# initial_params = vqe_params
# else:
# initial_params = None
#
#
# print('Doing VQE')
# algorithm = VQE(qop_paulis,var_op,optimizer,'paulis', initial_point=initial_params, )
# #VQE_Circ = algorithm.construct_circuit(dumpy_params, backend1)
# #print('The VQE circuit:\n',VQE_Circ)
# result = algorithm.run(backend1)
# vqe_energy = result['energy'] + nuclear_repulsion_energy
# vqe_params = result['opt_params']
# # print('The VQE energy is: ',vqe_energy)
# # print('The optimized params are {}.'.format(vqe_params))
# ###################################################################
#
# ################### EXACT RESULT ##################################
# exact_eigensolver = ExactEigensolver(qop, k=2)
# ret = exact_eigensolver.run()
# print('The electronic energy is: {:.12f}'.format(ret['eigvals'][0].real))
# print('The total FCI energy is: {:.12f}'.format(ret['eigvals'][0].real + nuclear_repulsion_energy))
# exact_energy = ret['eigvals'][0].real + nuclear_repulsion_energy
# exact_energy_fe = ret['eigvals'][1].real + nuclear_repulsion_energy
# qop.to_matrix()
# #print(qop)
# # eigval, eigvec = np.linalg.eigh(qop.matrix.toarray())
# # exact_energy = eigval[0].real + nuclear_repulsion_energy
# # exact_energy_fe = eigval[1].real + nuclear_repulsion_energy
# # print('{} is the groundstate energy and {} is the first excited state'.format(eigval[0].real,eigval[1].real))
# # print('Groundstate: \n', eigv[:,0])
# # print('First excited state: \n', eigv[:, 0])
# ###################################################################
# # The outputs to plot
# my_info = [dist,exact_energy,vqe_energy]
# param_info = [dist,vqe_params]
# # my_info = [dist, exact_energy,eigval[1].real + nuclear_repulsion_energy, eigval[2].real + nuclear_repulsion_energy, eigval[3].real\
# # + nuclear_repulsion_energy, eigval[4].real + nuclear_repulsion_energy, eigval[5].real + nuclear_repulsion_energy, \
# # eigval[6].real + nuclear_repulsion_energy, eigval[7].real + nuclear_repulsion_energy, eigval[8].real + nuclear_repulsion_energy, eigval[9].real + nuclear_repulsion_energy, \
# # eigval[10].real + nuclear_repulsion_energy, eigval[11].real + nuclear_repulsion_energy]
# output_data.append(my_info)
# my_info_to_str = " ".join(str(e) for e in my_info)
# params_to_str = " ".join(str(e) for e in param_info)
# Fout.write(my_info_to_str + "\n")
# Fout_op.write(params_to_str + "\n")
print(output_data)
Fout.close()
Fout_op.close()
# output_data[:,0] = np.sort(output_data[:,0],axis=0)
# print(output_data)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
from qiskit_chemistry import FermionicOperator, QMolecule
from qiskit_chemistry.aqua_extensions.components.initial_states import HartreeFock
from qiskit_chemistry.aqua_extensions.components.variational_forms import UCCSD
from qiskit_chemistry import QMolecule as qm
from qiskit_aqua.components.optimizers import COBYLA
from qiskit_aqua import Operator
from qiskit_aqua.algorithms import VQE, ExactEigensolver
from qiskit import Aer
from scipy import linalg as la
import numpy as np
import yaml as yml
from yaml import SafeLoader as Loader
import os
from dask.distributed import Client, LocalCluster
import dask
import Load_Hamiltonians as lh
#Define functions that can be used in parallel algorithm
def read_variables(root_dir, file1, file2):
Ham_data_file = str(os.path.join(root_dir, file1))
OrbE_data_file = str(os.path.join(root_dir + '/DOWNFOLDED_ORBITAL_ENERGIES', file2))
try:
doc_nw = open(Ham_data_file, 'r')
doc_orbe = open(OrbE_data_file, 'r')
dat = yml.load(doc_nw, Loader)
content_orbe = doc_orbe.readlines()
finally:
doc_nw.close()
doc_orbe.close()
# Import all the data from a yaml file
print('Getting data')
#Importing the integrals
one_e = dat['integral_sets'][0]['hamiltonian']['one_electron_integrals']['values']
two_e = dat['integral_sets'][0]['hamiltonian']['two_electron_integrals']['values']
num_spatial_orbitals = dat['integral_sets'][0]['n_orbitals']
coulomb_energy = dat['integral_sets'][0]['coulomb_repulsion']['value']
num_orbitals = 2 * num_spatial_orbitals
num_particles = dat['integral_sets'][0]['n_electrons']
d = 2 * dat['integral_sets'][0]['geometry']['atoms'][1]['coords'][2]
print('Bond distance is {}'.format(d))
if map_type == 'parity':
# For two-qubit reduction
num_qubits = num_orbitals - 2
else:
num_qubits = num_orbitals
# Populating the QMolecule class with the data to make calculations easier - No need for returns
# qm.num_orbitals = num_spatial_orbitals
# qm.num_alpha = num_particles // 2
# qm.num_beta = num_particles // 2
# qm.core_orbitals = 0
# qm.nuclear_repulsion_energy = coulomb_energy
# qm.hf_energy = dat['integral_sets'][0]['scf_energy']['value']
###################Get Orbital Energies from FOCK file########################
orbital_energies = []
found = False
count = 0
for line in content_orbe:
if 'Eigenvalues:' in line.split()[0]:
found = True
if found and len(line.split()) > 1:
orbital_energies.append(float(line.split()[1]))
count += 1
if count >= num_spatial_orbitals:
break
qm.orbital_energies = orbital_energies
return num_spatial_orbitals, num_orbitals, num_particles, num_qubits, d, coulomb_energy, one_e, two_e
def get_molecular_qubit_operator(one_ints, two_ints, n_orbitals, thresh, qubit_map):
# Getting spatial integrals and spin integrals to construct Hamiltonian
one_electron_spatial_integrals, two_electron_spatial_integrals = lh.get_spatial_integrals(one_ints,
two_ints,
n_orbitals)
h1, h2 = lh.convert_to_spin_index(one_electron_spatial_integrals, two_electron_spatial_integrals,
n_orbitals, thresh)
# For the MP2 Calculation
qm.mo_eri_ints = two_electron_spatial_integrals
# Constructing the fermion operator and qubit operator from integrals data
fop = FermionicOperator(h1, h2)
qop_paulis = fop.mapping(qubit_map)
return qop_paulis
def run_vqe(pauli_operator, num_orbitals, num_particles, num_qubits, coulomb_energy, mapping, backend):
var_energy = 0
#Get Variational form and intial state
initial_state = HartreeFock(num_qubits, num_orbitals, num_particles, mapping, two_qubit_reduction=False)
var_op = UCCSD(num_qubits, 1, num_orbitals, num_particles, active_occupied=None, active_unoccupied=None, initial_state=initial_state, qubit_mapping=mapping, mp2_reduction=True)
######################## VQE RESULT ###############################
# setup a classical optimizer for VQE
max_eval = 200
optimizer = COBYLA(maxiter=max_eval, disp=True, tol=1e-3)
print('Doing VQE')
algorithm = VQE(pauli_operator, var_op, optimizer,'paulis', initial_point=None, )
result = algorithm.run(backend)
var_energy = result['energy'] + coulomb_energy
# vqe_params = result['opt_params']
return var_energy
def run_exact(pauli_operator, coulomb_energy):
exact_eigensolver = ExactEigensolver(pauli_operator, k=1)
ret = exact_eigensolver.run()
print('The electronic energy is: {:.12f}'.format(ret['eigvals'][0].real))
print('The total FCI energy is: {:.12f}'.format(ret['eigvals'][0].real + coulomb_energy))
ed_energy = ret['eigvals'][0].real + coulomb_energy
return ed_energy
##Carefully upgrade terra to see if qasm/state-vector simulator perform quicker.##
#################### WALK ROOT DIR ############################
root_dir = 'IntegralData/vqe-data-master/Li2_cc-pVTZ/4_ORBITALS'
data_file_list = []
data_file_list_oe = []
for dirName, subdirList, fileList in os.walk(root_dir):
print('Found directory: %s' % dirName)
for fname in sorted(fileList):
if fname.endswith('.yaml'):
data_file_list.append(fname)
if fname.endswith('.FOCK'):
data_file_list_oe.append(fname)
#This 'del' is four the 4-orbital case since the OEs are missing for the distance 13...
#This should be resolved for the future
del data_file_list[-1]
#I added an x in front of the 10s for distance to force the sorting, else it sees 13 as 1
#If any distance is in the 100s (unlikely) then add a 'y' in front of dist in file name
###############################################################
############# Output Files to Plot stuff ###############
print(data_file_list)
Fout = open('Li2_ExactEnergies_wMP2_4-orbitals_061219.dat',"w")
###########################################################
#Variables that can be assigned outside of Loop
map_type = str('jordan_wigner')
truncation_threshold = 0.01
################# IBM BACKEND #####################
backend1 = Aer.get_backend('statevector_simulator')
backend2 = Aer.get_backend('qasm_simulator')
###################################################
@dask.delayed
def final(root_dir, file1, file2):
spatial_orbitals, spin_orbitals, particle_num, qubits_num, dist, nuclear_energy, one_electron_import, two_electron_import = read_variables(
root_dir, file1, file2)
qop = get_molecular_qubit_operator(one_electron_import, two_electron_import, spatial_orbitals, truncation_threshold,
map_type)
# vqe_energy = run_vqe(qop, spin_orbitals, particle_num, qubits_num, nuclear_energy, map_type, backend1)
vqe_energy = 0
exact_energy = run_exact(qop, nuclear_energy)
my_info = [dist, exact_energy, vqe_energy]
return my_info
# print(output_data)
Fout.close()
if __name__ == "__main__":
computations = []
cluster = LocalCluster()
client = Client(cluster, asyncronous=True)
for file1, file2 in zip(data_file_list, data_file_list_oe):
computations.append(final(root_dir, file1, file2))
# my_info_to_str = " ".join(str(e) for e in final_energies)
# Fout.write(my_info_to_str + "\n")
output_data = dask.compute(*computations, scheduler='distributed')
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
#Once debugged, put this in Jupyter notebook
from math import pi
import numpy as np
import scipy as sp
# importing Qiskit
from qiskit import Aer
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
from qiskit.tools.visualization import plot_histogram, matplotlib_circuit_drawer
from scipy import linalg as las
def xx_unitary(qcirc,theta, qa, qi, qj):
# This is the circuit to do simulate an X_iX_j exponentiated Pauli operator where i < j
qcirc.h(qi)
qcirc.h( qj)
qcirc.cx(qj, qi)
qcirc.crz(2.0 *theta,qa,qi)
qcirc.cx(qj, qi)
qcirc.h(qi)
qcirc.h( qj)
def yy_unitary(qcirc,theta, qa, qi, qj):
# This is the circuit to do simulate an Y_iY_j exponentiated Pauli operator where i < j
qcirc.rx(pi/2.,qi)
qcirc.rx(pi / 2., qj)
qcirc.cx(qj, qi)
qcirc.crz(2.0 * theta,qa,qi)
qcirc.cx(qj, qi)
qcirc.rx(-pi/2.,qi)
qcirc.rx(-pi / 2., qj)
def zz_unitary(qcirc,theta, qa, qi, qj):
# This is the circuit to do simulate an Z_iZ_j exponentiated Pauli operator where i < j
#I had to add a multiple of 2 for the CZ and now the eigenvalues match the unitaries in Miro's code
qcirc.cx(qj, qi)
qcirc.crz(2.0 * theta,qa,qi)
qcirc.cx(qj, qi)
def z_unitary(qcirc,theta, qa, qi):
qcirc.crz(2.0 * theta, qa, qi)
def unitary_specifiedtrotter(qcirc, h0, h1, h2, h3, h4, qa, q0, q1):
z_unitary(qcirc, h0, qa, q0)
z_unitary(qcirc, h1, qa, q1)
xx_unitary(qcirc, h2, qa, q0, q1)
yy_unitary(qcirc, h3, qa, q0, q1)
# Expectation value of the following term can be computed classically with HF state.
zz_unitary(qcirc, h4, qa, q0, q1)
# print(qcirc)
return 0
# Now begins main()
backend = Aer.get_backend('qasm_simulator')
# backend = Aer.get_backend('unitary_simulator')
# qr = QuantumRegister(2,name='qr')
# a = QuantumRegister(1, name='a')
# cr = ClassicalRegister(1)
# Circuit = QuantumCircuit(qr,cr)
# Circuit.add_register(a)
# Hamiltonian Values - Interestingly the entangling XX and YY terms are dominant when R is large - why?
# R = 1.55
hI = -0.2265
h0 = 0.1843
h1 = -0.0549
h2 = 0.1165
h3 = 0.1165
h4 = 0.4386
#Strangly there is a t_0 being used for U(2^k t_0) = (e^i\theta Ht_0)^(2^k)
#remember is trotter expansion dt = t_0
t_0 = 9.830
# Digit of precision
bits = 8
# Circuit.h(a[0])
# Circuit.rz(0,a[0]) # This is identity, but will be needed in the circuit to get increased bits of precision
# Circuit.x(qr[0]) # Initialize HF state for two qubit system
# unitary_specifiedtrotter(Circuit,(2**bits)*h0*t_0, (2**bits)*h1*t_0, (2**bits)*h2*t_0, (2**bits)*h3*t_0,\
# (2**bits)*h4*t_0, a[0], qr[0], qr[1])
#
# # Circuit.u1(t_0 * hI * (2 ** bits), qr[0])
# Circuit.h(a[0])
# Circuit.measure(a[0], cr[0])
#
# # print('Circuit for least significant bit\n',Circuit)
# #Circuit.draw(output='mpl')
#
#
# alg = execute(Circuit, backend)
# result = alg.result()
# count = result.get_counts(Circuit)
# print(count)
# x = 1 if count['1'] > count['0'] else 0
# c1 = count['1']/1024
# c2 = count['0']/1024
# print('The distribution of measurements are {} with population percentage {}'.format(x, c1)) if count['1'] > count['0']\
# else print('The distribution of measurements are {} with population percentage {}'.format(x, c1))
# Execute unitary_sim
# result = execute(Circuit, backend).result()
# unitary = result.get_unitary(Circuit)
# print("Circuit unitary:\n", unitary)
# eval, evec = las.eigh(unitary)
# print(eval[0])
binary_phase = []
x = 0
omega_coef = 0
for k in range(bits,0, -1):
it_num = k-1
print('exponent: ', it_num)
omega_coef /= 2.0
# omega_coef = 0
# for j in range(1,k-1):
# print('j = ',j)
# omega_coef += -pi*binary_phase[j-1]/(2**j)
print(' {} is phase kickback'.format(omega_coef))
qr = QuantumRegister(2, name='qr')
a = QuantumRegister(1, name='a')
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.add_register(a)
qc.h(a[0])
qc.u1(-pi*2.*omega_coef,a[0])
qc.x(qr[0]) # Initialize HF state for two qubit system
unitary_specifiedtrotter(qc,(2**it_num)*h0*t_0, (2**it_num)*h1*t_0, (2**it_num)*h2*t_0, (2**it_num)*h3*t_0,\
(2**it_num)*h4*t_0, a[0], qr[0], qr[1])
# qc.u1(t_0 * hI * (2 ** bits), a[0])
qc.h(a[0])
qc.measure(a[0], cr[0])
alg = execute(qc, backend)
result = alg.result()
count = result.get_counts(qc)
x = 1 if count['1'] > count['0'] else 0
omega_coef = omega_coef + x / 2
print('phase is {} with a bit {} for k = {}'.format(omega_coef, x, k))
binary_phase.insert(0,x)
E = (omega_coef-3*pi)/t_0
print(E+hI)
print(binary_phase)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
from math import pi
import numpy as np
import scipy as sp
# importing Qiskit
from qiskit import Aer
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
from qiskit.tools.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
# We first define controlled gates used in the IPEA
def cu1fixed(qProg, c, t, a):
qProg.u1(-a, t)
qProg.cx(c, t)
qProg.u1(a, t)
qProg.cx(c, t)
def cu5pi8(qProg, c, t):
cu1fixed(qProg, c, t, -5.0*pi/8.0)
backend = Aer.get_backend('statevector_simulator')
# backend = Aer.get_backend('qasm_simulator')
# We then prepare quantum and classical registers and the circuit
qr = QuantumRegister(2)
cr = ClassicalRegister(1)
Circuit = QuantumCircuit(qr,cr)
# Apply IPEA
Circuit.h(qr[0])
cu5pi8(Circuit, qr[0], qr[1])
# for i in range(8):
# cu5pi8(Circuit, qr[0], qr[1])
# Circuit.u1(-3*pi/4,qr[0])
Circuit.h(qr[0])
#Circuit.measure(qr[0], cr[0])
print('Circuit for least significant bit',Circuit)
alg = execute(Circuit, backend)
result = alg.result()
print(result)
vec = result.get_statevector(Circuit)
vecx = np.conj(vec)
print(vec)
#plot_histogram(result.get_counts())
'''
Circuit.h(qr[0])
Circuit.u1(-pi/4., qr[1])
Circuit.cx(qr[0], qr[1])
Circuit.u1(pi/4., qr[1])
Circuit.cx(qr[0], qr[1])
Circuit.h(qr[0])
Circuit.measure(qr[0], cr[0])
print(Circuit)
alg = execute(Circuit, backend)
result = alg.result()
count = result.get_counts(Circuit)
print(count)
# state_vec = result.get_statevector(Circuit)
# vecx = np.conj(state_vec)
# print(np.outer(vecx,state_vec))
'''
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
from qiskit_chemistry import FermionicOperator, QMolecule
from qiskit_chemistry.aqua_extensions.components.initial_states import HartreeFock
from qiskit_chemistry.aqua_extensions.components.variational_forms import UCCSD
from qiskit_aqua.components.optimizers import COBYLA
from qiskit_aqua import Operator
from qiskit_aqua.algorithms import VQE, ExactEigensolver
from qiskit import Aer
from scipy import linalg as la
import numpy as np
import yaml as yml
from yaml import SafeLoader as Loader
import os
from dask.distributed import Client, LocalCluster
import dask
import Load_Hamiltonians as lh
#Define functions that can be used in parallel algorithm
def read_variables(root_dir, file1):
#print('Root directory\n',root_dir)
#print('The file: \n', file1)
Ham_data_file = str(os.path.join(root_dir, file1[0]))
try:
doc_nw = open(Ham_data_file, 'r')
dat = yml.load(doc_nw, Loader)
finally:
doc_nw.close()
# Import all the data from a yaml file
print('Getting data')
#Importing the integrals
one_e = dat['integral_sets'][0]['hamiltonian']['one_electron_integrals']['values']
two_e = dat['integral_sets'][0]['hamiltonian']['two_electron_integrals']['values']
num_spatial_orbitals = dat['integral_sets'][0]['n_orbitals']
coulomb_energy = dat['integral_sets'][0]['coulomb_repulsion']['value']
num_orbitals = 2 * num_spatial_orbitals
num_particles = dat['integral_sets'][0]['n_electrons']
d = 2 * dat['integral_sets'][0]['geometry']['atoms'][1]['coords'][2]
print('Bond distance is {}'.format(d))
if map_type == 'parity':
# For two-qubit reduction
num_qubits = num_orbitals - 2
else:
num_qubits = num_orbitals
return num_spatial_orbitals, num_orbitals, num_particles, num_qubits, d, coulomb_energy, one_e, two_e
def get_molecular_qubit_operator(one_ints, two_ints, n_orbitals, thresh, qubit_map):
# Getting spatial integrals and spin integrals to construct Hamiltonian
one_electron_spatial_integrals, two_electron_spatial_integrals = lh.get_spatial_integrals(one_ints,
two_ints,
n_orbitals)
h1, h2 = lh.convert_to_spin_index(one_electron_spatial_integrals, two_electron_spatial_integrals,
n_orbitals, thresh)
# Constructing the fermion operator and qubit operator from integrals data
fop = FermionicOperator(h1, h2)
qop_paulis = fop.mapping(qubit_map)
return qop_paulis
def run_vqe(pauli_operator, num_orbitals, num_particles, num_qubits, coulomb_energy, mapping, backend):
var_energy = 0
#Get Variational form and intial state
initial_state = HartreeFock(num_qubits, num_orbitals, num_particles, mapping, two_qubit_reduction=False)
var_op = UCCSD(num_qubits, 1, num_orbitals, num_particles, active_occupied=None, active_unoccupied=None, initial_state=initial_state, qubit_mapping=mapping)
######################## VQE RESULT ###############################
# setup a classical optimizer for VQE
max_eval = 200
optimizer = COBYLA(maxiter=max_eval, disp=True, tol=1e-3)
print('Doing VQE')
algorithm = VQE(pauli_operator, var_op, optimizer,'paulis', initial_point=None, )
result = algorithm.run(backend)
var_energy = result['energy'] + coulomb_energy
# vqe_params = result['opt_params']
return var_energy
def run_exact(pauli_operator, coulomb_energy):
exact_eigensolver = ExactEigensolver(pauli_operator, k=1)
ret = exact_eigensolver.run()
print('The electronic energy is: {:.12f}'.format(ret['eigvals'][0].real))
print('The total FCI energy is: {:.12f}'.format(ret['eigvals'][0].real + coulomb_energy))
ed_energy = ret['eigvals'][0].real + coulomb_energy
return ed_energy
##Carefully upgrade terra to see if qasm/state-vector simulator perform quicker.##
#################### WALK ROOT DIR ############################
#U
root_dir = '/Users/mmetcalf/Dropbox/Quantum Embedding/Codes/Lithium_Downfolding/Qiskit Chem/HamiltonianDownfolding_w_IBM/IntegralData/vqe-data-master/Li2_cc-pVTZ/4_ORBITALS/'
data_file_list = []
for dirName, subdirList, fileList in os.walk(root_dir):
print('Found directory: %s' % dirName)
for fname in sorted(fileList):
if fname.endswith('.yaml'):
data_file_list.append(fname)
############# Output Files to Plot stuff ###############
print(data_file_list)
Fout = open('Mekena_OutputData.dat',"w")
###########################################################
#Variables that can be assigned outside of Loop
map_type = str('jordan_wigner')
truncation_threshold = 0.01
################# IBM BACKEND #####################
backend1 = Aer.get_backend('statevector_simulator')
###################################################
@dask.delayed
def final(root_dir, file1):
#print('Starting Loop')
spatial_orbitals, spin_orbitals, particle_num, qubits_num, dist, nuclear_energy, one_electron_import, two_electron_import = read_variables(
root_dir, file1)
#print('Have variables')
qop = get_molecular_qubit_operator(one_electron_import, two_electron_import, spatial_orbitals, truncation_threshold,
map_type)
#print('Have qubit operator')
# vqe_energy = run_vqe(qop, spin_orbitals, particle_num, qubits_num, nuclear_energy, map_type, backend1)
vqe_energy = 0
exact_energy = run_exact(qop, nuclear_energy)
#print('Obtained the energy')
my_info = [dist, exact_energy, vqe_energy]
#print('info: ',my_info)
return my_info
# print(output_data)
Fout.close()
if __name__ == "__main__":
computations = []
cluster = LocalCluster()
client = Client(cluster, asyncronous=True)
for file1 in zip(data_file_list):
computations.append(final(root_dir, file1))
# final(root_dir, file1)
# my_info_to_str = " ".join(str(e) for e in final_energies)
# Fout.write(my_info_to_str + "\n")
output_data = dask.compute(*computations, scheduler='distributed')
print(output_data)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
from qiskit_chemistry import FermionicOperator, QMolecule
from qiskit_chemistry.aqua_extensions.components.initial_states import HartreeFock
from qiskit_chemistry.aqua_extensions.components.variational_forms import UCCSD
from qiskit_aqua.components.optimizers import COBYLA
from qiskit_aqua import Operator
from qiskit_aqua.algorithms import VQE, ExactEigensolver
from qiskit import Aer
from scipy import linalg as la
import numpy as np
import yaml as yml
from yaml import SafeLoader as Loader
import os
from qiskit.tools.parallel import parallel_map
from qiskit.tools.events import TextProgressBar
import Load_Hamiltonians as lh
#Define functions that can be used in parallel algorithm
def read_variables(root_dir, file1):
#print('Root directory\n',root_dir)
#print('The file: \n', file1)
Ham_data_file = str(os.path.join(root_dir, file1))
try:
doc_nw = open(Ham_data_file, 'r')
dat = yml.load(doc_nw, Loader)
finally:
doc_nw.close()
# Import all the data from a yaml file
print('Getting data')
#Importing the integrals
one_e = dat['integral_sets'][0]['hamiltonian']['one_electron_integrals']['values']
two_e = dat['integral_sets'][0]['hamiltonian']['two_electron_integrals']['values']
num_spatial_orbitals = dat['integral_sets'][0]['n_orbitals']
coulomb_energy = dat['integral_sets'][0]['coulomb_repulsion']['value']
num_orbitals = 2 * num_spatial_orbitals
num_particles = dat['integral_sets'][0]['n_electrons']
d = 2 * dat['integral_sets'][0]['geometry']['atoms'][1]['coords'][2]
print('Bond distance is {}'.format(d))
if map_type == 'parity':
# For two-qubit reduction
num_qubits = num_orbitals - 2
else:
num_qubits = num_orbitals
return num_spatial_orbitals, num_orbitals, num_particles, num_qubits, d, coulomb_energy, one_e, two_e
def get_molecular_qubit_operator(one_ints, two_ints, n_orbitals, thresh, qubit_map):
# Getting spatial integrals and spin integrals to construct Hamiltonian
one_electron_spatial_integrals, two_electron_spatial_integrals = lh.get_spatial_integrals(one_ints,
two_ints,
n_orbitals)
h1, h2 = lh.convert_to_spin_index(one_electron_spatial_integrals, two_electron_spatial_integrals,
n_orbitals, thresh)
# Constructing the fermion operator and qubit operator from integrals data
fop = FermionicOperator(h1, h2)
qop_paulis = fop.mapping(qubit_map, num_workers=1)
return qop_paulis
def run_vqe(pauli_operator, num_orbitals, num_particles, num_qubits, coulomb_energy, mapping, backend):
var_energy = 0
#Get Variational form and intial state
initial_state = HartreeFock(num_qubits, num_orbitals, num_particles, mapping, two_qubit_reduction=False)
var_op = UCCSD(num_qubits, 1, num_orbitals, num_particles, active_occupied=None, active_unoccupied=None, initial_state=initial_state, qubit_mapping=mapping)
######################## VQE RESULT ###############################
# setup a classical optimizer for VQE
max_eval = 200
optimizer = COBYLA(maxiter=max_eval, disp=True, tol=1e-3)
print('Doing VQE')
algorithm = VQE(pauli_operator, var_op, optimizer,'paulis', initial_point=None, )
result = algorithm.run(backend)
var_energy = result['energy'] + coulomb_energy
# vqe_params = result['opt_params']
return var_energy
def run_exact(pauli_operator, coulomb_energy):
exact_eigensolver = ExactEigensolver(pauli_operator, k=1)
ret = exact_eigensolver.run()
print('The electronic energy is: {:.12f}'.format(ret['eigvals'][0].real))
print('The total FCI energy is: {:.12f}'.format(ret['eigvals'][0].real + coulomb_energy))
ed_energy = ret['eigvals'][0].real + coulomb_energy
return ed_energy
def final(file, root_directory, backend):
# print('Starting Loop')
spatial_orbitals, spin_orbitals, particle_num, qubits_num, dist, nuclear_energy, one_electron_import, two_electron_import = read_variables(root_directory, file)
# print('Have variables')
qop = get_molecular_qubit_operator(one_electron_import, two_electron_import, spatial_orbitals, truncation_threshold,
map_type)
# print('Have qubit operator')
# vqe_energy = run_vqe(qop, spin_orbitals, particle_num, qubits_num, nuclear_energy, map_type, backend)
vqe_energy = 0
exact_energy = run_exact(qop, nuclear_energy)
# print('Obtained the energy')
my_info = [dist, exact_energy, vqe_energy]
# print('info: ',my_info)
return my_info
##Carefully upgrade terra to see if qasm/state-vector simulator perform quicker.##
#################### WALK ROOT DIR ############################
#U
root_dir = '/Users/mmetcalf/Dropbox/Quantum Embedding/Codes/Lithium_Downfolding/Qiskit Chem/HamiltonianDownfolding_w_IBM/IntegralData/vqe-data-master/Li2_cc-pVTZ/4_ORBITALS/'
data_file_list = []
for dirName, subdirList, fileList in os.walk(root_dir):
print('Found directory: %s' % dirName)
for fname in sorted(fileList):
if fname.endswith('.yaml'):
data_file_list.append(fname)
############# Output Files to Plot stuff ###############
# print(data_file_list)
Fout = open('Mekena_OutputData.dat',"w")
###########################################################
#Variables that can be assigned outside of Loop
map_type = str('jordan_wigner')
truncation_threshold = 0.01
################# IBM BACKEND #####################
backend1 = Aer.get_backend('statevector_simulator')
###################################################
result = parallel_map(final, data_file_list, task_args=(root_dir, backend1))
print(result)
# print(output_data)
Fout.close()
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
from qiskit.chemistry import FermionicOperator
from qiskit.chemistry.aqua_extensions.components.initial_states import HartreeFock
from qiskit.chemistry.aqua_extensions.components.variational_forms import UCCSD
from qiskit.chemistry import QMolecule as qm
from qiskit.aqua.components.optimizers import COBYLA
from qiskit.aqua import Operator
from qiskit.aqua.algorithms import VQE, ExactEigensolver
from qiskit import Aer
from qiskit.tools.visualization import circuit_drawer
from qiskit.chemistry.drivers import PySCFDriver, UnitsType
import numpy as np
import yaml as yml
from yaml import SafeLoader as Loader
import Load_Hamiltonians as lh
import os
#Importing data generated from NW Chem to run experiments
#Li2_cc-pVTZ_4_ORBITALS_Li2-4_ORBITALS-ccpVTZ-2_1384
root_dir = '/Users/mmetcalf/Dropbox/Quantum Embedding/Codes/Lithium_Downfolding/Qiskit Chem/HamiltonianDownfolding_w_IBM/IntegralData/H2_MEKENA/'
NW_data_file = str(root_dir+'h2_ccpvtz_ccsd_0_80au_ducc_1_3.yaml')
# NW_data_file = str('H2.yaml')
OE_data_file = str(root_dir+ 'h2_ccpvtz_ccsd_0_80au.FOCK')
# NW_data_file = 'H2.yaml'
doc_nw = open(NW_data_file,'r')
doc_oe = open(OE_data_file,'r')
data = yml.load(doc_nw,Loader)
content_oe = doc_oe.readlines()
#################
backend1 = Aer.get_backend('statevector_simulator')
backend2 = Aer.get_backend('qasm_simulator')
#################
###########################################################
#Initialize Variables
map_type = str('jordan_wigner')
truncation_threshold = 0.1
n_spatial_orbitals = data['integral_sets'][0]['n_orbitals']
nuclear_repulsion_energy = data['integral_sets'][0]['coulomb_repulsion']['value']
print('repulsion: ',nuclear_repulsion_energy)
n_orbitals = 2*n_spatial_orbitals
n_particles = data['integral_sets'][0]['n_electrons']
#Populating the QMolecule class with the data to make calculations easier
qm.num_orbitals = n_spatial_orbitals
qm.num_alpha = n_particles//2
qm.num_beta = n_particles//2
#This is just a place holder for freezing the core that I need for the MP2 calculations
qm.core_orbitals = 0
qm.nuclear_repulsion_energy = nuclear_repulsion_energy
qm.hf_energy = data['integral_sets'][0]['scf_energy']['value']
###################Get Orbital Energies from FOCK file########################
orbital_energies = []
found = False
count = 0
for line in content_oe:
if 'Eigenvalues:' in line.split()[0]:
found =True
if found and len(line.split()) > 1:
orbital_energies.append(float(line.split()[1]))
count += 1
if count >= n_spatial_orbitals:
break
qm.orbital_energies = orbital_energies
print(orbital_energies)
#7 orbitals
#qm.orbital_energies = [-2.4533,-2.4530,-0.1817,0.0065, 0.0273, 0.0273, 0.0385]
##############################################################################
dist = 2*data['integral_sets'][0]['geometry']['atoms'][1]['coords'][2]
if map_type == 'parity':
#For two-qubit reduction
n_qubits = n_orbitals-2
else:
n_qubits = n_orbitals
active_occ = n_particles//2
active_virt = (n_orbitals-n_particles)//2
active_occ_list = np.arange(active_occ)
active_occ_list = active_occ_list.tolist()
#print('Orbitals {} are occupied'.format(active_occ_list))
active_virt_list = np.arange(active_virt)
active_virt_list = active_virt_list.tolist()
#print('Orbitals {} are unoccupied'.format(active_virt_list))
###########################################################
#Output Files to Plot stuff
Fout = open('ErrorFromTruncation_Li2_Orb-{}_Dist-{}'.format(n_spatial_orbitals,dist),"w")
###########################################################
###Running Pyscf driver to check integrals
# driver = PySCFDriver(atom='Li .0 .0 .0; Li .0 .0 {}'.format(dist),
# unit=UnitsType.ANGSTROM,
# basis='cc-pvtz')
# molecule = driver.run()
# print(molecule.num_orbitals)
# print('Spatial Integrals from Pyscf\n',molecule.mo_eri_ints)
# Get Hamiltonian in array form from data and get excitations
#Setting singles so they are not us
dumpy_singles = [[0,0]]
one_electron_import = data['integral_sets'][0]['hamiltonian']['one_electron_integrals']['values']
two_electron_import = data['integral_sets'][0]['hamiltonian']['two_electron_integrals']['values']
one_electron_spatial_integrals, two_electron_spatial_integrals = lh.get_spatial_integrals(one_electron_import,two_electron_import,n_spatial_orbitals)
one_electron_spatial_integrals, two_electron_spatial_integrals = lh.trunctate_spatial_integrals(one_electron_spatial_integrals,two_electron_spatial_integrals,.001)
#print('Spatial Integrals from my program\n',two_electron_spatial_integrals)
#print('The difference\n',molecule.mo_eri_ints-two_electron_spatial_integrals)
#For the MP2 calculation
qm.mo_eri_ints = two_electron_spatial_integrals
# qm.mo_onee_ints = one_electron_spatial_integrals
h1, h2 = lh.convert_to_spin_index(one_electron_spatial_integrals,two_electron_spatial_integrals,n_spatial_orbitals, .001)
#print(h1)
# h1 = qm.onee_to_spin(one_electron_spatial_integrals)
# h2 = qm.twoe_to_spin(np.einsum('ijkl->ljik', two_electron_spatial_integrals))
#fop = FermionicOperator(one_temp,two_temp)
fop = FermionicOperator(h1, h2)
qop_paulis = fop.mapping(map_type)
qop = Operator(paulis=qop_paulis.paulis)
###########################################
#Exact Result to compare to: This can also be obtained via the yaml file once we verify correctness.
#Don't use trunctated Hamiltonian
# print('Getting energy')
# exact_eigensolver = ExactEigensolver(qop, k=2)
# ret = exact_eigensolver.run()
# print('The electronic energy is: {:.12f}'.format(ret['eigvals'][0].real))
# print('The total FCI energy is: {:.12f}'.format(ret['eigvals'][0].real + nuclear_repulsion_energy))
###########################################
init_state = HartreeFock(n_qubits, n_orbitals, n_particles, map_type,two_qubit_reduction=False)
#Keep in mind Jarrod didn't use any singles for his ansatz. Maybe just stick to some local doubles, diagonal cancel
var_op = UCCSD(num_qubits=n_qubits, depth=1, num_orbitals=n_orbitals, num_particles=n_particles, active_occupied=active_occ_list,\
active_unoccupied=active_virt_list,initial_state=init_state, qubit_mapping=map_type, mp2_reduction=True)
dumpy_params = np.random.rand(var_op.num_parameters)
#var_cirq = var_op.construct_circuit(dumpy_params)
# singles, doubles = var_op.return_excitations()
# setup a classical optimizer for VQE
# max_eval = 200
# #WOuld using a different optimizer yield better results at long distances?
# optimizer = COBYLA(maxiter=max_eval,disp=True, tol=1e-2)
# print('params: ',var_op.num_parameters)
# dumpy_params = np.random.rand(var_op.num_parameters)
# #Call the VQE algorithm class with your qubit operator for the Hamiltonian and the variational op
# # print('Doing VQE')
# algorithm = VQE(qop_paulis,var_op,optimizer,'paulis', initial_point=var_op._mp2_coeff)
# VQE_Circ = algorithm.construct_circuit(dumpy_params, backend=None)
# print('The VQE circuit:\n',circuit_drawer(VQE_Circ, output='text'))
# result = algorithm.run(backend1)
# print('The VQE energy is: ',result['energy']+nuclear_repulsion_energy)
# print('the params are {}.'.format(result['opt_params']))
# print(qop)
# exact_eigensolver = ExactEigensolver(qop, k=2)
# ret = exact_eigensolver.run()
# print('The total FCI energy is: {:.12f}'.format(ret['eigvals'][0].real + nuclear_repulsion_energy))
Fout.close()
# Junk Code I don't want to delete
# Determining a method to reduce the excitation list with MP2
# All I am missing are the orbital energies and then I am good to go
# It might be worth integrating this into the UCCSD class, so you can get the right circuit
# without having to redo it.
# mp2 = MP2Info(qm)
# mp2_coeff, new_energies = mp2.mp2_get_term_info(var_op._double_excitations)
#
# print('{} are the new MP2 coeffs with energies {}'.format(mp2_coeff,new_energies))
# new_doubles = []
# for i, val in enumerate(doubles):
# if mp2_coeff[i] != 0:
# new_doubles.append(val)
#print('These are the new doubles {}'.format(new_doubles))
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
This trial wavefunction is a Unitary Coupled-Cluster Single and Double excitations
variational form.
For more information, see https://arxiv.org/abs/1805.04340
"""
import logging
import sys
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.tools import parallel_map
from qiskit.tools.events import TextProgressBar
from qiskit.aqua import Operator, aqua_globals
from qiskit.aqua.components.variational_forms import VariationalForm
from qiskit.chemistry.fermionic_operator import FermionicOperator
from qiskit.chemistry import MP2Info
from qiskit.chemistry import QMolecule as qm
logger = logging.getLogger(__name__)
class UCCSD(VariationalForm):
"""
This trial wavefunction is a Unitary Coupled-Cluster Single and Double excitations
variational form.
For more information, see https://arxiv.org/abs/1805.04340
"""
CONFIGURATION = {
'name': 'UCCSD',
'description': 'UCCSD Variational Form',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'uccsd_schema',
'type': 'object',
'properties': {
'depth': {
'type': 'integer',
'default': 1,
'minimum': 1
},
'num_orbitals': {
'type': 'integer',
'default': 4,
'minimum': 1
},
'num_particles': {
'type': 'integer',
'default': 2,
'minimum': 1
},
'active_occupied': {
'type': ['array', 'null'],
'default': None
},
'active_unoccupied': {
'type': ['array', 'null'],
'default': None
},
'qubit_mapping': {
'type': 'string',
'default': 'parity',
'oneOf': [
{'enum': ['jordan_wigner', 'parity', 'bravyi_kitaev']}
]
},
'two_qubit_reduction': {
'type': 'boolean',
'default': False
},
'mp2_reduction': {
'type': 'boolean',
'default': False
},
'num_time_slices': {
'type': 'integer',
'default': 1,
'minimum': 1
},
},
'additionalProperties': False
},
'depends': [
{
'pluggable_type': 'initial_state',
'default': {
'name': 'HartreeFock',
}
},
],
}
def __init__(self, num_qubits, depth, num_orbitals, num_particles,
active_occupied=None, active_unoccupied=None, initial_state=None,
qubit_mapping='parity', two_qubit_reduction=False, mp2_reduction=False, num_time_slices=1,
cliffords=None, sq_list=None, tapering_values=None, symmetries=None,
shallow_circuit_concat=True):
"""Constructor.
Args:
num_orbitals (int): number of spin orbitals
depth (int): number of replica of basic module
num_particles (int): number of particles
active_occupied (list): list of occupied orbitals to consider as active space
active_unoccupied (list): list of unoccupied orbitals to consider as active space
initial_state (InitialState): An initial state object.
qubit_mapping (str): qubit mapping type.
two_qubit_reduction (bool): two qubit reduction is applied or not.
num_time_slices (int): parameters for dynamics.
cliffords ([Operator]): list of unitary Clifford transformation
sq_list ([int]): position of the single-qubit operators that anticommute
with the cliffords
tapering_values ([int]): array of +/- 1 used to select the subspace. Length
has to be equal to the length of cliffords and sq_list
symmetries ([Pauli]): represent the Z2 symmetries
shallow_circuit_concat (bool): indicate whether to use shallow (cheap) mode for circuit concatenation
"""
self.validate(locals())
super().__init__()
self._cliffords = cliffords
self._sq_list = sq_list
self._tapering_values = tapering_values
self._symmetries = symmetries
if self._cliffords is not None and self._sq_list is not None and \
self._tapering_values is not None and self._symmetries is not None:
self._qubit_tapering = True
else:
self._qubit_tapering = False
self._num_qubits = num_orbitals if not two_qubit_reduction else num_orbitals - 2
self._num_qubits = self._num_qubits if not self._qubit_tapering else self._num_qubits - len(sq_list)
if self._num_qubits != num_qubits:
raise ValueError('Computed num qubits {} does not match actual {}'
.format(self._num_qubits, num_qubits))
self._depth = depth
self._num_orbitals = num_orbitals
self._num_particles = num_particles
if self._num_particles > self._num_orbitals:
raise ValueError('# of particles must be less than or equal to # of orbitals.')
self._initial_state = initial_state
self._qubit_mapping = qubit_mapping
self._two_qubit_reduction = two_qubit_reduction
self._num_time_slices = num_time_slices
self._shallow_circuit_concat = shallow_circuit_concat
self._single_excitations, self._double_excitations = \
UCCSD.compute_excitation_lists(num_particles, num_orbitals,
active_occupied, active_unoccupied)
self._single_excitations = []
print('{} are the old doubles'.format(self._double_excitations))
print(mp2_reduction)
if mp2_reduction:
print('Getting new doubles')
self._double_excitations = get_mp2_doubles(self._single_excitations,self._double_excitations)
print('{} are the new doubles'.format(self._double_excitations))
self._hopping_ops, self._num_parameters = self._build_hopping_operators()
self._bounds = [(-np.pi, np.pi) for _ in range(self._num_parameters)]
self._logging_construct_circuit = True
def _build_hopping_operators(self):
from .uccsd import UCCSD
hopping_ops = []
if logger.isEnabledFor(logging.DEBUG):
TextProgressBar(sys.stderr)
results = parallel_map(UCCSD._build_hopping_operator, self._single_excitations + self._double_excitations,
task_args=(self._num_orbitals, self._num_particles,
self._qubit_mapping, self._two_qubit_reduction, self._qubit_tapering,
self._symmetries, self._cliffords, self._sq_list, self._tapering_values),
num_processes=aqua_globals.num_processes)
hopping_ops = [qubit_op for qubit_op in results if qubit_op is not None]
num_parameters = len(hopping_ops) * self._depth
return hopping_ops, num_parameters
@staticmethod
def _build_hopping_operator(index, num_orbitals, num_particles, qubit_mapping,
two_qubit_reduction, qubit_tapering, symmetries,
cliffords, sq_list, tapering_values):
def check_commutativity(op_1, op_2):
com = op_1 * op_2 - op_2 * op_1
com.zeros_coeff_elimination()
return True if com.is_empty() else False
h1 = np.zeros((num_orbitals, num_orbitals))
h2 = np.zeros((num_orbitals, num_orbitals, num_orbitals, num_orbitals))
if len(index) == 2:
i, j = index
h1[i, j] = 1.0
h1[j, i] = -1.0
elif len(index) == 4:
i, j, k, m = index
h2[i, j, k, m] = 1.0
h2[m, k, j, i] = -1.0
dummpy_fer_op = FermionicOperator(h1=h1, h2=h2)
qubit_op = dummpy_fer_op.mapping(qubit_mapping)
qubit_op = qubit_op.two_qubit_reduced_operator(num_particles) \
if two_qubit_reduction else qubit_op
if qubit_tapering:
for symmetry in symmetries:
symmetry_op = Operator(paulis=[[1.0, symmetry]])
symm_commuting = check_commutativity(symmetry_op, qubit_op)
if not symm_commuting:
break
if qubit_tapering:
if symm_commuting:
qubit_op = Operator.qubit_tapering(qubit_op, cliffords,
sq_list, tapering_values)
else:
qubit_op = None
if qubit_op is None:
logger.debug('Excitation ({}) is skipped since it is not commuted '
'with symmetries'.format(','.join([str(x) for x in index])))
return qubit_op
def construct_circuit(self, parameters, q=None):
"""
Construct the variational form, given its parameters.
Args:
parameters (numpy.ndarray): circuit parameters
q (QuantumRegister): Quantum Register for the circuit.
Returns:
QuantumCircuit: a quantum circuit with given `parameters`
Raises:
ValueError: the number of parameters is incorrect.
"""
from .uccsd import UCCSD
if len(parameters) != self._num_parameters:
raise ValueError('The number of parameters has to be {}'.format(self._num_parameters))
if q is None:
q = QuantumRegister(self._num_qubits, name='q')
if self._initial_state is not None:
circuit = self._initial_state.construct_circuit('circuit', q)
else:
circuit = QuantumCircuit(q)
if logger.isEnabledFor(logging.DEBUG) and self._logging_construct_circuit:
logger.debug("Evolving hopping operators:")
TextProgressBar(sys.stderr)
self._logging_construct_circuit = False
num_excitations = len(self._hopping_ops)
results = parallel_map(UCCSD._construct_circuit_for_one_excited_operator,
[(self._hopping_ops[index % num_excitations], parameters[index])
for index in range(self._depth * num_excitations)],
task_args=(q, self._num_time_slices),
num_processes=aqua_globals.num_processes)
for qc in results:
if self._shallow_circuit_concat:
circuit.data += qc.data
else:
circuit += qc
return circuit
@staticmethod
def _construct_circuit_for_one_excited_operator(qubit_op_and_param, qr, num_time_slices):
qubit_op, param = qubit_op_and_param
qc = qubit_op.evolve(None, param * -1j, 'circuit', num_time_slices, qr)
return qc
@property
def preferred_init_points(self):
"""Getter of preferred initial points based on the given initial state."""
if self._initial_state is None:
return None
else:
bitstr = self._initial_state.bitstr
if bitstr is not None:
return np.zeros(self._num_parameters, dtype=np.float)
else:
return None
@staticmethod
def compute_excitation_lists(num_particles, num_orbitals, active_occ_list=None,
active_unocc_list=None, same_spin_doubles=True):
"""
Computes single and double excitation lists
Args:
num_particles: Total number of particles
num_orbitals: Total number of spin orbitals
active_occ_list: List of occupied orbitals to include, indices are
0 to n where n is num particles // 2
active_unocc_list: List of unoccupied orbitals to include, indices are
0 to m where m is (num_orbitals - num particles) // 2
same_spin_doubles: True to include alpha,alpha and beta,beta double excitations
as well as alpha,beta pairings. False includes only alpha,beta
Returns:
Single and double excitation lists
"""
if num_particles < 2 or num_particles % 2 != 0:
raise ValueError('Invalid number of particles {}'.format(num_particles))
if num_orbitals < 4 or num_orbitals % 2 != 0:
raise ValueError('Invalid number of orbitals {}'.format(num_orbitals))
if num_orbitals <= num_particles:
raise ValueError('No unoccupied orbitals')
if active_occ_list is not None:
active_occ_list = [i if i >= 0 else i + num_particles // 2 for i in active_occ_list]
for i in active_occ_list:
if i >= num_particles // 2:
raise ValueError('Invalid index {} in active active_occ_list {}'
.format(i, active_occ_list))
if active_unocc_list is not None:
active_unocc_list = [i + num_particles // 2 if i >=
0 else i + num_orbitals // 2 for i in active_unocc_list]
for i in active_unocc_list:
if i < 0 or i >= num_orbitals // 2:
raise ValueError('Invalid index {} in active active_unocc_list {}'
.format(i, active_unocc_list))
if active_occ_list is None or len(active_occ_list) <= 0:
active_occ_list = [i for i in range(0, num_particles // 2)]
if active_unocc_list is None or len(active_unocc_list) <= 0:
active_unocc_list = [i for i in range(num_particles // 2, num_orbitals // 2)]
single_excitations = []
double_excitations = []
logger.debug('active_occ_list {}'.format(active_occ_list))
logger.debug('active_unocc_list {}'.format(active_unocc_list))
beta_idx = num_orbitals // 2
for occ_alpha in active_occ_list:
for unocc_alpha in active_unocc_list:
single_excitations.append([occ_alpha, unocc_alpha])
for occ_beta in [i + beta_idx for i in active_occ_list]:
for unocc_beta in [i + beta_idx for i in active_unocc_list]:
single_excitations.append([occ_beta, unocc_beta])
for occ_alpha in active_occ_list:
for unocc_alpha in active_unocc_list:
for occ_beta in [i + beta_idx for i in active_occ_list]:
for unocc_beta in [i + beta_idx for i in active_unocc_list]:
double_excitations.append([occ_alpha, unocc_alpha, occ_beta, unocc_beta])
if same_spin_doubles and len(active_occ_list) > 1 and len(active_unocc_list) > 1:
for i, occ_alpha in enumerate(active_occ_list[:-1]):
for j, unocc_alpha in enumerate(active_unocc_list[:-1]):
for occ_alpha_1 in active_occ_list[i + 1:]:
for unocc_alpha_1 in active_unocc_list[j + 1:]:
double_excitations.append([occ_alpha, unocc_alpha,
occ_alpha_1, unocc_alpha_1])
up_active_occ_list = [i + beta_idx for i in active_occ_list]
up_active_unocc_list = [i + beta_idx for i in active_unocc_list]
for i, occ_beta in enumerate(up_active_occ_list[:-1]):
for j, unocc_beta in enumerate(up_active_unocc_list[:-1]):
for occ_beta_1 in up_active_occ_list[i + 1:]:
for unocc_beta_1 in up_active_unocc_list[j + 1:]:
double_excitations.append([occ_beta, unocc_beta,
occ_beta_1, unocc_beta_1])
logger.debug('single_excitations ({}) {}'.format(len(single_excitations), single_excitations))
logger.debug('double_excitations ({}) {}'.format(len(double_excitations), double_excitations))
return single_excitations, double_excitations
def get_mp2_doubles(single_excitations, double_excitations):
print('Is the class still populated with the correct info: ', qm.nuclear_repulsion_energy)
mp2 = MP2Info(qm, single_excitations, double_excitations, threshold=1e-3)
mp2_doubles = mp2._mp2_doubles
return mp2_doubles
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
from __future__ import print_function
from imp import reload
import matplotlib
reload(matplotlib)
matplotlib.use('nbagg')
import matplotlib.backends.backend_nbagg
reload(matplotlib.backends.backend_nbagg)
import matplotlib.backends.backend_webagg_core
reload(matplotlib.backends.backend_webagg_core)
import matplotlib.pyplot as plt
plt.interactive(False)
fig1 = plt.figure()
plt.plot(range(10))
plt.show()
plt.plot([3, 2, 1])
plt.show()
print(matplotlib.backends.backend_nbagg.connection_info())
plt.close(fig1)
plt.plot(range(10))
print(matplotlib.backends.backend_nbagg.connection_info())
plt.show()
plt.figure()
plt.plot(range(5))
plt.show()
plt.interactive(True)
plt.figure()
plt.plot([3, 2, 1])
plt.plot(range(3))
print(matplotlib.backends.backend_nbagg.connection_info())
plt.interactive(False)
plt.gcf().canvas.manager.reshow()
fig = plt.figure()
plt.axes()
plt.show()
plt.plot([1, 2, 3])
plt.show()
from matplotlib.backends.backend_nbagg import new_figure_manager,show
manager = new_figure_manager(1000)
fig = manager.canvas.figure
ax = fig.add_subplot(1,1,1)
ax.plot([1,2,3])
fig.show()
import matplotlib.animation as animation
import numpy as np
fig, ax = plt.subplots()
x = np.arange(0, 2*np.pi, 0.01) # x-array
line, = ax.plot(x, np.sin(x))
def animate(i):
line.set_ydata(np.sin(x+i/10.0)) # update the data
return line,
#Init only required for blitting to give a clean slate.
def init():
line.set_ydata(np.ma.array(x, mask=True))
return line,
ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), init_func=init,
interval=32., blit=True)
plt.show()
import matplotlib
matplotlib.rcParams.update({'figure.facecolor': 'red',
'savefig.facecolor': 'yellow'})
plt.figure()
plt.plot([3, 2, 1])
plt.show()
import itertools
fig, ax = plt.subplots()
x = np.linspace(0,10,10000)
y = np.sin(x)
ln, = ax.plot(x,y)
evt = []
colors = iter(itertools.cycle(['r', 'g', 'b', 'k', 'c']))
def on_event(event):
if event.name.startswith('key'):
fig.suptitle('%s: %s' % (event.name, event.key))
elif event.name == 'scroll_event':
fig.suptitle('%s: %s' % (event.name, event.step))
else:
fig.suptitle('%s: %s' % (event.name, event.button))
evt.append(event)
ln.set_color(next(colors))
fig.canvas.draw()
fig.canvas.draw_idle()
fig.canvas.mpl_connect('button_press_event', on_event)
fig.canvas.mpl_connect('button_release_event', on_event)
fig.canvas.mpl_connect('scroll_event', on_event)
fig.canvas.mpl_connect('key_press_event', on_event)
fig.canvas.mpl_connect('key_release_event', on_event)
plt.show()
import time
fig, ax = plt.subplots()
text = ax.text(0.5, 0.5, '', ha='center')
def update(text):
text.set(text=time.ctime())
text.axes.figure.canvas.draw()
timer = fig.canvas.new_timer(500, [(update, [text], {})])
timer.start()
plt.show()
fig, ax = plt.subplots()
text = ax.text(0.5, 0.5, '', ha='center')
timer = fig.canvas.new_timer(500, [(update, [text], {})])
timer.single_shot = True
timer.start()
plt.show()
fig, ax = plt.subplots()
text = ax.text(0.5, 0.5, '', ha='center')
timer = fig.canvas.new_timer(500, [(update, [text], {})])
timer.start()
timer.stop()
plt.show()
fig, ax = plt.subplots()
text = ax.text(0.5, 0.5, '', ha='center')
timer = fig.canvas.new_timer(500, [(update, [text], {})])
timer.single_shot = True
timer.start()
timer.stop()
plt.show()
fig, ax = plt.subplots()
ax.plot(range(5))
plt.show()
fig.canvas.manager.reshow()
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# Copyright 2019 Cambridge Quantum 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from qiskit import Aer
from qiskit.compiler import assemble
from qiskit.providers.aer.noise import NoiseModel
from pytket.backends import Backend
from pytket.qiskit import tk_to_qiskit
from pytket.backends.ibm.ibm import _convert_bin_str
from pytket._circuit import Circuit
from pytket._transform import Transform
from pytket._simulation import pauli_tensor_matrix, operator_matrix
import numpy as np
class AerBackend(Backend) :
def __init__(self, noise_model:NoiseModel=None) :
"""Backend for running simulations on Qiskit Aer Qasm simulator.
:param noise_model: Noise model to use in simulation, defaults to None.
:type noise_model: NoiseModel, optional
"""
self._backend = Aer.get_backend('qasm_simulator')
self.noise_model = noise_model
def run(self, circuit:Circuit, shots:int, fit_to_constraints=True, seed:int=None) -> np.ndarray:
"""Run a circuit on Qiskit Aer Qasm simulator.
:param circuit: The circuit to run
:type circuit: Circuit
:param shots: Number of shots (repeats) to run
:type shots: int
:param fit_to_constraints: Compile the circuit to meet the constraints of the backend, defaults to True
:type fit_to_constraints: bool, optional
:param seed: random seed to for simulator
:type seed: int
:return: Table of shot results, each row is a shot, columns are ordered by qubit ordering. Values are 0 or 1, corresponding to qubit basis states.
:rtype: numpy.ndarray
"""
c = circuit.copy()
if fit_to_constraints :
Transform.RebaseToQiskit().apply(c)
qc = tk_to_qiskit(c)
qobj = assemble(qc, shots=shots, seed_simulator=seed, memory=True)
job = self._backend.run(qobj, noise_model=self.noise_model)
shot_list = job.result().get_memory(qc)
return np.asarray([_convert_bin_str(shot) for shot in shot_list])
def get_counts(self, circuit, shots, fit_to_constraints=True, seed=None) :
"""
Run the circuit on the backend and accumulate the results into a summary of counts
:param circuit: The circuit to run
:param shots: Number of shots (repeats) to run
:param fit_to_constraints: Compile the circuit to meet the constraints of the backend, defaults to True
:param seed: Random seed to for simulator
:return: Dictionary mapping bitvectors of results to number of times that result was observed (zero counts are omitted)
"""
c = circuit.copy()
if fit_to_constraints :
Transform.RebaseToQiskit().apply(c)
qc = tk_to_qiskit(c)
qobj = assemble(qc, shots=shots, seed_simulator=seed)
job = self._backend.run(qobj, noise_model=self.noise_model)
counts = job.result().get_counts(qc)
return {tuple(_convert_bin_str(b)) : c for b, c in counts.items()}
class AerStateBackend(Backend) :
def __init__(self) :
self._backend = Aer.get_backend('statevector_simulator')
def get_state(self, circuit, fit_to_constraints=True) :
"""
Calculate the statevector for a circuit.
:param circuit: circuit to calculate
:return: complex numpy array of statevector
"""
c = circuit.copy()
if fit_to_constraints :
Transform.RebaseToQiskit().apply(c)
qc = tk_to_qiskit(c)
qobj = assemble(qc)
job = self._backend.run(qobj)
return np.asarray(job.result().get_statevector(qc, decimals=16))
def run(self, circuit, shots, fit_to_constraints=True) :
raise Exception("Aer State Backend cannot currently generate shots. Use `get_state` instead.")
def get_pauli_expectation_value(self, state_circuit, pauli, shots=1000) :
state = self.get_state(state_circuit)
pauli_op = pauli_tensor_matrix(pauli, state_circuit.n_qubits)
return np.vdot(state, pauli_op.dot(state))
def get_operator_expectation_value(self, state_circuit, operator, shots=1000) :
"""
Calculates expectation value for an OpenFermion QubitOperator by summing over pauli expectations
Note: This method is significantly faster using the ProjectQBackend than the AerStateBackend.
"""
state = self.get_state(state_circuit)
n_qubits = state_circuit.n_qubits
op_as_lists = [(list(p),c) for p,c in operator.terms.items()]
op = operator_matrix(op_as_lists, n_qubits)
return np.vdot(state, op.dot(state))
class AerUnitaryBackend(Backend) :
def __init__(self) :
self._backend = Aer.get_backend('unitary_simulator')
def run(self, circuit, shots, fit_to_constraints=True) :
raise Exception("Aer Unitary Backend cannot currently generate shots. Use `get_unitary` instead.")
def get_unitary(self, circuit, fit_to_constraints=True) :
"""
Obtains the unitary for a given quantum circuit
:param circuit: The circuit to inspect
:type circuit: Circuit
:param fit_to_constraints: Forces the circuit to be decomposed into the correct gate set, defaults to True
:type fit_to_constraints: bool, optional
:return: The unitary of the circuit. Qubits are ordered with qubit 0 as the least significant qubit
"""
c = circuit.copy()
if fit_to_constraints :
Transform.RebaseToQiskit().apply(c)
qc = tk_to_qiskit(c)
qobj = assemble(qc)
job = self._backend.run(qobj)
return job.result().get_unitary(qc)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# Copyright 2019 Cambridge Quantum 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import itertools
import qiskit
from typing import Tuple, Iterable
from qiskit import IBMQ, QuantumCircuit
from qiskit.compiler import assemble
from qiskit.tools.monitor import job_monitor
from pytket.backends import Backend
from pytket.qiskit import tk_to_qiskit
from pytket._routing import route, Architecture
from pytket._transform import Transform
from pytket._circuit import Circuit
import numpy as np
VALID_BACKEND_GATES = (
qiskit.extensions.standard.u1.U1Gate,
qiskit.extensions.standard.u2.U2Gate,
qiskit.extensions.standard.u3.U3Gate,
qiskit.extensions.standard.cx.CnotGate,
qiskit.circuit.measure.Measure
)
def _qiskit_circ_valid(qc: QuantumCircuit, coupling:Iterable[Tuple[int]] ) -> bool:
valid = True
measure_count = 0
for instruction in qc:
if type(instruction[0]) not in VALID_BACKEND_GATES:
valid = False
break
if isinstance(instruction[0], qiskit.circuit.measure.Measure):
measure_count += 1
if len(instruction[1]) > 1:
control = instruction[1][0][1]
target = instruction[1][1][1]
if [control, target] not in coupling:
valid =False
break
return valid, (measure_count > 0)
def _routed_ibmq_circuit(circuit:Circuit, arc: Architecture) -> QuantumCircuit:
c = circuit.copy()
Transform.RebaseToQiskit().apply(c)
physical_c = route(c, arc)
physical_c.decompose_SWAP_to_CX()
physical_c.redirect_CX_gates(arc)
Transform.OptimisePostRouting().apply(physical_c)
qc = tk_to_qiskit(physical_c)
return qc
def _convert_bin_str(string) :
return [int(b) for b in string.replace(' ', '')][::-1]
class IBMQBackend(Backend) :
def __init__(self, backend_name:str, monitor:bool=True) :
"""A backend for running circuits on remote IBMQ devices.
:param backend_name: name of ibmq device. e.g. `ibmqx4`, `ibmq_16_melbourne`.
:type backend_name: str
:param monitor: Use IBM job monitor, defaults to True
:type monitor: bool, optional
:raises ValueError: If no IBMQ account has been set up.
"""
if len(IBMQ.stored_accounts()) ==0:
raise ValueError('No IBMQ credentials found on disk. Store some first.')
IBMQ.load_accounts()
self._backend = IBMQ.get_backend(backend_name)
self.config = self._backend.configuration()
self.coupling = self.config.coupling_map
self.architecture = Architecture(self.coupling)
self._monitor = monitor
def run(self, circuit:Circuit, shots:int, fit_to_constraints:bool=True) -> np.ndarray :
if fit_to_constraints:
qc = _routed_ibmq_circuit(circuit, self.architecture)
else:
qc = tk_to_qiskit(circuit)
valid, measures = _qiskit_circ_valid(qc, self.coupling)
if not valid:
raise RuntimeWarning("QuantumCircuit does not pass validity test, will likely fail on remote backend.")
if not measures:
raise RuntimeWarning("Measure gates are required for output.")
qobj = assemble(qc, shots=shots, memory=self.config.memory)
job = self._backend.run(qobj)
if self._monitor :
job_monitor(job)
shot_list = []
if self.config.memory:
shot_list = job.result().get_memory(qc)
else:
for string, count in job.result().get_counts().items():
shot_list += [string]*count
return np.asarray([_convert_bin_str(shot) for shot in shot_list])
def get_counts(self, circuit, shots, fit_to_constraints=True) :
"""
Run the circuit on the backend and accumulate the results into a summary of counts
:param circuit: The circuit to run
:param shots: Number of shots (repeats) to run
:param fit_to_constraints: Compile the circuit to meet the constraints of the backend, defaults to True
:param seed: Random seed to for simulator
:return: Dictionary mapping bitvectors of results to number of times that result was observed (zero counts are omitted)
"""
if fit_to_constraints:
qc = _routed_ibmq_circuit(circuit, self.architecture)
else:
qc = tk_to_qiskit(circuit)
valid, measures = _qiskit_circ_valid(qc, self.coupling)
if not valid:
raise RuntimeWarning("QuantumCircuit does not pass validity test, will likely fail on remote backend.")
if not measures:
raise RuntimeWarning("Measure gates are required for output.")
qobj = assemble(qc, shots=shots)
job = self._backend.run(qobj)
counts = job.result().get_counts(qc)
return {tuple(_convert_bin_str(b)) : c for b, c in counts.items()}
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# Copyright 2019 Cambridge Quantum 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
#
# https://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.
"""
Engine for the Quantum Subspace Expansion algorithm
"""
import time
import logging
import itertools
from typing import List
import numpy as np
from multiprocessing import Pool, cpu_count
from _pickle import PicklingError
from qiskit import QuantumCircuit, ClassicalRegister
from pytket.chemistry.aqua.qse_subs import QseMatrices
from qiskit.aqua import QuantumAlgorithm, AquaError, Operator
from qiskit.aqua.components.variational_forms import VariationalForm
logger = logging.getLogger(__name__)
logger = logging.getLogger('qiskit.aqua')
class QSE(QuantumAlgorithm):
"""
:py:class:`qiskit.aqua.QuantumAlgorithm` implementation for Quantum Subspace Expansion (QSE)
[See Phys. Rev. A 95, 042308 (2017)].
"""
CONFIGURATION = {
'name': 'QSE',
'description': 'QSE Algorithm',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'qse_schema',
'type': 'object',
'properties': {
'operator_mode': {
'type': 'string',
'default': 'matrix',
'oneOf': [
{'enum': ['matrix', 'paulis', 'grouped_paulis']}
]
},
'initial_point': {
'type': ['array', 'null'],
"items": {
"type": "number"
},
'default': None
}
},
'additionalProperties': False
},
'problems': ['energy', 'ising'],
'depends': ['variational_form', 'initial_state'],
'defaults': {
'variational_form': {
'name': 'UCCSD'
},
'initial_state': {
'name': 'ZERO'
}
}
}
def __init__(self, qse_operators:QseMatrices, operator_mode:str, var_form:VariationalForm,
opt_init_point:np.ndarray=None, aux_operators:List[Operator]=[]):
"""
:param qse_operators: Qubit operator generator
:param operator_mode: Operator mode to be used for evaluation of the operator
:param var_form: Parametrized variational form
:param opt_init_point: Initial point for the optimisation
:param aux_operators: Auxiliary operators to be evaluated at each eigenvalue
"""
super().__init__()
self._qse_operators = qse_operators
self._operator = None
self._operator_mode = operator_mode
self._var_form = var_form
self.opt_var_params = opt_init_point
self._aux_operators = aux_operators
self._ret = {}
self._eval_count = 0
self._eval_time = 0
if opt_init_point is None:
self.opt_var_params = var_form.preferred_init_points
else:
self.opt_circuit = self._var_form.construct_circuit(self.opt_var_params)
self._quantum_state = None
@property
def setting(self):
ret = "Algorithm: {}\n".format(self._configuration['name'])
params = ""
for key, value in self.__dict__.items():
if key != "_configuration" and key[0] == "_":
if "opt_init_point" in key and value is None:
params += "-- {}: {}\n".format(key[1:], "Random seed")
else:
params += "-- {}: {}\n".format(key[1:], value)
ret += "{}".format(params)
return ret
def print_setting(self) -> str:
"""
Presents the QSE settings as a string.
:return: The formatted settings of the QSE instance
"""
ret = "\n"
ret += "==================== Setting of {} ============================\n".format(self.configuration['name'])
ret += "{}".format(self.setting)
ret += "===============================================================\n"
ret += "{}".format(self._var_form.setting)
ret += "===============================================================\n"
return ret
def _energy_evaluation(self, operator):
"""
Evaluate the energy of the current input circuit with respect to the given operator.
:param operator: Hamiltonian of the system
:return: Energy of the Hamiltonian
"""
if self._quantum_state is not None:
input_circuit = self._quantum_state
else:
input_circuit = [self.opt_circuit]
if operator._paulis:
mean_energy, std_energy = operator.evaluate_with_result(self._operator_mode, input_circuit,
self._quantum_instance.backend, self.ret)
else:
mean_energy = 0.0
std_energy = 0.0
operator.disable_summarize_circuits()
logger.debug('Energy evaluation {} returned {}'.format(self._eval_count, np.real(mean_energy)))
return np.real(mean_energy), np.real(std_energy)
def _h_qse_finder(self, pair):
i, j = pair
term = self._qse_operators.hamiltonian_term(i, j)
term.chop(1e-10)
result, std_ij = self._energy_evaluation(term)
return result
#Measure elements of the overlap matrix
def _s_qse_finder(self, pair):
i, j = pair
term = self._qse_operators.overlap_term(i, j)
result, std_ij = self._energy_evaluation(term)
return result
def _linear_compute(self, terms, _n_qubits):
matrix = np.zeros((_n_qubits**2, _n_qubits**2), dtype=np.float)
pairs = filter(lambda x: x[1]>=x[0], itertools.product(range(_n_qubits**2), repeat=2))
completed = 0
total = _n_qubits**4
for pair, term in zip(pairs, terms):
i, j = pair
result, std = self._energy_evaluation(term)
matrix[[i,j], [j,i]] = result
completed += 2
if completed % 1 ==0:
logger.info("Matrix Filled: {0:.2%}".format(completed/total))
return matrix
def _parallel_compute(self, terms, _n_qubits):
matrix = np.zeros((_n_qubits**2, _n_qubits**2), dtype=np.float)
N_CORES = cpu_count()
pairs = filter(lambda x: x[1]>=x[0], itertools.product(range(_n_qubits**2), repeat=2))
n_calcs = N_CORES*5
next_terms = list(itertools.islice(terms, n_calcs))
next_pairs = list(itertools.islice(pairs, n_calcs))
completed = 0
total = _n_qubits**4
with Pool(N_CORES) as p:
while next_terms:
start = time.time()
results, stdev = zip(*p.map(self._energy_evaluation, next_terms))
i_s, j_s = zip(*next_pairs)
results = np.array(list(results))
matrix[i_s, j_s] = results
matrix[j_s, i_s] = results
next_terms = list(itertools.islice(terms, n_calcs))
next_pairs = list(itertools.islice(pairs, n_calcs))
completed += n_calcs*2
logger.debug("{} calculations in {}".format(n_calcs, time.time() - start))
logger.info("Matrix Filled: {0:.2%}".format(completed/total))
return matrix
def _generate_terms(self):
n_qubits = self._qse_operators.n_qubits
pairs = list(filter(lambda x: x[1]>=x[0], itertools.product(range(n_qubits**2), repeat=2)))
def chop(term):
term.chop(1e-10)
return term
h_terms = (chop(term) for term in(self._qse_operators.hamiltonian_term(i, j) for i, j in pairs))
s_terms = (self._qse_operators.overlap_term(i, j) for i, j in pairs)
return h_terms, s_terms
def _solve(self, parallel=True):
h_terms, s_terms = self._generate_terms()
n_qubits = self._qse_operators.n_qubits
if parallel:
h_qse_matrix = self._parallel_compute(h_terms, n_qubits)
s_qse_matrix = self._parallel_compute(s_terms, n_qubits)
else:
h_qse_matrix = self._linear_compute(h_terms, n_qubits)
s_qse_matrix = self._linear_compute(s_terms, n_qubits)
eigvals, vectors = np.linalg.eig(np.matmul(np.linalg.pinv(s_qse_matrix),h_qse_matrix))
eigvals = np.real(eigvals)
eigvals.sort()
self._ret['eigvals'] = eigvals
def _eval_aux_ops(self, threshold=1e-12):
wavefn_circuit = self._var_form.construct_circuit(self._ret['opt_params'])
values = []
for operator in self._aux_operators:
mean, std = 0.0, 0.0
if not operator.is_empty():
mean, std = operator.eval(self._operator_mode, wavefn_circuit,
self._backend, self._execute_config, self._qjob_config)
mean = mean.real if abs(mean.real) > threshold else 0.0
std = std.real if abs(std.real) > threshold else 0.0
values.append((mean, std))
if len(values) > 0:
aux_op_vals = np.empty([1, len(self._aux_operators), 2])
aux_op_vals[0, :] = np.asarray(values)
self._ret['aux_ops'] = aux_op_vals
def _run(self) -> dict:
"""
Runs the QSE algorithm to compute the eigenvalues of the Hamiltonian.
:return: Dictionary of results
"""
if not self._quantum_instance.is_statevector:
raise AquaError("Can only calculate state for QSE with statevector backends")
ret = self._quantum_instance.execute(self.opt_circuit)
self.ret = ret
self._eval_count = 0
self._solve()
self._ret['eval_count'] = self._eval_count
self._ret['eval_time'] = self._eval_time
return self._ret
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# import common packages
import itertools
import numpy as np
from numpy import array, concatenate, zeros
import qiskit
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.quantum_info import Pauli
# lib from Qiskit AQUA Chemistry
from qiskit.chemistry import FermionicOperator
# lib from optimizer and algorithm
from qiskit.aqua.operator import Operator
# lib for driver
from collections import OrderedDict
from abc import ABC, abstractmethod
import time
def _jordan_wigner_mode(n):
"""
Jordan_Wigner mode.
Args:
n (int): number of modes
"""
a = []
for i in range(n):
xv = np.asarray([1] * i + [0] + [0] * (n - i - 1))
xw = np.asarray([0] * i + [1] + [0] * (n - i - 1))
yv = np.asarray([1] * i + [1] + [0] * (n - i - 1))
yw = np.asarray([0] * i + [1] + [0] * (n - i - 1))
a.append((Pauli(xv, xw), Pauli(yv, yw)))
return a
def _one_body_mapping(a_i, a_j, threshold=0.000001):
"""
Subroutine for one body mapping.
Args:
a_i (Pauli): pauli at index i
a_j (Pauli): pauli at index j
threshold: (float): threshold to remove a pauli
Returns:
Operator: Operator for those paulis
"""
pauli_list = []
for alpha in range(2):
for beta in range(2):
pauli_prod = Pauli.sgn_prod(a_i[alpha], a_j[beta])
coeff = 1.0/4 * pauli_prod[1] * np.power(-1j, alpha) * np.power(1j, beta)
pauli_term = [coeff, pauli_prod[0]]
if np.absolute(pauli_term[0]) > threshold:
pauli_list.append(pauli_term)
return Operator(paulis=pauli_list)
class QseMatrices():
def __init__(self, qubit_hamiltonian, n_qubits):
self.qubit_hamiltonian = qubit_hamiltonian
self.n_qubits = n_qubits
self.c_i = None
paulis_test = _jordan_wigner_mode(n_qubits)
excit_operator = []
excit_operator_conjugated = []
#Construct operators C_i C_j^+ and conjugated operators
#C_i : 2nd quantization annihilation operator
#C_i^+ : 2nd quantization creation operator
k = 0
for i, j in itertools.product(range(n_qubits), repeat=2):
second_q_operator = _one_body_mapping(paulis_test[i],paulis_test[j])
excit_operator.append(second_q_operator)
second_q_op_conjugated = _one_body_mapping(paulis_test[j],paulis_test[i])
excit_operator_conjugated.append(second_q_op_conjugated)
k += 1
self.excit_operator = excit_operator
self.excit_operator_conjugated = excit_operator_conjugated
def overlap(self):
return np.outer(self.excit_operator_conjugated, self.excit_operator)
def overlap_term(self, i, j):
return self.excit_operator_conjugated[j]*self.excit_operator[i]
def hamiltonian_term(self, i, j):
return self.excit_operator_conjugated[j]*self.qubit_hamiltonian*self.excit_operator[i]
def unroll_paulis(paulis):
coeffs = np.zeros(len(paulis), dtype=np.complex)
bools = np.zeros((len(paulis), 2*paulis[0][1].numberofqubits), dtype=np.int)
for i, pauli in enumerate(paulis):
coeffs[i] = pauli[0]
bools[i, :4] = pauli[1].v
bools[i, 4:] = pauli[1].w
return coeffs, bools
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# Copyright 2019 Cambridge Quantum 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
#
# https://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.
"""Methods to allow conversion between Qiskit and pytket circuit classes
"""
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit import Instruction, Measure
from qiskit.extensions.standard import *
from pytket._circuit import Circuit, Op, OpType
from pytket._routing import PhysicalCircuit
from sympy import pi
_known_qiskit_gate = {
IdGate : OpType.noop,
XGate : OpType.X,
YGate : OpType.Y,
ZGate : OpType.Z,
SGate : OpType.S,
SdgGate : OpType.Sdg,
TGate : OpType.T,
TdgGate : OpType.Tdg,
HGate : OpType.H,
RXGate : OpType.Rx,
RYGate : OpType.Ry,
RZGate : OpType.Rz,
U1Gate : OpType.U1,
U2Gate : OpType.U2,
U3Gate : OpType.U3,
CnotGate : OpType.CX,
CyGate : OpType.CY,
CzGate : OpType.CZ,
CHGate : OpType.CH,
SwapGate : OpType.SWAP,
ToffoliGate : OpType.CCX,
FredkinGate : OpType.CSWAP,
CrzGate : OpType.CRz,
Cu1Gate : OpType.CU1,
Cu3Gate : OpType.CU3,
Measure : OpType.Measure
}
_known_qiskit_gate_rev = {v : k for k, v in _known_qiskit_gate.items()}
def qiskit_to_tk(qcirc: QuantumCircuit) -> Circuit :
"""Convert a :py:class:`qiskit.QuantumCircuit` to a :py:class:`Circuit`.
:param qcirc: A circuit to be converted
:type qcirc: QuantumCircuit
:return: The converted circuit
:rtype: Circuit
"""
tkc = Circuit()
qregmap = {}
for reg in qcirc.qregs :
tk_reg = tkc.add_q_register(reg.name, len(reg))
qregmap.update({reg : tk_reg})
cregmap = {}
for reg in qcirc.cregs :
tk_reg = tkc.add_c_register(reg.name, len(reg))
cregmap.update({reg : tk_reg})
for i, qargs, cargs in qcirc.data :
if i.control is not None :
raise NotImplementedError("Cannot convert conditional gates from Qiskit to tket")
optype = _known_qiskit_gate[type(i)]
qubits = [qregmap[r][ind] for r, ind in qargs]
bits = [cregmap[r][ind] for r, ind in cargs]
if optype == OpType.Measure :
tkc.add_measure(*qubits, *bits)
continue
params = [p/pi for p in i.params]
tkc.add_gate(optype, params, qubits, [])
return tkc
def tk_to_qiskit(tkcirc: Circuit) -> QuantumCircuit :
"""Convert back
:param tkcirc: A circuit to be converted
:type tkcirc: Circuit
:return: The converted circuit
:rtype: QuantumCircuit
"""
tkc = tkcirc
if isinstance(tkcirc, PhysicalCircuit) :
tkc = tkcirc._get_circuit()
qcirc = QuantumCircuit()
qregmap = {}
for _, reg in tkc.q_regs.items() :
if reg.size() == 0 :
continue
name = reg.name
if len(name) == 0 :
name = None
qis_reg = QuantumRegister(reg.size(), name)
qregmap.update({reg : qis_reg})
qcirc.add_register(qis_reg)
cregmap = {}
for _, reg in tkc.c_regs.items() :
if reg.size() == 0 :
continue
name = reg.name
if len(name) == 0 :
name = None
qis_reg = ClassicalRegister(reg.size(), name)
cregmap.update({reg : qis_reg})
qcirc.add_register(qis_reg)
tempregmap = {}
for command in tkc :
op = command.op
qubits = command.qubits
qargs = [qregmap[q.reg][q.index] for q in qubits]
if len(command.controls) != 0 :
raise NotImplementedError("Cannot convert conditional gates from tket to Qiskit")
if op.get_type() == OpType.Measure :
bits = [_convert_bit(b, cregmap, qcirc, tempregmap) for b in command.bits]
qcirc.measure(*qargs, *bits)
continue
params = [p * pi for p in op.get_params()]
try :
gatetype = _known_qiskit_gate_rev[op.get_type()]
except KeyError as error :
raise NotImplementedError("Cannot convert tket Op to Qiskit gate: " + op.get_name()) from error
g = gatetype(*params)
qcirc.append(g, qargs=qargs)
return qcirc
def _convert_bit(bit, cregmap, qcirc, tempregmap) :
index = bit.index
if bit.temp :
if bit not in tempregmap :
new_reg = ClassicalRegister(1, "temp"+str(index))
qcirc.add_register(new_reg)
tempregmap.update({bit : new_reg})
return new_reg[0]
return tempregmap[bit][0]
return cregmap[bit.reg][index]
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
import qiskit
from qiskit.dagcircuit import DAGCircuit
from qiskit.providers import BaseBackend
from qiskit.transpiler.basepasses import TransformationPass, BasePass
from qiskit.converters import circuit_to_dag, dag_to_circuit
from pytket._transform import Transform
from pytket._routing import route, Architecture
from pytket.qiskit import qiskit_to_tk, tk_to_qiskit
class TketPass(TransformationPass):
"""The :math:`\\mathrm{t|ket}\\rangle` compiler to be plugged in to the Qiskit compilation sequence"""
filecount = 0
def __init__(self,backend:BaseBackend, DROP_CONDS:bool=False,BOX_UNKNOWN:bool=True,name:str="T|KET>") :
BasePass.__init__(self)
self.DROP_CONDS=DROP_CONDS
self.BOX_UNKNOWN=BOX_UNKNOWN
self.name = name
my_backend = None
if isinstance(backend, BaseBackend):
my_backend = backend
else:
raise RuntimeError("Requires BaseBackend instance")
self.coupling_map = my_backend.configuration().to_dict().get('coupling_map', None)
def process_circ(self, circ):
num_qubits = circ.n_qubits
if num_qubits == 1 or self.coupling_map == "all-to-all":
coupling_map = None
else:
coupling_map = self.coupling_map
# pre-routing optimise
Transform.OptimisePhaseGadgets().apply(circ)
circlay = list(range(num_qubits))
if coupling_map:
directed_arc = Architecture(coupling_map)
# route_ibm fnction that takes directed Arc, returns dag with cnots etc.
circ, circlay = route(circ,directed_arc)
circ.apply_boundary_map(circlay[0])
# post route optimise
Transform.OptimisePostRouting().apply(circ)
circ.remove_blank_wires()
return circ, circlay
def run(self, dag:DAGCircuit) -> DAGCircuit:
"""
Run one pass of optimisation on the circuit and route for the given backend.
:param dag: The circuit to optimise and route
:return: The modified circuit
"""
qc = dag_to_circuit(dag)
circ = qiskit_to_tk(qc)
circ, circlay = self.process_circ(circ)
qc = tk_to_qiskit(circ)
newdag = circuit_to_dag(qc)
newdag.name = dag.name
finlay = dict()
for i, qi in enumerate(circlay):
finlay[('q', i)] = ('q', qi)
newdag.final_layout = finlay
return newdag
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Utils for reading a user preference config files."""
import configparser
import os
from qiskit import exceptions
DEFAULT_FILENAME = os.path.join(os.path.expanduser("~"),
'.qiskit', 'settings.conf')
class UserConfig:
"""Class representing a user config file
The config file format should look like:
[default]
circuit_drawer = mpl
"""
def __init__(self, filename=None):
"""Create a UserConfig
Args:
filename (str): The path to the user config file. If one isn't
specified ~/.qiskit/settings.conf is used.
"""
if filename is None:
self.filename = DEFAULT_FILENAME
else:
self.filename = filename
self.settings = {}
self.config_parser = configparser.ConfigParser()
def read_config_file(self):
"""Read config file and parse the contents into the settings attr."""
if not os.path.isfile(self.filename):
return
self.config_parser.read(self.filename)
if 'default' in self.config_parser.sections():
circuit_drawer = self.config_parser.get('default',
'circuit_drawer')
if circuit_drawer:
if circuit_drawer not in ['text', 'mpl', 'latex',
'latex_source']:
raise exceptions.QiskitUserConfigError(
"%s is not a valid circuit drawer backend. Must be "
"either 'text', 'mpl', 'latex', or 'latex_source'"
% circuit_drawer)
self.settings['circuit_drawer'] = circuit_drawer
def get_config():
"""Read the config file from the default location or env var
It will read a config file at either the default location
~/.qiskit/settings.conf or if set the value of the QISKIT_SETTINGS env var.
It will return the parsed settings dict from the parsed config file.
Returns:
dict: The settings dict from the parsed config file.
"""
filename = os.getenv('QISKIT_SETTINGS', DEFAULT_FILENAME)
if not os.path.isfile(filename):
return {}
user_config = UserConfig(filename)
user_config.read_config_file()
return user_config.settings
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import copy
import itertools
from functools import reduce
import logging
import json
from operator import iadd as op_iadd, isub as op_isub
import sys
import numpy as np
from scipy import sparse as scisparse
from scipy import linalg as scila
from qiskit import ClassicalRegister, QuantumCircuit
from qiskit.quantum_info import Pauli
from qiskit.qasm import pi
from qiskit.assembler.run_config import RunConfig
from qiskit.tools import parallel_map
from qiskit.tools.events import TextProgressBar
from qiskit.aqua import AquaError, aqua_globals
from qiskit.aqua.utils import PauliGraph, compile_and_run_circuits, find_regs_by_name
from qiskit.aqua.utils.backend_utils import is_statevector_backend
logger = logging.getLogger(__name__)
class Operator(object):
"""
Operators relevant for quantum applications
Note:
For grouped paulis representation, all operations will always convert it to paulis and then convert it back.
(It might be a performance issue.)
"""
def __init__(self, paulis=None, grouped_paulis=None, matrix=None, coloring="largest-degree"):
"""
Args:
paulis ([[float, Pauli]]): each list contains a coefficient (real number) and a corresponding Pauli class object.
grouped_paulis ([[[float, Pauli]]]): each list of list contains a grouped paulis.
matrix (numpy.ndarray or scipy.sparse.csr_matrix) : a 2-D sparse matrix represents operator (using CSR format internally)
coloring (bool): method to group paulis.
"""
self._paulis = paulis
self._coloring = coloring
self._grouped_paulis = grouped_paulis
if matrix is not None:
matrix = matrix if scisparse.issparse(matrix) else scisparse.csr_matrix(matrix)
matrix = matrix if scisparse.isspmatrix_csr(matrix) else matrix.to_csr(copy=True)
self._matrix = matrix
self._to_dia_matrix(mode="matrix")
# use for fast lookup whether or not the paulis is existed.
self._simplify_paulis()
self._summarize_circuits = False
def _extend_or_combine(self, rhs, mode, operation=op_iadd):
"""
Add two operators either extend (in-place) or combine (copy) them.
The addition performs optimized combiniation of two operators.
If `rhs` has identical basis, the coefficient are combined rather than
appended.
Args:
rhs (Operator): to-be-combined operator
mode (str): in-place or not.
Returns:
Operator: the operator.
"""
if mode == 'inplace':
lhs = self
elif mode == 'non-inplace':
lhs = copy.deepcopy(self)
if lhs._paulis is not None and rhs._paulis is not None:
for pauli in rhs._paulis:
pauli_label = pauli[1].to_label()
idx = lhs._paulis_table.get(pauli_label, None)
if idx is not None:
lhs._paulis[idx][0] = operation(lhs._paulis[idx][0], pauli[0])
else:
lhs._paulis_table[pauli_label] = len(lhs._paulis)
new_pauli = copy.deepcopy(pauli)
new_pauli[0] = operation(0.0, pauli[0])
lhs._paulis.append(new_pauli)
elif lhs._grouped_paulis is not None and rhs._grouped_paulis is not None:
lhs._grouped_paulis_to_paulis()
rhs._grouped_paulis_to_paulis()
lhs = operation(lhs, rhs)
lhs._paulis_to_grouped_paulis()
elif lhs._matrix is not None and rhs._matrix is not None:
lhs._matrix = operation(lhs._matrix, rhs._matrix)
lhs._to_dia_matrix(mode='matrix')
else:
raise TypeError("the representations of two Operators should be the same. ({}, {})".format(
lhs.representations, rhs.representations))
return lhs
def __add__(self, rhs):
"""Overload + operation"""
return self._extend_or_combine(rhs, 'non-inplace', op_iadd)
def __iadd__(self, rhs):
"""Overload += operation"""
return self._extend_or_combine(rhs, 'inplace', op_iadd)
def __sub__(self, rhs):
"""Overload - operation"""
return self._extend_or_combine(rhs, 'non-inplace', op_isub)
def __isub__(self, rhs):
"""Overload -= operation"""
return self._extend_or_combine(rhs, 'inplace', op_isub)
def __neg__(self):
"""Overload unary - """
ret = copy.deepcopy(self)
ret.scaling_coeff(-1.0)
return ret
def __eq__(self, rhs):
"""Overload == operation"""
if self._matrix is not None and rhs._matrix is not None:
return np.all(self._matrix == rhs._matrix)
if self._paulis is not None and rhs._paulis is not None:
if len(self._paulis) != len(rhs._paulis):
return False
for coeff, pauli in self._paulis:
found_pauli = False
rhs_coeff = 0.0
for coeff2, pauli2 in rhs._paulis:
if pauli == pauli2:
found_pauli = True
rhs_coeff = coeff2
break
if not found_pauli and rhs_coeff != 0.0: # since we might have 0 weights of paulis.
return False
if coeff != rhs_coeff:
return False
return True
if self._grouped_paulis is not None and rhs._grouped_paulis is not None:
self._grouped_paulis_to_paulis()
rhs._grouped_paulis_to_paulis()
return self.__eq__(rhs)
def __ne__(self, rhs):
""" != """
return not self.__eq__(rhs)
def __str__(self):
"""Overload str()"""
curr_repr = ""
length = ""
group = None
if self._paulis is not None:
curr_repr = 'paulis'
length = len(self._paulis)
elif self._grouped_paulis is not None:
curr_repr = 'grouped_paulis'
group = len(self._grouped_paulis)
length = sum([len(gp) - 1 for gp in self._grouped_paulis])
elif self._matrix is not None:
curr_repr = 'matrix'
length = "{}x{}".format(2 ** self.num_qubits, 2 ** self.num_qubits)
ret = "Representation: {}, qubits: {}, size: {}{}".format(
curr_repr, self.num_qubits, length, "" if group is None else " (number of groups: {})".format(group))
return ret
def copy(self):
"""Get a copy of self."""
return copy.deepcopy(self)
def chop(self, threshold=1e-15):
"""
Eliminate the real and imagine part of coeff in each pauli by `threshold`.
If pauli's coeff is less then `threshold` in both real and imagine parts, the pauli is removed.
To align the internal representations, all available representations are chopped.
The chopped result is stored back to original property.
Note: if coeff is real-only, the imag part is skipped.
Args:
threshold (float): threshold chops the paulis
"""
def chop_real_imag(coeff, threshold):
temp_real = coeff.real if np.absolute(coeff.real) >= threshold else 0.0
temp_imag = coeff.imag if np.absolute(coeff.imag) >= threshold else 0.0
if temp_real == 0.0 and temp_imag == 0.0:
return 0.0
else:
new_coeff = temp_real + 1j * temp_imag
return new_coeff
if self._paulis is not None:
for i in range(len(self._paulis)):
self._paulis[i][0] = chop_real_imag(self._paulis[i][0], threshold)
paulis = [x for x in self._paulis if x[0] != 0.0]
self._paulis = paulis
self._paulis_table = {pauli[1].to_label(): i for i, pauli in enumerate(self._paulis)}
if self._dia_matrix is not None:
self._to_dia_matrix('paulis')
elif self._grouped_paulis is not None:
grouped_paulis = []
for group_idx in range(1, len(self._grouped_paulis)):
for pauli_idx in range(len(self._grouped_paulis[group_idx])):
self._grouped_paulis[group_idx][pauli_idx][0] = chop_real_imag(
self._grouped_paulis[group_idx][pauli_idx][0], threshold)
paulis = [x for x in self._grouped_paulis[group_idx] if x[0] != 0.0]
grouped_paulis.append(paulis)
self._grouped_paulis = grouped_paulis
if self._dia_matrix is not None:
self._to_dia_matrix('grouped_paulis')
elif self._matrix is not None:
rows, cols = self._matrix.nonzero()
for row, col in zip(rows, cols):
self._matrix[row, col] = chop_real_imag(self._matrix[row, col], threshold)
self._matrix.eliminate_zeros()
if self._dia_matrix is not None:
self._to_dia_matrix('matrix')
def _simplify_paulis(self):
"""
Merge the paulis (grouped_paulis) whose bases are identical but the pauli with zero coefficient
would not be removed.
Usually used in construction.
"""
if self._paulis is not None:
new_paulis = []
new_paulis_table = {}
for curr_paulis in self._paulis:
pauli_label = curr_paulis[1].to_label()
new_idx = new_paulis_table.get(pauli_label, None)
if new_idx is not None:
new_paulis[new_idx][0] += curr_paulis[0]
else:
new_paulis_table[pauli_label] = len(new_paulis)
new_paulis.append(curr_paulis)
self._paulis = new_paulis
self._paulis_table = new_paulis_table
elif self._grouped_paulis is not None:
self._grouped_paulis_to_paulis()
self._simplify_paulis()
self._paulis_to_grouped_paulis()
def __mul__(self, rhs):
"""
Overload * operation. Only support two Operators have the same representation mode.
Returns:
Operator: the multipled Operator.
Raises:
TypeError, if two Operators do not have the same representations.
"""
if self._paulis is not None and rhs._paulis is not None:
ret_pauli = Operator(paulis=[])
for existed_pauli in self._paulis:
for pauli in rhs._paulis:
basis, sign = Pauli.sgn_prod(existed_pauli[1], pauli[1])
coeff = existed_pauli[0] * pauli[0] * sign
if abs(coeff) > 1e-15:
pauli_term = [coeff, basis]
ret_pauli += Operator(paulis=[pauli_term])
return ret_pauli
elif self._grouped_paulis is not None and rhs._grouped_paulis is not None:
self._grouped_paulis_to_paulis()
rhs._grouped_paulis_to_paulis()
mul_pauli = self * rhs
mul_pauli._paulis_to_grouped_paulis()
ret_grouped_pauli = Operator(paulis=mul_pauli._paulis, grouped_paulis=mul_pauli._grouped_paulis)
return ret_grouped_pauli
elif self._matrix is not None and rhs._matrix is not None:
ret_matrix = self._matrix.dot(rhs._matrix)
return Operator(matrix=ret_matrix)
else:
raise TypeError("the representations of two Operators should be the same. ({}, {})".format(
self.representations, rhs.representations))
@property
def coloring(self):
"""Getter of method of grouping paulis"""
return self._coloring
@coloring.setter
def coloring(self, new_coloring):
"""Setter of method of grouping paulis"""
self._coloring = new_coloring
@property
def aer_paulis(self):
if getattr(self, '_aer_paulis', None) is None:
self.to_paulis()
aer_paulis = []
for coeff, p in self._paulis:
new_coeff = [coeff.real, coeff.imag]
new_p = p.to_label()
aer_paulis.append([new_coeff, new_p])
self._aer_paulis = aer_paulis
return self._aer_paulis
def _to_dia_matrix(self, mode):
"""
Convert the reprenetations into diagonal matrix if possible and then store it back.
For paulis, if all paulis are Z or I (identity), convert to dia_matrix.
Args:
mode (str): "matrix", "paulis" or "grouped_paulis".
"""
if mode not in ['matrix', 'paulis', 'grouped_paulis']:
raise ValueError(
'Mode should be one of "matrix", "paulis", "grouped_paulis"')
if mode == 'matrix' and self._matrix is not None:
dia_matrix = self._matrix.diagonal()
if not scisparse.csr_matrix(dia_matrix).nnz == self._matrix.nnz:
dia_matrix = None
self._dia_matrix = dia_matrix
elif mode == 'paulis' and self._paulis is not None:
if self._paulis == []:
self._dia_matrix = None
else:
valid_dia_matrix_flag = True
dia_matrix = 0.0
for idx in range(len(self._paulis)):
coeff, pauli = self._paulis[idx][0], self._paulis[idx][1]
if not (np.all(np.logical_not(pauli.x))):
valid_dia_matrix_flag = False
break
dia_matrix += coeff * pauli.to_spmatrix().diagonal()
self._dia_matrix = dia_matrix.copy() if valid_dia_matrix_flag else None
elif mode == 'grouped_paulis' and self._grouped_paulis is not None:
self._grouped_paulis_to_paulis()
self._to_dia_matrix(mode='paulis')
self._paulis_to_grouped_paulis()
else:
self._dia_matrix = None
@property
def paulis(self):
"""Getter of Pauli list."""
return self._paulis
@property
def grouped_paulis(self):
"""Getter of grouped Pauli list."""
return self._grouped_paulis
@property
def matrix(self):
"""Getter of matrix; if matrix is diagonal, diagonal matrix is returned instead."""
return self._dia_matrix if self._dia_matrix is not None else self._matrix
def enable_summarize_circuits(self):
self._summarize_circuits = True
def disable_summarize_circuits(self):
self._summarize_circuits = False
@property
def representations(self):
"""
Return the available representations in the Operator.
Returns:
list: available representations ([str])
"""
ret = []
if self._paulis is not None:
ret.append("paulis")
if self._grouped_paulis is not None:
ret.append("grouped_paulis")
if self._matrix is not None:
ret.append("matrix")
return ret
@property
def num_qubits(self):
"""
number of qubits required for the operator.
Returns:
int: number of qubits
"""
if self._paulis is not None:
if self._paulis != []:
return len(self._paulis[0][1])
else:
return 0
elif self._grouped_paulis is not None and self._grouped_paulis != []:
return len(self._grouped_paulis[0][0][1])
else:
return int(np.log2(self._matrix.shape[0]))
@staticmethod
def load_from_file(file_name, before_04=False):
"""
Load paulis in a file to construct an Operator.
Args:
file_name (str): path to the file, which contains a list of Paulis and coefficients.
before_04 (bool): support the format < 0.4.
Returns:
Operator class: the loaded operator.
"""
with open(file_name, 'r') as file:
return Operator.load_from_dict(json.load(file), before_04=before_04)
def save_to_file(self, file_name):
"""
Save operator to a file in pauli representation.
Args:
file_name (str): path to the file
"""
with open(file_name, 'w') as f:
json.dump(self.save_to_dict(), f)
@staticmethod
def load_from_dict(dictionary, before_04=False):
"""
Load paulis in a dict to construct an Operator, \
the dict must be represented as follows: label and coeff (real and imag). \
E.g.: \
{'paulis': \
[ \
{'label': 'IIII', \
'coeff': {'real': -0.33562957575267038, 'imag': 0.0}}, \
{'label': 'ZIII', \
'coeff': {'real': 0.28220597164664896, 'imag': 0.0}}, \
... \
] \
} \
Args:
dictionary (dict): dictionary, which contains a list of Paulis and coefficients.
before_04 (bool): support the format < 0.4.
Returns:
Operator: the loaded operator.
"""
if 'paulis' not in dictionary:
raise AquaError('Dictionary missing "paulis" key')
paulis = []
for op in dictionary['paulis']:
if 'label' not in op:
raise AquaError('Dictionary missing "label" key')
pauli_label = op['label']
if 'coeff' not in op:
raise AquaError('Dictionary missing "coeff" key')
pauli_coeff = op['coeff']
if 'real' not in pauli_coeff:
raise AquaError('Dictionary missing "real" key')
coeff = pauli_coeff['real']
if 'imag' in pauli_coeff:
coeff = complex(pauli_coeff['real'], pauli_coeff['imag'])
pauli_label = pauli_label[::-1] if before_04 else pauli_label
paulis.append([coeff, Pauli.from_label(pauli_label)])
return Operator(paulis=paulis)
def save_to_dict(self):
"""
Save operator to a dict in pauli representation.
Returns:
dict: a dictionary contains an operator with pauli representation.
"""
self._check_representation("paulis")
ret_dict = {"paulis": []}
for pauli in self._paulis:
op = {"label": pauli[1].to_label()}
if isinstance(pauli[0], complex):
op["coeff"] = {"real": np.real(pauli[0]),
"imag": np.imag(pauli[0])
}
else:
op["coeff"] = {"real": pauli[0]}
ret_dict["paulis"].append(op)
return ret_dict
def print_operators(self, print_format='paulis'):
"""
Print out the paulis in the selected representation.
Args:
print_format (str): "paulis", "grouped_paulis", "matrix"
Returns:
str: a formated operator.
Raises:
ValueError: if `print_format` is not supported.
"""
ret = ""
if print_format == 'paulis':
self._check_representation("paulis")
for pauli in self._paulis:
ret = ''.join([ret, "{}\t{}\n".format(pauli[1].to_label(), pauli[0])])
if ret == "":
ret = ''.join([ret, "Pauli list is empty."])
elif print_format == 'grouped_paulis':
self._check_representation("grouped_paulis")
for i in range(len(self._grouped_paulis)):
ret = ''.join([ret, 'Post Rotations of TPB set {} '.format(i)])
ret = ''.join([ret, ': {} '.format(self._grouped_paulis[i][0][1].to_label())])
ret = ''.join([ret, '\n'])
for j in range(1, len(self._grouped_paulis[i])):
ret = ''.join([ret, '{} '.format(self._grouped_paulis[i][j][1].to_label())])
ret = ''.join([ret, '{}\n'.format(self._grouped_paulis[i][j][0])])
ret = ''.join([ret, '\n'])
if ret == "":
ret = ''.join([ret, "Grouped pauli list is empty."])
elif print_format == 'matrix':
self._check_representation("matrix")
ret = str(self._matrix.toarray())
else:
raise ValueError('Mode should be one of "matrix", "paulis", "grouped_paulis"')
return ret
def construct_evaluation_circuit(self, operator_mode, input_circuit, backend, use_simulator_operator_mode=False):
"""
Construct the circuits for evaluation.
Args:
operator_mode (str): representation of operator, including paulis, grouped_paulis and matrix
input_circuit (QuantumCircuit): the quantum circuit.
backend (BaseBackend): backend selection for quantum machine.
use_simulator_operator_mode (bool): if aer_provider is used, we can do faster
evaluation for pauli mode on statevector simualtion
Returns:
[QuantumCircuit]: the circuits for evaluation.
"""
if is_statevector_backend(backend):
if operator_mode == 'matrix':
circuits = [input_circuit]
else:
self._check_representation("paulis")
if use_simulator_operator_mode:
circuits = [input_circuit]
else:
n_qubits = self.num_qubits
q = find_regs_by_name(input_circuit, 'q')
circuits = [input_circuit]
for idx, pauli in enumerate(self._paulis):
circuit = QuantumCircuit() + input_circuit
if np.all(np.logical_not(pauli[1].z)) and np.all(np.logical_not(pauli[1].x)): # all I
continue
for qubit_idx in range(n_qubits):
if not pauli[1].z[qubit_idx] and pauli[1].x[qubit_idx]:
circuit.u3(np.pi, 0.0, np.pi, q[qubit_idx]) # x
elif pauli[1].z[qubit_idx] and not pauli[1].x[qubit_idx]:
circuit.u1(np.pi, q[qubit_idx]) # z
elif pauli[1].z[qubit_idx] and pauli[1].x[qubit_idx]:
circuit.u3(np.pi, np.pi/2, np.pi/2, q[qubit_idx]) # y
circuits.append(circuit)
else:
if operator_mode == 'matrix':
raise AquaError("matrix mode can not be used with non-statevector simulator.")
n_qubits = self.num_qubits
circuits = []
base_circuit = QuantumCircuit() + input_circuit
c = find_regs_by_name(base_circuit, 'c', qreg=False)
if c is None:
c = ClassicalRegister(n_qubits, name='c')
base_circuit.add_register(c)
if operator_mode == "paulis":
self._check_representation("paulis")
for idx, pauli in enumerate(self._paulis):
circuit = QuantumCircuit() + base_circuit
q = find_regs_by_name(circuit, 'q')
c = find_regs_by_name(circuit, 'c', qreg=False)
for qubit_idx in range(n_qubits):
if pauli[1].x[qubit_idx]:
if pauli[1].z[qubit_idx]:
# Measure Y
circuit.u1(-np.pi/2, q[qubit_idx]) # sdg
circuit.u2(0.0, np.pi, q[qubit_idx]) # h
else:
# Measure X
circuit.u2(0.0, np.pi, q[qubit_idx]) # h
circuit.barrier(q)
circuit.measure(q, c)
circuits.append(circuit)
else:
self._check_representation("grouped_paulis")
for idx, tpb_set in enumerate(self._grouped_paulis):
circuit = QuantumCircuit() + base_circuit
q = find_regs_by_name(circuit, 'q')
c = find_regs_by_name(circuit, 'c', qreg=False)
for qubit_idx in range(n_qubits):
if tpb_set[0][1].x[qubit_idx]:
if tpb_set[0][1].z[qubit_idx]:
# Measure Y
circuit.u1(-np.pi/2, q[qubit_idx]) # sdg
circuit.u2(0.0, np.pi, q[qubit_idx]) # h
else:
# Measure X
circuit.u2(0.0, np.pi, q[qubit_idx]) # h
circuit.barrier(q)
circuit.measure(q, c)
circuits.append(circuit)
return circuits
def evaluate_with_result(self, operator_mode, circuits, backend, result, use_simulator_operator_mode=False):
"""
Use the executed result with operator to get the evaluated value.
Args:
operator_mode (str): representation of operator, including paulis, grouped_paulis and matrix
circuits (list of qiskit.QuantumCircuit): the quantum circuits.
backend (str): backend selection for quantum machine.
result (qiskit.Result): the result from the backend.
use_simulator_operator_mode (bool): if aer_provider is used, we can do faster
evaluation for pauli mode on statevector simualtion
Returns:
float: the mean value
float: the standard deviation
"""
avg, std_dev, variance = 0.0, 0.0, 0.0
if is_statevector_backend(backend):
if operator_mode == "matrix":
self._check_representation("matrix")
if self._dia_matrix is None:
self._to_dia_matrix(mode='matrix')
quantum_state = np.asarray(result.get_statevector(circuits[0]))
if self._dia_matrix is not None:
avg = np.sum(self._dia_matrix * np.absolute(quantum_state) ** 2)
else:
avg = np.vdot(quantum_state, self._matrix.dot(quantum_state))
else:
self._check_representation("paulis")
if use_simulator_operator_mode:
temp = result.data(circuits[0])['snapshots']['expectation_value']['test'][0]['value']
avg = temp[0] + 1j * temp[1]
else:
quantum_state = np.asarray(result.get_statevector(circuits[0]))
circuit_idx = 1
for idx, pauli in enumerate(self._paulis):
if np.all(np.logical_not(pauli[1].z)) and np.all(np.logical_not(pauli[1].x)):
avg += pauli[0]
else:
quantum_state_i = np.asarray(result.get_statevector(circuits[circuit_idx]))
avg += pauli[0] * (np.vdot(quantum_state, quantum_state_i))
circuit_idx += 1
else:
if logger.isEnabledFor(logging.DEBUG):
logger.debug("Computing the expectation from measurement results:")
TextProgressBar(sys.stderr)
num_shots = sum(list(result.get_counts(circuits[0]).values()))
if operator_mode == "paulis":
self._check_representation("paulis")
results = parallel_map(Operator._routine_paulis_with_shots,
[(pauli, result.get_counts(circuits[idx]))
for idx, pauli in enumerate(self._paulis)],
num_processes=aqua_globals.num_processes)
for result in results:
avg += result[0]
variance += result[1]
else:
self._check_representation("grouped_paulis")
results = parallel_map(Operator._routine_grouped_paulis_with_shots,
[(tpb_set, result.get_counts(circuits[tpb_idx]))
for tpb_idx, tpb_set in enumerate(self._grouped_paulis)],
num_processes=aqua_globals.num_processes)
for result in results:
avg += result[0]
variance += result[1]
std_dev = np.sqrt(variance / num_shots)
return avg, std_dev
@staticmethod
def _routine_grouped_paulis_with_shots(args):
tpb_set, measured_results = args
avg_paulis = []
avg = 0.0
variance = 0.0
for pauli_idx, pauli in enumerate(tpb_set):
if pauli_idx == 0:
continue
observable = Operator._measure_pauli_z(measured_results, pauli[1])
avg_paulis.append(observable)
avg += pauli[0] * observable
# Compute the covariance matrix elements of tpb_set
# and add up to the total standard deviation
# tpb_set = grouped_paulis, tensor product basis set
for pauli_1_idx, pauli_1 in enumerate(tpb_set):
for pauli_2_idx, pauli_2 in enumerate(tpb_set):
if pauli_1_idx == 0 or pauli_2_idx == 0:
continue
variance += pauli_1[0] * pauli_2[0] * \
Operator._covariance(measured_results, pauli_1[1], pauli_2[1],
avg_paulis[pauli_1_idx-1], avg_paulis[pauli_2_idx-1])
return avg, variance
@staticmethod
def _routine_paulis_with_shots(args):
pauli, measured_results = args
curr_result = Operator._measure_pauli_z(measured_results, pauli[1])
avg = pauli[0] * curr_result
variance = (pauli[0] ** 2) * Operator._covariance(measured_results, pauli[1], pauli[1],
curr_result, curr_result)
return avg, variance
def _eval_directly(self, quantum_state):
self._check_representation("matrix")
if self._dia_matrix is None:
self._to_dia_matrix(mode='matrix')
if self._dia_matrix is not None:
avg = np.sum(self._dia_matrix * np.absolute(quantum_state) ** 2)
else:
avg = np.vdot(quantum_state, self._matrix.dot(quantum_state))
return avg
def eval(self, operator_mode, input_circuit, backend, backend_config=None, compile_config=None,
run_config=None, qjob_config=None, noise_config=None):
"""
Supporting three ways to evaluate the given circuits with the operator.
1. If `input_circuit` is a numpy.ndarray, it will directly perform inner product with the operator.
2. If `backend` is a statevector simulator, use quantum backend to get statevector \
and then evaluate with the operator.
3. Other cases: it use with quanutm backend (simulator or real quantum machine), \
to obtain the mean and standard deviation of measured results.
Args:
operator_mode (str): representation of operator, including paulis, grouped_paulis and matrix
input_circuit (QuantumCircuit or numpy.ndarray): the quantum circuit.
backend (BaseBackend): backend selection for quantum machine.
backend_config (dict): configuration for backend
compile_config (dict): configuration for compilation
run_config (RunConfig): configuration for running a circuit
qjob_config (dict): the setting to retrieve results from quantum backend, including timeout and wait.
noise_config (dict) the setting of noise model for the qasm simulator in the Aer provider.
Returns:
float, float: mean and standard deviation of avg
"""
backend_config = backend_config or {}
compile_config = compile_config or {}
if run_config is not None:
if isinstance(run_config, dict):
run_config = RunConfig(**run_config)
else:
run_config = RunConfig()
qjob_config = qjob_config or {}
noise_config = noise_config or {}
if isinstance(input_circuit, np.ndarray):
avg = self._eval_directly(input_circuit)
std_dev = 0.0
else:
if is_statevector_backend(backend):
run_config.shots = 1
circuits = self.construct_evaluation_circuit(operator_mode, input_circuit, backend)
result = compile_and_run_circuits(circuits, backend=backend, backend_config=backend_config,
compile_config=compile_config, run_config=run_config,
qjob_config=qjob_config, noise_config=noise_config,
show_circuit_summary=self._summarize_circuits)
avg, std_dev = self.evaluate_with_result(operator_mode, circuits, backend, result)
return avg, std_dev
def to_paulis(self):
self._check_representation('paulis')
def to_grouped_paulis(self):
self._check_representation('grouped_paulis')
def to_matrix(self):
self._check_representation('matrix')
def convert(self, input_format, output_format, force=False):
"""
A wrapper for conversion among all representations.
Note that, if the output target is already there, it will skip the conversion.
The result is stored back into its property directly.
Args:
input_format (str): case-insensitive input format,
should be one of "paulis", "grouped_paulis", "matrix"
output_format (str): case-insensitive output format,
should be one of "paulis", "grouped_paulis", "matrix"
force (bool): convert to targeted format regardless its present.
Raises:
ValueError: if the unsupported output_format is specified.
"""
input_format = input_format.lower()
output_format = output_format.lower()
if input_format not in ["paulis", "grouped_paulis", "matrix"]:
raise ValueError(
"Input format {} is not supported".format(input_format))
if output_format not in ["paulis", "grouped_paulis", "matrix"]:
raise ValueError(
"Output format {} is not supported".format(output_format))
if output_format == "paulis" and (self._paulis is None or force):
if input_format == "matrix":
self._matrix_to_paulis()
elif input_format == "grouped_paulis":
self._grouped_paulis_to_paulis()
elif output_format == "grouped_paulis" and (self._grouped_paulis is None or force):
if self._grouped_paulis == []:
return
if input_format == "paulis":
self._paulis_to_grouped_paulis()
elif input_format == "matrix":
self._matrix_to_grouped_paulis()
elif output_format == "matrix" and (self._matrix is None or force):
if input_format == "paulis":
self._paulis_to_matrix()
elif input_format == "grouped_paulis":
self._grouped_paulis_to_matrix()
def _grouped_paulis_to_paulis(self):
"""
Convert grouped paulis to paulis, and save it in internal property directly.
Note:
Ideally, all paulis in grouped_paulis should be unique.
No need to check whether it is existed.
"""
if self._grouped_paulis == []:
return
paulis = []
for group in self._grouped_paulis:
for idx in range(1, len(group)): # the first one is the header.
paulis.append(group[idx])
self._paulis = paulis
self._matrix = None
self._grouped_paulis = None
def _matrix_to_paulis(self):
"""
Convert matrix to paulis, and save it in internal property directly.
Note:
Conversion from Paulis to matrix: H = sum_i alpha_i * Pauli_i
Conversion from matrix to Paulis: alpha_i = coeff * Trace(H.Pauli_i) (dot product of trace)
where coeff = 2^(- # of qubits), # of qubit = log2(dim of matrix)
"""
if self._matrix.nnz == 0:
return
num_qubits = self.num_qubits
coeff = 2 ** (-num_qubits)
paulis = []
# generate all possible paulis basis
for basis in itertools.product('IXYZ', repeat=num_qubits):
pauli_i = Pauli.from_label(''.join(basis))
trace_value = np.sum(self._matrix.dot(pauli_i.to_spmatrix()).diagonal())
alpha_i = trace_value * coeff
if alpha_i != 0.0:
paulis.append([alpha_i, pauli_i])
self._paulis = paulis
self._matrix = None
self._grouped_paulis = None
def _paulis_to_grouped_paulis(self):
"""
Convert paulis to grouped_paulis, and save it in internal property directly.
Groups a list of [coeff,Pauli] into tensor product basis (tpb) sets
"""
if self._paulis == []:
return
if self._coloring is not None:
self._grouped_paulis = PauliGraph(self._paulis, mode=self._coloring).grouped_paulis
else:
temp_paulis = copy.deepcopy(self._paulis)
n = self.num_qubits
grouped_paulis = []
sorted_paulis = []
def check_pauli_in_list(target, pauli_list):
ret = False
for pauli in pauli_list:
if target[1] == pauli[1]:
ret = True
break
return ret
for i in range(len(temp_paulis)):
p_1 = temp_paulis[i]
if not check_pauli_in_list(p_1, sorted_paulis):
paulis_temp = []
# pauli_list_temp.extend(p_1) # this is going to signal the total
# post-rotations of the set (set master)
paulis_temp.append(p_1)
paulis_temp.append(copy.deepcopy(p_1))
paulis_temp[0][0] = 0.0 # zero coeff for HEADER
for j in range(i+1, len(temp_paulis)):
p_2 = temp_paulis[j]
if not check_pauli_in_list(p_2, sorted_paulis) and p_1[1] != p_2[1]:
j = 0
for i in range(n):
# p_2 is identity, p_1 is identity, p_1 and p_2 has same basis
if not ((not p_2[1].z[i] and not p_2[1].x[i]) or
(not p_1[1].z[i] and not p_1[1].x[i]) or
(p_2[1].z[i] == p_1[1].z[i] and
p_2[1].x[i] == p_1[1].x[i])):
break
else:
# update master, if p_2 is not identity
if p_2[1].z[i] or p_2[1].x[i]:
paulis_temp[0][1].update_z(p_2[1].z[i], i)
paulis_temp[0][1].update_x(p_2[1].x[i], i)
j += 1
if j == n:
paulis_temp.append(p_2)
sorted_paulis.append(p_2)
grouped_paulis.append(paulis_temp)
self._grouped_paulis = grouped_paulis
self._matrix = None
self._paulis = None
def _matrix_to_grouped_paulis(self):
"""
Convert matrix to grouped_paulis, and save it in internal property directly.
"""
if self._matrix.nnz == 0:
return
self._matrix_to_paulis()
self._paulis_to_grouped_paulis()
self._matrix = None
self._paulis = None
def _paulis_to_matrix(self):
"""
Convert paulis to matrix, and save it in internal property directly.
If all paulis are Z or I (identity), convert to dia_matrix.
"""
if self._paulis == []:
return
p = self._paulis[0]
hamiltonian = p[0] * p[1].to_spmatrix()
for idx in range(1, len(self._paulis)):
p = self._paulis[idx]
hamiltonian += p[0] * p[1].to_spmatrix()
self._matrix = hamiltonian
self._to_dia_matrix(mode='matrix')
self._paulis = None
self._grouped_paulis = None
def _grouped_paulis_to_matrix(self):
"""
Convert grouped_paulis to matrix, and save it in internal property directly.
If all paulis are Z or I (identity), convert to dia_matrix.
"""
if self._grouped_paulis == []:
return
p = self._grouped_paulis[0][1]
hamiltonian = p[0] * p[1].to_spmatrix()
for idx in range(2, len(self._grouped_paulis[0])):
p = self._grouped_paulis[0][idx]
hamiltonian += p[0] * p[1].to_spmatrix()
for group_idx in range(1, len(self._grouped_paulis)):
group = self._grouped_paulis[group_idx]
for idx in range(1, len(group)):
p = group[idx]
hamiltonian += p[0] * p[1].to_spmatrix()
self._matrix = hamiltonian
self._to_dia_matrix(mode='matrix')
self._paulis = None
self._grouped_paulis = None
@staticmethod
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(np.bool)
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
@staticmethod
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(np.bool)
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
def two_qubit_reduced_operator(self, m, threshold=10**-13):
"""
Eliminates the central and last qubit in a list of Pauli that has
diagonal operators (Z,I) at those positions
Chemistry specific method:
It can be used to taper two qubits in parity and binary-tree mapped
fermionic Hamiltonians when the spin orbitals are ordered in two spin
sectors, (block spin order) according to the number of particles in the system.
Args:
m (int): number of fermionic particles
threshold (float): threshold for Pauli simplification
Returns:
Operator: a new operator whose qubit number is reduced by 2.
"""
if self._paulis is None or self._paulis == []:
return self
operator_out = Operator(paulis=[])
par_1 = 1 if m % 2 == 0 else -1
par_2 = 1 if m % 4 == 0 else -1
n = self.num_qubits
last_idx = n - 1
mid_idx = n // 2 - 1
for pauli_term in self._paulis: # loop over Pauli terms
coeff_out = pauli_term[0]
# Z operator encountered at qubit n/2-1
if pauli_term[1].z[mid_idx] and not pauli_term[1].x[mid_idx]:
coeff_out = par_2 * coeff_out
# Z operator encountered at qubit n-1
if pauli_term[1].z[last_idx] and not pauli_term[1].x[last_idx]:
coeff_out = par_1 * coeff_out
# TODO: can change to delete
z_temp = []
x_temp = []
for j in range(n - 1):
if j != mid_idx:
z_temp.append(pauli_term[1].z[j])
x_temp.append(pauli_term[1].x[j])
pauli_term_out = [coeff_out, Pauli(np.asarray(z_temp), np.asarray(x_temp))]
if np.absolute(coeff_out) > threshold:
operator_out += Operator(paulis=[pauli_term_out])
operator_out.chop(threshold=threshold)
return operator_out
def get_flat_pauli_list(self):
"""
Get the flat list of paulis
Returns:
list: The list of pauli terms
"""
if self._paulis is not None:
return [] + self._paulis
else:
if self._grouped_paulis is not None:
return [pauli for group in self._grouped_paulis for pauli in group[1:]]
elif self._matrix is not None:
self._check_representation('paulis')
return [] + self._paulis
@staticmethod
def construct_evolution_circuit(slice_pauli_list, evo_time, num_time_slices, state_registers,
ancillary_registers=None, ctl_idx=0, unitary_power=None, use_basis_gates=True,
shallow_slicing=False):
"""
Construct the evolution circuit according to the supplied specification.
Args:
slice_pauli_list (list): The list of pauli terms corresponding to a single time slice to be evolved
evo_time (int): The evolution time
num_time_slices (int): The number of time slices for the expansion
state_registers (QuantumRegister): The Qiskit QuantumRegister corresponding to the qubits of the system
ancillary_registers (QuantumRegister): The optional Qiskit QuantumRegister corresponding to the control
qubits for the state_registers of the system
ctl_idx (int): The index of the qubit of the control ancillary_registers to use
unitary_power (int): The power to which the unitary operator is to be raised
use_basis_gates (bool): boolean flag for indicating only using basis gates when building circuit.
shallow_slicing (bool): boolean flag for indicating using shallow qc.data reference repetition for slicing
Returns:
QuantumCircuit: The Qiskit QuantumCircuit corresponding to specified evolution.
"""
if state_registers is None:
raise ValueError('Quantum state registers are required.')
qc_slice = QuantumCircuit(state_registers)
if ancillary_registers is not None:
qc_slice.add_register(ancillary_registers)
# for each pauli [IXYZ]+, record the list of qubit pairs needing CX's
cnot_qubit_pairs = [None] * len(slice_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(slice_pauli_list)
for pauli_idx, pauli in enumerate(reversed(slice_pauli_list)):
n_qubits = pauli[1].numberofqubits
# 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.u2(0.0, pi, 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.u3(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('Unrecognized pauli: {}'.format(pauli[1]))
if len(nontrivial_pauli_indices) > 0:
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:
if ancillary_registers is None:
lam = (2.0 * pauli[0] * evo_time / num_time_slices).real
if use_basis_gates:
qc_slice.u1(lam, state_registers[top_XYZ_pauli_indices[pauli_idx]])
else:
qc_slice.rz(lam, state_registers[top_XYZ_pauli_indices[pauli_idx]])
else:
unitary_power = (2 ** ctl_idx) if unitary_power is None else unitary_power
lam = (2.0 * pauli[0] * evo_time / num_time_slices * unitary_power).real
if use_basis_gates:
qc_slice.u1(lam / 2, state_registers[top_XYZ_pauli_indices[pauli_idx]])
qc_slice.cx(ancillary_registers[ctl_idx], state_registers[top_XYZ_pauli_indices[pauli_idx]])
qc_slice.u1(-lam / 2, state_registers[top_XYZ_pauli_indices[pauli_idx]])
qc_slice.cx(ancillary_registers[ctl_idx], state_registers[top_XYZ_pauli_indices[pauli_idx]])
else:
qc_slice.crz(lam, ancillary_registers[ctl_idx],
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.u2(0.0, pi, 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.u3(-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.')
qc_slice.data *= num_time_slices
qc = qc_slice
else:
qc = QuantumCircuit()
for _ in range(num_time_slices):
qc += qc_slice
return qc
@staticmethod
def _suzuki_expansion_slice_matrix(pauli_list, lam, expansion_order):
"""
Compute the matrix for a single slice of the suzuki expansion following the paper
https://arxiv.org/pdf/quant-ph/0508139.pdf
Args:
pauli_list (list): The operator's complete list of pauli terms for the suzuki expansion
lam (complex): The parameter lambda as defined in said paper
expansion_order (int): The order for the suzuki expansion
Returns:
numpy array: The matrix representation corresponding to the specified suzuki expansion
"""
if expansion_order == 1:
left = reduce(
lambda x, y: x @ y,
[scila.expm(lam / 2 * c * p.to_spmatrix().tocsc()) for c, p in pauli_list]
)
right = reduce(
lambda x, y: x @ y,
[scila.expm(lam / 2 * c * p.to_spmatrix().tocsc()) for c, p in reversed(pauli_list)]
)
return left @ right
else:
pk = (4 - 4 ** (1 / (2 * expansion_order - 1))) ** -1
side_base = Operator._suzuki_expansion_slice_matrix(
pauli_list,
lam * pk,
expansion_order - 1
)
side = side_base @ side_base
middle = Operator._suzuki_expansion_slice_matrix(
pauli_list,
lam * (1 - 4 * pk),
expansion_order - 1
)
return side @ middle @ side
@staticmethod
def _suzuki_expansion_slice_pauli_list(pauli_list, lam_coef, expansion_order):
"""
Similar to _suzuki_expansion_slice_matrix, with the difference that this method
computes the list of pauli terms for a single slice of the suzuki expansion,
which can then be fed to construct_evolution_circuit to build the QuantumCircuit.
"""
if expansion_order == 1:
half = [[lam_coef / 2 * c, p] for c, p in pauli_list]
return half + list(reversed(half))
else:
pk = (4 - 4 ** (1 / (2 * expansion_order - 1))) ** -1
side_base = Operator._suzuki_expansion_slice_pauli_list(
pauli_list,
lam_coef * pk,
expansion_order - 1
)
side = side_base * 2
middle = Operator._suzuki_expansion_slice_pauli_list(
pauli_list,
lam_coef * (1 - 4 * pk),
expansion_order - 1
)
return side + middle + side
def evolve(
self,
state_in=None,
evo_time=0,
evo_mode=None,
num_time_slices=0,
quantum_registers=None,
expansion_mode='trotter',
expansion_order=1
):
"""
Carry out the eoh evolution for the operator under supplied specifications.
Args:
state_in: The initial state for the evolution
evo_time (int): The evolution time
evo_mode (str): The mode under which the evolution is carried out.
Currently only support 'matrix' or 'circuit'
num_time_slices (int): The number of time slices for the expansion
quantum_registers (QuantumRegister): The QuantumRegister to build the QuantumCircuit off of
expansion_mode (str): The mode under which the expansion is to be done.
Currently support 'trotter', which follows the expansion as discussed in
http://science.sciencemag.org/content/273/5278/1073,
and 'suzuki', which corresponds to the discussion in
https://arxiv.org/pdf/quant-ph/0508139.pdf
expansion_order (int): The order for suzuki expansion
Returns:
Depending on the evo_mode specified, either return the matrix vector multiplication result
or the constructed QuantumCircuit.
"""
if num_time_slices < 0 or not isinstance(num_time_slices, int):
raise ValueError('Number of time slices should be a non-negative integer.')
if not (expansion_mode == 'trotter' or expansion_mode == 'suzuki'):
raise NotImplementedError('Expansion mode {} not supported.'.format(expansion_mode))
pauli_list = self.get_flat_pauli_list()
if evo_mode == 'matrix':
self._check_representation("matrix")
if num_time_slices == 0:
return scila.expm(-1.j * evo_time * self._matrix.tocsc()) @ state_in
else:
if len(pauli_list) == 1:
approx_matrix_slice = scila.expm(
-1.j * evo_time / num_time_slices * pauli_list[0][0] * pauli_list[0][1].to_spmatrix().tocsc()
)
else:
if expansion_mode == 'trotter':
approx_matrix_slice = reduce(
lambda x, y: x @ y,
[
scila.expm(-1.j * evo_time / num_time_slices * c * p.to_spmatrix().tocsc())
for c, p in pauli_list
]
)
# suzuki expansion
elif expansion_mode == 'suzuki':
approx_matrix_slice = Operator._suzuki_expansion_slice_matrix(
pauli_list,
-1.j * evo_time / num_time_slices,
expansion_order
)
else:
raise ValueError('Unrecognized expansion mode {}.'.format(expansion_mode))
return reduce(lambda x, y: x @ y, [approx_matrix_slice] * num_time_slices) @ state_in
elif evo_mode == 'circuit':
if num_time_slices == 0:
raise ValueError('Number of time slices should be a positive integer for {} mode.'.format(evo_mode))
else:
if quantum_registers is None:
raise ValueError('Quantum registers are needed for circuit construction.')
if len(pauli_list) == 1:
slice_pauli_list = pauli_list
else:
if expansion_mode == 'trotter':
slice_pauli_list = pauli_list
# suzuki expansion
else:
slice_pauli_list = Operator._suzuki_expansion_slice_pauli_list(
pauli_list,
1,
expansion_order
)
return self.construct_evolution_circuit(
slice_pauli_list, evo_time, num_time_slices, quantum_registers
)
else:
raise ValueError('Evolution mode should be either "matrix" or "circuit".')
def is_empty(self):
"""
Check Operator is empty or not.
Returns:
bool: is empty?
"""
if self._matrix is None and self._dia_matrix is None \
and (self._paulis == [] or self._paulis is None) \
and (self._grouped_paulis == [] or self._grouped_paulis is None):
return True
else:
return False
def _check_representation(self, targeted_representation):
"""
Check the targeted representation is existed or not, if not, find available representations
and then convert to the targeted one.
Args:
targeted_representation (str): should be one of paulis, grouped_paulis and matrix
Raises:
ValueError: if the `targeted_representation` is not recognized.
"""
if targeted_representation == 'paulis':
if self._paulis is None:
if self._matrix is not None:
self._matrix_to_paulis()
elif self._grouped_paulis is not None:
self._grouped_paulis_to_paulis()
else:
raise AquaError(
"at least having one of the three operator representations.")
elif targeted_representation == 'grouped_paulis':
if self._grouped_paulis is None:
if self._paulis is not None:
self._paulis_to_grouped_paulis()
elif self._matrix is not None:
self._matrix_to_grouped_paulis()
else:
raise AquaError(
"at least having one of the three operator representations.")
elif targeted_representation == 'matrix':
if self._matrix is None:
if self._paulis is not None:
self._paulis_to_matrix()
elif self._grouped_paulis is not None:
self._grouped_paulis_to_matrix()
else:
raise AquaError(
"at least having one of the three operator representations.")
else:
raise ValueError(
'"targeted_representation" should be one of "paulis", "grouped_paulis" and "matrix".'
)
@staticmethod
def row_echelon_F2(matrix_in):
"""
Computes the row Echelon form of a binary matrix on the binary
finite field
Args:
matrix_in (numpy.ndarray): binary matrix
Returns:
numpy.ndarray : matrix_in in Echelon row form
"""
size = matrix_in.shape
for i in range(size[0]):
pivot_index = 0
for j in range(size[1]):
if matrix_in[i, j] == 1:
pivot_index = j
break
for k in range(size[0]):
if k != i and matrix_in[k, pivot_index] == 1:
matrix_in[k, :] = np.mod(matrix_in[k, :] + matrix_in[i, :], 2)
matrix_out_temp = copy.deepcopy(matrix_in)
indices = []
matrix_out = np.zeros(size)
for i in range(size[0] - 1):
if np.array_equal(matrix_out_temp[i, :], np.zeros(size[1])):
indices.append(i)
for row in np.sort(indices)[::-1]:
matrix_out_temp = np.delete(matrix_out_temp, (row), axis=0)
matrix_out[0:size[0] - len(indices), :] = matrix_out_temp
matrix_out = matrix_out.astype(int)
return matrix_out
@staticmethod
def kernel_F2(matrix_in):
"""
Computes the kernel of a binary matrix on the binary finite field
Args:
matrix_in (numpy.ndarray): binary matrix
Returns:
[numpy.ndarray]: the list of kernel vectors
"""
size = matrix_in.shape
kernel = []
matrix_in_id = np.vstack((matrix_in, np.identity(size[1])))
matrix_in_id_ech = (Operator.row_echelon_F2(matrix_in_id.transpose())).transpose()
for col in range(size[1]):
if (np.array_equal(matrix_in_id_ech[0:size[0], col], np.zeros(size[0])) and not
np.array_equal(matrix_in_id_ech[size[0]:, col], np.zeros(size[1]))):
kernel.append(matrix_in_id_ech[size[0]:, col])
return kernel
def find_Z2_symmetries(self):
"""
Finds Z2 Pauli-type symmetries of an Operator
Returns:
[Pauli]: the list of Pauli objects representing the Z2 symmetries
[Pauli]: the list of single - qubit Pauli objects to construct the Cliffors operators
[Operators]: the list of Clifford unitaries to block diagonalize Operator
[int]: the list of support of the single-qubit Pauli objects used to build the clifford operators
"""
Pauli_symmetries = []
sq_paulis = []
cliffords = []
sq_list = []
stacked_paulis = []
if self.is_empty():
logger.info("Operator is empty.")
return [], [], [], []
self._check_representation("paulis")
for pauli in self._paulis:
stacked_paulis.append(np.concatenate((pauli[1].x, pauli[1].z), axis=0).astype(np.int))
stacked_matrix = np.array(np.stack(stacked_paulis))
symmetries = Operator.kernel_F2(stacked_matrix)
if len(symmetries) == 0:
logger.info("No symmetry is found.")
return [], [], [], []
stacked_symmetries = np.stack(symmetries)
symm_shape = stacked_symmetries.shape
for row in range(symm_shape[0]):
Pauli_symmetries.append(Pauli(stacked_symmetries[row, : symm_shape[1] // 2],
stacked_symmetries[row, symm_shape[1] // 2:]))
stacked_symm_del = np.delete(stacked_symmetries, (row), axis=0)
for col in range(symm_shape[1] // 2):
# case symmetries other than one at (row) have Z or I on col qubit
Z_or_I = True
for symm_idx in range(symm_shape[0] - 1):
if not (stacked_symm_del[symm_idx, col] == 0
and stacked_symm_del[symm_idx, col + symm_shape[1] // 2] in (0, 1)):
Z_or_I = False
if Z_or_I:
if ((stacked_symmetries[row, col] == 1 and
stacked_symmetries[row, col + symm_shape[1] // 2] == 0) or
(stacked_symmetries[row, col] == 1 and
stacked_symmetries[row, col + symm_shape[1] // 2] == 1)):
sq_paulis.append(Pauli(np.zeros(symm_shape[1] // 2),
np.zeros(symm_shape[1] // 2)))
sq_paulis[row].z[col] = False
sq_paulis[row].x[col] = True
sq_list.append(col)
break
# case symmetries other than one at (row) have X or I on col qubit
X_or_I = True
for symm_idx in range(symm_shape[0] - 1):
if not (stacked_symm_del[symm_idx, col] in (0, 1) and
stacked_symm_del[symm_idx, col + symm_shape[1] // 2] == 0):
X_or_I = False
if X_or_I:
if ((stacked_symmetries[row, col] == 0 and
stacked_symmetries[row, col + symm_shape[1] // 2] == 1) or
(stacked_symmetries[row, col] == 1 and
stacked_symmetries[row, col + symm_shape[1] // 2] == 1)):
sq_paulis.append(Pauli(np.zeros(symm_shape[1] // 2), np.zeros(symm_shape[1] // 2)))
sq_paulis[row].z[col] = True
sq_paulis[row].x[col] = False
sq_list.append(col)
break
# case symmetries other than one at (row) have Y or I on col qubit
Y_or_I = True
for symm_idx in range(symm_shape[0] - 1):
if not ((stacked_symm_del[symm_idx, col] == 1 and
stacked_symm_del[symm_idx, col + symm_shape[1] // 2] == 1)
or (stacked_symm_del[symm_idx, col] == 0 and
stacked_symm_del[symm_idx, col + symm_shape[1] // 2] == 0)):
Y_or_I = False
if Y_or_I:
if ((stacked_symmetries[row, col] == 0 and
stacked_symmetries[row, col + symm_shape[1] // 2] == 1) or
(stacked_symmetries[row, col] == 1 and
stacked_symmetries[row, col + symm_shape[1] // 2] == 0)):
sq_paulis.append(Pauli(np.zeros(symm_shape[1] // 2), np.zeros(symm_shape[1] // 2)))
sq_paulis[row].z[col] = True
sq_paulis[row].x[col] = True
sq_list.append(col)
break
for symm_idx, Pauli_symm in enumerate(Pauli_symmetries):
cliffords.append(Operator([[1 / np.sqrt(2), Pauli_symm], [1 / np.sqrt(2), sq_paulis[symm_idx]]]))
return Pauli_symmetries, sq_paulis, cliffords, sq_list
@staticmethod
def qubit_tapering(operator, cliffords, sq_list, tapering_values):
"""
Builds an Operator which has a number of qubits tapered off,
based on a block-diagonal Operator built using a list of cliffords.
The block-diagonal subspace is an input parameter, set through the list
tapering_values, which takes values +/- 1.
Args:
operator (Operator): the target operator to be tapered
cliffords ([Operator]): list of unitary Clifford transformation
sq_list ([int]): position of the single-qubit operators that anticommute
with the cliffords
tapering_values ([int]): array of +/- 1 used to select the subspace. Length
has to be equal to the length of cliffords and sq_list
Returns:
Operator : the tapered operator, or empty operator if the `operator` is empty.
"""
if len(cliffords) == 0 or len(sq_list) == 0 or len(tapering_values) == 0:
logger.warning("Cliffords, single qubit list and tapering values cannot be empty.\n"
"Return the original operator instead.")
return operator
if len(cliffords) != len(sq_list):
logger.warning("Number of Clifford unitaries has to be the same as length of single"
"qubit list and tapering values.\n"
"Return the original operator instead.")
return operator
if len(sq_list) != len(tapering_values):
logger.warning("Number of Clifford unitaries has to be the same as length of single"
"qubit list and tapering values.\n"
"Return the original operator instead.")
return operator
if operator.is_empty():
logger.warning("The operator is empty, return the empty operator directly.")
return operator
operator.to_paulis()
for clifford in cliffords:
operator = clifford * operator * clifford
operator_out = Operator(paulis=[])
for pauli_term in operator.paulis:
coeff_out = pauli_term[0]
for idx, qubit_idx in enumerate(sq_list):
if not (not pauli_term[1].z[qubit_idx] and not pauli_term[1].x[qubit_idx]):
coeff_out = tapering_values[idx] * coeff_out
z_temp = np.delete(pauli_term[1].z.copy(), np.asarray(sq_list))
x_temp = np.delete(pauli_term[1].x.copy(), np.asarray(sq_list))
pauli_term_out = [coeff_out, Pauli(z_temp, x_temp)]
operator_out += Operator(paulis=[pauli_term_out])
operator_out.zeros_coeff_elimination()
return operator_out
def zeros_coeff_elimination(self):
"""
Elinminate paulis or grouped paulis whose coefficients are zeros.
The difference from `_simplify_paulis` method is that, this method will not remove duplicated
paulis.
"""
if self._paulis is not None:
new_paulis = [pauli for pauli in self._paulis if pauli[0] != 0]
self._paulis = new_paulis
self._paulis_table = {pauli[1].to_label(): i for i, pauli in enumerate(self._paulis)}
elif self._grouped_paulis is not None:
self._grouped_paulis_to_paulis()
self.zeros_coeff_elimination()
self._paulis_to_grouped_paulis()
self._paulis = None
def scaling_coeff(self, scaling_factor):
"""
Constant scale the coefficient in an operator.
Note that: the behavior of scaling in paulis (grouped_paulis) might be different from matrix
Args:
scaling_factor (float): the sacling factor
"""
if self._paulis is not None:
for idx in range(len(self._paulis)):
self._paulis[idx] = [self._paulis[idx][0] * scaling_factor, self._paulis[idx][1]]
elif self._grouped_paulis is not None:
self._grouped_paulis_to_paulis()
self._scale_paulis(scaling_factor)
self._paulis_to_grouped_paulis()
elif self._matrix is not None:
self._matrix *= scaling_factor
if self._dia_matrix is not None:
self._dia_matrix *= scaling_factor
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import logging
import numpy as np
from qiskit.util import local_hardware_info
import qiskit
from .aqua_error import AquaError
logger = logging.getLogger(__name__)
class QiskitAquaGlobals(object):
"""Aqua class for global properties."""
CPU_COUNT = local_hardware_info()['cpus']
def __init__(self):
self._random_seed = None
self._num_processes = QiskitAquaGlobals.CPU_COUNT
self._random = None
@property
def random_seed(self):
"""Return random seed."""
return self._random_seed
@random_seed.setter
def random_seed(self, seed):
"""Set random seed."""
self._random_seed = seed
self._random = None
@property
def num_processes(self):
"""Return num processes."""
return self._num_processes
@num_processes.setter
def num_processes(self, num_processes):
"""Set num processes."""
if num_processes < 1:
raise AquaError('Invalid Number of Processes {}.'.format(num_processes))
if num_processes > QiskitAquaGlobals.CPU_COUNT:
raise AquaError('Number of Processes {} cannot be greater than cpu count {}.'
.format(num_processes, QiskitAquaGlobals.CPU_COUNT))
self._num_processes = num_processes
# TODO: change Terra CPU_COUNT until issue gets resolved: https://github.com/Qiskit/qiskit-terra/issues/1963
try:
qiskit.tools.parallel.CPU_COUNT = self.num_processes
except Exception as e:
logger.warning("Failed to set qiskit.tools.parallel.CPU_COUNT to value: '{}': Error: '{}'".
format(self.num_processes, str(e)))
@property
def random(self):
"""Return a numpy random."""
if self._random is None:
if self._random_seed is None:
self._random = np.random
else:
self._random = np.random.RandomState(self._random_seed)
return self._random
# Global instance to be used as the entry point for globals.
aqua_globals = QiskitAquaGlobals()
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import logging
import time
from qiskit import __version__ as terra_version
from qiskit.assembler.run_config import RunConfig
from qiskit.transpiler import Layout
from .utils import (run_qobjs, compile_circuits, CircuitCache,
get_measured_qubits_from_qobj,
build_measurement_error_mitigation_fitter,
mitigate_measurement_error)
from .utils.backend_utils import (is_aer_provider,
is_ibmq_provider,
is_statevector_backend,
is_simulator_backend,
is_local_backend)
logger = logging.getLogger(__name__)
class QuantumInstance:
"""Quantum Backend including execution setting."""
BACKEND_CONFIG = ['basis_gates', 'coupling_map']
COMPILE_CONFIG = ['pass_manager', 'initial_layout', 'seed_transpiler']
RUN_CONFIG = ['shots', 'max_credits', 'memory', 'seed']
QJOB_CONFIG = ['timeout', 'wait']
NOISE_CONFIG = ['noise_model']
# https://github.com/Qiskit/qiskit-aer/blob/master/qiskit/providers/aer/backends/qasm_simulator.py
BACKEND_OPTIONS_QASM_ONLY = ["statevector_sample_measure_opt", "max_parallel_shots"]
BACKEND_OPTIONS = ["initial_statevector", "chop_threshold", "max_parallel_threads",
"max_parallel_experiments", "statevector_parallel_threshold",
"statevector_hpc_gate_opt"] + BACKEND_OPTIONS_QASM_ONLY
def __init__(self, backend, shots=1024, seed=None, max_credits=10,
basis_gates=None, coupling_map=None,
initial_layout=None, pass_manager=None, seed_transpiler=None,
backend_options=None, noise_model=None, timeout=None, wait=5,
circuit_caching=True, cache_file=None, skip_qobj_deepcopy=True,
skip_qobj_validation=True, measurement_error_mitigation_cls=None,
cals_matrix_refresh_period=30):
"""Constructor.
Args:
backend (BaseBackend): instance of selected backend
shots (int, optional): number of repetitions of each circuit, for sampling
seed (int, optional): random seed for simulators
max_credits (int, optional): maximum credits to use
basis_gates (list[str], optional): list of basis gate names supported by the
target. Default: ['u1','u2','u3','cx','id']
coupling_map (list[list]): coupling map (perhaps custom) to target in mapping
initial_layout (dict, optional): initial layout of qubits in mapping
pass_manager (PassManager, optional): pass manager to handle how to compile the circuits
seed_transpiler (int, optional): the random seed for circuit mapper
backend_options (dict, optional): all running options for backend, please refer to the provider.
noise_model (qiskit.provider.aer.noise.noise_model.NoiseModel, optional): noise model for simulator
timeout (float, optional): seconds to wait for job. If None, wait indefinitely.
wait (float, optional): seconds between queries to result
circuit_caching (bool, optional): USe CircuitCache when calling compile_and_run_circuits
cache_file(str, optional): filename into which to store the cache as a pickle file
skip_qobj_deepcopy (bool, optional): Reuses the same qobj object over and over to avoid deepcopying
skip_qobj_validation (bool, optional): Bypass Qobj validation to decrease submission time
measurement_error_mitigation_cls (callable, optional): the approach to mitigate measurement error,
CompleteMeasFitter or TensoredMeasFitter
cals_matrix_refresh_period (int): how long to refresh the calibration matrix in measurement mitigation,
unit in minutes
"""
self._backend = backend
# setup run config
run_config = RunConfig(shots=shots, max_credits=max_credits)
if seed:
run_config.seed = seed
if getattr(run_config, 'shots', None) is not None:
if self.is_statevector and run_config.shots != 1:
logger.info("statevector backend only works with shot=1, change "
"shots from {} to 1.".format(run_config.shots))
run_config.shots = 1
self._run_config = run_config
# setup backend config
basis_gates = basis_gates or backend.configuration().basis_gates
coupling_map = coupling_map or getattr(backend.configuration(),
'coupling_map', None)
self._backend_config = {
'basis_gates': basis_gates,
'coupling_map': coupling_map
}
# setup noise config
noise_config = None
if noise_model is not None:
if is_aer_provider(self._backend):
if not self.is_statevector:
noise_config = noise_model
else:
logger.info("The noise model can be only used with Aer qasm simulator. "
"Change it to None.")
else:
logger.info("The noise model can be only used with Qiskit Aer. "
"Please install it.")
self._noise_config = {} if noise_config is None else {'noise_model': noise_config}
# setup compile config
if initial_layout is not None and not isinstance(initial_layout, Layout):
initial_layout = Layout(initial_layout)
self._compile_config = {
'pass_manager': pass_manager,
'initial_layout': initial_layout,
'seed_transpiler': seed_transpiler
}
# setup job config
self._qjob_config = {'timeout': timeout} if self.is_local \
else {'timeout': timeout, 'wait': wait}
# setup backend options for run
self._backend_options = {}
if is_ibmq_provider(self._backend):
logger.info("backend_options can not used with the backends in IBMQ provider.")
else:
self._backend_options = {} if backend_options is None \
else {'backend_options': backend_options}
self._shared_circuits = False
self._circuit_summary = False
self._circuit_cache = CircuitCache(skip_qobj_deepcopy=skip_qobj_deepcopy,
cache_file=cache_file) if circuit_caching else None
self._skip_qobj_validation = skip_qobj_validation
self._measurement_error_mitigation_cls = None
if self.is_statevector:
if measurement_error_mitigation_cls is not None:
logger.info("Measurement error mitigation does not work with statevector simulation, disable it.")
else:
self._measurement_error_mitigation_cls = measurement_error_mitigation_cls
self._measurement_error_mitigation_fitter = None
self._measurement_error_mitigation_method = 'least_squares'
self._cals_matrix_refresh_period = cals_matrix_refresh_period
self._prev_timestamp = 0
if self._measurement_error_mitigation_cls is not None:
logger.info("The measurement error mitigation is enable. "
"It will automatically submit an additional job to help calibrate the result of other jobs. "
"The current approach will submit a job with 2^N circuits to build the calibration matrix, "
"where N is the number of measured qubits. "
"Furthermore, Aqua will re-use the calibration matrix for {} minutes "
"and re-build it after that.".format(self._cals_matrix_refresh_period))
logger.info(self)
def __str__(self):
"""Overload string.
Returns:
str: the info of the object.
"""
info = "\nQiskit Terra version: {}\n".format(terra_version)
info += "Backend: '{} ({})', with following setting:\n{}\n{}\n{}\n{}\n{}\n{}".format(
self.backend_name, self._backend.provider(), self._backend_config, self._compile_config,
self._run_config, self._qjob_config, self._backend_options, self._noise_config)
info += "\nMeasurement mitigation: {}".format(self._measurement_error_mitigation_cls)
return info
def execute(self, circuits, **kwargs):
"""
A wrapper to interface with quantum backend.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to execute
Returns:
Result: Result object
"""
qobjs = compile_circuits(circuits, self._backend, self._backend_config, self._compile_config, self._run_config,
show_circuit_summary=self._circuit_summary, circuit_cache=self._circuit_cache,
**kwargs)
if self._measurement_error_mitigation_cls is not None:
if self.maybe_refresh_cals_matrix():
logger.info("Building calibration matrix for measurement error mitigation.")
qubit_list = get_measured_qubits_from_qobj(qobjs)
self._measurement_error_mitigation_fitter = build_measurement_error_mitigation_fitter(qubit_list,
self._measurement_error_mitigation_cls,
self._backend,
self._backend_config,
self._compile_config,
self._run_config,
self._qjob_config,
self._backend_options,
self._noise_config)
result = run_qobjs(qobjs, self._backend, self._qjob_config, self._backend_options, self._noise_config,
self._skip_qobj_validation)
if self._measurement_error_mitigation_fitter is not None:
result = mitigate_measurement_error(result, self._measurement_error_mitigation_fitter,
self._measurement_error_mitigation_method)
if self._circuit_summary:
self._circuit_summary = False
return result
def set_config(self, **kwargs):
"""Set configurations for the quantum instance."""
for k, v in kwargs.items():
if k in QuantumInstance.RUN_CONFIG:
setattr(self._run_config, k, v)
elif k in QuantumInstance.QJOB_CONFIG:
self._qjob_config[k] = v
elif k in QuantumInstance.COMPILE_CONFIG:
self._compile_config[k] = v
elif k in QuantumInstance.BACKEND_CONFIG:
self._backend_config[k] = v
elif k in QuantumInstance.BACKEND_OPTIONS:
if is_ibmq_provider(self._backend):
logger.info("backend_options can not used with the backends in IBMQ provider.")
else:
if k in QuantumInstance.BACKEND_OPTIONS_QASM_ONLY and self.is_statevector:
logger.info("'{}' is only applicable for qasm simulator but "
"statevector simulator is used. Skip the setting.")
else:
if 'backend_options' not in self._backend_options:
self._backend_options['backend_options'] = {}
self._backend_options['backend_options'][k] = v
elif k in QuantumInstance.NOISE_CONFIG:
self._noise_config[k] = v
else:
raise ValueError("unknown setting for the key ({}).".format(k))
@property
def qjob_config(self):
"""Getter of qjob_config."""
return self._qjob_config
@property
def backend_config(self):
"""Getter of backend_config."""
return self._backend_config
@property
def compile_config(self):
"""Getter of compile_config."""
return self._compile_config
@property
def run_config(self):
"""Getter of run_config."""
return self._run_config
@property
def noise_config(self):
"""Getter of noise_config."""
return self._noise_config
@property
def backend_options(self):
"""Getter of backend_options."""
return self._backend_options
@property
def shared_circuits(self):
"""Getter of shared_circuits."""
return self._shared_circuits
@shared_circuits.setter
def shared_circuits(self, new_value):
self._shared_circuits = new_value
@property
def circuit_summary(self):
"""Getter of circuit summary."""
return self._circuit_summary
@circuit_summary.setter
def circuit_summary(self, new_value):
self._circuit_summary = new_value
@property
def backend(self):
"""Return BaseBackend backend object."""
return self._backend
@property
def backend_name(self):
"""Return backend name."""
return self._backend.name()
@property
def is_statevector(self):
"""Return True if backend is a statevector-type simulator."""
return is_statevector_backend(self._backend)
@property
def is_simulator(self):
"""Return True if backend is a simulator."""
return is_simulator_backend(self._backend)
@property
def is_local(self):
"""Return True if backend is a local backend."""
return is_local_backend(self._backend)
@property
def circuit_cache(self):
return self._circuit_cache
@property
def has_circuit_caching(self):
return self._circuit_cache is not None
@property
def skip_qobj_validation(self):
return self._skip_qobj_validation
@skip_qobj_validation.setter
def skip_qobj_validation(self, new_value):
self._skip_qobj_validation = new_value
def maybe_refresh_cals_matrix(self):
"""
Calculate the time difference from the query of last time.
Returns:
bool: whether or not refresh the cals_matrix
"""
ret = False
curr_timestamp = time.time()
difference = int(curr_timestamp - self._prev_timestamp) / 60.0
if difference > self._cals_matrix_refresh_period:
self._prev_timestamp = curr_timestamp
ret = True
return ret
@property
def cals_matrix(self):
cals_matrix = None
if self._measurement_error_mitigation_fitter is not None:
cals_matrix = self._measurement_error_mitigation_fitter.cal_matrix
return cals_matrix
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import numpy as np
from functools import reduce
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.quantum_info import Pauli
from qiskit.aqua import Operator
class QAOAVarForm:
"""Global X phases and parameterized problem hamiltonian."""
def __init__(self, cost_operator, p, initial_state=None, mixer_operator=None):
self._cost_operator = cost_operator
self._p = p
self._initial_state = initial_state
self.num_parameters = 2 * p
self.parameter_bounds = [(0, np.pi)] * p + [(0, 2 * np.pi)] * p
self.preferred_init_points = [0] * p * 2
# prepare the mixer operator
v = np.zeros(self._cost_operator.num_qubits)
ws = np.eye(self._cost_operator.num_qubits)
if mixer_operator is None:
self._mixer_operator = reduce(
lambda x, y: x + y,
[
Operator([[1, Pauli(v, ws[i, :])]])
for i in range(self._cost_operator.num_qubits)
]
)
else:
if not type(mixer_operator) == Operator:
raise TypeError('The mixer should be a qiskit.aqua.Operator '
+ 'object, found {} instead'.format(type(mixer_operator)))
self._mixer_operator = mixer_operator
def construct_circuit(self, angles):
if not len(angles) == self.num_parameters:
raise ValueError('Incorrect number of angles: expecting {}, but {} given.'.format(
self.num_parameters, len(angles)
))
circuit = QuantumCircuit()
if self._initial_state:
circuit += self._initial_state.construct_circuit('circuit')
if len(circuit.qregs) == 0:
q = QuantumRegister(self._cost_operator.num_qubits, name='q')
circuit.add_register(q)
elif len(circuit.qregs) == 1:
q = circuit.qregs[0]
else:
raise NotImplementedError
circuit.u2(0, np.pi, q)
for idx in range(self._p):
beta, gamma = angles[idx], angles[idx + self._p]
circuit += self._cost_operator.evolve(
evo_time=gamma, evo_mode='circuit', num_time_slices=1, quantum_registers=q
)
circuit += self._mixer_operator.evolve(
evo_time=beta, evo_mode='circuit', num_time_slices=1, quantum_registers=q
)
return circuit
@property
def setting(self):
ret = "Variational Form: {}\n".format(self.__class__.__name__)
params = ""
for key, value in self.__dict__.items():
if key != "_configuration" and key[0] == "_":
params += "-- {}: {}\n".format(key[1:], value)
ret += "{}".format(params)
return ret
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import logging
import math
import numpy as np
from sklearn.utils import shuffle
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
from qiskit.aqua import Pluggable, PluggableType, get_pluggable_class, AquaError
from qiskit.aqua.components.feature_maps import FeatureMap
from qiskit.aqua.utils import get_feature_dimension
from qiskit.aqua.utils import map_label_to_class_name
from qiskit.aqua.utils import split_dataset_to_data_and_labels
from qiskit.aqua.utils import find_regs_by_name
from qiskit.aqua.algorithms.adaptive.vq_algorithm import VQAlgorithm
logger = logging.getLogger(__name__)
def assign_label(measured_key, num_classes):
"""
Classes = 2:
- If odd number of qubits we use majority vote
- If even number of qubits we use parity
Classes = 3
- We use part-parity
{ex. for 2 qubits: [00], [01,10], [11] would be the three labels}
Args:
measured_key (str): measured key
num_classes (int): number of classes
"""
measured_key = np.asarray([int(k) for k in list(measured_key)])
num_qubits = len(measured_key)
if num_classes == 2:
if num_qubits % 2 != 0:
total = np.sum(measured_key)
return 1 if total > num_qubits / 2 else 0
else:
hamming_weight = np.sum(measured_key)
is_odd_parity = hamming_weight % 2
return is_odd_parity
elif num_classes == 3:
first_half = int(np.floor(num_qubits / 2))
modulo = num_qubits % 2
# First half of key
hamming_weight_1 = np.sum(measured_key[0:first_half + modulo])
# Second half of key
hamming_weight_2 = np.sum(measured_key[first_half + modulo:])
is_odd_parity_1 = hamming_weight_1 % 2
is_odd_parity_2 = hamming_weight_2 % 2
return is_odd_parity_1 + is_odd_parity_2
else:
total_size = 2**num_qubits
class_step = np.floor(total_size / num_classes)
decimal_value = measured_key.dot(1 << np.arange(measured_key.shape[-1] - 1, -1, -1))
key_order = int(decimal_value / class_step)
return key_order if key_order < num_classes else num_classes - 1
def cost_estimate(probs, gt_labels, shots=None):
"""Calculate cross entropy
# shots is kept since it may be needed in future.
Args:
shots (int): the number of shots used in quantum computing
probs (numpy.ndarray): NxK array, N is the number of data and K is the number of class
gt_labels (numpy.ndarray): Nx1 array
Returns:
float: cross entropy loss between estimated probs and gt_labels
"""
mylabels = np.zeros(probs.shape)
for i in range(gt_labels.shape[0]):
whichindex = gt_labels[i]
mylabels[i][whichindex] = 1
def cross_entropy(predictions, targets, epsilon=1e-12):
predictions = np.clip(predictions, epsilon, 1. - epsilon)
N = predictions.shape[0]
tmp = np.sum(targets*np.log(predictions), axis=1)
ce = -np.sum(tmp)/N
return ce
x = cross_entropy(probs, mylabels)
return x
def cost_estimate_sigmoid(shots, probs, gt_labels):
"""Calculate sigmoid cross entropy
Args:
shots (int): the number of shots used in quantum computing
probs (numpy.ndarray): NxK array, N is the number of data and K is the number of class
gt_labels (numpy.ndarray): Nx1 array
Returns:
float: sigmoid cross entropy loss between estimated probs and gt_labels
"""
#Error in the order of parameters corrected below - 19 Dec 2018
#x = cost_estimate(shots, probs, gt_labels)
x = cost_estimate(probs, gt_labels, shots)
loss = (1.) / (1. + np.exp(-x))
return loss
def return_probabilities(counts, num_classes):
"""Return the probabilities of given measured counts
Args:
counts ([dict]): N data and each with a dict recording the counts
num_classes (int): number of classes
Returns:
numpy.ndarray: NxK array
"""
probs = np.zeros(((len(counts), num_classes)))
for idx in range(len(counts)):
count = counts[idx]
shots = sum(count.values())
for k, v in count.items():
label = assign_label(k, num_classes)
probs[idx][label] += v / shots
return probs
class VQC(VQAlgorithm):
CONFIGURATION = {
'name': 'VQC',
'description': 'Variational Quantum Classifier',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'vqc_schema',
'type': 'object',
'properties': {
'override_SPSA_params': {
'type': 'boolean',
'default': True
},
'max_evals_grouped': {
'type': 'integer',
'default': 1
},
'minibatch_size': {
'type': 'integer',
'default': -1
}
},
'additionalProperties': False
},
'problems': ['classification'],
'depends': [
{
'pluggable_type': 'optimizer',
'default': {
'name': 'SPSA'
},
},
{
'pluggable_type': 'feature_map',
'default': {
'name': 'SecondOrderExpansion',
'depth': 2
},
},
{
'pluggable_type': 'variational_form',
'default': {
'name': 'RYRZ',
'depth': 3
},
},
],
}
def __init__(
self,
optimizer=None,
feature_map=None,
var_form=None,
training_dataset=None,
test_dataset=None,
datapoints=None,
max_evals_grouped=1,
minibatch_size=-1,
callback=None
):
"""Initialize the object
Args:
optimizer (Optimizer): The classical optimizer to use.
feature_map (FeatureMap): The FeatureMap instance to use.
var_form (VariationalForm): The variational form instance.
training_dataset (dict): The training dataset, in the format: {'A': np.ndarray, 'B': np.ndarray, ...}.
test_dataset (dict): The test dataset, in same format as `training_dataset`.
datapoints (np.ndarray): NxD array, N is the number of data and D is data dimension.
max_evals_grouped (int): The maximum number of evaluations to perform simultaneously.
minibatch_size (int): The size of a mini-batch.
callback (Callable): a callback that can access the intermediate data during the optimization.
Internally, four arguments are provided as follows the index of data batch, the index of evaluation,
parameters of variational form, evaluated value.
Notes:
We use `label` to denotes numeric results and `class` the class names (str).
"""
self.validate(locals())
super().__init__(
var_form=var_form,
optimizer=optimizer,
cost_fn=self._cost_function_wrapper
)
self._optimizer.set_max_evals_grouped(max_evals_grouped)
self._callback = callback
if feature_map is None:
raise AquaError('Missing feature map.')
if training_dataset is None:
raise AquaError('Missing training dataset.')
self._training_dataset, self._class_to_label = split_dataset_to_data_and_labels(
training_dataset)
self._label_to_class = {label: class_name for class_name, label
in self._class_to_label.items()}
self._num_classes = len(list(self._class_to_label.keys()))
if test_dataset is not None:
self._test_dataset = split_dataset_to_data_and_labels(test_dataset,
self._class_to_label)
else:
self._test_dataset = test_dataset
if datapoints is not None and not isinstance(datapoints, np.ndarray):
datapoints = np.asarray(datapoints)
self._datapoints = datapoints
self._minibatch_size = minibatch_size
self._eval_count = 0
self._ret = {}
self._feature_map = feature_map
self._num_qubits = feature_map.num_qubits
@classmethod
def init_params(cls, params, algo_input):
algo_params = params.get(Pluggable.SECTION_KEY_ALGORITHM)
override_spsa_params = algo_params.get('override_SPSA_params')
max_evals_grouped = algo_params.get('max_evals_grouped')
minibatch_size = algo_params.get('minibatch_size')
# Set up optimizer
opt_params = params.get(Pluggable.SECTION_KEY_OPTIMIZER)
# If SPSA then override SPSA params as reqd to our predetermined values
if opt_params['name'] == 'SPSA' and override_spsa_params:
opt_params['c0'] = 4.0
opt_params['c1'] = 0.1
opt_params['c2'] = 0.602
opt_params['c3'] = 0.101
opt_params['c4'] = 0.0
opt_params['skip_calibration'] = True
optimizer = get_pluggable_class(PluggableType.OPTIMIZER,
opt_params['name']).init_params(params)
# Set up feature map
fea_map_params = params.get(Pluggable.SECTION_KEY_FEATURE_MAP)
feature_dimension = get_feature_dimension(algo_input.training_dataset)
fea_map_params['feature_dimension'] = feature_dimension
feature_map = get_pluggable_class(PluggableType.FEATURE_MAP,
fea_map_params['name']).init_params(params)
# Set up variational form, we need to add computed num qubits
# Pass all parameters so that Variational Form can create its dependents
var_form_params = params.get(Pluggable.SECTION_KEY_VAR_FORM)
var_form_params['num_qubits'] = feature_map.num_qubits
var_form = get_pluggable_class(PluggableType.VARIATIONAL_FORM,
var_form_params['name']).init_params(params)
return cls(optimizer, feature_map, var_form, algo_input.training_dataset,
algo_input.test_dataset, algo_input.datapoints, max_evals_grouped,
minibatch_size)
def construct_circuit(self, x, theta, measurement=False):
"""
Construct circuit based on data and parameters in variational form.
Args:
x (numpy.ndarray): 1-D array with D dimension
theta ([numpy.ndarray]): list of 1-D array, parameters sets for variational form
measurement (bool): flag to add measurement
Returns:
QuantumCircuit: the circuit
"""
qr = QuantumRegister(self._num_qubits, name='q')
cr = ClassicalRegister(self._num_qubits, name='c')
qc = QuantumCircuit(qr, cr)
qc += self._feature_map.construct_circuit(x, qr)
qc += self._var_form.construct_circuit(theta, qr)
if measurement:
qc.barrier(qr)
qc.measure(qr, cr)
return qc
def _get_prediction(self, data, theta):
"""
Make prediction on data based on each theta.
Args:
data (numpy.ndarray): 2-D array, NxD, N data points, each with D dimension
theta ([numpy.ndarray]): list of 1-D array, parameters sets for variational form
Returns:
numpy.ndarray or [numpy.ndarray]: list of NxK array
numpy.ndarray or [numpy.ndarray]: list of Nx1 array
"""
# if self._quantum_instance.is_statevector:
# raise ValueError('Selected backend "{}" is not supported.'.format(
# self._quantum_instance.backend_name))
circuits = {}
circuit_id = 0
num_theta_sets = len(theta) // self._var_form.num_parameters
theta_sets = np.split(theta, num_theta_sets)
for theta in theta_sets:
for datum in data:
if self._quantum_instance.is_statevector:
circuit = self.construct_circuit(datum, theta, measurement=False)
else:
circuit = self.construct_circuit(datum, theta, measurement=True)
circuits[circuit_id] = circuit
circuit_id += 1
results = self._quantum_instance.execute(list(circuits.values()))
circuit_id = 0
predicted_probs = []
predicted_labels = []
for _ in theta_sets:
counts = []
for _ in data:
if self._quantum_instance.is_statevector:
temp = results.get_statevector(circuits[circuit_id])
outcome_vector = (temp * temp.conj()).real
# convert outcome_vector to outcome_dict, where key is a basis state and value is the count.
# Note: the count can be scaled linearly, i.e., it does not have to be an integer.
outcome_dict = {}
bitstr_size = int(math.log2(len(outcome_vector)))
for i in range(len(outcome_vector)):
bitstr_i = format(i, '0' + str(bitstr_size) + 'b')
outcome_dict[bitstr_i] = outcome_vector[i]
else:
outcome_dict = results.get_counts(circuits[circuit_id])
counts.append(outcome_dict)
circuit_id += 1
probs = return_probabilities(counts, self._num_classes)
predicted_probs.append(probs)
predicted_labels.append(np.argmax(probs, axis=1))
if len(predicted_probs) == 1:
predicted_probs = predicted_probs[0]
if len(predicted_labels) == 1:
predicted_labels = predicted_labels[0]
return predicted_probs, predicted_labels
# Breaks data into minibatches. Labels are optional, but will be broken into batches if included.
def batch_data(self, data, labels=None, minibatch_size=-1):
label_batches = None
if 0 < minibatch_size < len(data):
batch_size = min(minibatch_size, len(data))
if labels is not None:
shuffled_samples, shuffled_labels = shuffle(data, labels, random_state=self.random)
label_batches = np.array_split(shuffled_labels, batch_size)
else:
shuffled_samples = shuffle(data, random_state=self.random)
batches = np.array_split(shuffled_samples, batch_size)
else:
batches = np.asarray([data])
label_batches = np.asarray([labels])
return batches, label_batches
def is_gradient_really_supported(self):
return self.optimizer.is_gradient_supported and not self.optimizer.is_gradient_ignored
def train(self, data, labels, quantum_instance=None, minibatch_size=-1):
"""Train the models, and save results.
Args:
data (numpy.ndarray): NxD array, N is number of data and D is dimension
labels (numpy.ndarray): Nx1 array, N is number of data
quantum_instance (QuantumInstance): quantum backend with all setting
minibatch_size (int): the size of each minibatched accuracy evalutation
"""
self._quantum_instance = self._quantum_instance if quantum_instance is None else quantum_instance
minibatch_size = minibatch_size if minibatch_size > 0 else self._minibatch_size
self._batches, self._label_batches = self.batch_data(data, labels, minibatch_size)
self._batch_index = 0
if self.initial_point is None:
self.initial_point = self.random.randn(self._var_form.num_parameters)
self._eval_count = 0
grad_fn = None
if minibatch_size > 0 and self.is_gradient_really_supported(): # we need some wrapper
grad_fn = self._gradient_function_wrapper
self._ret = self.find_minimum(
initial_point=self.initial_point,
var_form=self.var_form,
cost_fn=self._cost_function_wrapper,
optimizer=self.optimizer,
gradient_fn = grad_fn # func for computing gradient
)
if self._ret['num_optimizer_evals'] is not None and self._eval_count >= self._ret['num_optimizer_evals']:
self._eval_count = self._ret['num_optimizer_evals']
self._eval_time = self._ret['eval_time']
logger.info('Optimization complete in {} seconds.\nFound opt_params {} in {} evals'.format(
self._eval_time, self._ret['opt_params'], self._eval_count))
self._ret['eval_count'] = self._eval_count
del self._batches
del self._label_batches
del self._batch_index
self._ret['training_loss'] = self._ret['min_val']
# temporary fix: this code should be unified with the gradient api in optimizer.py
def _gradient_function_wrapper(self, theta):
"""Compute and return the gradient at the point theta.
Args:
theta (numpy.ndarray): 1-d array
Returns:
numpy.ndarray: 1-d array with the same shape as theta. The gradient computed
"""
epsilon = 1e-8
f_orig = self._cost_function_wrapper(theta)
grad = np.zeros((len(theta),), float)
for k in range(len(theta)):
theta[k] += epsilon
f_new = self._cost_function_wrapper(theta)
grad[k] = (f_new - f_orig) / epsilon
theta[k] -= epsilon # recover to the center state
if self.is_gradient_really_supported():
self._batch_index += 1 # increment the batch after gradient callback
return grad
def _cost_function_wrapper(self, theta):
batch_index = self._batch_index % len(self._batches)
predicted_probs, predicted_labels = self._get_prediction(self._batches[batch_index], theta)
total_cost = []
if not isinstance(predicted_probs, list):
predicted_probs = [predicted_probs]
for i in range(len(predicted_probs)):
curr_cost = cost_estimate(predicted_probs[i], self._label_batches[batch_index])
total_cost.append(curr_cost)
if self._callback is not None:
self._callback(
self._eval_count,
theta[i * self._var_form.num_parameters:(i + 1) * self._var_form.num_parameters],
curr_cost,
self._batch_index
)
self._eval_count += 1
if not self.is_gradient_really_supported():
self._batch_index += 1 # increment the batch after eval callback
logger.debug('Intermediate batch cost: {}'.format(sum(total_cost)))
return total_cost if len(total_cost) > 1 else total_cost[0]
def test(self, data, labels, quantum_instance=None, minibatch_size=-1, params=None):
"""Predict the labels for the data, and test against with ground truth labels.
Args:
data (numpy.ndarray): NxD array, N is number of data and D is data dimension
labels (numpy.ndarray): Nx1 array, N is number of data
quantum_instance (QuantumInstance): quantum backend with all setting
minibatch_size (int): the size of each minibatched accuracy evalutation
params (list): list of parameters to populate in the variational form
Returns:
float: classification accuracy
"""
# minibatch size defaults to setting in instance variable if not set
minibatch_size = minibatch_size if minibatch_size > 0 else self._minibatch_size
batches, label_batches = self.batch_data(data, labels, minibatch_size)
self.batch_num = 0
if params is None:
params = self.optimal_params
total_cost = 0
total_correct = 0
total_samples = 0
self._quantum_instance = self._quantum_instance if quantum_instance is None else quantum_instance
for batch, label_batch in zip(batches, label_batches):
predicted_probs, predicted_labels = self._get_prediction(batch, params)
total_cost += cost_estimate(predicted_probs, label_batch)
total_correct += np.sum((np.argmax(predicted_probs, axis=1) == label_batch))
total_samples += label_batch.shape[0]
int_accuracy = np.sum((np.argmax(predicted_probs, axis=1) == label_batch)) / label_batch.shape[0]
logger.debug('Intermediate batch accuracy: {:.2f}%'.format(int_accuracy * 100.0))
total_accuracy = total_correct / total_samples
logger.info('Accuracy is {:.2f}%'.format(total_accuracy * 100.0))
self._ret['testing_accuracy'] = total_accuracy
self._ret['test_success_ratio'] = total_accuracy
self._ret['testing_loss'] = total_cost / len(batches)
return total_accuracy
def predict(self, data, quantum_instance=None, minibatch_size=-1, params=None):
"""Predict the labels for the data.
Args:
data (numpy.ndarray): NxD array, N is number of data, D is data dimension
quantum_instance (QuantumInstance): quantum backend with all setting
minibatch_size (int): the size of each minibatched accuracy evalutation
params (list): list of parameters to populate in the variational form
Returns:
list: for each data point, generates the predicted probability for each class
list: for each data point, generates the predicted label (that with the highest prob)
"""
# minibatch size defaults to setting in instance variable if not set
minibatch_size = minibatch_size if minibatch_size > 0 else self._minibatch_size
batches, _ = self.batch_data(data, None, minibatch_size)
if params is None:
params = self.optimal_params
predicted_probs = None
predicted_labels = None
self._quantum_instance = self._quantum_instance if quantum_instance is None else quantum_instance
for i, batch in enumerate(batches):
if len(batches) > 0:
logger.debug('Predicting batch {}'.format(i))
batch_probs, batch_labels = self._get_prediction(batch, params)
if not predicted_probs and not predicted_labels:
predicted_probs = batch_probs
predicted_labels = batch_labels
else:
np.concatenate((predicted_probs, batch_probs))
np.concatenate((predicted_labels, batch_labels))
self._ret['predicted_probs'] = predicted_probs
self._ret['predicted_labels'] = predicted_labels
return predicted_probs, predicted_labels
def _run(self):
self.train(self._training_dataset[0], self._training_dataset[1])
if self._test_dataset is not None:
self.test(self._test_dataset[0], self._test_dataset[1])
if self._datapoints is not None:
predicted_probs, predicted_labels = self.predict(self._datapoints)
self._ret['predicted_classes'] = map_label_to_class_name(predicted_labels,
self._label_to_class)
return self._ret
def get_optimal_cost(self):
if 'opt_params' not in self._ret:
raise AquaError("Cannot return optimal cost before running the algorithm to find optimal params.")
return self._ret['min_val']
def get_optimal_circuit(self):
if 'opt_params' not in self._ret:
raise AquaError("Cannot find optimal circuit before running the algorithm to find optimal params.")
return self._var_form.construct_circuit(self._ret['opt_params'])
def get_optimal_vector(self):
if 'opt_params' not in self._ret:
raise AquaError("Cannot find optimal vector before running the algorithm to find optimal params.")
qc = self.get_optimal_circuit()
if self._quantum_instance.is_statevector:
ret = self._quantum_instance.execute(qc)
self._ret['min_vector'] = ret.get_statevector(qc, decimals=16)
else:
c = ClassicalRegister(qc.width(), name='c')
q = find_regs_by_name(qc, 'q')
qc.add_register(c)
qc.barrier(q)
qc.measure(q, c)
ret = self._quantum_instance.execute(qc)
self._ret['min_vector'] = ret.get_counts(qc)
return self._ret['min_vector']
@property
def optimal_params(self):
if 'opt_params' not in self._ret:
raise AquaError("Cannot find optimal params before running the algorithm.")
return self._ret['opt_params']
@property
def ret(self):
return self._ret
@ret.setter
def ret(self, new_value):
self._ret = new_value
@property
def label_to_class(self):
return self._label_to_class
@property
def class_to_label(self):
return self._class_to_label
def load_model(self, file_path):
model_npz = np.load(file_path)
self._ret['opt_params'] = model_npz['opt_params']
def save_model(self, file_path):
model = {'opt_params': self._ret['opt_params']}
np.savez(file_path, **model)
@property
def test_dataset(self):
return self._test_dataset
@property
def training_dataset(self):
return self._training_dataset
@property
def datapoints(self):
return self._datapoints
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
The Variational Quantum Eigensolver algorithm.
See https://arxiv.org/abs/1304.3061
"""
import logging
import functools
import numpy as np
from qiskit import ClassicalRegister, QuantumCircuit
from qiskit.aqua.algorithms.adaptive.vq_algorithm import VQAlgorithm
from qiskit.aqua import AquaError, Pluggable, PluggableType, get_pluggable_class
from qiskit.aqua.utils.backend_utils import is_aer_statevector_backend
from qiskit.aqua.utils import find_regs_by_name
logger = logging.getLogger(__name__)
class VQE(VQAlgorithm):
"""
The Variational Quantum Eigensolver algorithm.
See https://arxiv.org/abs/1304.3061
"""
CONFIGURATION = {
'name': 'VQE',
'description': 'VQE Algorithm',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'vqe_schema',
'type': 'object',
'properties': {
'operator_mode': {
'type': 'string',
'default': 'matrix',
'oneOf': [
{'enum': ['matrix', 'paulis', 'grouped_paulis']}
]
},
'initial_point': {
'type': ['array', 'null'],
"items": {
"type": "number"
},
'default': None
},
'max_evals_grouped': {
'type': 'integer',
'default': 1
}
},
'additionalProperties': False
},
'problems': ['energy', 'ising'],
'depends': [
{'pluggable_type': 'optimizer',
'default': {
'name': 'L_BFGS_B'
}
},
{'pluggable_type': 'variational_form',
'default': {
'name': 'RYRZ'
}
},
],
}
def __init__(self, operator, var_form, optimizer, operator_mode='matrix',
initial_point=None, max_evals_grouped=1, aux_operators=None, callback=None):
"""Constructor.
Args:
operator (Operator): Qubit operator
operator_mode (str): operator mode, used for eval of operator
var_form (VariationalForm): parametrized variational form.
optimizer (Optimizer): the classical optimization algorithm.
initial_point (numpy.ndarray): optimizer initial point.
max_evals_grouped (int): max number of evaluations performed simultaneously
aux_operators (list of Operator): Auxiliary operators to be evaluated at each eigenvalue
callback (Callable): a callback that can access the intermediate data during the optimization.
Internally, four arguments are provided as follows
the index of evaluation, parameters of variational form,
evaluated mean, evaluated standard devation.
"""
self.validate(locals())
super().__init__(var_form=var_form,
optimizer=optimizer,
cost_fn=self._energy_evaluation,
initial_point=initial_point)
self._optimizer.set_max_evals_grouped(max_evals_grouped)
self._callback = callback
if initial_point is None:
self._initial_point = var_form.preferred_init_points
self._operator = operator
self._operator_mode = operator_mode
self._eval_count = 0
if aux_operators is None:
self._aux_operators = []
else:
self._aux_operators = [aux_operators] if not isinstance(aux_operators, list) else aux_operators
logger.info(self.print_settings())
@classmethod
def init_params(cls, params, algo_input):
"""
Initialize via parameters dictionary and algorithm input instance.
Args:
params (dict): parameters dictionary
algo_input (EnergyInput): EnergyInput instance
Returns:
VQE: vqe object
"""
if algo_input is None:
raise AquaError("EnergyInput instance is required.")
operator = algo_input.qubit_op
vqe_params = params.get(Pluggable.SECTION_KEY_ALGORITHM)
operator_mode = vqe_params.get('operator_mode')
initial_point = vqe_params.get('initial_point')
max_evals_grouped = vqe_params.get('max_evals_grouped')
# Set up variational form, we need to add computed num qubits
# Pass all parameters so that Variational Form can create its dependents
var_form_params = params.get(Pluggable.SECTION_KEY_VAR_FORM)
var_form_params['num_qubits'] = operator.num_qubits
var_form = get_pluggable_class(PluggableType.VARIATIONAL_FORM,
var_form_params['name']).init_params(params)
# Set up optimizer
opt_params = params.get(Pluggable.SECTION_KEY_OPTIMIZER)
optimizer = get_pluggable_class(PluggableType.OPTIMIZER,
opt_params['name']).init_params(params)
return cls(operator, var_form, optimizer, operator_mode=operator_mode,
initial_point=initial_point, max_evals_grouped=max_evals_grouped,
aux_operators=algo_input.aux_ops)
@property
def setting(self):
"""Prepare the setting of VQE as a string."""
ret = "Algorithm: {}\n".format(self._configuration['name'])
params = ""
for key, value in self.__dict__.items():
if key != "_configuration" and key[0] == "_":
if "initial_point" in key and value is None:
params += "-- {}: {}\n".format(key[1:], "Random seed")
else:
params += "-- {}: {}\n".format(key[1:], value)
ret += "{}".format(params)
return ret
def print_settings(self):
"""
Preparing the setting of VQE into a string.
Returns:
str: the formatted setting of VQE
"""
ret = "\n"
ret += "==================== Setting of {} ============================\n".format(self.configuration['name'])
ret += "{}".format(self.setting)
ret += "===============================================================\n"
ret += "{}".format(self._var_form.setting)
ret += "===============================================================\n"
ret += "{}".format(self._optimizer.setting)
ret += "===============================================================\n"
return ret
def construct_circuit(self, parameter, backend=None, use_simulator_operator_mode=False):
"""Generate the circuits.
Args:
parameters (numpy.ndarray): parameters for variational form.
backend (qiskit.BaseBackend): backend object.
use_simulator_operator_mode (bool): is backend from AerProvider, if True and mode is paulis,
single circuit is generated.
Returns:
[QuantumCircuit]: the generated circuits with Hamiltonian.
"""
input_circuit = self._var_form.construct_circuit(parameter)
if backend is None:
warning_msg = "Circuits used in VQE depends on the backend type, "
from qiskit import BasicAer
if self._operator_mode == 'matrix':
temp_backend_name = 'statevector_simulator'
else:
temp_backend_name = 'qasm_simulator'
backend = BasicAer.get_backend(temp_backend_name)
warning_msg += "since operator_mode is '{}', '{}' backend is used.".format(
self._operator_mode, temp_backend_name)
logger.warning(warning_msg)
circuit = self._operator.construct_evaluation_circuit(self._operator_mode,
input_circuit, backend, use_simulator_operator_mode)
return circuit
def _eval_aux_ops(self, threshold=1e-12, params=None):
if params is None:
params = self.optimal_params
wavefn_circuit = self._var_form.construct_circuit(params)
circuits = []
values = []
params = []
for operator in self._aux_operators:
if not operator.is_empty():
temp_circuit = QuantumCircuit() + wavefn_circuit
circuit = operator.construct_evaluation_circuit(self._operator_mode, temp_circuit,
self._quantum_instance.backend,
self._use_simulator_operator_mode)
params.append(operator.aer_paulis)
else:
circuit = None
circuits.append(circuit)
if len(circuits) > 0:
to_be_simulated_circuits = functools.reduce(lambda x, y: x + y, [c for c in circuits if c is not None])
if self._use_simulator_operator_mode:
extra_args = {'expectation': {
'params': params,
'num_qubits': self._operator.num_qubits}
}
else:
extra_args = {}
result = self._quantum_instance.execute(to_be_simulated_circuits, **extra_args)
for operator, circuit in zip(self._aux_operators, circuits):
if circuit is None:
mean, std = 0.0, 0.0
else:
mean, std = operator.evaluate_with_result(self._operator_mode,
circuit, self._quantum_instance.backend,
result, self._use_simulator_operator_mode)
mean = mean.real if abs(mean.real) > threshold else 0.0
std = std.real if abs(std.real) > threshold else 0.0
values.append((mean, std))
if len(values) > 0:
aux_op_vals = np.empty([1, len(self._aux_operators), 2])
aux_op_vals[0, :] = np.asarray(values)
self._ret['aux_ops'] = aux_op_vals
def _run(self):
"""
Run the algorithm to compute the minimum eigenvalue.
Returns:
Dictionary of results
"""
if not self._quantum_instance.is_statevector and self._operator_mode == 'matrix':
logger.warning('Qasm simulation does not work on {} mode, changing '
'the operator_mode to "paulis"'.format(self._operator_mode))
self._operator_mode = 'paulis'
self._use_simulator_operator_mode = \
is_aer_statevector_backend(self._quantum_instance.backend) \
and self._operator_mode != 'matrix'
self._quantum_instance.circuit_summary = True
self._eval_count = 0
self._ret = self.find_minimum(initial_point=self.initial_point,
var_form=self.var_form,
cost_fn=self._energy_evaluation,
optimizer=self.optimizer)
if self._ret['num_optimizer_evals'] is not None and self._eval_count >= self._ret['num_optimizer_evals']:
self._eval_count = self._ret['num_optimizer_evals']
self._eval_time = self._ret['eval_time']
logger.info('Optimization complete in {} seconds.\nFound opt_params {} in {} evals'.format(
self._eval_time, self._ret['opt_params'], self._eval_count))
self._ret['eval_count'] = self._eval_count
self._ret['energy'] = self.get_optimal_cost()
self._ret['eigvals'] = np.asarray([self.get_optimal_cost()])
self._ret['eigvecs'] = np.asarray([self.get_optimal_vector()])
self._eval_aux_ops()
return self._ret
# This is the objective function to be passed to the optimizer that is uses for evaluation
def _energy_evaluation(self, parameters):
"""
Evaluate energy at given parameters for the variational form.
Args:
parameters (numpy.ndarray): parameters for variational form.
Returns:
float or list of float: energy of the hamiltonian of each parameter.
"""
num_parameter_sets = len(parameters) // self._var_form.num_parameters
circuits = []
parameter_sets = np.split(parameters, num_parameter_sets)
mean_energy = []
std_energy = []
for idx in range(len(parameter_sets)):
parameter = parameter_sets[idx]
circuit = self.construct_circuit(parameter, self._quantum_instance.backend, self._use_simulator_operator_mode)
circuits.append(circuit)
to_be_simulated_circuits = functools.reduce(lambda x, y: x + y, circuits)
if self._use_simulator_operator_mode:
extra_args = {'expectation': {
'params': [self._operator.aer_paulis],
'num_qubits': self._operator.num_qubits}
}
else:
extra_args = {}
result = self._quantum_instance.execute(to_be_simulated_circuits, **extra_args)
for idx in range(len(parameter_sets)):
mean, std = self._operator.evaluate_with_result(
self._operator_mode, circuits[idx], self._quantum_instance.backend, result, self._use_simulator_operator_mode)
mean_energy.append(np.real(mean))
std_energy.append(np.real(std))
self._eval_count += 1
if self._callback is not None:
self._callback(self._eval_count, parameter_sets[idx], np.real(mean), np.real(std))
logger.info('Energy evaluation {} returned {}'.format(self._eval_count, np.real(mean)))
return mean_energy if len(mean_energy) > 1 else mean_energy[0]
def get_optimal_cost(self):
if 'opt_params' not in self._ret:
raise AquaError("Cannot return optimal cost before running the algorithm to find optimal params.")
return self._ret['min_val']
def get_optimal_circuit(self):
if 'opt_params' not in self._ret:
raise AquaError("Cannot find optimal circuit before running the algorithm to find optimal params.")
return self._var_form.construct_circuit(self._ret['opt_params'])
def get_optimal_vector(self):
if 'opt_params' not in self._ret:
raise AquaError("Cannot find optimal vector before running the algorithm to find optimal params.")
qc = self.get_optimal_circuit()
if self._quantum_instance.is_statevector:
ret = self._quantum_instance.execute(qc)
self._ret['min_vector'] = ret.get_statevector(qc, decimals=16)
else:
c = ClassicalRegister(qc.width(), name='c')
q = find_regs_by_name(qc, 'q')
qc.add_register(c)
qc.barrier(q)
qc.measure(q, c)
ret = self._quantum_instance.execute(qc)
self._ret['min_vector'] = ret.get_counts(qc)
return self._ret['min_vector']
@property
def optimal_params(self):
if 'opt_params' not in self._ret:
raise AquaError("Cannot find optimal params before running the algorithm.")
return self._ret['opt_params']
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
The Quantum Dynamics algorithm.
"""
import logging
from qiskit import QuantumRegister
from qiskit.aqua.algorithms import QuantumAlgorithm
from qiskit.aqua import AquaError, Pluggable, PluggableType, get_pluggable_class
logger = logging.getLogger(__name__)
class EOH(QuantumAlgorithm):
"""
The Quantum EOH (Evolution of Hamiltonian) algorithm.
"""
PROP_OPERATOR_MODE = 'operator_mode'
PROP_EVO_TIME = 'evo_time'
PROP_NUM_TIME_SLICES = 'num_time_slices'
PROP_EXPANSION_MODE = 'expansion_mode'
PROP_EXPANSION_ORDER = 'expansion_order'
CONFIGURATION = {
'name': 'EOH',
'description': 'Evolution of Hamiltonian for Quantum Systems',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'EOH_schema',
'type': 'object',
'properties': {
PROP_OPERATOR_MODE: {
'type': 'string',
'default': 'paulis',
'oneOf': [
{'enum': [
'paulis',
'grouped_paulis',
'matrix'
]}
]
},
PROP_EVO_TIME: {
'type': 'number',
'default': 1,
'minimum': 0
},
PROP_NUM_TIME_SLICES: {
'type': 'integer',
'default': 1,
'minimum': 0
},
PROP_EXPANSION_MODE: {
'type': 'string',
'default': 'trotter',
'oneOf': [
{'enum': [
'trotter',
'suzuki'
]}
]
},
PROP_EXPANSION_ORDER: {
'type': 'integer',
'default': 1,
'minimum': 1
}
},
'additionalProperties': False
},
'problems': ['eoh'],
'depends': [
{'pluggable_type': 'initial_state',
'default': {
'name': 'ZERO'
}
},
],
}
def __init__(self, operator, initial_state, evo_operator, operator_mode='paulis', evo_time=1, num_time_slices=1,
expansion_mode='trotter', expansion_order=1):
self.validate(locals())
super().__init__()
self._operator = operator
self._operator_mode = operator_mode
self._initial_state = initial_state
self._evo_operator = evo_operator
self._evo_time = evo_time
self._num_time_slices = num_time_slices
self._expansion_mode = expansion_mode
self._expansion_order = expansion_order
self._ret = {}
@classmethod
def init_params(cls, params, algo_input):
"""
Initialize via parameters dictionary and algorithm input instance
Args:
params: parameters dictionary
algo_input: EnergyInput instance
"""
if algo_input is None:
raise AquaError("EnergyInput instance is required.")
# For getting the extra operator, caller has to do something like: algo_input.add_aux_op(evo_op)
operator = algo_input.qubit_op
aux_ops = algo_input.aux_ops
if aux_ops is None or len(aux_ops) != 1:
raise AquaError("EnergyInput, a single aux op is required for evaluation.")
evo_operator = aux_ops[0]
if evo_operator is None:
raise AquaError("EnergyInput, invalid aux op.")
dynamics_params = params.get(Pluggable.SECTION_KEY_ALGORITHM)
operator_mode = dynamics_params.get(EOH.PROP_OPERATOR_MODE)
evo_time = dynamics_params.get(EOH.PROP_EVO_TIME)
num_time_slices = dynamics_params.get(EOH.PROP_NUM_TIME_SLICES)
expansion_mode = dynamics_params.get(EOH.PROP_EXPANSION_MODE)
expansion_order = dynamics_params.get(EOH.PROP_EXPANSION_ORDER)
# Set up initial state, we need to add computed num qubits to params
initial_state_params = params.get(Pluggable.SECTION_KEY_INITIAL_STATE)
initial_state_params['num_qubits'] = operator.num_qubits
initial_state = get_pluggable_class(PluggableType.INITIAL_STATE,
initial_state_params['name']).init_params(params)
return cls(operator, initial_state, evo_operator, operator_mode, evo_time, num_time_slices,
expansion_mode=expansion_mode,
expansion_order=expansion_order)
def construct_circuit(self):
"""
Construct the circuit.
Returns:
QuantumCircuit: the circuit.
"""
quantum_registers = QuantumRegister(self._operator.num_qubits, name='q')
qc = self._initial_state.construct_circuit('circuit', quantum_registers)
qc += self._evo_operator.evolve(
evo_time=self._evo_time,
evo_mode='circuit',
num_time_slices=self._num_time_slices,
quantum_registers=quantum_registers,
expansion_mode=self._expansion_mode,
expansion_order=self._expansion_order,
)
return qc
def _run(self):
qc = self.construct_circuit()
qc_with_op = self._operator.construct_evaluation_circuit(
self._operator_mode, qc, self._quantum_instance.backend
)
result = self._quantum_instance.execute(qc_with_op)
self._ret['avg'], self._ret['std_dev'] = self._operator.evaluate_with_result(
self._operator_mode, qc_with_op, self._quantum_instance.backend, result
)
return self._ret
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import logging
import sys
import numpy as np
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
from qiskit.tools import parallel_map
from qiskit.tools.events import TextProgressBar
from qiskit.aqua import aqua_globals
from qiskit.aqua.algorithms import QuantumAlgorithm
from qiskit.aqua import AquaError, Pluggable, PluggableType, get_pluggable_class
from qiskit.aqua.algorithms.many_sample.qsvm._qsvm_binary import _QSVM_Binary
from qiskit.aqua.algorithms.many_sample.qsvm._qsvm_multiclass import _QSVM_Multiclass
from qiskit.aqua.algorithms.many_sample.qsvm._qsvm_estimator import _QSVM_Estimator
from qiskit.aqua.utils.dataset_helper import get_feature_dimension, get_num_classes
from qiskit.aqua.utils import split_dataset_to_data_and_labels
logger = logging.getLogger(__name__)
class QSVM(QuantumAlgorithm):
"""
Quantum SVM method.
Internally, it will run the binary classification or multiclass classification
based on how many classes the data have.
"""
CONFIGURATION = {
'name': 'QSVM',
'description': 'QSVM Algorithm',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'QSVM_schema',
'type': 'object',
'properties': {
},
'additionalProperties': False
},
'problems': ['classification'],
'depends': [
{'pluggable_type': 'multiclass_extension'},
{'pluggable_type': 'feature_map',
'default': {
'name': 'SecondOrderExpansion',
'depth': 2
}
},
],
}
BATCH_SIZE = 1000
def __init__(self, feature_map, training_dataset, test_dataset=None, datapoints=None,
multiclass_extension=None):
"""Constructor.
Args:
feature_map (FeatureMap): feature map module, used to transform data
training_dataset (dict): training dataset.
test_dataset (Optional[dict]): testing dataset.
datapoints (Optional[numpy.ndarray]): prediction dataset.
multiclass_extension (Optional[MultiExtension]): if number of classes > 2 then
a multiclass scheme is needed.
Raises:
ValueError: if training_dataset is None
AquaError: use binary classifer for classes > 3
"""
super().__init__()
if training_dataset is None:
raise ValueError('Training dataset must be provided')
is_multiclass = get_num_classes(training_dataset) > 2
if is_multiclass:
if multiclass_extension is None:
raise AquaError('Dataset has more than two classes. '
'A multiclass extension must be provided.')
else:
if multiclass_extension is not None:
logger.warning("Dataset has just two classes. "
"Supplied multiclass extension will be ignored")
self.training_dataset, self.class_to_label = split_dataset_to_data_and_labels(
training_dataset)
if test_dataset is not None:
self.test_dataset = split_dataset_to_data_and_labels(test_dataset,
self.class_to_label)
else:
self.test_dataset = None
self.label_to_class = {label: class_name for class_name, label
in self.class_to_label.items()}
self.num_classes = len(list(self.class_to_label.keys()))
if datapoints is not None and not isinstance(datapoints, np.ndarray):
datapoints = np.asarray(datapoints)
self.datapoints = datapoints
self.feature_map = feature_map
self.num_qubits = self.feature_map.num_qubits
if multiclass_extension is None:
qsvm_instance = _QSVM_Binary(self)
else:
qsvm_instance = _QSVM_Multiclass(self, multiclass_extension)
self.instance = qsvm_instance
@classmethod
def init_params(cls, params, algo_input):
"""Constructor from params."""
feature_dimension = get_feature_dimension(algo_input.training_dataset)
fea_map_params = params.get(Pluggable.SECTION_KEY_FEATURE_MAP)
fea_map_params['feature_dimension'] = feature_dimension
feature_map = get_pluggable_class(PluggableType.FEATURE_MAP,
fea_map_params['name']).init_params(params)
multiclass_extension = None
multiclass_extension_params = params.get(Pluggable.SECTION_KEY_MULTICLASS_EXTENSION)
if multiclass_extension_params is not None:
multiclass_extension_params['params'] = [feature_map]
multiclass_extension_params['estimator_cls'] = _QSVM_Estimator
multiclass_extension = get_pluggable_class(PluggableType.MULTICLASS_EXTENSION,
multiclass_extension_params['name']).init_params(params)
logger.info("Multiclass classifier based on {}".format(multiclass_extension_params['name']))
return cls(feature_map, algo_input.training_dataset, algo_input.test_dataset,
algo_input.datapoints, multiclass_extension)
@staticmethod
def _construct_circuit(x, num_qubits, feature_map, measurement):
x1, x2 = x
if x1.shape[0] != x2.shape[0]:
raise ValueError("x1 and x2 must be the same dimension.")
q = QuantumRegister(num_qubits, 'q')
c = ClassicalRegister(num_qubits, 'c')
qc = QuantumCircuit(q, c)
# write input state from sample distribution
qc += feature_map.construct_circuit(x1, q)
qc += feature_map.construct_circuit(x2, q, inverse=True)
if measurement:
qc.barrier(q)
qc.measure(q, c)
return qc
@staticmethod
def _compute_overlap(idx, results, is_statevector_sim, measurement_basis):
if is_statevector_sim:
temp = results.get_statevector(idx)[0]
# |<0|Psi^daggar(y) x Psi(x)|0>|^2,
kernel_value = np.dot(temp.T.conj(), temp).real
else:
result = results.get_counts(idx)
kernel_value = result.get(measurement_basis, 0) / sum(result.values())
return kernel_value
def construct_circuit(self, x1, x2, measurement=False):
"""
Generate inner product of x1 and x2 with the given feature map.
The dimension of x1 and x2 must be the same.
Args:
x1 (numpy.ndarray): data points, 1-D array, dimension is D
x2 (numpy.ndarray): data points, 1-D array, dimension is D
measurement (bool): add measurement gates at the end
"""
return QSVM._construct_circuit((x1, x2), self.num_qubits,
self.feature_map, measurement)
def construct_kernel_matrix(self, x1_vec, x2_vec=None, quantum_instance=None):
"""
Construct kernel matrix, if x2_vec is None, self-innerproduct is conducted.
Args:
x1_vec (numpy.ndarray): data points, 2-D array, N1xD, where N1 is the number of data,
D is the feature dimension
x2_vec (numpy.ndarray): data points, 2-D array, N2xD, where N2 is the number of data,
D is the feature dimension
quantum_instance (QuantumInstance): quantum backend with all setting
Returns:
numpy.ndarray: 2-D matrix, N1xN2
"""
self._quantum_instance = self._quantum_instance \
if quantum_instance is None else quantum_instance
from .qsvm import QSVM
if x2_vec is None:
is_symmetric = True
x2_vec = x1_vec
else:
is_symmetric = False
is_statevector_sim = self.quantum_instance.is_statevector
measurement = not is_statevector_sim
measurement_basis = '0' * self.num_qubits
mat = np.ones((x1_vec.shape[0], x2_vec.shape[0]))
# get all indices
if is_symmetric:
mus, nus = np.triu_indices(x1_vec.shape[0], k=1) # remove diagonal term
else:
mus, nus = np.indices((x1_vec.shape[0], x2_vec.shape[0]))
mus = np.asarray(mus.flat)
nus = np.asarray(nus.flat)
for idx in range(0, len(mus), QSVM.BATCH_SIZE):
to_be_computed_list = []
to_be_computed_index = []
for sub_idx in range(idx, min(idx + QSVM.BATCH_SIZE, len(mus))):
i = mus[sub_idx]
j = nus[sub_idx]
x1 = x1_vec[i]
x2 = x2_vec[j]
if not np.all(x1 == x2):
to_be_computed_list.append((x1, x2))
to_be_computed_index.append((i, j))
if logger.isEnabledFor(logging.DEBUG):
logger.debug("Building circuits:")
TextProgressBar(sys.stderr)
circuits = parallel_map(QSVM._construct_circuit,
to_be_computed_list,
task_args=(self.num_qubits, self.feature_map,
measurement),
num_processes=aqua_globals.num_processes)
results = self.quantum_instance.execute(circuits)
if logger.isEnabledFor(logging.DEBUG):
logger.debug("Calculating overlap:")
TextProgressBar(sys.stderr)
matrix_elements = parallel_map(QSVM._compute_overlap, range(len(circuits)),
task_args=(results, is_statevector_sim, measurement_basis),
num_processes=aqua_globals.num_processes)
for idx in range(len(to_be_computed_index)):
i, j = to_be_computed_index[idx]
mat[i, j] = matrix_elements[idx]
if is_symmetric:
mat[j, i] = mat[i, j]
return mat
def train(self, data, labels, quantum_instance=None):
"""
Train the svm.
Args:
data (numpy.ndarray): NxD array, where N is the number of data,
D is the feature dimension.
labels (numpy.ndarray): Nx1 array, where N is the number of data
quantum_instance (QuantumInstance): quantum backend with all setting
"""
self._quantum_instance = self._quantum_instance \
if quantum_instance is None else quantum_instance
self.instance.train(data, labels)
def test(self, data, labels, quantum_instance=None):
"""
Test the svm.
Args:
data (numpy.ndarray): NxD array, where N is the number of data,
D is the feature dimension.
labels (numpy.ndarray): Nx1 array, where N is the number of data
quantum_instance (QuantumInstance): quantum backend with all setting
Returns:
float: accuracy
"""
self._quantum_instance = self._quantum_instance \
if quantum_instance is None else quantum_instance
return self.instance.test(data, labels)
def predict(self, data, quantum_instance=None):
"""
Predict using the svm.
Args:
data (numpy.ndarray): NxD array, where N is the number of data,
D is the feature dimension.
quantum_instance (QuantumInstance): quantum backend with all setting
Returns:
numpy.ndarray: predicted labels, Nx1 array
"""
self._quantum_instance = self._quantum_instance \
if quantum_instance is None else quantum_instance
return self.instance.predict(data)
def _run(self):
return self.instance.run()
@property
def ret(self):
return self.instance.ret
@ret.setter
def ret(self, new_value):
self.instance.ret = new_value
def load_model(self, file_path):
"""Load a model from a file path.
Args:
file_path (str): tthe path of the saved model.
"""
self.instance.load_model(file_path)
def save_model(self, file_path):
"""Save the model to a file path.
Args:
file_path (str): a path to save the model.
"""
self.instance.save_model(file_path)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
The Amplitude Estimation Algorithm.
"""
import logging
from collections import OrderedDict
import numpy as np
from qiskit import ClassicalRegister
from qiskit.aqua import AquaError
from qiskit.aqua import Pluggable, PluggableType, get_pluggable_class
from qiskit.aqua.algorithms import QuantumAlgorithm
from qiskit.aqua.circuits import PhaseEstimationCircuit
from qiskit.aqua.components.iqfts import Standard
from .q_factory import QFactory
logger = logging.getLogger(__name__)
class AmplitudeEstimation(QuantumAlgorithm):
"""
The Amplitude Estimation algorithm.
"""
CONFIGURATION = {
'name': 'AmplitudeEstimation',
'description': 'Amplitude Estimation Algorithm',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'AmplitudeEstimation_schema',
'type': 'object',
'properties': {
'num_eval_qubits': {
'type': 'integer',
'default': 5,
'minimum': 1
}
},
'additionalProperties': False
},
'problems': ['uncertainty'],
'depends': [
{
'pluggable_type': 'uncertainty_problem',
'default': {
'name': 'EuropeanCallDelta'
}
},
{
'pluggable_type': 'iqft',
'default': {
'name': 'STANDARD',
}
},
],
}
def __init__(self, num_eval_qubits, a_factory, i_objective=None, q_factory=None, iqft=None):
"""
Constructor.
Args:
num_eval_qubits (int): number of evaluation qubits
a_factory (CircuitFactory): the CircuitFactory subclass object representing the problem unitary
q_factory (CircuitFactory): the CircuitFactory subclass object representing an amplitude estimation sample (based on a_factory)
iqft (IQFT): the Inverse Quantum Fourier Transform pluggable component, defaults to using a standard iqft when None
"""
self.validate(locals())
super().__init__()
# get/construct A/Q operator
self.a_factory = a_factory
if q_factory is None:
if i_objective is None:
i_objective = self.a_factory.num_target_qubits - 1
self.q_factory = QFactory(a_factory, i_objective)
else:
self.q_factory = q_factory
# get parameters
self._m = num_eval_qubits
self._M = 2 ** num_eval_qubits
# determine number of ancillas
self._num_ancillas = self.q_factory.required_ancillas_controlled()
self._num_qubits = self.a_factory.num_target_qubits + self._m + self._num_ancillas
if iqft is None:
iqft = Standard(self._m)
self._iqft = iqft
self._circuit = None
self._ret = {}
@classmethod
def init_params(cls, params, algo_input):
"""
Initialize via parameters dictionary and algorithm input instance
Args:
params: parameters dictionary
algo_input: Input instance
"""
if algo_input is not None:
raise AquaError("Input instance not supported.")
ae_params = params.get(Pluggable.SECTION_KEY_ALGORITHM)
num_eval_qubits = ae_params.get('num_eval_qubits')
# Set up uncertainty problem. The params can include an uncertainty model
# type dependent on the uncertainty problem and is this its responsibility
# to create for itself from the complete params set that is passed to it.
uncertainty_problem_params = params.get(Pluggable.SECTION_KEY_UNCERTAINTY_PROBLEM)
uncertainty_problem = get_pluggable_class(
PluggableType.UNCERTAINTY_PROBLEM,
uncertainty_problem_params['name']).init_params(params)
# Set up iqft, we need to add num qubits to params which is our num_ancillae bits here
iqft_params = params.get(Pluggable.SECTION_KEY_IQFT)
iqft_params['num_qubits'] = num_eval_qubits
iqft = get_pluggable_class(PluggableType.IQFT, iqft_params['name']).init_params(params)
return cls(num_eval_qubits, uncertainty_problem, q_factory=None, iqft=iqft)
def construct_circuit(self, measurement=False):
"""
Construct the Amplitude Estimation quantum circuit.
Args:
measurement (bool): Boolean flag to indicate if measurement should be included in the circuit.
Returns:
the QuantumCircuit object for the constructed circuit
"""
pec = PhaseEstimationCircuit(
iqft=self._iqft, num_ancillae=self._m,
state_in_circuit_factory=self.a_factory,
unitary_circuit_factory=self.q_factory
)
self._circuit = pec.construct_circuit(measurement=measurement)
return self._circuit
def _evaluate_statevector_results(self, probabilities):
# map measured results to estimates
y_probabilities = OrderedDict()
for i, probability in enumerate(probabilities):
b = "{0:b}".format(i).rjust(self._num_qubits, '0')[::-1]
y = int(b[:self._m], 2)
y_probabilities[y] = y_probabilities.get(y, 0) + probability
a_probabilities = OrderedDict()
for y, probability in y_probabilities.items():
if y >= int(self._M / 2):
y = self._M - y
a = np.power(np.sin(y * np.pi / 2 ** self._m), 2)
a_probabilities[a] = a_probabilities.get(a, 0) + probability
return a_probabilities, y_probabilities
def _run(self):
if self._quantum_instance.is_statevector:
self.construct_circuit(measurement=False)
# run circuit on statevector simlator
ret = self._quantum_instance.execute(self._circuit)
state_vector = np.asarray([ret.get_statevector(self._circuit)])
self._ret['statevector'] = state_vector
# get state probabilities
state_probabilities = np.real(state_vector.conj() * state_vector)[0]
# evaluate results
a_probabilities, y_probabilities = self._evaluate_statevector_results(state_probabilities)
else:
# run circuit on QASM simulator
self.construct_circuit(measurement=True)
ret = self._quantum_instance.execute(self._circuit)
# get counts
self._ret['counts'] = ret.get_counts()
# construct probabilities
y_probabilities = {}
a_probabilities = {}
shots = sum(ret.get_counts().values())
for state, counts in ret.get_counts().items():
y = int(state.replace(' ', '')[:self._m][::-1], 2)
p = counts / shots
y_probabilities[y] = p
a = np.power(np.sin(y * np.pi / 2 ** self._m), 2)
a_probabilities[a] = a_probabilities.get(a, 0.0) + p
# construct a_items and y_items
a_items = [(a, p) for (a, p) in a_probabilities.items() if p > 1e-6]
y_items = [(y, p) for (y, p) in y_probabilities.items() if p > 1e-6]
a_items = sorted(a_items)
y_items = sorted(y_items)
self._ret['a_items'] = a_items
self._ret['y_items'] = y_items
# map estimated values to original range and extract probabilities
self._ret['mapped_values'] = [self.a_factory.value_to_estimation(a_item[0]) for a_item in self._ret['a_items']]
self._ret['values'] = [a_item[0] for a_item in self._ret['a_items']]
self._ret['y_values'] = [y_item[0] for y_item in y_items]
self._ret['probabilities'] = [a_item[1] for a_item in self._ret['a_items']]
self._ret['mapped_items'] = [(self._ret['mapped_values'][i], self._ret['probabilities'][i]) for i in range(len(self._ret['mapped_values']))]
# determine most likely estimator
self._ret['estimation'] = None
self._ret['max_probability'] = 0
for val, prob in self._ret['mapped_items']:
if prob > self._ret['max_probability']:
self._ret['max_probability'] = prob
self._ret['estimation'] = val
return self._ret
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
The Bernstein-Vazirani algorithm.
"""
import logging
import operator
import numpy as np
from qiskit import ClassicalRegister, QuantumCircuit
from qiskit.aqua import AquaError, Pluggable, PluggableType, get_pluggable_class
from qiskit.aqua.algorithms import QuantumAlgorithm
from qiskit.aqua.utils import get_subsystem_density_matrix
logger = logging.getLogger(__name__)
class BernsteinVazirani(QuantumAlgorithm):
"""The Bernstein-Vazirani algorithm."""
CONFIGURATION = {
'name': 'BernsteinVazirani',
'description': 'Bernstein Vazirani',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'bv_schema',
'type': 'object',
'properties': {
},
'additionalProperties': False
},
'problems': ['hiddenstringfinding'],
'depends': [
{
'pluggable_type': 'oracle',
'default': {
'name': 'TruthTableOracle',
},
},
],
}
def __init__(self, oracle):
self.validate(locals())
super().__init__()
self._oracle = oracle
self._circuit = None
self._ret = {}
@classmethod
def init_params(cls, params, algo_input):
if algo_input is not None:
raise AquaError("Input instance not supported.")
oracle_params = params.get(Pluggable.SECTION_KEY_ORACLE)
oracle = get_pluggable_class(
PluggableType.ORACLE,
oracle_params['name']).init_params(params)
return cls(oracle)
def construct_circuit(self, measurement=False):
"""
Construct the quantum circuit
Args:
measurement (bool): Boolean flag to indicate if measurement should be included in the circuit.
Returns:
the QuantumCircuit object for the constructed circuit
"""
if self._circuit is not None:
return self._circuit
qc_preoracle = QuantumCircuit(
self._oracle.variable_register,
self._oracle.output_register,
)
qc_preoracle.h(self._oracle.variable_register)
qc_preoracle.x(self._oracle.output_register)
qc_preoracle.h(self._oracle.output_register)
qc_preoracle.barrier()
# oracle circuit
qc_oracle = self._oracle.circuit
qc_oracle.barrier()
# postoracle circuit
qc_postoracle = QuantumCircuit(
self._oracle.variable_register,
self._oracle.output_register,
)
qc_postoracle.h(self._oracle.variable_register)
self._circuit = qc_preoracle + qc_oracle + qc_postoracle
# measurement circuit
if measurement:
measurement_cr = ClassicalRegister(len(self._oracle.variable_register), name='m')
self._circuit.add_register(measurement_cr)
self._circuit.measure(self._oracle.variable_register, measurement_cr)
return self._circuit
def _run(self):
if self._quantum_instance.is_statevector:
qc = self.construct_circuit(measurement=False)
result = self._quantum_instance.execute(qc)
complete_state_vec = result.get_statevector(qc)
variable_register_density_matrix = get_subsystem_density_matrix(
complete_state_vec,
range(len(self._oracle.variable_register), qc.width())
)
variable_register_density_matrix_diag = np.diag(variable_register_density_matrix)
max_amplitude = max(
variable_register_density_matrix_diag.min(),
variable_register_density_matrix_diag.max(),
key=abs
)
max_amplitude_idx = np.where(variable_register_density_matrix_diag == max_amplitude)[0][0]
top_measurement = np.binary_repr(max_amplitude_idx, len(self._oracle.variable_register))
else:
qc = self.construct_circuit(measurement=True)
measurement = self._quantum_instance.execute(qc).get_counts(qc)
self._ret['measurement'] = measurement
top_measurement = max(measurement.items(), key=operator.itemgetter(1))[0]
self._ret['result'] = top_measurement
return self._ret
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
The Deutsch-Jozsa algorithm.
"""
import logging
import operator
import numpy as np
from qiskit import ClassicalRegister, QuantumCircuit
from qiskit.aqua import AquaError, Pluggable, PluggableType, get_pluggable_class
from qiskit.aqua.algorithms import QuantumAlgorithm
from qiskit.aqua.utils import get_subsystem_density_matrix
logger = logging.getLogger(__name__)
class DeutschJozsa(QuantumAlgorithm):
"""The Deutsch-Jozsa algorithm."""
CONFIGURATION = {
'name': 'DeutschJozsa',
'description': 'Deutsch Jozsa',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'dj_schema',
'type': 'object',
'properties': {
},
'additionalProperties': False
},
'problems': ['functionevaluation'],
'depends': [
{
'pluggable_type': 'oracle',
'default': {
'name': 'TruthTableOracle',
},
},
],
}
def __init__(self, oracle):
self.validate(locals())
super().__init__()
self._oracle = oracle
self._circuit = None
self._ret = {}
@classmethod
def init_params(cls, params, algo_input):
if algo_input is not None:
raise AquaError("Input instance not supported.")
oracle_params = params.get(Pluggable.SECTION_KEY_ORACLE)
oracle = get_pluggable_class(
PluggableType.ORACLE,
oracle_params['name']).init_params(params)
return cls(oracle)
def construct_circuit(self, measurement=False):
"""
Construct the quantum circuit
Args:
measurement (bool): Boolean flag to indicate if measurement should be included in the circuit.
Returns:
the QuantumCircuit object for the constructed circuit
"""
if self._circuit is not None:
return self._circuit
# preoracle circuit
qc_preoracle = QuantumCircuit(
self._oracle.variable_register,
self._oracle.output_register,
)
qc_preoracle.h(self._oracle.variable_register)
qc_preoracle.x(self._oracle.output_register)
qc_preoracle.h(self._oracle.output_register)
qc_preoracle.barrier()
# oracle circuit
qc_oracle = self._oracle.circuit
# postoracle circuit
qc_postoracle = QuantumCircuit(
self._oracle.variable_register,
self._oracle.output_register,
)
qc_postoracle.h(self._oracle.variable_register)
qc_postoracle.barrier()
self._circuit = qc_preoracle + qc_oracle + qc_postoracle
# measurement circuit
if measurement:
measurement_cr = ClassicalRegister(len(self._oracle.variable_register), name='m')
self._circuit.add_register(measurement_cr)
self._circuit.measure(self._oracle.variable_register, measurement_cr)
return self._circuit
def _run(self):
if self._quantum_instance.is_statevector:
qc = self.construct_circuit(measurement=False)
result = self._quantum_instance.execute(qc)
complete_state_vec = result.get_statevector(qc)
variable_register_density_matrix = get_subsystem_density_matrix(
complete_state_vec,
range(len(self._oracle.variable_register), qc.width())
)
variable_register_density_matrix_diag = np.diag(variable_register_density_matrix)
max_amplitude = max(
variable_register_density_matrix_diag.min(),
variable_register_density_matrix_diag.max(),
key=abs
)
max_amplitude_idx = np.where(variable_register_density_matrix_diag == max_amplitude)[0][0]
top_measurement = np.binary_repr(max_amplitude_idx, len(self._oracle.variable_register))
else:
qc = self.construct_circuit(measurement=True)
measurement = self._quantum_instance.execute(qc).get_counts(qc)
self._ret['measurement'] = measurement
top_measurement = max(measurement.items(), key=operator.itemgetter(1))[0]
self._ret['result'] = 'constant' if int(top_measurement) == 0 else 'balanced'
return self._ret
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
"""Python implementation of Grovers algorithm through use of the Qiskit library to find the value 3 (|11>)
out of four possible values."""
#import numpy and plot library
import matplotlib.pyplot as plt
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.providers.ibmq import least_busy
from qiskit.quantum_info import Statevector
# import basic plot tools
from qiskit.visualization import plot_histogram
# define variables, 1) initialize qubits to zero
n = 2
grover_circuit = QuantumCircuit(n)
#define initialization function
def initialize_s(qc, qubits):
'''Apply a H-gate to 'qubits' in qc'''
for q in qubits:
qc.h(q)
return qc
### begin grovers circuit ###
#2) Put qubits in equal state of superposition
grover_circuit = initialize_s(grover_circuit, [0,1])
# 3) Apply oracle reflection to marked instance x_0 = 3, (|11>)
grover_circuit.cz(0,1)
statevec = job_sim.result().get_statevector()
from qiskit_textbook.tools import vector2latex
vector2latex(statevec, pretext="|\\psi\\rangle =")
# 4) apply additional reflection (diffusion operator)
grover_circuit.h([0,1])
grover_circuit.z([0,1])
grover_circuit.cz(0,1)
grover_circuit.h([0,1])
# 5) measure the qubits
grover_circuit.measure_all()
# Load IBM Q account and get the least busy backend device
provider = IBMQ.load_account()
device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and
not x.configuration().simulator and x.status().operational==True))
print("Running on current least busy device: ", device)
from qiskit.tools.monitor import job_monitor
job = execute(grover_circuit, backend=device, shots=1024, optimization_level=3)
job_monitor(job, interval = 2)
results = job.result()
answer = results.get_counts(grover_circuit)
plot_histogram(answer)
#highest amplitude should correspond with marked value x_0 (|11>)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
The HHL algorithm.
"""
import logging
import numpy as np
from copy import deepcopy
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.aqua.algorithms import QuantumAlgorithm
from qiskit.aqua import AquaError, Pluggable, PluggableType, get_pluggable_class
from qiskit.ignis.verification.tomography import state_tomography_circuits, \
StateTomographyFitter
from qiskit.converters import circuit_to_dag
logger = logging.getLogger(__name__)
class HHL(QuantumAlgorithm):
"""The HHL algorithm.
The quantum circuit for this algorithm is returned by `generate_circuit`.
Running the algorithm will execute the circuit and return the result
vector, measured (real hardware backend) or derived (qasm_simulator) via
state tomography or calculated from the statevector (statevector_simulator).
"""
CONFIGURATION = {
'name': 'HHL',
'description': 'The HHL Algorithm for Solving Linear Systems of '
'equations',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'hhl_schema',
'type': 'object',
'properties': {
'truncate_powerdim': {
'type': 'boolean',
'default': False
},
'truncate_hermitian': {
'type': 'boolean',
'default': False
},
'orig_size': {
'type': ['integer', 'null'],
'default': None
}
},
'additionalProperties': False
},
'problems': ['linear_system'],
'depends': [
{'pluggable_type': 'initial_state',
'default': {
'name': 'CUSTOM',
}
},
{'pluggable_type': 'eigs',
'default': {
'name': 'EigsQPE',
'num_ancillae': 6,
'num_time_slices': 50,
'expansion_mode': 'suzuki',
'expansion_order': 2
}
},
{'pluggable_type': 'reciprocal',
'default': {
'name': 'Lookup'
}
}
],
}
def __init__(
self,
matrix=None,
vector=None,
truncate_powerdim=False,
truncate_hermitian=False,
eigs=None,
init_state=None,
reciprocal=None,
num_q=0,
num_a=0,
orig_size=None
):
"""
Constructor.
Args:
matrix (np.array): the input matrix of linear system of equations
vector (np.array): the input vector of linear system of equations
truncate_powerdim (bool): flag indicating expansion to 2**n matrix to be truncated
truncate_hermitian (bool): flag indicating expansion to hermitian matrix to be truncated
eigs (Eigenvalues): the eigenvalue estimation instance
init_state (InitialState): the initial quantum state preparation
reciprocal (Reciprocal): the eigenvalue reciprocal and controlled rotation instance
num_q (int): number of qubits required for the matrix Operator instance
num_a (int): number of ancillary qubits for Eigenvalues instance
orig_size (int): The original dimension of the problem (if truncate_powerdim)
"""
super().__init__()
super().validate(locals())
if matrix.shape[0] != matrix.shape[1]:
raise ValueError("Input matrix must be square!")
if matrix.shape[0] != len(vector):
raise ValueError("Input vector dimension does not match input "
"matrix dimension!")
if not np.allclose(matrix, matrix.conj().T):
raise ValueError("Input matrix must be hermitian!")
if np.log2(matrix.shape[0]) % 1 != 0:
raise ValueError("Input matrix dimension must be 2**n!")
if truncate_powerdim and orig_size is None:
raise ValueError("Truncation to {} dimensions is not "
"possible!".format(self._original_dimension))
self._matrix = matrix
self._vector = vector
self._truncate_powerdim = truncate_powerdim
self._truncate_hermitian = truncate_hermitian
self._eigs = eigs
self._init_state = init_state
self._reciprocal = reciprocal
self._num_q = num_q
self._num_a = num_a
self._circuit = None
self._io_register = None
self._eigenvalue_register = None
self._ancilla_register = None
self._success_bit = None
self._original_dimension = orig_size
self._ret = {}
@classmethod
def init_params(cls, params, algo_input):
"""Initialize via parameters dictionary and algorithm input instance
Args:
params: parameters dictionary
algo_input: LinearSystemInput instance
"""
if algo_input is None:
raise AquaError("LinearSystemInput instance is required.")
matrix = algo_input.matrix
vector = algo_input.vector
if not isinstance(matrix, np.ndarray):
matrix = np.asarray(matrix)
if not isinstance(vector, np.ndarray):
vector = np.asarray(vector)
if matrix.shape[0] != matrix.shape[1]:
raise ValueError("Input matrix must be square!")
if matrix.shape[0] != len(vector):
raise ValueError("Input vector dimension does not match input "
"matrix dimension!")
hhl_params = params.get(Pluggable.SECTION_KEY_ALGORITHM)
truncate_powerdim = hhl_params.get('truncate_powerdim')
truncate_hermitian = hhl_params.get('truncate_hermitian')
orig_size = hhl_params.get('orig_size')
if orig_size is None:
orig_size = len(vector)
is_powerdim = np.log2(matrix.shape[0]) % 1 == 0
if not is_powerdim:
logger.warning("Input matrix does not have dimension 2**n. It "
"will be expanded automatically.")
matrix, vector = cls.expand_to_powerdim(matrix, vector)
truncate_powerdim = True
is_hermitian = np.allclose(matrix, matrix.conj().T)
if not is_hermitian:
logger.warning("Input matrix is not hermitian. It will be "
"expanded to a hermitian matrix automatically.")
matrix, vector = cls.expand_to_hermitian(matrix, vector)
truncate_hermitian = True
# Initialize eigenvalue finding module
eigs_params = params.get(Pluggable.SECTION_KEY_EIGS)
eigs = get_pluggable_class(PluggableType.EIGENVALUES,
eigs_params['name']).init_params(params, matrix)
num_q, num_a = eigs.get_register_sizes()
# Initialize initial state module
tmpvec = vector
init_state_params = params.get(Pluggable.SECTION_KEY_INITIAL_STATE)
init_state_params["num_qubits"] = num_q
init_state_params["state_vector"] = tmpvec
init_state = get_pluggable_class(PluggableType.INITIAL_STATE,
init_state_params['name']).init_params(params)
# Initialize reciprocal rotation module
reciprocal_params = params.get(Pluggable.SECTION_KEY_RECIPROCAL)
reciprocal_params["negative_evals"] = eigs._negative_evals
reciprocal_params["evo_time"] = eigs._evo_time
reci = get_pluggable_class(PluggableType.RECIPROCAL,
reciprocal_params['name']).init_params(params)
return cls(matrix, vector, truncate_powerdim, truncate_hermitian, eigs,
init_state, reci, num_q, num_a, orig_size)
def construct_circuit(self, measurement=False):
"""Construct the HHL circuit.
Args:
measurement (bool): indicate whether measurement on ancillary qubit
should be performed
Returns:
the QuantumCircuit object for the constructed circuit
"""
q = QuantumRegister(self._num_q, name="io")
qc = QuantumCircuit(q)
# InitialState
qc += self._init_state.construct_circuit("circuit", q)
# EigenvalueEstimation (QPE)
qc += self._eigs.construct_circuit("circuit", q)
a = self._eigs._output_register
# Reciprocal calculation with rotation
qc += self._reciprocal.construct_circuit("circuit", a)
s = self._reciprocal._anc
# Inverse EigenvalueEstimation
qc += self._eigs.construct_inverse("circuit", self._eigs._circuit)
# Measurement of the ancilla qubit
if measurement:
c = ClassicalRegister(1)
qc.add_register(c)
qc.measure(s, c)
self._success_bit = c
self._io_register = q
self._eigenvalue_register = a
self._ancilla_register = s
self._circuit = qc
return qc
@staticmethod
def expand_to_powerdim(matrix, vector):
""" Expand a matrix to the next-larger 2**n dimensional matrix with
ones on the diagonal and zeros on the off-diagonal and expand the
vector with zeros accordingly.
Args:
matrix (np.array): the input matrix
vector (np.array): the input vector
Returns:
matrix (np.array): the expanded matrix
vector (np.array): the expanded vector
"""
mat_dim = matrix.shape[0]
next_higher = int(np.ceil(np.log2(mat_dim)))
new_matrix = np.identity(2 ** next_higher)
new_matrix = np.array(new_matrix, dtype=complex)
new_matrix[:mat_dim, :mat_dim] = matrix[:, :]
matrix = new_matrix
new_vector = np.zeros((1, 2 ** next_higher))
new_vector[0, :vector.shape[0]] = vector
vector = new_vector.reshape(np.shape(new_vector)[1])
return matrix, vector
@staticmethod
def expand_to_hermitian(matrix, vector):
""" Expand a non-hermitian matrix A to a hermitian matrix by
[[0, A.H], [A, 0]] and expand vector b to [b.conj, b].
Args:
matrix (np.array): the input matrix
vector (np.array): the input vector
Returns:
matrix (np.array): the expanded matrix
vector (np.array): the expanded vector
"""
#
half_dim = matrix.shape[0]
full_dim = 2 * half_dim
new_matrix = np.zeros([full_dim, full_dim])
new_matrix = np.array(new_matrix, dtype=complex)
new_matrix[0:half_dim, half_dim:full_dim] = matrix[:, :]
new_matrix[half_dim:full_dim, 0:half_dim] = matrix.conj().T[:, :]
matrix = new_matrix
new_vector = np.zeros((1, full_dim))
new_vector = np.array(new_vector, dtype=complex)
new_vector[0, :vector.shape[0]] = vector.conj()
new_vector[0, vector.shape[0]:] = vector
vector = new_vector.reshape(np.shape(new_vector)[1])
return matrix, vector
def _resize_vector(self, vec):
if self._truncate_hermitian:
half_dim = int(vec.shape[0] / 2)
vec = vec[:half_dim]
if self._truncate_powerdim:
vec = vec[:self._original_dimension]
return vec
def _resize_matrix(self, matrix):
if self._truncate_hermitian:
full_dim = matrix.shape[0]
half_dim = int(full_dim / 2)
new_matrix = np.ndarray(shape=(half_dim, half_dim), dtype=complex)
new_matrix[:, :] = matrix[0:half_dim, half_dim:full_dim]
matrix = new_matrix
if self._truncate_powerdim:
new_matrix = np.ndarray(shape=(self._original_dimension, self._original_dimension), dtype=complex)
new_matrix[:, :] = matrix[:self._original_dimension, :self._original_dimension]
matrix = new_matrix
return matrix
def _statevector_simulation(self):
"""The statevector simulation.
The HHL result gets extracted from the statevector. Only for
statevector simulator available.
"""
res = self._quantum_instance.execute(self._circuit)
sv = np.asarray(res.get_statevector(self._circuit))
# Extract solution vector from statevector
vec = self._reciprocal.sv_to_resvec(sv, self._num_q)
# remove added dimensions
self._ret['probability_result'] = np.real(self._resize_vector(vec).dot(self._resize_vector(vec).conj()))
vec = vec/np.linalg.norm(vec)
self._hhl_results(vec)
def _state_tomography(self):
"""The state tomography.
The HHL result gets extracted via state tomography. Available for
qasm simulator and real hardware backends.
"""
# Preparing the state tomography circuits
tomo_circuits = state_tomography_circuits(self._circuit,
self._io_register)
tomo_circuits_noanc = deepcopy(tomo_circuits)
ca = ClassicalRegister(1)
for circ in tomo_circuits:
circ.add_register(ca)
circ.measure(self._reciprocal._anc, ca[0])
# Extracting the probability of successful run
results = self._quantum_instance.execute(tomo_circuits)
probs = []
for circ in tomo_circuits:
counts = results.get_counts(circ)
s, f = 0, 0
for k, v in counts.items():
if k[0] == "1":
s += v
else:
f += v
probs.append(s/(f+s))
probs = self._resize_vector(probs)
self._ret["probability_result"] = np.real(probs)
# Filtering the tomo data for valid results with ancillary measured
# to 1, i.e. c1==1
results_noanc = self._tomo_postselect(results)
tomo_data = StateTomographyFitter(results_noanc, tomo_circuits_noanc)
rho_fit = tomo_data.fit()
vec = np.diag(rho_fit) / np.sqrt(sum(np.diag(rho_fit) ** 2))
self._hhl_results(vec)
def _tomo_postselect(self, results):
new_results = deepcopy(results)
for resultidx, _ in enumerate(results.results):
old_counts = results.get_counts(resultidx)
new_counts = {}
# change the size of the classical register
new_results.results[resultidx].header.creg_sizes = [
new_results.results[resultidx].header.creg_sizes[0]]
new_results.results[resultidx].header.clbit_labels = \
new_results.results[resultidx].header.clbit_labels[0:-1]
new_results.results[resultidx].header.memory_slots = \
new_results.results[resultidx].header.memory_slots - 1
for reg_key in old_counts:
reg_bits = reg_key.split(' ')
if reg_bits[0] == '1':
new_counts[reg_bits[1]] = old_counts[reg_key]
new_results.results[resultidx].data.counts = \
new_results.results[resultidx]. \
data.counts.from_dict(new_counts)
return new_results
def _hhl_results(self, vec):
res_vec = self._resize_vector(vec)
in_vec = self._resize_vector(self._vector)
matrix = self._resize_matrix(self._matrix)
self._ret["output"] = res_vec
# Rescaling the output vector to the real solution vector
tmp_vec = matrix.dot(res_vec)
f1 = np.linalg.norm(in_vec)/np.linalg.norm(tmp_vec)
f2 = sum(np.angle(in_vec*tmp_vec.conj()-1+1))/(np.log2(matrix.shape[0])) # "-1+1" to fix angle error for -0.-0.j
self._ret["solution"] = f1*res_vec*np.exp(-1j*f2)
def _run(self):
if self._quantum_instance.is_statevector:
self.construct_circuit(measurement=False)
self._statevector_simulation()
else:
self.construct_circuit(measurement=False)
self._state_tomography()
# Adding a bit of general result information
self._ret["matrix"] = self._resize_matrix(self._matrix)
self._ret["vector"] = self._resize_vector(self._vector)
self._ret["circuit_info"] = circuit_to_dag(self._circuit).properties()
return self._ret
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
The Iterative Quantum Phase Estimation Algorithm.
See https://arxiv.org/abs/quant-ph/0610214
"""
import logging
import numpy as np
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.quantum_info import Pauli
from qiskit.aqua import Operator, AquaError
from qiskit.aqua import Pluggable, PluggableType, get_pluggable_class
from qiskit.aqua.utils import get_subsystem_density_matrix
from qiskit.aqua.algorithms import QuantumAlgorithm
logger = logging.getLogger(__name__)
class IQPE(QuantumAlgorithm):
"""
The Iterative Quantum Phase Estimation algorithm.
See https://arxiv.org/abs/quant-ph/0610214
"""
PROP_NUM_TIME_SLICES = 'num_time_slices'
PROP_EXPANSION_MODE = 'expansion_mode'
PROP_EXPANSION_ORDER = 'expansion_order'
PROP_NUM_ITERATIONS = 'num_iterations'
CONFIGURATION = {
'name': 'IQPE',
'description': 'Iterative Quantum Phase Estimation for Quantum Systems',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'IQPE_schema',
'type': 'object',
'properties': {
PROP_NUM_TIME_SLICES: {
'type': 'integer',
'default': 1,
'minimum': 1
},
PROP_EXPANSION_MODE: {
'type': 'string',
'default': 'suzuki',
'oneOf': [
{'enum': [
'suzuki',
'trotter'
]}
]
},
PROP_EXPANSION_ORDER: {
'type': 'integer',
'default': 2,
'minimum': 1
},
PROP_NUM_ITERATIONS: {
'type': 'integer',
'default': 1,
'minimum': 1
}
},
'additionalProperties': False
},
'problems': ['energy'],
'depends': [
{'pluggable_type': 'initial_state',
'default': {
'name': 'ZERO',
},
},
],
}
def __init__(self, operator, state_in, num_time_slices=1, num_iterations=1,
expansion_mode='suzuki', expansion_order=2,
shallow_circuit_concat=False):
"""
Constructor.
Args:
operator (Operator): the hamiltonian Operator object
state_in (InitialState): the InitialState pluggable component representing the initial quantum state
num_time_slices (int): the number of time slices
num_iterations (int): the number of iterations
expansion_mode (str): the expansion mode (trotter|suzuki)
expansion_order (int): the suzuki expansion order
shallow_circuit_concat (bool): indicate whether to use shallow (cheap) mode for circuit concatenation
"""
self.validate(locals())
super().__init__()
self._operator = operator
self._state_in = state_in
self._num_time_slices = num_time_slices
self._num_iterations = num_iterations
self._expansion_mode = expansion_mode
self._expansion_order = expansion_order
self._shallow_circuit_concat = shallow_circuit_concat
self._state_register = None
self._ancillary_register = None
self._pauli_list = None
self._ret = {}
self._setup()
@classmethod
def init_params(cls, params, algo_input):
"""
Initialize via parameters dictionary and algorithm input instance.
Args:
params: parameters dictionary
algo_input: EnergyInput instance
"""
if algo_input is None:
raise AquaError("EnergyInput instance is required.")
operator = algo_input.qubit_op
iqpe_params = params.get(Pluggable.SECTION_KEY_ALGORITHM)
num_time_slices = iqpe_params.get(IQPE.PROP_NUM_TIME_SLICES)
expansion_mode = iqpe_params.get(IQPE.PROP_EXPANSION_MODE)
expansion_order = iqpe_params.get(IQPE.PROP_EXPANSION_ORDER)
num_iterations = iqpe_params.get(IQPE.PROP_NUM_ITERATIONS)
# Set up initial state, we need to add computed num qubits to params
init_state_params = params.get(Pluggable.SECTION_KEY_INITIAL_STATE)
init_state_params['num_qubits'] = operator.num_qubits
init_state = get_pluggable_class(PluggableType.INITIAL_STATE,
init_state_params['name']).init_params(params)
return cls(operator, init_state, num_time_slices=num_time_slices, num_iterations=num_iterations,
expansion_mode=expansion_mode,
expansion_order=expansion_order)
def _setup(self):
self._pauli_list = self._operator.get_flat_pauli_list()
self._ret['translation'] = sum([abs(p[0]) for p in self._pauli_list])
self._ret['stretch'] = 0.5 / self._ret['translation']
# translate the operator
self._operator._simplify_paulis()
translation_op = Operator([
[
self._ret['translation'],
Pauli(
np.zeros(self._operator.num_qubits),
np.zeros(self._operator.num_qubits)
)
]
])
translation_op._simplify_paulis()
self._operator += translation_op
# stretch the operator
for p in self._pauli_list:
p[0] = p[0] * self._ret['stretch']
if len(self._pauli_list) == 1:
slice_pauli_list = self._pauli_list
else:
if self._expansion_mode == 'trotter':
slice_pauli_list = self._pauli_list
else:
slice_pauli_list = Operator._suzuki_expansion_slice_pauli_list(self._pauli_list, 1, self._expansion_order)
self._slice_pauli_list = slice_pauli_list
def construct_circuit(self, k=None, omega=0, measurement=False):
"""Construct the kth iteration Quantum Phase Estimation circuit.
For details of parameters, please see Fig. 2 in https://arxiv.org/pdf/quant-ph/0610214.pdf.
Args:
k (int): the iteration idx.
omega (float): the feedback angle.
measurement (bool): Boolean flag to indicate if measurement should be included in the circuit.
Returns:
QuantumCircuit: the quantum circuit per iteration
"""
k = self._num_iterations if k is None else k
a = QuantumRegister(1, name='a')
q = QuantumRegister(self._operator.num_qubits, name='q')
self._ancillary_register = a
self._state_register = q
qc = QuantumCircuit(q)
qc += self._state_in.construct_circuit('circuit', q)
# hadamard on a[0]
qc.add_register(a)
qc.u2(0, np.pi, a[0])
# controlled-U
qc_evolutions = Operator.construct_evolution_circuit(
self._slice_pauli_list, -2 * np.pi, self._num_time_slices, q, a, unitary_power=2 ** (k - 1),
shallow_slicing=self._shallow_circuit_concat
)
if self._shallow_circuit_concat:
qc.data += qc_evolutions.data
else:
qc += qc_evolutions
# global phase due to identity pauli
qc.u1(2 * np.pi * self._ancilla_phase_coef * (2 ** (k - 1)), a[0])
# rz on a[0]
qc.u1(omega, a[0])
# hadamard on a[0]
qc.u2(0, np.pi, a[0])
if measurement:
c = ClassicalRegister(1, name='c')
qc.add_register(c)
# qc.barrier(self._ancillary_register)
qc.measure(self._ancillary_register, c)
return qc
def _estimate_phase_iteratively(self):
"""Iteratively construct the different order of controlled evolution circuit to carry out phase estimation."""
self._ret['top_measurement_label'] = ''
omega_coef = 0
# k runs from the number of iterations back to 1
for k in range(self._num_iterations, 0, -1):
omega_coef /= 2
if self._quantum_instance.is_statevector:
qc = self.construct_circuit(k, -2 * np.pi * omega_coef, measurement=False)
result = self._quantum_instance.execute(qc)
complete_state_vec = result.get_statevector(qc)
ancilla_density_mat = get_subsystem_density_matrix(
complete_state_vec,
range(self._operator.num_qubits)
)
ancilla_density_mat_diag = np.diag(ancilla_density_mat)
max_amplitude = max(ancilla_density_mat_diag.min(), ancilla_density_mat_diag.max(), key=abs)
x = np.where(ancilla_density_mat_diag == max_amplitude)[0][0]
else:
qc = self.construct_circuit(k, -2 * np.pi * omega_coef, measurement=True)
measurements = self._quantum_instance.execute(qc).get_counts(qc)
if '0' not in measurements:
if '1' in measurements:
x = 1
else:
raise RuntimeError('Unexpected measurement {}.'.format(measurements))
else:
if '1' not in measurements:
x = 0
else:
x = 1 if measurements['1'] > measurements['0'] else 0
self._ret['top_measurement_label'] = '{}{}'.format(x, self._ret['top_measurement_label'])
omega_coef = omega_coef + x / 2
logger.info('Reverse iteration {} of {} with measured bit {}'.format(k, self._num_iterations, x))
return omega_coef
def _compute_energy(self):
# check for identify paulis to get its coef for applying global phase shift on ancilla later
num_identities = 0
self._pauli_list = self._operator.get_flat_pauli_list()
for p in self._pauli_list:
if np.all(np.logical_not(p[1].z)) and np.all(np.logical_not(p[1].x)):
num_identities += 1
if num_identities > 1:
raise RuntimeError('Multiple identity pauli terms are present.')
self._ancilla_phase_coef = p[0].real if isinstance(p[0], complex) else p[0]
self._ret['phase'] = self._estimate_phase_iteratively()
self._ret['top_measurement_decimal'] = sum([t[0] * t[1] for t in zip(
[1 / 2 ** p for p in range(1, self._num_iterations + 1)],
[int(n) for n in self._ret['top_measurement_label']]
)])
self._ret['energy'] = self._ret['phase'] / self._ret['stretch'] - self._ret['translation']
def _run(self):
self._compute_energy()
return self._ret
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
"""The following is python code utilizing the qiskit library that can be run on extant quantum
hardware using 5 qubits for factoring the integer 15 into 3 and 5. Using period finding,
for a^r mod N = 1, where a = 11 and N = 15 (the integer to be factored) the problem is to find
r values for this identity such that one can find the prime factors of N. For 11^r mod(15) =1,
results (as shown in fig 1.) correspond with period r = 4 (|00100>) and r = 0 (|00000>).
To find the factor, use the equivalence a^r mod 15. From this:
(a^r -1) mod 15 = (a^(r/2) + 1)(a^(r/2) - 1) mod 15.In this case, a = 11. Plugging in the two r
values for this a value yields (11^(0/2) +1)(11^(4/2) - 1) mod 15 = 2*(11 +1)(11-1) mod 15
Thus, we find (24)(20) mod 15. By finding the greatest common factor between the two coefficients,
gcd(24,15) and gcd(20,15), yields 3 and 5 respectively. These are the prime factors of 15,
so the result of running shors algorithm to find the prime factors of an integer using quantum
hardware are demonstrated. Note, this is not the same as the technical implementation of shor's
algorithm described in this section for breaking the discrete log hardness assumption,
though the proof of concept remains."""
# Import libraries
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from numpy import pi
from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.providers.ibmq import least_busy
from qiskit.visualization import plot_histogram
# Initialize qubit registers
qreg_q = QuantumRegister(5, 'q')
creg_c = ClassicalRegister(5, 'c')
circuit = QuantumCircuit(qreg_q, creg_c)
circuit.reset(qreg_q[0])
circuit.reset(qreg_q[1])
circuit.reset(qreg_q[2])
circuit.reset(qreg_q[3])
circuit.reset(qreg_q[4])
# Apply Hadamard transformations to qubit registers
circuit.h(qreg_q[0])
circuit.h(qreg_q[1])
circuit.h(qreg_q[2])
# Apply first QFT, modular exponentiation, and another QFT
circuit.h(qreg_q[1])
circuit.cx(qreg_q[2], qreg_q[3])
circuit.crx(pi/2, qreg_q[0], qreg_q[1])
circuit.ccx(qreg_q[2], qreg_q[3], qreg_q[4])
circuit.h(qreg_q[0])
circuit.rx(pi/2, qreg_q[2])
circuit.crx(pi/2, qreg_q[1], qreg_q[2])
circuit.crx(pi/2, qreg_q[1], qreg_q[2])
circuit.cx(qreg_q[0], qreg_q[1])
# Measure the qubit registers 0-2
circuit.measure(qreg_q[2], creg_c[2])
circuit.measure(qreg_q[1], creg_c[1])
circuit.measure(qreg_q[0], creg_c[0])
# Get least busy quantum hardware backend to run on
provider = IBMQ.load_account()
device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and
not x.configuration().simulator and x.status().operational==True))
print("Running on current least busy device: ", device)
# Run the circuit on available quantum hardware and plot histogram
from qiskit.tools.monitor import job_monitor
job = execute(circuit, backend=device, shots=1024, optimization_level=3)
job_monitor(job, interval = 2)
results = job.result()
answer = results.get_counts(circuit)
plot_histogram(answer)
#largest amplitude results correspond with r values used to find the prime factor of N.
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
"""Qiskit code for running Simon's algorithm on quantum hardware for 2 qubits and b = '11' """
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, execute
# import basic plot tools
from qiskit.visualization import plot_histogram
from qiskit_textbook.tools import simon_oracle
#set b equal to '11'
b = '11'
#1) initialize qubits
n = 2
simon_circuit_2 = QuantumCircuit(n*2, n)
#2) Apply Hadamard gates before querying the oracle
simon_circuit_2.h(range(n))
#3) Query oracle
simon_circuit_2 += simon_oracle(b)
#5) Apply Hadamard gates to the input register
simon_circuit_2.h(range(n))
#3) and 6) Measure qubits
simon_circuit_2.measure(range(n), range(n))
# Load saved IBMQ accounts and get the least busy backend device
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= n and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
# Execute and monitor the job
from qiskit.tools.monitor import job_monitor
shots = 1024
job = execute(simon_circuit_2, backend=backend, shots=shots, optimization_level=3)
job_monitor(job, interval = 2)
# Get results and plot counts
device_counts = job.result().get_counts()
plot_histogram(device_counts)
#additionally, function for calculating dot product of results
def bdotz(b, z):
accum = 0
for i in range(len(b)):
accum += int(b[i]) * int(z[i])
return (accum % 2)
print('b = ' + b)
for z in device_counts:
print( '{}.{} = {} (mod 2) ({:.1f}%)'.format(b, z, bdotz(b,z), device_counts[z]*100/shots))
#the most significant results are those for which b dot z=0(mod 2).
'''b = 11
11.00 = 0 (mod 2) (45.0%)
11.01 = 1 (mod 2) (6.2%)
11.10 = 1 (mod 2) (6.4%)
11.11 = 0 (mod 2) (42.4%)'''
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Boolean Logical DNF, CNF, and ESOP Circuits.
"""
import logging
from abc import abstractmethod, ABC
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.qasm import pi
from qiskit.aqua import AquaError
from .gates import mct
logger = logging.getLogger(__name__)
class BooleanLogicNormalForm(ABC):
@staticmethod
def _get_ast_depth(ast):
if ast[0] == 'const' or ast[0] == 'lit':
return 0
else:
return 1 + max([BooleanLogicNormalForm._get_ast_depth(c) for c in ast[1:]])
@staticmethod
def _get_ast_num_vars(ast):
if ast[0] == 'const':
return 0
all_vars = set()
def get_ast_vars(cur_ast):
if cur_ast[0] == 'lit':
all_vars.add(abs(cur_ast[1]))
else:
for c in cur_ast[1:]:
get_ast_vars(c)
get_ast_vars(ast)
return max(all_vars)
@staticmethod
def _lits_to_flags(vs):
_vs = []
for v in vs:
if v in _vs:
continue
elif -v in _vs:
return None
else:
_vs.append(v)
flags = abs(max(_vs, key=abs)) * [0]
for v in _vs:
flags[abs(v) - 1] = 1 if v > 0 else -1
return flags
"""
The base abstract class for:
- CNF (Conjunctive Normal Forms),
- DNF (Disjunctive Normal Forms), and
- ESOP (Exclusive Sum of Products)
"""
def __init__(self, ast, num_vars=None):
"""
Constructor.
Args:
ast (tuple): The logic expression as an Abstract Syntax Tree (AST) tuple
num_vars (int): Number of boolean variables
"""
ast_depth = BooleanLogicNormalForm._get_ast_depth(ast)
if ast_depth > 2:
raise AquaError('Expressions of depth greater than 2 are not supported.')
self._depth = ast_depth
inferred_num_vars = BooleanLogicNormalForm._get_ast_num_vars(ast)
if num_vars is None:
self._num_variables = inferred_num_vars
else:
if inferred_num_vars > num_vars:
raise AquaError('{} variables present, but only {} specified.'.format(inferred_num_vars, num_vars))
self._num_variables = num_vars
if ast_depth == 0:
self._ast = ast
self._num_clauses = 0
self._max_clause_size = 0
else:
if ast_depth == 1:
if self._depth == 1:
self._num_clauses = 1
self._max_clause_size = len(ast) - 1
self._ast = ast
else: # depth == 2:
if ast[0] == 'and':
op = 'or'
elif ast[0] == 'or':
op = 'and'
else:
raise AquaError('Unexpected expression root operator {}.'.format(ast[0]))
self._num_clauses = len(ast) - 1
self._max_clause_size = 1
self._ast = (ast[0], *[(op, l) for l in ast[1:]])
else: # self._depth == 2
self._num_clauses = len(ast) - 1
self._max_clause_size = max([len(l) - 1 for l in ast[1:]])
self._ast = ast
self._variable_register = None
self._clause_register = None
self._output_register = None
self._ancillary_register = None
@property
def num_variables(self):
return self._num_variables
@property
def num_clauses(self):
return self._num_clauses
@property
def variable_register(self):
return self._variable_register
@property
def clause_register(self):
return self._clause_register
@property
def output_register(self):
return self._output_register
@property
def ancillary_register(self):
return self._ancillary_register
@staticmethod
def _set_up_register(num_qubits_needed, provided_register, description):
if provided_register == 'skip':
return None
else:
if provided_register is None:
if num_qubits_needed > 0:
return QuantumRegister(num_qubits_needed, name=description[0])
else:
num_qubits_provided = len(provided_register)
if num_qubits_needed > num_qubits_provided:
raise ValueError(
'The {} QuantumRegister needs {} qubits, but the provided register contains only {}.'.format(
description, num_qubits_needed, num_qubits_provided
))
else:
return provided_register
def _set_up_circuit(
self,
circuit=None,
variable_register=None,
clause_register=None,
output_register=None,
output_idx=None,
ancillary_register=None,
mct_mode='basic'
):
self._variable_register = BooleanLogicNormalForm._set_up_register(
self.num_variables, variable_register, 'variable'
)
if self._depth > 1:
self._clause_register = BooleanLogicNormalForm._set_up_register(
self.num_clauses, clause_register, 'clause'
)
self._output_register = BooleanLogicNormalForm._set_up_register(
1, output_register, 'output'
)
self._output_idx = output_idx if output_idx else 0
max_num_ancillae = max(
max(
self._num_clauses if self._clause_register else 0,
self._max_clause_size
) - 2,
0
)
num_ancillae = 0
if mct_mode == 'basic' or mct_mode == 'basic-dirty-ancilla':
num_ancillae = max_num_ancillae
elif mct_mode == 'advanced':
if max_num_ancillae >= 3:
num_ancillae = 1
elif mct_mode == 'noancilla':
pass
else:
raise ValueError('Unsupported MCT mode {}.'.format(mct_mode))
self._ancillary_register = BooleanLogicNormalForm._set_up_register(
num_ancillae, ancillary_register, 'ancilla'
)
if circuit is None:
circuit = QuantumCircuit()
if self._variable_register:
circuit.add_register(self._variable_register)
if self._clause_register:
circuit.add_register(self._clause_register)
if self._output_register:
circuit.add_register(self._output_register)
if self._ancillary_register:
circuit.add_register(self._ancillary_register)
return circuit
def _construct_circuit_for_tiny_expr(self, circuit, output_idx=0):
if self._ast == ('const', 1):
circuit.u3(pi, 0, pi, self._output_register[output_idx])
elif self._ast[0] == 'lit':
idx = abs(self._ast[1]) - 1
if self._ast[1] < 0:
circuit.u3(pi, 0, pi, self._variable_register[idx])
circuit.cx(self._variable_register[idx], self._output_register[output_idx])
@abstractmethod
def construct_circuit(self, *args, **kwargs):
raise NotImplementedError
class CNF(BooleanLogicNormalForm):
"""
Class for constructing circuits for Conjunctive Normal Forms
"""
def construct_circuit(
self,
circuit=None,
variable_register=None,
clause_register=None,
output_register=None,
ancillary_register=None,
mct_mode='basic'
):
"""
Construct circuit.
Args:
circuit (QuantumCircuit): The optional circuit to extend from
variable_register (QuantumRegister): The optional quantum register to use for problem variables
clause_register (QuantumRegister): The optional quantum register to use for problem clauses
output_register (QuantumRegister): The optional quantum register to use for holding the output
ancillary_register (QuantumRegister): The optional quantum register to use as ancilla
mct_mode (str): The mode to use for building Multiple-Control Toffoli
Returns:
QuantumCircuit: quantum circuit.
"""
circuit = self._set_up_circuit(
circuit=circuit,
variable_register=variable_register,
clause_register=clause_register,
output_register=output_register,
ancillary_register=ancillary_register,
mct_mode=mct_mode
)
if self._depth == 0:
self._construct_circuit_for_tiny_expr(circuit)
elif self._depth == 1:
lits = [l[1] for l in self._ast[1:]]
flags = BooleanLogicNormalForm._lits_to_flags(lits)
circuit.AND(
self._variable_register,
self._output_register[0],
self._ancillary_register,
flags=flags,
mct_mode=mct_mode
)
else: # self._depth == 2:
# compute all clauses
for clause_index, clause_expr in enumerate(self._ast[1:]):
if clause_expr[0] == 'or':
lits = [l[1] for l in clause_expr[1:]]
elif clause_expr[0] == 'lit':
lits = [clause_expr[1]]
else:
raise AquaError(
'Operator "{}" of clause {} in logic expression {} is unexpected.'.format(
clause_expr[0], clause_index, self._ast)
)
flags = BooleanLogicNormalForm._lits_to_flags(lits)
circuit.OR(
self._variable_register,
self._clause_register[clause_index],
self._ancillary_register,
flags=flags,
mct_mode=mct_mode
)
# collect results from all clauses
circuit.mct(
self._clause_register,
self._output_register[self._output_idx],
self._ancillary_register,
mode=mct_mode
)
# uncompute all clauses
for clause_index, clause_expr in enumerate(self._ast[1:]):
if clause_expr[0] == 'or':
lits = [l[1] for l in clause_expr[1:]]
else: # clause_expr[0] == 'lit':
lits = [clause_expr[1]]
flags = BooleanLogicNormalForm._lits_to_flags(lits)
circuit.OR(
self._variable_register,
self._clause_register[clause_index],
self._ancillary_register,
flags=flags,
mct_mode=mct_mode
)
return circuit
class DNF(BooleanLogicNormalForm):
"""
Class for constructing circuits for Disjunctive Normal Forms
"""
def construct_circuit(
self,
circuit=None,
variable_register=None,
clause_register=None,
output_register=None,
ancillary_register=None,
mct_mode='basic'
):
"""
Construct circuit.
Args:
circuit (QuantumCircuit): The optional circuit to extend from
variable_register (QuantumRegister): The optional quantum register to use for problem variables
clause_register (QuantumRegister): The optional quantum register to use for problem clauses
output_register (QuantumRegister): The optional quantum register to use for holding the output
ancillary_register (QuantumRegister): The optional quantum register to use as ancilla
mct_mode (str): The mode to use for building Multiple-Control Toffoli
Returns:
QuantumCircuit: quantum circuit.
"""
circuit = self._set_up_circuit(
circuit=circuit,
variable_register=variable_register,
clause_register=clause_register,
output_register=output_register,
ancillary_register=ancillary_register,
mct_mode=mct_mode
)
if self._depth == 0:
self._construct_circuit_for_tiny_expr(circuit)
elif self._depth == 1:
lits = [l[1] for l in self._ast[1:]]
flags = BooleanLogicNormalForm._lits_to_flags(lits)
circuit.OR(
self._variable_register,
self._output_register[0],
self._ancillary_register,
flags=flags,
mct_mode=mct_mode
)
else: # self._depth == 2
# compute all clauses
for clause_index, clause_expr in enumerate(self._ast[1:]):
if clause_expr[0] == 'and':
lits = [l[1] for l in clause_expr[1:]]
elif clause_expr[0] == 'lit':
lits = [clause_expr[1]]
else:
raise AquaError(
'Operator "{}" of clause {} in logic expression {} is unexpected.'.format(
clause_expr[0], clause_index, self._ast)
)
flags = BooleanLogicNormalForm._lits_to_flags(lits)
circuit.AND(
self._variable_register,
self._clause_register[clause_index],
self._ancillary_register,
flags=flags,
mct_mode=mct_mode
)
# init the output qubit to 1
circuit.u3(pi, 0, pi, self._output_register[self._output_idx])
# collect results from all clauses
circuit.u3(pi, 0, pi, self._clause_register)
circuit.mct(
self._clause_register,
self._output_register[self._output_idx],
self._ancillary_register,
mode=mct_mode
)
circuit.u3(pi, 0, pi, self._clause_register)
# uncompute all clauses
for clause_index, clause_expr in enumerate(self._ast[1:]):
if clause_expr[0] == 'and':
lits = [l[1] for l in clause_expr[1:]]
else: # clause_expr[0] == 'lit':
lits = [clause_expr[1]]
flags = BooleanLogicNormalForm._lits_to_flags(lits)
circuit.AND(
self._variable_register,
self._clause_register[clause_index],
self._ancillary_register,
flags=flags,
mct_mode=mct_mode
)
return circuit
class ESOP(BooleanLogicNormalForm):
"""
Class for constructing circuits for Exclusive Sum of Products
"""
def construct_circuit(
self,
circuit=None,
variable_register=None,
output_register=None,
output_idx=None,
ancillary_register=None,
mct_mode='basic'
):
"""
Construct circuit.
Args:
circuit (QuantumCircuit): The optional circuit to extend from
variable_register (QuantumRegister): The optional quantum register to use for problem variables
output_register (QuantumRegister): The optional quantum register to use for holding the output
output_idx (int): The index of the output register to write to
ancillary_register (QuantumRegister): The optional quantum register to use as ancilla
mct_mode (str): The mode to use for building Multiple-Control Toffoli
Returns:
QuantumCircuit: quantum circuit.
"""
circuit = self._set_up_circuit(
circuit=circuit,
variable_register=variable_register,
clause_register='skip',
output_register=output_register,
output_idx=output_idx,
ancillary_register=ancillary_register,
mct_mode=mct_mode
)
# compute all clauses
if self._depth == 0:
self._construct_circuit_for_tiny_expr(circuit, output_idx=output_idx)
else:
for clause_index, clause_expr in enumerate(self._ast[1:]):
if clause_expr[0] == 'and':
lits = [l[1] for l in clause_expr[1:]]
else: # clause_expr[0] == 'lit':
lits = [clause_expr[1]]
flags = BooleanLogicNormalForm._lits_to_flags(lits)
circuit.AND(
self._variable_register,
self._output_register[self._output_idx],
self._ancillary_register,
flags=flags,
mct_mode=mct_mode
)
return circuit
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Quantum Fourier Transform Circuit.
"""
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.aqua import AquaError
from qiskit.aqua.utils.circuit_utils import is_qubit_list
class FourierTransformCircuits:
@staticmethod
def _do_swaps(circuit, qubits):
num_qubits = len(qubits)
for i in range(num_qubits // 2):
circuit.cx(qubits[i], qubits[num_qubits - i - 1])
circuit.cx(qubits[num_qubits - i - 1], qubits[i])
circuit.cx(qubits[i], qubits[num_qubits - i - 1])
@staticmethod
def construct_circuit(
circuit=None,
qubits=None,
inverse=False,
approximation_degree=0,
do_swaps=True
):
"""
Construct the circuit representing the desired state vector.
Args:
circuit (QuantumCircuit): The optional circuit to extend from.
qubits (QuantumRegister | list of qubits): The optional qubits to construct the circuit with.
approximation_degree (int): degree of approximation for the desired circuit
inverse (bool): Boolean flag to indicate Inverse Quantum Fourier Transform
do_swaps (bool): Boolean flag to specify if swaps should be included to align the qubit order of
input and output. The output qubits would be in reversed order without the swaps.
Returns:
QuantumCircuit.
"""
if circuit is None:
raise AquaError('Missing input QuantumCircuit.')
if qubits is None:
raise AquaError('Missing input qubits.')
else:
if isinstance(qubits, QuantumRegister):
if not circuit.has_register(qubits):
circuit.add_register(qubits)
elif is_qubit_list(qubits):
for qubit in qubits:
if not circuit.has_register(qubit[0]):
circuit.add_register(qubit[0])
else:
raise AquaError('A QuantumRegister or a list of qubits is expected for the input qubits.')
if do_swaps and not inverse:
FourierTransformCircuits._do_swaps(circuit, qubits)
qubit_range = reversed(range(len(qubits))) if inverse else range(len(qubits))
for j in qubit_range:
neighbor_range = range(np.max([0, j - len(qubits) + approximation_degree + 1]), j)
if inverse:
neighbor_range = reversed(neighbor_range)
circuit.u2(0, np.pi, qubits[j])
for k in neighbor_range:
lam = 1.0 * np.pi / float(2 ** (j - k))
if inverse:
lam *= -1
circuit.u1(lam / 2, qubits[j])
circuit.cx(qubits[j], qubits[k])
circuit.u1(-lam / 2, qubits[k])
circuit.cx(qubits[j], qubits[k])
circuit.u1(lam / 2, qubits[k])
if not inverse:
circuit.u2(0, np.pi, qubits[j])
if do_swaps and inverse:
FourierTransformCircuits._do_swaps(circuit, qubits)
return circuit
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Quantum Phase Estimation Circuit.
"""
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit.aqua import Operator, AquaError
class PhaseEstimationCircuit:
def __init__(
self,
operator=None,
state_in=None,
iqft=None,
num_time_slices=1,
num_ancillae=1,
expansion_mode='trotter',
expansion_order=1,
evo_time=2*np.pi,
state_in_circuit_factory=None,
unitary_circuit_factory=None,
shallow_circuit_concat=False,
pauli_list=None
):
"""
Constructor.
Args:
operator (Operator): the hamiltonian Operator object
state_in (InitialState): the InitialState pluggable component representing the initial quantum state
iqft (IQFT): the Inverse Quantum Fourier Transform pluggable component
num_time_slices (int): the number of time slices
num_ancillae (int): the number of ancillary qubits to use for the measurement
expansion_mode (str): the expansion mode (trotter|suzuki)
expansion_order (int): the suzuki expansion order
evo_time (float): the evolution time
state_in_circuit_factory (CircuitFactory): the initial state represented by a CircuitFactory object
unitary_circuit_factory (CircuitFactory): the problem unitary represented by a CircuitFactory object
shallow_circuit_concat (bool): indicate whether to use shallow (cheap) mode for circuit concatenation
pauli_list ([Pauli]): the flat list of paulis for the operator
"""
if (
operator is not None and unitary_circuit_factory is not None
) or (
operator is None and unitary_circuit_factory is None
):
raise AquaError('Please supply either an operator or a unitary circuit factory but not both.')
self._operator = operator
if operator is not None:
self._pauli_list = operator.get_flat_pauli_list() if pauli_list is None else pauli_list
self._unitary_circuit_factory = unitary_circuit_factory
self._state_in = state_in
self._state_in_circuit_factory = state_in_circuit_factory
self._iqft = iqft
self._num_time_slices = num_time_slices
self._num_ancillae = num_ancillae
self._expansion_mode = expansion_mode
self._expansion_order = expansion_order
self._evo_time = evo_time
self._shallow_circuit_concat = shallow_circuit_concat
self._ancilla_phase_coef = 1
self._state_register = None
self._ancillary_register = None
self._auxiliary_register = None
self._circuit = None
def construct_circuit(
self,
state_register=None,
ancillary_register=None,
auxiliary_register=None,
measurement=False,
):
"""
Construct the Phase Estimation circuit
Args:
state_register (QuantumRegister): the optional register to use for the quantum state
ancillary_register (QuantumRegister): the optional register to use for the ancillary measurement qubits
auxiliary_register (QuantumRegister): an optional auxiliary quantum register
measurement (bool): Boolean flag to indicate if measurement should be included in the circuit.
Returns:
the QuantumCircuit object for the constructed circuit
"""
if self._circuit is None:
if ancillary_register is None:
a = QuantumRegister(self._num_ancillae, name='a')
else:
a = ancillary_register
self._ancillary_register = a
if state_register is None:
if self._operator is not None:
q = QuantumRegister(self._operator.num_qubits, name='q')
elif self._unitary_circuit_factory is not None:
q = QuantumRegister(self._unitary_circuit_factory.num_target_qubits, name='q')
else:
raise RuntimeError('Missing operator specification.')
else:
q = state_register
self._state_register = q
qc = QuantumCircuit(a, q)
if auxiliary_register is None:
num_aux_qubits, aux = 0, None
if self._state_in_circuit_factory is not None:
num_aux_qubits = self._state_in_circuit_factory.required_ancillas()
if self._unitary_circuit_factory is not None:
num_aux_qubits = max(num_aux_qubits, self._unitary_circuit_factory.required_ancillas_controlled())
if num_aux_qubits > 0:
aux = QuantumRegister(num_aux_qubits, name='aux')
qc.add_register(aux)
else:
aux = auxiliary_register
qc.add_register(aux)
# initialize state_in
if self._state_in is not None:
qc.data += self._state_in.construct_circuit('circuit', q).data
elif self._state_in_circuit_factory is not None:
self._state_in_circuit_factory.build(qc, q, aux)
# Put all ancillae in uniform superposition
qc.u2(0, np.pi, a)
# phase kickbacks via dynamics
if self._operator is not None:
# check for identify paulis to get its coef for applying global phase shift on ancillae later
num_identities = 0
for p in self._pauli_list:
if np.all(np.logical_not(p[1].z)) and np.all(np.logical_not(p[1].x)):
num_identities += 1
if num_identities > 1:
raise RuntimeError('Multiple identity pauli terms are present.')
self._ancilla_phase_coef = p[0].real if isinstance(p[0], complex) else p[0]
if len(self._pauli_list) == 1:
slice_pauli_list = self._pauli_list
else:
if self._expansion_mode == 'trotter':
slice_pauli_list = self._pauli_list
elif self._expansion_mode == 'suzuki':
slice_pauli_list = Operator._suzuki_expansion_slice_pauli_list(
self._pauli_list,
1,
self._expansion_order
)
else:
raise ValueError('Unrecognized expansion mode {}.'.format(self._expansion_mode))
for i in range(self._num_ancillae):
qc_evolutions = Operator.construct_evolution_circuit(
slice_pauli_list, -self._evo_time,
self._num_time_slices, q, a, ctl_idx=i,
shallow_slicing=self._shallow_circuit_concat
)
if self._shallow_circuit_concat:
qc.data += qc_evolutions.data
else:
qc += qc_evolutions
# global phase shift for the ancilla due to the identity pauli term
qc.u1(self._evo_time * self._ancilla_phase_coef * (2 ** i), a[i])
elif self._unitary_circuit_factory is not None:
for i in range(self._num_ancillae):
self._unitary_circuit_factory.build_controlled_power(qc, q, a[i], 2 ** i, aux)
# inverse qft on ancillae
self._iqft.construct_circuit(mode='circuit', qubits=a, circuit=qc, do_swaps=False)
if measurement:
c_ancilla = ClassicalRegister(self._num_ancillae, name='ca')
qc.add_register(c_ancilla)
# qc.barrier(a)
qc.measure(a, c_ancilla)
self._circuit = qc
return self._circuit
@property
def state_register(self):
return self._state_register
@property
def ancillary_register(self):
return self._ancillary_register
@property
def auxiliary_register(self):
return self._auxiliary_register
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Arbitrary State-Vector Circuit.
"""
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.aqua import AquaError
from qiskit.aqua.utils.arithmetic import normalize_vector, is_power_of_2, log2
from qiskit.aqua.utils.circuit_utils import convert_to_basis_gates
class StateVectorCircuit:
def __init__(self, state_vector):
"""Constructor.
Args:
state_vector: vector representation of the desired quantum state
"""
if not is_power_of_2(len(state_vector)):
raise AquaError('The length of the input state vector needs to be a power of 2.')
self._num_qubits = log2(len(state_vector))
self._state_vector = normalize_vector(state_vector)
def construct_circuit(self, circuit=None, register=None):
"""
Construct the circuit representing the desired state vector.
Args:
circuit (QuantumCircuit): The optional circuit to extend from.
register (QuantumRegister): The optional register to construct the circuit with.
Returns:
QuantumCircuit.
"""
if register is None:
register = QuantumRegister(self._num_qubits, name='q')
# in case the register is a list of qubits
if type(register) is list:
# create empty circuit if necessary
if circuit is None:
circuit = QuantumCircuit()
# loop over all qubits and add the required registers
for q in register:
if not circuit.has_register(q[0]):
circuit.add_register(q[0])
# construct state initialization circuit
temp = QuantumCircuit(*circuit.qregs)
# otherwise, if it is a real register
else:
if len(register) < self._num_qubits:
raise AquaError('The provided register does not have enough qubits.')
if circuit is None:
circuit = QuantumCircuit(register)
else:
if not circuit.has_register(register):
circuit.add_register(register)
# TODO: add capability to start in the middle of the register
temp = QuantumCircuit(register)
temp.initialize(self._state_vector, [register[i] for i in range(self._num_qubits)])
temp = convert_to_basis_gates(temp)
# remove the reset gates terra's unroller added
temp.data = [g for g in temp.data if not g[0].name == 'reset']
circuit += temp
return circuit
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.