repo
stringclasses 900
values | file
stringclasses 754
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/usamisaori/Grover
|
usamisaori
|
import math
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.pyplot import arrow
from mpl_toolkits.axisartist.axislines import SubplotZero
from matplotlib.patches import Arc
%matplotlib inline
import warnings
warnings.filterwarnings('ignore')
def get_line_plot(angle, *, linewidth=1, linestyle="-", color="black"):
angle = math.radians(angle)
return Line2D([0, math.cos(angle) * 0.92], [0, math.sin(angle) * 0.92],
linewidth=linewidth, linestyle=linestyle, color=color)
def get_angle_plot(line1, line2, *, offset=1, color=None, origin=(0, 0),
len_x_axis = 1, len_y_axis = 1):
l1xy = line1.get_xydata()
# Angle between line1 and x-axis
y1 = l1xy[1][1] - l1xy[0][1]
x1 = l1xy[1][0] - l1xy[0][0]
slope1 = y1 / float(x1)
# Allows you to use this in different quadrants
angle1 = math.degrees(math.atan2(y1, x1))
l2xy = line2.get_xydata()
# Angle between line2 and x-axis
y2 = l2xy[1][1] - l2xy[0][1]
x2 = l2xy[1][0] - l2xy[0][0]
slope2 = y2 / float(x2)
angle2 = math.degrees(math.atan2(y2, x2))
theta1 = min(angle1, angle2)
theta2 = max(angle1, angle2)
angle = theta2 - theta1
if angle > 180:
angle = 360 - angle
theta1 = 360 + theta1
if theta1 > theta2:
theta1, theta2 = theta2, theta1
if color is None:
color = line1.get_color() # Uses the color of line 1 if color parameter is not passed.
return Arc(origin, len_x_axis*offset, len_y_axis*offset, 0,
theta1, theta2, color=color,
label = r'${:.4}^\circ$'.format(float(angle)))
def get_angle_text(angle_plot):
angle = angle_plot.get_label()
# angle = r'${:.4}^\circ$'.format(angle) # Display angle upto 2 decimal places
# Get the vertices of the angle arc
vertices = angle_plot.get_verts()
# Get the midpoint of the arc extremes
x_width = (vertices[0][0] + vertices[-1][0]) / 2.0
y_width = (vertices[0][1] + vertices[-1][1]) / 2.0
separation_radius = max(x_width / 2.0, y_width / 2.0)
return [x_width + separation_radius, y_width + separation_radius, angle]
class AnglePoltter:
def __init__(self):
self.lines = []
self.arcs = []
self.angles = []
def add_line(self, angle, *, linewidth=1, linestyle="-", color="black"):
line = get_line_plot(angle, linewidth=linewidth, linestyle=linestyle, color=color)
self.lines.append(
[
line.get_xdata()[0], line.get_ydata()[0], line.get_xdata()[1], line.get_ydata()[1],
linewidth, linestyle, color
]
)
return line
def add_angle(self, line1, line2, *, text=False, **kwargs):
angle = get_angle_plot(line1, line2, **kwargs)
self.arcs.append(angle)
if text:
self.angles.append(get_angle_text(angle))
def plot(self, *, title, fontsize=18):
fig = plt.figure()
ax = SubplotZero(fig, 1, 1, 1)
# draw a circle
theta = np.linspace(0, 2 * np.pi, 200)
x = np.cos(theta)
y = np.sin(theta)
ax.plot(x, y, color="#CCCCCC", linewidth=1.5)
fig.add_subplot(ax)
for direction in ["left", "right", "bottom", "top"]:
# hides borders
ax.axis[direction].set_visible(False)
for direction in ["xzero", "yzero"]:
# adds arrows at the ends of each axis
ax.axis[direction].set_axisline_style('-|>')
# adds X and Y-axis from the origin
ax.axis[direction].set_visible(True)
for line in self.lines:
if line[4] != 0:
ax.arrow(line[0], line[1], line[2], line[3],
head_width=0.06, head_length=0.06,
linewidth=line[4], linestyle=line[5], color=line[6])
for arc in self.arcs:
ax.add_patch(arc)
for angle in self.angles:
ax.text(*angle)
if title != None:
fig.suptitle(title, fontsize=fontsize)
plt.axis([-1.8, 1.8, -1.35, 1.35])
plt.grid()
plt.legend()
return ax
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(30, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.5, text=True)
ax = plotter.plot(title="Initial state")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(30, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(330, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
ax = plotter.plot(title="After applying Oracle")
x = math.cos(math.radians(30))
y = math.sin(math.radians(30))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(30, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(330, linewidth=1.5, linestyle="-.", color="#99CC33")
line_3 = plotter.add_line(90, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
ax = plotter.plot(title="After one Grover iteration")
x = math.cos(math.radians(30))
y = math.sin(math.radians(30))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, 0], [-y, 1], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x * 1.2, 0], [-y * 1.2, 0], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x * 1.2], [y, y * 1.2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(30, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(330, linewidth=1.5, linestyle="-.", color="#99CC33")
line_3 = plotter.add_line(90, linewidth=1.5, color="#99CCFF")
line_4 = plotter.add_line(-90, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
plotter.add_angle(line_4, x, offset=0.8)
ax = plotter.plot(title="Apply Oracle(second iteration)")
x = math.cos(math.radians(30))
y = math.sin(math.radians(30))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, 0], [-y, 1], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x * 1.2, 0], [-y * 1.2, 0], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x * 1.2], [y, y * 1.2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(30, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(330, linewidth=1.5, linestyle="-.", color="#99CC33")
line_3 = plotter.add_line(90, linewidth=1.5, color="#99CCFF")
line_4 = plotter.add_line(-90, linewidth=1.5, color="#FF9900")
line_5 = plotter.add_line(150, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
plotter.add_angle(line_4, x, offset=0.8)
plotter.add_angle(line_5, line_3, offset=0.6)
ax = plotter.plot(title="Apply Oracle(second iteration)")
x = math.cos(math.radians(30))
y = math.sin(math.radians(30))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, 0], [-y, 1], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x, 0], [y, -1], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x * 1.2, 0], [-y * 1.2, 0], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x * 1.2], [y, y * 1.2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
theta = math.degrees(math.asin(1/(8 ** 0.5)))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(theta, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.5, text=True)
ax = plotter.plot(title="Initial state")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(theta, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(-theta, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
ax = plotter.plot(title="After applying Oracle")
x = math.cos(math.radians(theta))
y = math.sin(math.radians(theta))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(theta, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(-theta, linewidth=1.5, linestyle="-.", color="#99CC33")
line_3 = plotter.add_line(3 * theta, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
ax = plotter.plot(title="After one Grover iteration")
x = math.cos(math.radians(theta))
y = math.sin(math.radians(theta))
x2 = math.cos(math.radians(3 * theta))
y2 = math.sin(math.radians(3 * theta))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x2], [-y, y2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x * 1.2, 0], [-y * 1.2, 0], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x * 1.2], [y, y * 1.2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(theta, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(-theta, linewidth=1.5, linestyle="-.", color="#99CC33")
line_3 = plotter.add_line(3 * theta, linewidth=1.5, color="#99CCFF")
line_4 = plotter.add_line(5 * theta, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
plotter.add_angle(line_4, line_3, offset=0.6)
ax = plotter.plot(title="After two Grover iteration")
x = math.cos(math.radians(theta))
y = math.sin(math.radians(theta))
x2 = math.cos(math.radians(3 * theta))
y2 = math.sin(math.radians(3 * theta))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x2], [-y, y2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x * 1.2, 0], [-y * 1.2, 0], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x * 1.2], [y, y * 1.2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(theta, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(-theta, linewidth=1.5, linestyle="-.", color="#99CC33")
line_3 = plotter.add_line(3 * theta, linewidth=1.5, color="#99CCFF")
line_4 = plotter.add_line(5 * theta, linewidth=1.5, color="#FF9900")
line_5 = plotter.add_line(7 * theta, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
plotter.add_angle(line_4, line_3, offset=0.6)
plotter.add_angle(line_5, line_4, offset=0.6)
ax = plotter.plot(title="After two Grover iteration")
x = math.cos(math.radians(theta))
y = math.sin(math.radians(theta))
x2 = math.cos(math.radians(3 * theta))
y2 = math.sin(math.radians(3 * theta))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x2], [-y, y2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x * 1.2, 0], [-y * 1.2, 0], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x * 1.2], [y, y * 1.2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.5, text=True)
ax = plotter.plot(title="Initial state")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, linestyle="-.", color="#99CC33")
line_2 = plotter.add_line(-45, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
ax = plotter.plot(title="After applying Oracle")
x = math.cos(math.radians(45))
y = math.sin(math.radians(45))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, linestyle="-.", color="#99CC33")
line_2 = plotter.add_line(-45, linewidth=1.5, linestyle="-.", color="#99CCFF")
line_3 = plotter.add_line(3 * 45, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
ax = plotter.plot(title="After one Grover iteration")
x = math.cos(math.radians(45))
y = math.sin(math.radians(45))
x2 = math.cos(math.radians(3 * 45))
y2 = math.sin(math.radians(3 * 45))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x * 1.2, 0], [-y * 1.2, 0], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x * 1.2], [y, y * 1.2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, linestyle="-.", color="#99CC33")
line_2 = plotter.add_line(-45, linewidth=1.5, linestyle="-.", color="#99CCFF")
line_3 = plotter.add_line(3 * 45, linewidth=1.5, color="#FF9900")
line_4 = plotter.add_line(5 * 45, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
plotter.add_angle(line_4, line_3, offset=0.6)
ax = plotter.plot(title="After two Grover iteration")
x = math.cos(math.radians(45))
y = math.sin(math.radians(45))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_s = plotter.add_line(40, linewidth=2, color="#6666CC")
line_phi = plotter.add_line(25, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_s, x, offset=0.6)
plotter.add_angle(line_phi, x, offset=0.4)
plotter.plot(title="Grover reflections - initial state")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_s = plotter.add_line(40, linewidth=2, color="#6666CC")
line_phi = plotter.add_line(25, linewidth=1.5, linestyle=":", color="#99CC33")
line_O_phi = plotter.add_line(335, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_s, x, offset=0.6)
plotter.add_angle(line_phi, x, offset=0.4)
plotter.add_angle(line_O_phi, x, offset=0.4)
ax = plotter.plot(title="Grover reflections - reflection 1")
x = math.cos(math.radians(25))
y = math.sin(math.radians(25))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_s = plotter.add_line(40, linewidth=2, color="#6666CC")
line_phi = plotter.add_line(25, linewidth=1.5, linestyle=":", color="#99CC33")
line_O_phi = plotter.add_line(335, linewidth=1.5, linestyle=":", color="#99CCFF")
line_RO_phi = plotter.add_line(285, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_s, x, offset=0.8)
plotter.add_angle(line_phi, x, offset=0.6)
plotter.add_angle(line_O_phi, x, offset=0.6)
plotter.add_angle(line_RO_phi, x, offset=0.4)
ax = plotter.plot(title="Grover reflections - reflection 2")
x1 = math.cos(math.radians(25))
y1 = math.sin(math.radians(25))
ax.add_line(Line2D([x1, x1], [-y1, y1], linewidth=1.5, linestyle="--", color="#CCCCCC"))
x2 = math.cos(math.radians(-75))
y2 = math.sin(math.radians(-75))
ax.add_line(Line2D([x1, x2], [-y1, y2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
x3 = math.cos(math.radians(130)) * 1.5
y3 = math.sin(math.radians(130)) * 1.5
ax.add_line(Line2D([x3, -x3], [y3, -y3], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_s = plotter.add_line(40, linewidth=2, color="#6666CC")
line_phi = plotter.add_line(25, linewidth=1.5, linestyle=":", color="#99CC33")
line_O_phi = plotter.add_line(335, linewidth=1.5, linestyle=":", color="#99CCFF")
line_RO_phi = plotter.add_line(285, linewidth=1.5, linestyle=":", color="#FF9900")
line_mRO_phi = plotter.add_line(105, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_s, x, offset=0.8)
plotter.add_angle(line_phi, x, offset=0.6)
plotter.add_angle(line_O_phi, x, offset=0.6)
plotter.add_angle(line_RO_phi, x, offset=0.4)
plotter.add_angle(line_mRO_phi, line_phi, offset=1)
ax = plotter.plot(title="Grover reflections - reflection3")
x1 = math.cos(math.radians(25))
y1 = math.sin(math.radians(25))
ax.add_line(Line2D([x1, x1], [-y1, y1], linewidth=1.5, linestyle="--", color="#CCCCCC"))
x2 = math.cos(math.radians(-75))
y2 = math.sin(math.radians(-75))
ax.add_line(Line2D([x1, x2], [-y1, y2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
x3 = math.cos(math.radians(130)) * 1.5
y3 = math.sin(math.radians(130)) * 1.5
ax.add_line(Line2D([x3, -x3], [y3, -y3], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.5, text=True)
ax = plotter.plot(title="Initial state")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, linestyle="-.", color="#99CCFF")
line_2 = plotter.add_line(-2, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
ax = plotter.plot(title="After applying Oracle")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, linestyle="-.", color="#99CCFF")
line_2 = plotter.add_line(-2, linewidth=1.5, linestyle="-.", color="#FF9900")
line_3 = plotter.add_line(92, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
ax = plotter.plot(title="After one Grover iteration")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.5, text=True)
ax = plotter.plot(title="Initial state")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, linestyle="-.", color="#99CCFF")
line_2 = plotter.add_line(40, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
ax = plotter.plot(title="After applying Oracle")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, linestyle="-.", color="#99CCFF")
line_2 = plotter.add_line(40, linewidth=1.5, linestyle="-.", color="#FF9900")
line_3 = plotter.add_line(50, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
ax = plotter.plot(title="After one Grover iteration")
|
https://github.com/usamisaori/Grover
|
usamisaori
|
import qiskit
from qiskit import QuantumCircuit
from qiskit.visualization import plot_histogram
import numpy as np
from qiskit import execute, Aer
simulator = Aer.get_backend('qasm_simulator')
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
from qiskit.quantum_info import DensityMatrix, Statevector, Operator
def getDensityMatrix(circuit):
return DensityMatrix(circuit).data
from functools import reduce
Dag = lambda matrix: matrix.conj().T
Kron = lambda *matrices: reduce(np.kron, matrices)
def pm(matrix):
for row in range(len(matrix)):
for col in range (len(matrix[row])):
print("{:.3f}".format(matrix[row][col]), end = " ")
print()
def initCircuit(n):
circuit = QuantumCircuit(n, n)
for i in range(n):
circuit.h(i)
circuit.barrier()
return circuit
inputCircuit_2q = initCircuit(2)
inputCircuit_2q.draw(output='mpl')
def createEvenOracle():
circuit = QuantumCircuit(2, 2)
circuit.x(0)
circuit.x(1)
circuit.cz(0, 1)
circuit.x(1)
circuit.cz(0, 1)
circuit.x(0)
circuit.barrier()
return circuit
evenOracle = createEvenOracle()
evenOracle.draw(output='mpl')
Operator(evenOracle).data # find 0 and 2
def createR_2q():
circuit = QuantumCircuit(2, 2)
circuit.z(0)
circuit.z(1)
circuit.cz(0, 1)
return circuit
def createDiffuser_2q():
circuit = QuantumCircuit(2, 2)
circuit.h(0)
circuit.h(1)
circuit = circuit.compose(createR_2q())
circuit.h(0)
circuit.h(1)
circuit.barrier()
return circuit
diffuserCircuit_2q = createDiffuser_2q()
diffuserCircuit_2q.draw(output='mpl')
grover_even = initCircuit(2).compose(createEvenOracle()).compose(createDiffuser_2q())
grover_even.draw(output='mpl')
grover_even.measure([0, 1], [0, 1])
job = execute(grover_even, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(grover_even)
print(counts)
plot_histogram(counts, figsize=(5, 5), color="#66CCCC", title="origin grover - find evens")
|
https://github.com/usamisaori/Grover
|
usamisaori
|
import qiskit
from qiskit import QuantumCircuit
from qiskit.visualization import plot_histogram
import math
import numpy as np
from qiskit import execute, Aer
simulator = Aer.get_backend('qasm_simulator')
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
state_0 = np.array([1, 0])
state_1 = np.array([0, 1])
from functools import reduce
Dag = lambda matrix: matrix.conj().T
Kron = lambda *matrices: reduce(np.kron, matrices)
def getMeasurements(n):
psi_0 = np.array([1.0, 0.0])
psi_1 = np.array([0.0, 1.0])
I = np.eye(2)
M_0 = psi_0.reshape([2, 1]) @ psi_0.reshape([1, 2]).conj()
M_1 = psi_1.reshape([2, 1]) @ psi_1.reshape([1, 2]).conj()
M = [M_0, M_1]
measurements = []
for i in range(2 ** n):
binnum = bin(i)[2:].rjust(n, '0')
temp = []
indices = map(lambda x: int(x), list(binnum))
for index in indices:
temp.append(M[index])
measurements.append( Kron(*temp) )
return measurements
def measure(M, state):
return Dag(state) @ Dag(M) @ M @ state
initState = Kron(
state_0, state_0, state_0, state_0, state_0,
state_0, state_0, state_0, state_0
)
H = np.array([[1,1], [1,-1]]) / (np.sqrt(2))
H_8 = Kron(H, H, H, H, H, H, H, H)
H_9 = Kron(H, H, H, H, H, H, H, H, H)
N = 2 ** 9
def createTargetState(n):
states = []
s = bin(n)[2:].rjust(9, "0")
for i in list(s):
if i == '0':
states.append(state_0)
else:
states.append(state_1)
return Kron(*states)
def createTargetStates(p):
n = math.floor(p * N)
state = createTargetState(0)
for i in range(1, n):
state = state + createTargetState(i)
return state / (np.sqrt(n))
target_states = [
[createTargetStates(0.05), 0.05], # 0.05
[createTargetStates(0.1), 0.1], # 0.1
[createTargetStates(0.15), 0.15], # 0.15
[createTargetStates(0.2), 0.2], # 0.2
[createTargetStates(0.25), 0.25], # 0.25
[createTargetStates(0.3), 0.3], # 0.3
[createTargetStates(0.35), 0.35], # 0.35
[createTargetStates(0.4), 0.4], # 0.4
[createTargetStates(0.45), 0.45], # 0.45
[createTargetStates(0.5), 0.5], # 0.5
[createTargetStates(0.55), 0.55], # 0.55
[createTargetStates(0.6), 0.6], # 0.6
[createTargetStates(0.65), 0.65], # 0.65
[createTargetStates(0.7), 0.7], # 0.7
[createTargetStates(0.75), 0.75], # 0.75
[createTargetStates(0.8), 0.8], # 0.8
[createTargetStates(0.85), 0.85], # 0.85
[createTargetStates(0.9), 0.9], # 0.9
[createTargetStates(0.95), 0.95], # 0.95
[createTargetStates(1), 1] # 1
]
def createOriginalOracle(target_state):
O = np.eye(N) - 2 * ( Dag(target_state).reshape(N, 1) @ target_state.reshape(1, N) )
return O
def createOriginalDiffuser():
R = 2 * (
Dag(initState).reshape(N, 1) @
initState.reshape(1, N)
) - np.eye(N)
return H_9 @ R @ Dag(H_9)
def createHalfPIOracle(target_state):
alpha = np.pi / 2
alpha_phase = np.exp(alpha * 1j)
# Oracle = I - (1 - e^(αi))|target><target|
O = np.eye(N) - (1 - alpha_phase) * \
( Dag(target_state).reshape(N, 1) @ target_state.reshape(1, N) )
return O
def createHalfPIDiffuser():
beta = -np.pi / 2
beta_phase = np.exp(beta * 1j)
# R = (1 - e^(βi))|0><0| + e^(βi)I
R = (1 - beta_phase) * (
Dag(initState).reshape(N, 1) @
initState.reshape(1, N)
) + beta_phase * np.eye(N)
return H_9 @ R @ Dag(H_9)
def createOneTenthPIOracle(target_state):
alpha = np.pi / 10
alpha_phase = np.exp(alpha * 1j)
# Oracle = I - (1 - e^(αi))|target><target|
O = np.eye(N) - (1 - alpha_phase) * \
( Dag(target_state).reshape(N, 1) @ target_state.reshape(1, N) )
return O
def createOneTenthPIDiffuser():
beta = -np.pi / 10
beta_phase = np.exp(beta * 1j)
# R = (1 - e^(βi))|0><0| + e^(βi)I
R = (1 - beta_phase) * (
Dag(initState).reshape(N, 1) @
initState.reshape(1, N)
) + beta_phase * np.eye(N)
return H_9 @ R @ Dag(H_9)
def createYouneOracle(n):
O = np.eye(N)
for i in range(n):
O[i][i] = 0
O[i][i + N // 2] = 1
O[i + N // 2][i + N // 2] = 0
O[i + N // 2][i] = 1
return O
def createYouneDiffuser():
R = (2 * Dag(initState).reshape(N, 1) @
initState.reshape(1, N) - np.eye(N))
return Kron(np.eye(2), H_8) @ R @ Dag(Kron(np.eye(2), H_8))
measurements = getMeasurements(9)
# test: one grover iteration
x_o = []
y_o = []
for target_state, p in target_states:
n = math.floor(p * N)
O = createOriginalOracle(target_state)
diff = createOriginalDiffuser()
final_state = diff @ O @ H_9 @ initState
probability = 0.0
for i in range(N):
if i < n:
probability = probability + measure(measurements[i], final_state)
# print(f'p={p}, probability={probability}')
x_o.append(p)
y_o.append(probability)
plt.title("Original Grover - apply one iterator")
plt.scatter(x_o, y_o, color="#66CCCC")
# test: best probability
x_o_best = []
y_o_best = []
for target_state, p in target_states:
n = math.floor(p * N)
O = createOriginalOracle(target_state)
diff = createOriginalDiffuser()
final_state = H_9 @ initState
theta = math.degrees( math.asin(math.sqrt(p)) )
k_tilde = math.floor( 180 / (4 * theta) - 0.5 )
for i in range(k_tilde):
final_state = diff @ O @ final_state
probability = 0.0
for i in range(N):
if i < n:
probability = probability + measure(measurements[i], final_state)
final_state = diff @ O @ final_state
probability2 = 0.0
for i in range(N):
if i < n:
probability2 = probability2 + measure(measurements[i], final_state)
# print(f'p={p}, probability={probability}')
x_o_best.append(p)
y_o_best.append(max(probability, probability2))
plt.title("Original Grover - best Probability")
x = np.arange(-0,1,0.01)
y = 1 - x
plt.plot(x, y, ls='--', color="#FFCC00")
plt.ylim(0, 1.05)
plt.scatter(x_o_best, y_o_best, color="#66CCCC")
# test: one grover iteration
x_half_pi = []
y_half_pi= []
for target_state, p in target_states:
n = math.floor(p * N)
O = createHalfPIOracle(target_state)
diff = createHalfPIDiffuser()
final_state = diff @ O @ H_9 @ initState
probability = 0.0
for i in range(N):
if i < n:
probability = probability + measure(measurements[i], final_state)
# print(f'p={p}, probability={probability}')
x_half_pi.append(p)
y_half_pi.append(probability)
plt.title("pi/2 Grover - apply one iterator")
plt.scatter(x_half_pi, y_half_pi, color="#66CCCC")
# one grover iteration - pi/2 vs origin
fig, ax = plt.subplots()
plt.title("Apply one iteration")
plt.axvline(1/3, linestyle='--', color="#FFCCCC", label="t/N = 1/3")
plt.axhline(0.925, linestyle='--', color="#FFCC00", label="P=0.925")
plt.scatter(x_o, y_o, color="#66CCCC", label="Original Grover")
plt.scatter(x_half_pi, y_half_pi, color="#FF6666", label="pi/2 phase based Grover")
ax.legend()
# test: one grover iteration
x_ot_pi = []
y_ot_pi= []
for target_state, p in target_states:
n = math.floor(p * N)
O = createOneTenthPIOracle(target_state)
diff = createOneTenthPIDiffuser()
final_state = diff @ O @ H_9 @ initState
probability = 0.0
for i in range(N):
if i < n:
probability = probability + measure(measurements[i], final_state)
# print(f'p={p}, probability={probability}')
x_ot_pi.append(p)
y_ot_pi.append(probability)
plt.title("0.1pi Grover - apply one iteration")
plt.scatter(x_ot_pi, y_ot_pi, color="#66CCCC")
# test: best probability
x_ot_best = []
y_ot_best = []
diff = createOneTenthPIDiffuser()
for target_state, p in target_states:
n = math.floor(p * N)
O = createOneTenthPIOracle(target_state)
# diff = createOneTenthPIDiffuser()
final_state = H_9 @ initState
p_best = 0.0
k_tilde = math.floor( 5 * np.sqrt(N) )
for i in range(k_tilde):
final_state = diff @ O @ final_state
probability = 0.0
for i in range(N):
if i < n:
probability = probability + measure(measurements[i], final_state)
p_best = max(p_best, probability)
# print(f'p={p}, probability={probability}')
x_ot_best.append(p)
y_ot_best.append(p_best)
plt.title("0.1pi Grover - best Probability")
plt.ylim(0, 1)
plt.scatter(x_ot_best, y_ot_best, color="#66CCCC")
# best probability - 0.1pi vs origin
fig, ax = plt.subplots()
plt.title("Best Probability")
x = np.arange(-0,1,0.01)
y = 1 - x
plt.plot(x, y, ls='--', color="#FFCC00")
plt.ylim(0, 1.05)
plt.scatter(x_o_best, y_o_best, color="#66CCCC", label="Original Grover")
plt.scatter(x_ot_best, y_ot_best, color="#FF6666", label="0.1pi phase based Grover")
ax.legend()
# test: best probability
x_y_best = []
y_y_best = []
for _, p in target_states:
n = math.floor(p * (N // 2))
O = createYouneOracle(n)
diff = createYouneDiffuser()
final_state = Kron( np.eye(2), H_8) @ initState
p_best = 0.0
k_tilde = math.floor(np.pi / (2 * np.sqrt(2)) * np.sqrt((N // 2) / n))
for i in range(k_tilde):
final_state = diff @ O @ final_state
probability = 0.0
for i in range(N // 2):
if i < n:
probability = probability + measure(measurements[i], final_state) + measure(measurements[i + N // 2], final_state)
# print(f'p={p}, probability={probability}')
x_y_best.append(p)
y_y_best.append(probability)
fig, ax = plt.subplots()
plt.title("Best Probability")
x = np.arange(-0, 1, 0.01)
y = 1 - x
plt.plot(x, y, ls='--', color="#FFCC00")
plt.axhline(0.8472, linestyle='--', color="#99CCFF", label="P=0.8472")
plt.axvline(0.308, linestyle='--', color="#FFCCCC", label="P=0.308")
plt.ylim(0, 1.05)
plt.scatter(x_y_best, y_y_best, color="#FF6666", label="Youne")
plt.scatter(x_o_best, y_o_best, color="#66CCCC", label="Original Grover")
ax.legend()
|
https://github.com/usamisaori/Grover
|
usamisaori
|
import qiskit
from qiskit import QuantumCircuit
from qiskit.visualization import plot_histogram
from qiskit.quantum_info import Operator
import numpy as np
from qiskit import execute, Aer
simulator = Aer.get_backend('qasm_simulator')
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
# https://arxiv.org/pdf/quant-ph/9605034.pdf
def initCircuit(n):
circuit = QuantumCircuit(n, n)
for i in range(n):
circuit.h(i)
circuit.barrier()
return circuit
inputCircuit_8q = initCircuit(8)
inputCircuit_8q.draw(output='mpl')
def createOracle_255():
circuit = QuantumCircuit(8, 8)
circuit.h(7)
circuit.mcx(list(range(7)), 7)
circuit.h(7)
circuit.barrier()
return circuit
oracleCircuit_255 = createOracle_255()
oracleCircuit_255.draw(output='mpl')
Operator(oracleCircuit_255).data
for index, row in enumerate(Operator(oracleCircuit_255).data):
if abs(row[index] - -1) < 1e-6:
print(index)
def createR_8q():
circuit = QuantumCircuit(8, 8)
circuit.x(7)
circuit.x(6)
circuit.x(5)
circuit.x(4)
circuit.x(3)
circuit.x(2)
circuit.x(0)
circuit.x(1)
circuit.h(7)
circuit.mcx(list(range(7)), 7)
circuit.barrier(0)
circuit.barrier(1)
circuit.barrier(2)
circuit.barrier(3)
circuit.barrier(4)
circuit.barrier(5)
circuit.barrier(6)
circuit.h(7)
circuit.x(2)
circuit.x(0)
circuit.x(1)
circuit.x(5)
circuit.x(4)
circuit.x(3)
circuit.x(7)
circuit.x(6)
return circuit
R_8q = createR_8q()
R_8q.draw(output='mpl')
def createDiffuser_8q():
circuit = QuantumCircuit(8, 8)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.h(3)
circuit.h(4)
circuit.h(5)
circuit.h(6)
circuit.h(7)
circuit = circuit.compose(createR_8q())
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.h(3)
circuit.h(4)
circuit.h(5)
circuit.h(6)
circuit.h(7)
circuit.barrier()
return circuit
diffuserCircuit_8q = createDiffuser_8q()
diffuserCircuit_8q.draw(output='mpl')
def createGroverIteration(oracle, diffuser):
return oracle.compose(diffuser)
groverIteration_8q = createGroverIteration(createOracle_255(), createDiffuser_8q())
groverIteration_8q.draw(output='mpl')
fullCircuit_8q = initCircuit(8).compose(groverIteration_8q)
fullCircuit_8q.draw(output='mpl')
import math
degree = math.degrees( math.asin(1 / np.sqrt(256)) )
degree
for k in range(1, 15):
print(f'k = {k}: { math.sin(math.radians( (2 * k+1) * degree) ) ** 2 }')
def groverMeasurements(k):
circuit = initCircuit(8)
for i in range(k):
circuit = circuit.compose(groverIteration_8q.copy())
circuit.measure(list(range(8)), list(range(8)))
job = execute(circuit, simulator, shots = 1)
results = job.result()
counts = results.get_counts(circuit)
return list(counts)[0]
from random import randrange
def solutionFinding(limit):
m = 1
lam = 6 / 5
count = 0 # iteration times
while count <= limit * (9/4):
if m > 1:
j = randrange(0, math.floor(m))
if j != 0:
count += j
answer = groverMeasurements(j)
if answer == '11111111':
# print(f'Find! - total times: {count}')
return count, True
m = min(lam * m, limit)
# print(f'Not find! - total times: {count}')
return count, False
times = 0
best = 1000
worst = 0
success = 0
for i in range(1000):
time, flag = solutionFinding(np.sqrt(256)) # √N
times += time
best = min(best, time)
worst = max(worst, time)
if flag:
success += 1
print(f'total test times: {1000}')
print('--------------------------')
print(f'Average run times: {times / 1000}')
print(f'best run times: {best}')
print(f'worst run times: {worst}')
print(f'Success rate: {success / 1000 * 100:.2f}%')
|
https://github.com/usamisaori/Grover
|
usamisaori
|
import qiskit
from qiskit import QuantumCircuit
from qiskit.visualization import plot_histogram
from qiskit.quantum_info import Operator
import numpy as np
from qiskit import execute, Aer
simulator = Aer.get_backend('qasm_simulator')
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
def createYouneInitCircuit():
circuit = QuantumCircuit(3, 2)
circuit.h(0)
circuit.h(1)
circuit.barrier()
return circuit
youneInitCircuit = createYouneInitCircuit()
youneInitCircuit.draw(output='mpl')
def createYouneOracle():
circuit = QuantumCircuit(3, 2)
circuit.x(0)
circuit.x(1)
circuit.ccx(0, 1, 2)
circuit.x(0)
circuit.x(1)
circuit.barrier()
circuit.x(0)
circuit.ccx(0, 1, 2)
circuit.x(0)
circuit.barrier()
return circuit
youneOracle = createYouneOracle()
youneOracle.draw(output='mpl')
def createYouneDiffuser():
circuit = QuantumCircuit(3, 2)
circuit.h(0)
circuit.h(1)
circuit.barrier(2)
circuit.x(2)
circuit.x(0)
circuit.x(1)
circuit.h(2)
circuit.ccx(0, 1, 2)
circuit.barrier(0)
circuit.barrier(1)
circuit.h(2)
circuit.x(2)
circuit.x(0)
circuit.x(1)
circuit.h(0)
circuit.h(1)
# circuit.h(2)
circuit.barrier()
return circuit
youneDiffuser = createYouneDiffuser()
youneDiffuser.draw(output='mpl')
youneGroverIteration = createYouneOracle().compose(createYouneDiffuser())
grover_youne = createYouneInitCircuit().compose(youneGroverIteration.copy())
grover_youne.draw(output='mpl')
grover_youne.measure([0, 1], [0, 1])
job = execute(grover_youne, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(grover_youne)
print(counts)
plot_histogram(counts, figsize=(4, 5), color="#0099CC", title="youne grover - find evens")
def createYouneOracle2():
circuit = QuantumCircuit(3, 2)
circuit.x(0)
circuit.cx(0, 2)
circuit.x(0)
circuit.barrier()
return circuit
youneOracle2 = createYouneOracle2()
youneOracle2.draw(output='mpl')
# 0 => 4 2 => 6
Operator(youneOracle2).data
youneGroverIteration2 = createYouneOracle2().compose(createYouneDiffuser())
grover_youne2 = createYouneInitCircuit().compose(youneGroverIteration2.copy())
grover_youne2.draw(output='mpl')
grover_youne2.measure([0, 1], [0, 1])
job = execute(grover_youne2, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(grover_youne2)
print(counts)
plot_histogram(counts, figsize=(4, 5), color="#66CCFF", title="youne grover(using another Oracle) - find evens")
|
https://github.com/usamisaori/Grover
|
usamisaori
|
import qiskit
from qiskit import QuantumCircuit
from qiskit.visualization import plot_histogram
from qiskit.quantum_info import Operator
import numpy as np
from qiskit import execute, Aer
simulator = Aer.get_backend('qasm_simulator')
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
# https://towardsdatascience.com/behind-oracles-grovers-algorithm-amplitude-amplification-46b928b46f1e
def createSATInitCircuit(var, clause):
# input + workspace(clause) + checker(1)
circuit = QuantumCircuit(var + clause + 1, var)
for i in range(var):
circuit.h(i)
circuit.barrier()
return circuit
SATInitCircuit = createSATInitCircuit(4, 3)
SATInitCircuit.draw(output='mpl')
def createSATOracle(var, clause):
circuit = QuantumCircuit(var + clause + 1, var)
# (a ∧ b ∧ ¬c)
circuit.x(2)
circuit.mcx([0, 1, 2], 4)
circuit.x(2)
circuit.barrier()
# (¬b ∧d )
circuit.x(1)
circuit.mcx([1, 3], 5)
circuit.x(1)
circuit.barrier()
# ¬d
circuit.x(3)
circuit.cx(3, 6)
circuit.x(3)
circuit.barrier()
# (a ∧ b ∧ ¬c) ∨ ¬(¬b ∧d ) ∨ ¬d
circuit.x(5)
circuit.mcx([4, 5, 6], 7)
circuit.x(5)
circuit.barrier()
# uncomputation
# ¬d
circuit.x(3)
circuit.cx(3, 6)
circuit.x(3)
circuit.barrier()
# (¬b ∧d )
circuit.x(1)
circuit.mcx([1, 3], 5)
circuit.x(1)
circuit.barrier()
# (a ∧ b ∧ ¬c)
circuit.x(2)
circuit.mcx([0, 1, 2], 4)
circuit.x(2)
circuit.barrier()
return circuit
SATOracleCircuit = createSATOracle(4, 3)
SATOracleCircuit.draw(output='mpl')
def createSATDiffuser(var, clause):
circuit = QuantumCircuit(var + clause + 1, var)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.h(3)
circuit.x(0)
circuit.x(1)
circuit.x(2)
circuit.x(3)
circuit.mcx([0, 1, 2, 3], var + clause)
circuit.x(0)
circuit.x(1)
circuit.x(2)
circuit.x(3)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.h(3)
return circuit
SATDiffuserCircuit = createSATDiffuser(4, 3)
SATDiffuserCircuit.draw(output='mpl')
SATCircuit = createSATInitCircuit(4, 3).compose(createSATOracle(4, 3)).compose(createSATDiffuser(4, 3))
SATCircuit.draw(output='mpl')
SATCircuit.measure([0, 1, 2, 3], [0, 1, 2, 3])
job = execute(SATCircuit, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(SATCircuit)
print(counts)
plot_histogram(counts, figsize=(12, 5), color="#CCCCFF", title="SAT - solving (a ∧ b ∧ ¬c) ∨ ¬(¬b ∧d ) ∨ ¬d, k = 1")
SATIteration = Operator(createSATOracle(4, 3).compose(createSATDiffuser(4, 3)))
SATCircuit2 = createSATInitCircuit(4, 3)
SATCircuit2.append(SATIteration, list(range(8)))
SATCircuit2.append(SATIteration, list(range(8)))
SATCircuit2.append(SATIteration, list(range(8)))
SATCircuit2.draw(output='mpl')
SATCircuit2.measure([0, 1, 2, 3], [0, 1, 2, 3])
job = execute(SATCircuit2, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(SATCircuit2)
print(counts)
plot_histogram(counts, figsize=(12, 5), color="#6666FF", title="SAT - solving (a ∧ b ∧ ¬c) ∨ ¬(¬b ∧d ) ∨ ¬d, k = 3")
import math
math.degrees( math.asin(1 / 4))
for k in range(1, 5):
print(f'k = {k}: { math.sin(math.radians( (2 * k+1) * 14.47) ) ** 2 }')
|
https://github.com/usamisaori/Grover
|
usamisaori
|
import qiskit
from qiskit import QuantumCircuit
from qiskit.visualization import plot_histogram
import numpy as np
from qiskit import execute, Aer
simulator = Aer.get_backend('qasm_simulator')
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
from qiskit.quantum_info import DensityMatrix, Statevector, Operator
def getDensityMatrix(circuit):
return DensityMatrix(circuit).data
state_0 = np.array([1, 0]) # |0>
state_1 = np.array([0, 1]) # |1>
from functools import reduce
Dag = lambda matrix: matrix.conj().T # Dag(M) = M†
Kron = lambda *matrices: reduce(np.kron, matrices)
def pm(matrix):
for row in range(len(matrix)):
for col in range (len(matrix[row])):
print("{:.3f}".format(matrix[row][col]), end = " ")
print()
# https://qiskit.org/textbook/ch-algorithms/grover.html
def initCircuit(n):
circuit = QuantumCircuit(n, n)
for i in range(n):
circuit.h(i)
circuit.barrier()
return circuit
inputCircuit_2q = initCircuit(2)
inputCircuit_2q.draw(output='mpl')
def createOracle_3():
circuit = QuantumCircuit(2, 2)
# Oracle for find 3
# U_f
circuit.cz(0, 1)
circuit.barrier()
return circuit
oracleCircuit_3 = createOracle_3()
oracleCircuit_3.draw(output='mpl')
O_3 = Operator(oracleCircuit_3).data
pm(O_3)
# all possible states
state_00 = Kron(state_0, state_0)
state_01 = Kron(state_0, state_1)
state_10 = Kron(state_1, state_0)
state_11 = Kron(state_1, state_1)
print("O|00>", O_3 @ state_00)
print("O|01>", O_3 @ state_01)
print("O|10>", O_3 @ state_10)
print("O|11>", O_3 @ state_11) # flip phase
# H R H, where R = 2|0><0| - I
def createR_2q():
circuit = QuantumCircuit(2, 2)
circuit.z(0)
circuit.z(1)
circuit.cz(0, 1)
return circuit
R_2q = createR_2q()
R_2q.draw(output='mpl')
R_2q = Operator(R_2q).data
pm(R_2q)
# flip phase(no work on zero states) => Conditional Phase Shift gate
print("RO|00>", R_2q @ O_3 @ state_00) # zero state => would not flip
print("RO|01>", R_2q @ O_3 @ state_01)
print("RO|10>", R_2q @ O_3 @ state_10)
print("RO|11>", R_2q @ O_3 @ state_11)
# H R H
def createDiffuser_2q():
circuit = QuantumCircuit(2, 2)
circuit.h(0)
circuit.h(1)
circuit = circuit.compose(createR_2q())
circuit.h(0)
circuit.h(1)
circuit.barrier()
return circuit
diffuserCircuit_2q = createDiffuser_2q()
diffuserCircuit_2q.draw(output='mpl')
diff_2q = Operator(diffuserCircuit_2q).data
pm(diff_2q)
DB = 0.5 * state_00 + 0.5 * state_01 + 0.5 * state_10 + 0.5 * state_11
print("DO|DB>", diff_2q @ O_3 @ DB)
def createGroverIteration(oracle, diffuser):
return oracle.compose(diffuser)
groverIteration_2q = createGroverIteration(createOracle_3(), createDiffuser_2q())
groverIteration_2q.draw(output='mpl')
groverIteration_2q = createGroverIteration(createOracle_3(), createDiffuser_2q())
grover_2q_1 = initCircuit(2).compose(groverIteration_2q.copy())
grover_2q_1.draw(output='mpl')
grover_2q_1.measure([0, 1], [0, 1])
job = execute(grover_2q_1, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(grover_2q_1)
print(counts)
plot_histogram(counts, figsize=(1, 5), color="#CC3333", title="one iteration - find 3")
grover_2q_2 = initCircuit(2).compose(groverIteration_2q.copy()).compose(groverIteration_2q.copy())
grover_2q_2.draw(output='mpl')
grover_2q_2.measure([0, 1], [0, 1])
job = execute(grover_2q_2, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(grover_2q_2)
print(counts)
plot_histogram(counts, figsize=(7, 5), color="#FF9999", title="two iterations - find 3")
|
https://github.com/usamisaori/Grover
|
usamisaori
|
import qiskit
from qiskit import QuantumCircuit
from qiskit.visualization import plot_histogram
import numpy as np
from qiskit import execute, Aer
simulator = Aer.get_backend('qasm_simulator')
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
from qiskit.quantum_info import DensityMatrix, Operator
# Quantum circuit to unitary matrix
def getDensityMatrix(circuit):
return DensityMatrix(circuit).data
state_0 = np.array([1, 0]) # |0>
state_1 = np.array([0, 1]) # |1>
from functools import reduce
Dag = lambda matrix: matrix.conj().T # Dag(M) = M†
Kron = lambda *matrices: reduce(np.kron, matrices) # Kron(state_0, state_0) is |00>
def pm(matrix):
for row in range(len(matrix)):
for col in range (len(matrix[row])):
print("{:.3f}".format(matrix[row][col]), end = " ")
print()
# https://qiskit.org/textbook/ch-algorithms/grover.html
def initCircuit(n):
circuit = QuantumCircuit(n, n)
for i in range(n):
circuit.h(i)
circuit.barrier()
return circuit
inputCircuit_3q = initCircuit(3)
inputCircuit_3q.draw(output='mpl')
def createOracle_6():
circuit = QuantumCircuit(3, 3)
# Oracle for find 6
# U_f
circuit.x(0)
circuit.h(2)
circuit.ccx(0, 1, 2)
circuit.h(2)
circuit.x(0)
circuit.barrier()
return circuit
oracleCircuit_6 = createOracle_6()
oracleCircuit_6.draw(output='mpl')
# where the entry that correspond to the marked item will have a negative phase
pm(Operator(oracleCircuit_6).data)
Operator(oracleCircuit_6).data
# H R H, where R = 2|0><0| - I
def createR_3q():
circuit = QuantumCircuit(3, 3)
circuit.x(2)
circuit.x(0)
circuit.x(1)
circuit.h(2)
circuit.ccx(0, 1, 2)
circuit.barrier(0)
circuit.barrier(1)
circuit.h(2)
circuit.x(2)
circuit.x(0)
circuit.x(1)
return circuit
R_3q = createR_3q()
R_3q.draw(output='mpl')
pm(Operator(R_3q).data)
print('|000>', Kron(state_0, state_0, state_0))
print('R|000>',Operator(R_3q).data @ Kron(state_0, state_0, state_0) )
print('|010>', Kron(state_0, state_1, state_0))
print('R|010>',Operator(R_3q).data @ Kron(state_0, state_1, state_0) )
print('|110>', Kron(state_1, state_1, state_0))
print('R|110>',Operator(R_3q).data @ Kron(state_1, state_1, state_0) )
# H R H
def createDiffuser_3q():
circuit = QuantumCircuit(3, 3)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit = circuit.compose(createR_3q())
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.barrier()
return circuit
diffuserCircuit_3q = createDiffuser_3q()
diffuserCircuit_3q.draw(output='mpl')
pm(Operator(diffuserCircuit_3q).data)
def createGroverIteration(oracle, diffuser):
return oracle.compose(diffuser)
groverIteration_3q = createGroverIteration(createOracle_6(), createDiffuser_3q())
groverIteration_3q.draw(output='mpl')
groverIteration_3q = createGroverIteration(createOracle_6(), createDiffuser_3q())
inputCircuit_3q = initCircuit(3)
inputCircuit_3q.draw(output='mpl')
inputCircuit_3q.measure([0, 1, 2], [0, 1, 2])
job = execute(inputCircuit_3q, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(inputCircuit_3q)
print(counts)
plot_histogram(counts, figsize=(10, 5), color="#FFFFCC", title="superposition state - 3 qubits")
grover_3q_1 = initCircuit(3).compose(groverIteration_3q.copy())
grover_3q_1.draw(output='mpl')
grover_3q_1.measure([0, 1, 2], [0, 1, 2])
job = execute(grover_3q_1, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(grover_3q_1)
print(counts)
plot_histogram(counts, figsize=(10, 5), color="#FFBB00", title="one iteration - find 6")
grover_3q_2 = initCircuit(3).compose(groverIteration_3q.copy()).compose(groverIteration_3q.copy())
# grover_3q_2.draw(output='mpl')
grover_3q_2.measure([0, 1, 2], [0, 1, 2])
job = execute(grover_3q_2, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(grover_3q_2)
print(counts)
plot_histogram(counts, figsize=(10, 5), color="#FF8822", title="two iteration - find 6")
grover_3q_3 = initCircuit(3).compose(groverIteration_3q.copy()).compose(groverIteration_3q.copy()).compose(groverIteration_3q.copy())
# grover_3q_3.draw(output='mpl')
grover_3q_3.measure([0, 1, 2], [0, 1, 2])
job = execute(grover_3q_3, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(grover_3q_3)
print(counts)
plot_histogram(counts, figsize=(10, 5), color="#FFFF3F", title="three iteration - find 6")
|
https://github.com/usamisaori/Grover
|
usamisaori
|
import math
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.pyplot import arrow
from mpl_toolkits.axisartist.axislines import SubplotZero
from matplotlib.patches import Arc
%matplotlib inline
import warnings
warnings.filterwarnings('ignore')
def get_line_plot(angle, *, linewidth=1, linestyle="-", color="black"):
angle = math.radians(angle)
return Line2D([0, math.cos(angle) * 0.92], [0, math.sin(angle) * 0.92],
linewidth=linewidth, linestyle=linestyle, color=color)
def get_angle_plot(line1, line2, *, offset=1, color=None, origin=(0, 0),
len_x_axis = 1, len_y_axis = 1):
l1xy = line1.get_xydata()
# Angle between line1 and x-axis
y1 = l1xy[1][1] - l1xy[0][1]
x1 = l1xy[1][0] - l1xy[0][0]
slope1 = y1 / float(x1)
# Allows you to use this in different quadrants
angle1 = math.degrees(math.atan2(y1, x1))
l2xy = line2.get_xydata()
# Angle between line2 and x-axis
y2 = l2xy[1][1] - l2xy[0][1]
x2 = l2xy[1][0] - l2xy[0][0]
slope2 = y2 / float(x2)
angle2 = math.degrees(math.atan2(y2, x2))
theta1 = min(angle1, angle2)
theta2 = max(angle1, angle2)
angle = theta2 - theta1
if angle > 180:
angle = 360 - angle
theta1 = 360 + theta1
if theta1 > theta2:
theta1, theta2 = theta2, theta1
if color is None:
color = line1.get_color() # Uses the color of line 1 if color parameter is not passed.
return Arc(origin, len_x_axis*offset, len_y_axis*offset, 0,
theta1, theta2, color=color,
label = r'${:.4}^\circ$'.format(float(angle)))
def get_angle_text(angle_plot):
angle = angle_plot.get_label()
# angle = r'${:.4}^\circ$'.format(angle) # Display angle upto 2 decimal places
# Get the vertices of the angle arc
vertices = angle_plot.get_verts()
# Get the midpoint of the arc extremes
x_width = (vertices[0][0] + vertices[-1][0]) / 2.0
y_width = (vertices[0][1] + vertices[-1][1]) / 2.0
separation_radius = max(x_width / 2.0, y_width / 2.0)
return [x_width + separation_radius, y_width + separation_radius, angle]
class AnglePoltter:
def __init__(self):
self.lines = []
self.arcs = []
self.angles = []
def add_line(self, angle, *, linewidth=1, linestyle="-", color="black"):
line = get_line_plot(angle, linewidth=linewidth, linestyle=linestyle, color=color)
self.lines.append(
[
line.get_xdata()[0], line.get_ydata()[0], line.get_xdata()[1], line.get_ydata()[1],
linewidth, linestyle, color
]
)
return line
def add_angle(self, line1, line2, *, text=False, **kwargs):
angle = get_angle_plot(line1, line2, **kwargs)
self.arcs.append(angle)
if text:
self.angles.append(get_angle_text(angle))
def plot(self, *, title, fontsize=18):
fig = plt.figure()
ax = SubplotZero(fig, 1, 1, 1)
# draw a circle
theta = np.linspace(0, 2 * np.pi, 200)
x = np.cos(theta)
y = np.sin(theta)
ax.plot(x, y, color="#CCCCCC", linewidth=1.5)
fig.add_subplot(ax)
for direction in ["left", "right", "bottom", "top"]:
# hides borders
ax.axis[direction].set_visible(False)
for direction in ["xzero", "yzero"]:
# adds arrows at the ends of each axis
ax.axis[direction].set_axisline_style('-|>')
# adds X and Y-axis from the origin
ax.axis[direction].set_visible(True)
for line in self.lines:
if line[4] != 0:
ax.arrow(line[0], line[1], line[2], line[3],
head_width=0.06, head_length=0.06,
linewidth=line[4], linestyle=line[5], color=line[6])
for arc in self.arcs:
ax.add_patch(arc)
for angle in self.angles:
ax.text(*angle)
if title != None:
fig.suptitle(title, fontsize=fontsize)
plt.axis([-1.8, 1.8, -1.35, 1.35])
plt.grid()
plt.legend()
return ax
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(30, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.5, text=True)
ax = plotter.plot(title="Initial state")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(30, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(330, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
ax = plotter.plot(title="After applying Oracle")
x = math.cos(math.radians(30))
y = math.sin(math.radians(30))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(30, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(330, linewidth=1.5, linestyle="-.", color="#99CC33")
line_3 = plotter.add_line(90, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
ax = plotter.plot(title="After one Grover iteration")
x = math.cos(math.radians(30))
y = math.sin(math.radians(30))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, 0], [-y, 1], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x * 1.2, 0], [-y * 1.2, 0], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x * 1.2], [y, y * 1.2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(30, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(330, linewidth=1.5, linestyle="-.", color="#99CC33")
line_3 = plotter.add_line(90, linewidth=1.5, color="#99CCFF")
line_4 = plotter.add_line(-90, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
plotter.add_angle(line_4, x, offset=0.8)
ax = plotter.plot(title="Apply Oracle(second iteration)")
x = math.cos(math.radians(30))
y = math.sin(math.radians(30))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, 0], [-y, 1], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x * 1.2, 0], [-y * 1.2, 0], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x * 1.2], [y, y * 1.2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(30, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(330, linewidth=1.5, linestyle="-.", color="#99CC33")
line_3 = plotter.add_line(90, linewidth=1.5, color="#99CCFF")
line_4 = plotter.add_line(-90, linewidth=1.5, color="#FF9900")
line_5 = plotter.add_line(150, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
plotter.add_angle(line_4, x, offset=0.8)
plotter.add_angle(line_5, line_3, offset=0.6)
ax = plotter.plot(title="Apply Oracle(second iteration)")
x = math.cos(math.radians(30))
y = math.sin(math.radians(30))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, 0], [-y, 1], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x, 0], [y, -1], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x * 1.2, 0], [-y * 1.2, 0], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x * 1.2], [y, y * 1.2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
theta = math.degrees(math.asin(1/(8 ** 0.5)))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(theta, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.5, text=True)
ax = plotter.plot(title="Initial state")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(theta, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(-theta, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
ax = plotter.plot(title="After applying Oracle")
x = math.cos(math.radians(theta))
y = math.sin(math.radians(theta))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(theta, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(-theta, linewidth=1.5, linestyle="-.", color="#99CC33")
line_3 = plotter.add_line(3 * theta, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
ax = plotter.plot(title="After one Grover iteration")
x = math.cos(math.radians(theta))
y = math.sin(math.radians(theta))
x2 = math.cos(math.radians(3 * theta))
y2 = math.sin(math.radians(3 * theta))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x2], [-y, y2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x * 1.2, 0], [-y * 1.2, 0], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x * 1.2], [y, y * 1.2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(theta, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(-theta, linewidth=1.5, linestyle="-.", color="#99CC33")
line_3 = plotter.add_line(3 * theta, linewidth=1.5, color="#99CCFF")
line_4 = plotter.add_line(5 * theta, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
plotter.add_angle(line_4, line_3, offset=0.6)
ax = plotter.plot(title="After two Grover iteration")
x = math.cos(math.radians(theta))
y = math.sin(math.radians(theta))
x2 = math.cos(math.radians(3 * theta))
y2 = math.sin(math.radians(3 * theta))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x2], [-y, y2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x * 1.2, 0], [-y * 1.2, 0], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x * 1.2], [y, y * 1.2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(theta, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(-theta, linewidth=1.5, linestyle="-.", color="#99CC33")
line_3 = plotter.add_line(3 * theta, linewidth=1.5, color="#99CCFF")
line_4 = plotter.add_line(5 * theta, linewidth=1.5, color="#FF9900")
line_5 = plotter.add_line(7 * theta, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
plotter.add_angle(line_4, line_3, offset=0.6)
plotter.add_angle(line_5, line_4, offset=0.6)
ax = plotter.plot(title="After two Grover iteration")
x = math.cos(math.radians(theta))
y = math.sin(math.radians(theta))
x2 = math.cos(math.radians(3 * theta))
y2 = math.sin(math.radians(3 * theta))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x2], [-y, y2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x * 1.2, 0], [-y * 1.2, 0], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x * 1.2], [y, y * 1.2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.5, text=True)
ax = plotter.plot(title="Initial state")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, linestyle="-.", color="#99CC33")
line_2 = plotter.add_line(-45, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
ax = plotter.plot(title="After applying Oracle")
x = math.cos(math.radians(45))
y = math.sin(math.radians(45))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, linestyle="-.", color="#99CC33")
line_2 = plotter.add_line(-45, linewidth=1.5, linestyle="-.", color="#99CCFF")
line_3 = plotter.add_line(3 * 45, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
ax = plotter.plot(title="After one Grover iteration")
x = math.cos(math.radians(45))
y = math.sin(math.radians(45))
x2 = math.cos(math.radians(3 * 45))
y2 = math.sin(math.radians(3 * 45))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x * 1.2, 0], [-y * 1.2, 0], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x * 1.2], [y, y * 1.2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, linestyle="-.", color="#99CC33")
line_2 = plotter.add_line(-45, linewidth=1.5, linestyle="-.", color="#99CCFF")
line_3 = plotter.add_line(3 * 45, linewidth=1.5, color="#FF9900")
line_4 = plotter.add_line(5 * 45, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
plotter.add_angle(line_4, line_3, offset=0.6)
ax = plotter.plot(title="After two Grover iteration")
x = math.cos(math.radians(45))
y = math.sin(math.radians(45))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_s = plotter.add_line(40, linewidth=2, color="#6666CC")
line_phi = plotter.add_line(25, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_s, x, offset=0.6)
plotter.add_angle(line_phi, x, offset=0.4)
plotter.plot(title="Grover reflections - initial state")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_s = plotter.add_line(40, linewidth=2, color="#6666CC")
line_phi = plotter.add_line(25, linewidth=1.5, linestyle=":", color="#99CC33")
line_O_phi = plotter.add_line(335, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_s, x, offset=0.6)
plotter.add_angle(line_phi, x, offset=0.4)
plotter.add_angle(line_O_phi, x, offset=0.4)
ax = plotter.plot(title="Grover reflections - reflection 1")
x = math.cos(math.radians(25))
y = math.sin(math.radians(25))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_s = plotter.add_line(40, linewidth=2, color="#6666CC")
line_phi = plotter.add_line(25, linewidth=1.5, linestyle=":", color="#99CC33")
line_O_phi = plotter.add_line(335, linewidth=1.5, linestyle=":", color="#99CCFF")
line_RO_phi = plotter.add_line(285, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_s, x, offset=0.8)
plotter.add_angle(line_phi, x, offset=0.6)
plotter.add_angle(line_O_phi, x, offset=0.6)
plotter.add_angle(line_RO_phi, x, offset=0.4)
ax = plotter.plot(title="Grover reflections - reflection 2")
x1 = math.cos(math.radians(25))
y1 = math.sin(math.radians(25))
ax.add_line(Line2D([x1, x1], [-y1, y1], linewidth=1.5, linestyle="--", color="#CCCCCC"))
x2 = math.cos(math.radians(-75))
y2 = math.sin(math.radians(-75))
ax.add_line(Line2D([x1, x2], [-y1, y2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
x3 = math.cos(math.radians(130)) * 1.5
y3 = math.sin(math.radians(130)) * 1.5
ax.add_line(Line2D([x3, -x3], [y3, -y3], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_s = plotter.add_line(40, linewidth=2, color="#6666CC")
line_phi = plotter.add_line(25, linewidth=1.5, linestyle=":", color="#99CC33")
line_O_phi = plotter.add_line(335, linewidth=1.5, linestyle=":", color="#99CCFF")
line_RO_phi = plotter.add_line(285, linewidth=1.5, linestyle=":", color="#FF9900")
line_mRO_phi = plotter.add_line(105, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_s, x, offset=0.8)
plotter.add_angle(line_phi, x, offset=0.6)
plotter.add_angle(line_O_phi, x, offset=0.6)
plotter.add_angle(line_RO_phi, x, offset=0.4)
plotter.add_angle(line_mRO_phi, line_phi, offset=1)
ax = plotter.plot(title="Grover reflections - reflection3")
x1 = math.cos(math.radians(25))
y1 = math.sin(math.radians(25))
ax.add_line(Line2D([x1, x1], [-y1, y1], linewidth=1.5, linestyle="--", color="#CCCCCC"))
x2 = math.cos(math.radians(-75))
y2 = math.sin(math.radians(-75))
ax.add_line(Line2D([x1, x2], [-y1, y2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
x3 = math.cos(math.radians(130)) * 1.5
y3 = math.sin(math.radians(130)) * 1.5
ax.add_line(Line2D([x3, -x3], [y3, -y3], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.5, text=True)
ax = plotter.plot(title="Initial state")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, linestyle="-.", color="#99CCFF")
line_2 = plotter.add_line(-2, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
ax = plotter.plot(title="After applying Oracle")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, linestyle="-.", color="#99CCFF")
line_2 = plotter.add_line(-2, linewidth=1.5, linestyle="-.", color="#FF9900")
line_3 = plotter.add_line(92, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
ax = plotter.plot(title="After one Grover iteration")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.5, text=True)
ax = plotter.plot(title="Initial state")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, linestyle="-.", color="#99CCFF")
line_2 = plotter.add_line(40, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
ax = plotter.plot(title="After applying Oracle")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, linestyle="-.", color="#99CCFF")
line_2 = plotter.add_line(40, linewidth=1.5, linestyle="-.", color="#FF9900")
line_3 = plotter.add_line(50, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
ax = plotter.plot(title="After one Grover iteration")
|
https://github.com/usamisaori/Grover
|
usamisaori
|
import qiskit
from qiskit import QuantumCircuit
from qiskit.visualization import plot_histogram
import numpy as np
from qiskit import execute, Aer
simulator = Aer.get_backend('qasm_simulator')
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
from qiskit.quantum_info import DensityMatrix, Statevector, Operator
def getDensityMatrix(circuit):
return DensityMatrix(circuit).data
from functools import reduce
Dag = lambda matrix: matrix.conj().T
Kron = lambda *matrices: reduce(np.kron, matrices)
def pm(matrix):
for row in range(len(matrix)):
for col in range (len(matrix[row])):
print("{:.3f}".format(matrix[row][col]), end = " ")
print()
def initCircuit(n):
circuit = QuantumCircuit(n, n)
for i in range(n):
circuit.h(i)
circuit.barrier()
return circuit
inputCircuit_2q = initCircuit(2)
inputCircuit_2q.draw(output='mpl')
def createEvenOracle():
circuit = QuantumCircuit(2, 2)
circuit.x(0)
circuit.x(1)
circuit.cz(0, 1)
circuit.x(1)
circuit.cz(0, 1)
circuit.x(0)
circuit.barrier()
return circuit
evenOracle = createEvenOracle()
evenOracle.draw(output='mpl')
Operator(evenOracle).data # find 0 and 2
def createR_2q():
circuit = QuantumCircuit(2, 2)
circuit.z(0)
circuit.z(1)
circuit.cz(0, 1)
return circuit
def createDiffuser_2q():
circuit = QuantumCircuit(2, 2)
circuit.h(0)
circuit.h(1)
circuit = circuit.compose(createR_2q())
circuit.h(0)
circuit.h(1)
circuit.barrier()
return circuit
diffuserCircuit_2q = createDiffuser_2q()
diffuserCircuit_2q.draw(output='mpl')
grover_even = initCircuit(2).compose(createEvenOracle()).compose(createDiffuser_2q())
grover_even.draw(output='mpl')
grover_even.measure([0, 1], [0, 1])
job = execute(grover_even, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(grover_even)
print(counts)
plot_histogram(counts, figsize=(5, 5), color="#66CCCC", title="origin grover - find evens")
|
https://github.com/usamisaori/Grover
|
usamisaori
|
import qiskit
from qiskit import QuantumCircuit
from qiskit.visualization import plot_histogram
import math
import numpy as np
from qiskit import execute, Aer
simulator = Aer.get_backend('qasm_simulator')
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
state_0 = np.array([1, 0])
state_1 = np.array([0, 1])
from functools import reduce
Dag = lambda matrix: matrix.conj().T
Kron = lambda *matrices: reduce(np.kron, matrices)
def getMeasurements(n):
psi_0 = np.array([1.0, 0.0])
psi_1 = np.array([0.0, 1.0])
I = np.eye(2)
M_0 = psi_0.reshape([2, 1]) @ psi_0.reshape([1, 2]).conj()
M_1 = psi_1.reshape([2, 1]) @ psi_1.reshape([1, 2]).conj()
M = [M_0, M_1]
measurements = []
for i in range(2 ** n):
binnum = bin(i)[2:].rjust(n, '0')
temp = []
indices = map(lambda x: int(x), list(binnum))
for index in indices:
temp.append(M[index])
measurements.append( Kron(*temp) )
return measurements
def measure(M, state):
return Dag(state) @ Dag(M) @ M @ state
initState = Kron(
state_0, state_0, state_0, state_0, state_0,
state_0, state_0, state_0, state_0
)
H = np.array([[1,1], [1,-1]]) / (np.sqrt(2))
H_8 = Kron(H, H, H, H, H, H, H, H)
H_9 = Kron(H, H, H, H, H, H, H, H, H)
N = 2 ** 9
def createTargetState(n):
states = []
s = bin(n)[2:].rjust(9, "0")
for i in list(s):
if i == '0':
states.append(state_0)
else:
states.append(state_1)
return Kron(*states)
def createTargetStates(p):
n = math.floor(p * N)
state = createTargetState(0)
for i in range(1, n):
state = state + createTargetState(i)
return state / (np.sqrt(n))
target_states = [
[createTargetStates(0.05), 0.05], # 0.05
[createTargetStates(0.1), 0.1], # 0.1
[createTargetStates(0.15), 0.15], # 0.15
[createTargetStates(0.2), 0.2], # 0.2
[createTargetStates(0.25), 0.25], # 0.25
[createTargetStates(0.3), 0.3], # 0.3
[createTargetStates(0.35), 0.35], # 0.35
[createTargetStates(0.4), 0.4], # 0.4
[createTargetStates(0.45), 0.45], # 0.45
[createTargetStates(0.5), 0.5], # 0.5
[createTargetStates(0.55), 0.55], # 0.55
[createTargetStates(0.6), 0.6], # 0.6
[createTargetStates(0.65), 0.65], # 0.65
[createTargetStates(0.7), 0.7], # 0.7
[createTargetStates(0.75), 0.75], # 0.75
[createTargetStates(0.8), 0.8], # 0.8
[createTargetStates(0.85), 0.85], # 0.85
[createTargetStates(0.9), 0.9], # 0.9
[createTargetStates(0.95), 0.95], # 0.95
[createTargetStates(1), 1] # 1
]
def createOriginalOracle(target_state):
O = np.eye(N) - 2 * ( Dag(target_state).reshape(N, 1) @ target_state.reshape(1, N) )
return O
def createOriginalDiffuser():
R = 2 * (
Dag(initState).reshape(N, 1) @
initState.reshape(1, N)
) - np.eye(N)
return H_9 @ R @ Dag(H_9)
def createHalfPIOracle(target_state):
alpha = np.pi / 2
alpha_phase = np.exp(alpha * 1j)
# Oracle = I - (1 - e^(αi))|target><target|
O = np.eye(N) - (1 - alpha_phase) * \
( Dag(target_state).reshape(N, 1) @ target_state.reshape(1, N) )
return O
def createHalfPIDiffuser():
beta = -np.pi / 2
beta_phase = np.exp(beta * 1j)
# R = (1 - e^(βi))|0><0| + e^(βi)I
R = (1 - beta_phase) * (
Dag(initState).reshape(N, 1) @
initState.reshape(1, N)
) + beta_phase * np.eye(N)
return H_9 @ R @ Dag(H_9)
def createOneTenthPIOracle(target_state):
alpha = np.pi / 10
alpha_phase = np.exp(alpha * 1j)
# Oracle = I - (1 - e^(αi))|target><target|
O = np.eye(N) - (1 - alpha_phase) * \
( Dag(target_state).reshape(N, 1) @ target_state.reshape(1, N) )
return O
def createOneTenthPIDiffuser():
beta = -np.pi / 10
beta_phase = np.exp(beta * 1j)
# R = (1 - e^(βi))|0><0| + e^(βi)I
R = (1 - beta_phase) * (
Dag(initState).reshape(N, 1) @
initState.reshape(1, N)
) + beta_phase * np.eye(N)
return H_9 @ R @ Dag(H_9)
def createYouneOracle(n):
O = np.eye(N)
for i in range(n):
O[i][i] = 0
O[i][i + N // 2] = 1
O[i + N // 2][i + N // 2] = 0
O[i + N // 2][i] = 1
return O
def createYouneDiffuser():
R = (2 * Dag(initState).reshape(N, 1) @
initState.reshape(1, N) - np.eye(N))
return Kron(np.eye(2), H_8) @ R @ Dag(Kron(np.eye(2), H_8))
measurements = getMeasurements(9)
# test: one grover iteration
x_o = []
y_o = []
for target_state, p in target_states:
n = math.floor(p * N)
O = createOriginalOracle(target_state)
diff = createOriginalDiffuser()
final_state = diff @ O @ H_9 @ initState
probability = 0.0
for i in range(N):
if i < n:
probability = probability + measure(measurements[i], final_state)
# print(f'p={p}, probability={probability}')
x_o.append(p)
y_o.append(probability)
plt.title("Original Grover - apply one iterator")
plt.scatter(x_o, y_o, color="#66CCCC")
# test: best probability
x_o_best = []
y_o_best = []
for target_state, p in target_states:
n = math.floor(p * N)
O = createOriginalOracle(target_state)
diff = createOriginalDiffuser()
final_state = H_9 @ initState
theta = math.degrees( math.asin(math.sqrt(p)) )
k_tilde = math.floor( 180 / (4 * theta) - 0.5 )
for i in range(k_tilde):
final_state = diff @ O @ final_state
probability = 0.0
for i in range(N):
if i < n:
probability = probability + measure(measurements[i], final_state)
final_state = diff @ O @ final_state
probability2 = 0.0
for i in range(N):
if i < n:
probability2 = probability2 + measure(measurements[i], final_state)
# print(f'p={p}, probability={probability}')
x_o_best.append(p)
y_o_best.append(max(probability, probability2))
plt.title("Original Grover - best Probability")
x = np.arange(-0,1,0.01)
y = 1 - x
plt.plot(x, y, ls='--', color="#FFCC00")
plt.ylim(0, 1.05)
plt.scatter(x_o_best, y_o_best, color="#66CCCC")
# test: one grover iteration
x_half_pi = []
y_half_pi= []
for target_state, p in target_states:
n = math.floor(p * N)
O = createHalfPIOracle(target_state)
diff = createHalfPIDiffuser()
final_state = diff @ O @ H_9 @ initState
probability = 0.0
for i in range(N):
if i < n:
probability = probability + measure(measurements[i], final_state)
# print(f'p={p}, probability={probability}')
x_half_pi.append(p)
y_half_pi.append(probability)
plt.title("pi/2 Grover - apply one iterator")
plt.scatter(x_half_pi, y_half_pi, color="#66CCCC")
# one grover iteration - pi/2 vs origin
fig, ax = plt.subplots()
plt.title("Apply one iteration")
plt.axvline(1/3, linestyle='--', color="#FFCCCC", label="t/N = 1/3")
plt.axhline(0.925, linestyle='--', color="#FFCC00", label="P=0.925")
plt.scatter(x_o, y_o, color="#66CCCC", label="Original Grover")
plt.scatter(x_half_pi, y_half_pi, color="#FF6666", label="pi/2 phase based Grover")
ax.legend()
# test: one grover iteration
x_ot_pi = []
y_ot_pi= []
for target_state, p in target_states:
n = math.floor(p * N)
O = createOneTenthPIOracle(target_state)
diff = createOneTenthPIDiffuser()
final_state = diff @ O @ H_9 @ initState
probability = 0.0
for i in range(N):
if i < n:
probability = probability + measure(measurements[i], final_state)
# print(f'p={p}, probability={probability}')
x_ot_pi.append(p)
y_ot_pi.append(probability)
plt.title("0.1pi Grover - apply one iteration")
plt.scatter(x_ot_pi, y_ot_pi, color="#66CCCC")
# test: best probability
x_ot_best = []
y_ot_best = []
diff = createOneTenthPIDiffuser()
for target_state, p in target_states:
n = math.floor(p * N)
O = createOneTenthPIOracle(target_state)
# diff = createOneTenthPIDiffuser()
final_state = H_9 @ initState
p_best = 0.0
k_tilde = math.floor( 5 * np.sqrt(N) )
for i in range(k_tilde):
final_state = diff @ O @ final_state
probability = 0.0
for i in range(N):
if i < n:
probability = probability + measure(measurements[i], final_state)
p_best = max(p_best, probability)
# print(f'p={p}, probability={probability}')
x_ot_best.append(p)
y_ot_best.append(p_best)
plt.title("0.1pi Grover - best Probability")
plt.ylim(0, 1)
plt.scatter(x_ot_best, y_ot_best, color="#66CCCC")
# best probability - 0.1pi vs origin
fig, ax = plt.subplots()
plt.title("Best Probability")
x = np.arange(-0,1,0.01)
y = 1 - x
plt.plot(x, y, ls='--', color="#FFCC00")
plt.ylim(0, 1.05)
plt.scatter(x_o_best, y_o_best, color="#66CCCC", label="Original Grover")
plt.scatter(x_ot_best, y_ot_best, color="#FF6666", label="0.1pi phase based Grover")
ax.legend()
# test: best probability
x_y_best = []
y_y_best = []
for _, p in target_states:
n = math.floor(p * (N // 2))
O = createYouneOracle(n)
diff = createYouneDiffuser()
final_state = Kron( np.eye(2), H_8) @ initState
p_best = 0.0
k_tilde = math.floor(np.pi / (2 * np.sqrt(2)) * np.sqrt((N // 2) / n))
for i in range(k_tilde):
final_state = diff @ O @ final_state
probability = 0.0
for i in range(N // 2):
if i < n:
probability = probability + measure(measurements[i], final_state) + measure(measurements[i + N // 2], final_state)
# print(f'p={p}, probability={probability}')
x_y_best.append(p)
y_y_best.append(probability)
fig, ax = plt.subplots()
plt.title("Best Probability")
x = np.arange(-0, 1, 0.01)
y = 1 - x
plt.plot(x, y, ls='--', color="#FFCC00")
plt.axhline(0.8472, linestyle='--', color="#99CCFF", label="P=0.8472")
plt.axvline(0.308, linestyle='--', color="#FFCCCC", label="P=0.308")
plt.ylim(0, 1.05)
plt.scatter(x_y_best, y_y_best, color="#FF6666", label="Youne")
plt.scatter(x_o_best, y_o_best, color="#66CCCC", label="Original Grover")
ax.legend()
|
https://github.com/usamisaori/Grover
|
usamisaori
|
import qiskit
from qiskit import QuantumCircuit
from qiskit.visualization import plot_histogram
from qiskit.quantum_info import Operator
import numpy as np
from qiskit import execute, Aer
simulator = Aer.get_backend('qasm_simulator')
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
# https://arxiv.org/pdf/quant-ph/9605034.pdf
def initCircuit(n):
circuit = QuantumCircuit(n, n)
for i in range(n):
circuit.h(i)
circuit.barrier()
return circuit
inputCircuit_8q = initCircuit(8)
inputCircuit_8q.draw(output='mpl')
def createOracle_255():
circuit = QuantumCircuit(8, 8)
circuit.h(7)
circuit.mcx(list(range(7)), 7)
circuit.h(7)
circuit.barrier()
return circuit
oracleCircuit_255 = createOracle_255()
oracleCircuit_255.draw(output='mpl')
Operator(oracleCircuit_255).data
for index, row in enumerate(Operator(oracleCircuit_255).data):
if abs(row[index] - -1) < 1e-6:
print(index)
def createR_8q():
circuit = QuantumCircuit(8, 8)
circuit.x(7)
circuit.x(6)
circuit.x(5)
circuit.x(4)
circuit.x(3)
circuit.x(2)
circuit.x(0)
circuit.x(1)
circuit.h(7)
circuit.mcx(list(range(7)), 7)
circuit.barrier(0)
circuit.barrier(1)
circuit.barrier(2)
circuit.barrier(3)
circuit.barrier(4)
circuit.barrier(5)
circuit.barrier(6)
circuit.h(7)
circuit.x(2)
circuit.x(0)
circuit.x(1)
circuit.x(5)
circuit.x(4)
circuit.x(3)
circuit.x(7)
circuit.x(6)
return circuit
R_8q = createR_8q()
R_8q.draw(output='mpl')
def createDiffuser_8q():
circuit = QuantumCircuit(8, 8)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.h(3)
circuit.h(4)
circuit.h(5)
circuit.h(6)
circuit.h(7)
circuit = circuit.compose(createR_8q())
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.h(3)
circuit.h(4)
circuit.h(5)
circuit.h(6)
circuit.h(7)
circuit.barrier()
return circuit
diffuserCircuit_8q = createDiffuser_8q()
diffuserCircuit_8q.draw(output='mpl')
def createGroverIteration(oracle, diffuser):
return oracle.compose(diffuser)
groverIteration_8q = createGroverIteration(createOracle_255(), createDiffuser_8q())
groverIteration_8q.draw(output='mpl')
fullCircuit_8q = initCircuit(8).compose(groverIteration_8q)
fullCircuit_8q.draw(output='mpl')
import math
degree = math.degrees( math.asin(1 / np.sqrt(256)) )
degree
for k in range(1, 15):
print(f'k = {k}: { math.sin(math.radians( (2 * k+1) * degree) ) ** 2 }')
def groverMeasurements(k):
circuit = initCircuit(8)
for i in range(k):
circuit = circuit.compose(groverIteration_8q.copy())
circuit.measure(list(range(8)), list(range(8)))
job = execute(circuit, simulator, shots = 1)
results = job.result()
counts = results.get_counts(circuit)
return list(counts)[0]
from random import randrange
def solutionFinding(limit):
m = 1
lam = 6 / 5
count = 0 # iteration times
while count <= limit * (9/4):
if m > 1:
j = randrange(0, math.floor(m))
if j != 0:
count += j
answer = groverMeasurements(j)
if answer == '11111111':
# print(f'Find! - total times: {count}')
return count, True
m = min(lam * m, limit)
# print(f'Not find! - total times: {count}')
return count, False
times = 0
best = 1000
worst = 0
success = 0
for i in range(1000):
time, flag = solutionFinding(np.sqrt(256)) # √N
times += time
best = min(best, time)
worst = max(worst, time)
if flag:
success += 1
print(f'total test times: {1000}')
print('--------------------------')
print(f'Average run times: {times / 1000}')
print(f'best run times: {best}')
print(f'worst run times: {worst}')
print(f'Success rate: {success / 1000 * 100:.2f}%')
|
https://github.com/usamisaori/Grover
|
usamisaori
|
import qiskit
from qiskit import QuantumCircuit
from qiskit.visualization import plot_histogram
from qiskit.quantum_info import Operator
import numpy as np
from qiskit import execute, Aer
simulator = Aer.get_backend('qasm_simulator')
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
def createYouneInitCircuit():
circuit = QuantumCircuit(3, 2)
circuit.h(0)
circuit.h(1)
circuit.barrier()
return circuit
youneInitCircuit = createYouneInitCircuit()
youneInitCircuit.draw(output='mpl')
def createYouneOracle():
circuit = QuantumCircuit(3, 2)
circuit.x(0)
circuit.x(1)
circuit.ccx(0, 1, 2)
circuit.x(0)
circuit.x(1)
circuit.barrier()
circuit.x(0)
circuit.ccx(0, 1, 2)
circuit.x(0)
circuit.barrier()
return circuit
youneOracle = createYouneOracle()
youneOracle.draw(output='mpl')
def createYouneDiffuser():
circuit = QuantumCircuit(3, 2)
circuit.h(0)
circuit.h(1)
circuit.barrier(2)
circuit.x(2)
circuit.x(0)
circuit.x(1)
circuit.h(2)
circuit.ccx(0, 1, 2)
circuit.barrier(0)
circuit.barrier(1)
circuit.h(2)
circuit.x(2)
circuit.x(0)
circuit.x(1)
circuit.h(0)
circuit.h(1)
# circuit.h(2)
circuit.barrier()
return circuit
youneDiffuser = createYouneDiffuser()
youneDiffuser.draw(output='mpl')
youneGroverIteration = createYouneOracle().compose(createYouneDiffuser())
grover_youne = createYouneInitCircuit().compose(youneGroverIteration.copy())
grover_youne.draw(output='mpl')
grover_youne.measure([0, 1], [0, 1])
job = execute(grover_youne, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(grover_youne)
print(counts)
plot_histogram(counts, figsize=(4, 5), color="#0099CC", title="youne grover - find evens")
def createYouneOracle2():
circuit = QuantumCircuit(3, 2)
circuit.x(0)
circuit.cx(0, 2)
circuit.x(0)
circuit.barrier()
return circuit
youneOracle2 = createYouneOracle2()
youneOracle2.draw(output='mpl')
# 0 => 4 2 => 6
Operator(youneOracle2).data
youneGroverIteration2 = createYouneOracle2().compose(createYouneDiffuser())
grover_youne2 = createYouneInitCircuit().compose(youneGroverIteration2.copy())
grover_youne2.draw(output='mpl')
grover_youne2.measure([0, 1], [0, 1])
job = execute(grover_youne2, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(grover_youne2)
print(counts)
plot_histogram(counts, figsize=(4, 5), color="#66CCFF", title="youne grover(using another Oracle) - find evens")
|
https://github.com/usamisaori/Grover
|
usamisaori
|
import qiskit
from qiskit import QuantumCircuit
from qiskit.visualization import plot_histogram
from qiskit.quantum_info import Operator
import numpy as np
from qiskit import execute, Aer
simulator = Aer.get_backend('qasm_simulator')
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
# https://towardsdatascience.com/behind-oracles-grovers-algorithm-amplitude-amplification-46b928b46f1e
def createSATInitCircuit(var, clause):
# input + workspace(clause) + checker(1)
circuit = QuantumCircuit(var + clause + 1, var)
for i in range(var):
circuit.h(i)
circuit.barrier()
return circuit
SATInitCircuit = createSATInitCircuit(4, 3)
SATInitCircuit.draw(output='mpl')
def createSATOracle(var, clause):
circuit = QuantumCircuit(var + clause + 1, var)
# (a ∧ b ∧ ¬c)
circuit.x(2)
circuit.mcx([0, 1, 2], 4)
circuit.x(2)
circuit.barrier()
# (¬b ∧d )
circuit.x(1)
circuit.mcx([1, 3], 5)
circuit.x(1)
circuit.barrier()
# ¬d
circuit.x(3)
circuit.cx(3, 6)
circuit.x(3)
circuit.barrier()
# (a ∧ b ∧ ¬c) ∨ ¬(¬b ∧d ) ∨ ¬d
circuit.x(5)
circuit.mcx([4, 5, 6], 7)
circuit.x(5)
circuit.barrier()
# uncomputation
# ¬d
circuit.x(3)
circuit.cx(3, 6)
circuit.x(3)
circuit.barrier()
# (¬b ∧d )
circuit.x(1)
circuit.mcx([1, 3], 5)
circuit.x(1)
circuit.barrier()
# (a ∧ b ∧ ¬c)
circuit.x(2)
circuit.mcx([0, 1, 2], 4)
circuit.x(2)
circuit.barrier()
return circuit
SATOracleCircuit = createSATOracle(4, 3)
SATOracleCircuit.draw(output='mpl')
def createSATDiffuser(var, clause):
circuit = QuantumCircuit(var + clause + 1, var)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.h(3)
circuit.x(0)
circuit.x(1)
circuit.x(2)
circuit.x(3)
circuit.mcx([0, 1, 2, 3], var + clause)
circuit.x(0)
circuit.x(1)
circuit.x(2)
circuit.x(3)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.h(3)
return circuit
SATDiffuserCircuit = createSATDiffuser(4, 3)
SATDiffuserCircuit.draw(output='mpl')
SATCircuit = createSATInitCircuit(4, 3).compose(createSATOracle(4, 3)).compose(createSATDiffuser(4, 3))
SATCircuit.draw(output='mpl')
SATCircuit.measure([0, 1, 2, 3], [0, 1, 2, 3])
job = execute(SATCircuit, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(SATCircuit)
print(counts)
plot_histogram(counts, figsize=(12, 5), color="#CCCCFF", title="SAT - solving (a ∧ b ∧ ¬c) ∨ ¬(¬b ∧d ) ∨ ¬d, k = 1")
SATIteration = Operator(createSATOracle(4, 3).compose(createSATDiffuser(4, 3)))
SATCircuit2 = createSATInitCircuit(4, 3)
SATCircuit2.append(SATIteration, list(range(8)))
SATCircuit2.append(SATIteration, list(range(8)))
SATCircuit2.append(SATIteration, list(range(8)))
SATCircuit2.draw(output='mpl')
SATCircuit2.measure([0, 1, 2, 3], [0, 1, 2, 3])
job = execute(SATCircuit2, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(SATCircuit2)
print(counts)
plot_histogram(counts, figsize=(12, 5), color="#6666FF", title="SAT - solving (a ∧ b ∧ ¬c) ∨ ¬(¬b ∧d ) ∨ ¬d, k = 3")
import math
math.degrees( math.asin(1 / 4))
for k in range(1, 5):
print(f'k = {k}: { math.sin(math.radians( (2 * k+1) * 14.47) ) ** 2 }')
|
https://github.com/usamisaori/Grover
|
usamisaori
|
import qiskit
from qiskit import QuantumCircuit
from qiskit.visualization import plot_histogram
import numpy as np
from qiskit import execute, Aer
simulator = Aer.get_backend('qasm_simulator')
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
from qiskit.quantum_info import DensityMatrix, Statevector, Operator
def getDensityMatrix(circuit):
return DensityMatrix(circuit).data
state_0 = np.array([1, 0])
state_1 = np.array([0, 1])
from functools import reduce
Dag = lambda matrix: matrix.conj().T
Kron = lambda *matrices: reduce(np.kron, matrices)
def pm(matrix):
for row in range(len(matrix)):
for col in range (len(matrix[row])):
print("{:.3f}".format(matrix[row][col]), end = " ")
print()
def getMeasurements(n):
psi_0 = np.array([1.0, 0.0])
psi_1 = np.array([0.0, 1.0])
I = np.eye(2)
M_0 = psi_0.reshape([2, 1]) @ psi_0.reshape([1, 2]).conj()
M_1 = psi_1.reshape([2, 1]) @ psi_1.reshape([1, 2]).conj()
M = [M_0, M_1]
measurements = []
for i in range(2 ** n):
binnum = bin(i)[2:].rjust(n, '0')
temp = []
indices = map(lambda x: int(x), list(binnum))
for index in indices:
temp.append(M[index])
measurements.append( Kron(*temp) )
return measurements
def measure(M, state):
return Dag(state) @ Dag(M) @ M @ state
# https://qiskit.org/textbook/ch-algorithms/grover.html
def initCircuit(n):
circuit = QuantumCircuit(n, n)
for i in range(n):
circuit.h(i)
circuit.barrier()
return circuit
inputCircuit_2q = initCircuit(2)
inputCircuit_2q.draw(output='mpl')
def createOracle_3():
circuit = QuantumCircuit(2, 2)
# Oracle for find 3
# U_f
circuit.cz(0, 1)
circuit.barrier()
return circuit
oracleCircuit_3 = createOracle_3()
oracleCircuit_3.draw(output='mpl')
O_3 = Operator(oracleCircuit_3).data
pm(O_3)
# all possible states
state_00 = Kron(state_0, state_0)
state_01 = Kron(state_0, state_1)
state_10 = Kron(state_1, state_0)
state_11 = Kron(state_1, state_1)
print("O|00>", O_3 @ state_00)
print("O|01>", O_3 @ state_01)
print("O|10>", O_3 @ state_10)
print("O|11>", O_3 @ state_11) # flip phase
# H R H, where R = 2|0><0| - I
def createR_2q():
circuit = QuantumCircuit(2, 2)
circuit.z(0)
circuit.z(1)
circuit.cz(0, 1)
return circuit
R_2q = createR_2q()
R_2q.draw(output='mpl')
R_2q = Operator(R_2q).data
pm(R_2q)
# flip phase(no work on zero states) => Conditional Phase Shift gate
print("RO|00>", R_2q @ O_3 @ state_00) # zero state => would not flip
print("RO|01>", R_2q @ O_3 @ state_01)
print("RO|10>", R_2q @ O_3 @ state_10)
print("RO|11>", R_2q @ O_3 @ state_11)
def createDiffuser_2q():
circuit = QuantumCircuit(2, 2)
circuit.h(0)
circuit.h(1)
circuit = circuit.compose(createR_2q())
circuit.h(0)
circuit.h(1)
circuit.barrier()
return circuit
diffuserCircuit_2q = createDiffuser_2q()
diffuserCircuit_2q.draw(output='mpl')
diff_2q = Operator(diffuserCircuit_2q).data
pm(diff_2q)
DB = 0.5 * state_00 + 0.5 * state_01 + 0.5 * state_10 + 0.5 * state_11
print("DO|DB>", diff_2q @ O_3 @ DB)
def createGroverIteration(oracle, diffuser):
return oracle.compose(diffuser)
groverIteration_2q = createGroverIteration(createOracle_3(), createDiffuser_2q())
groverIteration_2q.draw(output='mpl')
groverIteration_2q = createGroverIteration(createOracle_3(), createDiffuser_2q())
grover_2q_1 = initCircuit(2).compose(groverIteration_2q.copy())
grover_2q_1.draw(output='mpl')
grover_2q_1.measure([0, 1], [0, 1])
job = execute(grover_2q_1, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(grover_2q_1)
print(counts)
plot_histogram(counts, figsize=(1, 5), color="#CC3333", title="one iteration - find 3")
grover_2q_2 = initCircuit(2).compose(groverIteration_2q.copy()).compose(groverIteration_2q.copy())
grover_2q_2.draw(output='mpl')
grover_2q_2.measure([0, 1], [0, 1])
job = execute(grover_2q_2, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(grover_2q_2)
print(counts)
plot_histogram(counts, figsize=(7, 5), color="#FF9999", title="two iteration - find 3")
# https://www.quantum-inspire.com/kbase/grover-algorithm/
inputCircuit_3q = initCircuit(3)
inputCircuit_3q.draw(output='mpl')
def createOracle_6():
circuit = QuantumCircuit(3, 3)
# Oracle for find 6
# U_f
circuit.x(0)
circuit.h(2)
circuit.ccx(0, 1, 2)
circuit.h(2)
circuit.x(0)
circuit.barrier()
return circuit
oracleCircuit_6 = createOracle_6()
oracleCircuit_6.draw(output='mpl')
# where the entry that correspond to the marked item will have a negative phase
pm(Operator(oracleCircuit_6).data)
Operator(oracleCircuit_6).data
# H R H, where R = 2|0><0| - I
def createR_3q():
circuit = QuantumCircuit(3, 3)
circuit.x(2)
circuit.x(0)
circuit.x(1)
circuit.h(2)
circuit.ccx(0, 1, 2)
circuit.barrier(0)
circuit.barrier(1)
circuit.h(2)
circuit.x(2)
circuit.x(0)
circuit.x(1)
return circuit
R_3q = createR_3q()
R_3q.draw(output='mpl')
pm(Operator(R_3q).data)
print('|000>', Kron(state_0, state_0, state_0))
print('R|000>',Operator(R_3q).data @ Kron(state_0, state_0, state_0) )
print('|010>', Kron(state_0, state_1, state_0))
print('R|010>',Operator(R_3q).data @ Kron(state_0, state_1, state_0) )
print('|110>', Kron(state_1, state_1, state_0))
print('R|110>',Operator(R_3q).data @ Kron(state_1, state_1, state_0) )
def createDiffuser_3q():
circuit = QuantumCircuit(3, 3)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit = circuit.compose(createR_3q())
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.barrier()
return circuit
diffuserCircuit_3q = createDiffuser_3q()
diffuserCircuit_3q.draw(output='mpl')
pm(Operator(diffuserCircuit_3q).data)
groverIteration_3q = createGroverIteration(createOracle_6(), createDiffuser_3q())
groverIteration_3q.draw(output='mpl')
inputCircuit_3q = initCircuit(3)
inputCircuit_3q.draw(output='mpl')
inputCircuit_3q.measure([0, 1, 2], [0, 1, 2])
job = execute(inputCircuit_3q, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(inputCircuit_3q)
print(counts)
plot_histogram(counts, figsize=(10, 5), color="#FFFFCC", title="superposition state - 3 qubits")
grover_3q_1 = initCircuit(3).compose(groverIteration_3q.copy())
grover_3q_1.draw(output='mpl')
grover_3q_1.measure([0, 1, 2], [0, 1, 2])
job = execute(grover_3q_1, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(grover_3q_1)
print(counts)
plot_histogram(counts, figsize=(10, 5), color="#FFBB00", title="one iteration - find 6")
grover_3q_2 = initCircuit(3).compose(groverIteration_3q.copy()).compose(groverIteration_3q.copy())
# grover_3q_2.draw(output='mpl')
grover_3q_2.measure([0, 1, 2], [0, 1, 2])
job = execute(grover_3q_2, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(grover_3q_2)
print(counts)
plot_histogram(counts, figsize=(10, 5), color="#FF8822", title="two iteration - find 6")
grover_3q_3 = initCircuit(3).compose(groverIteration_3q.copy()).compose(groverIteration_3q.copy()).compose(groverIteration_3q.copy())
# grover_3q_3.draw(output='mpl')
grover_3q_3.measure([0, 1, 2], [0, 1, 2])
job = execute(grover_3q_3, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(grover_3q_3)
print(counts)
plot_histogram(counts, figsize=(10, 5), color="#FFFF3F", title="three iteration - find 6")
import math
theta = math.degrees( math.asin(1 / math.sqrt(8)) )
theta
k_tilde = 180 / (4 * theta) - 0.5
k_tilde
for k in range(1, 4):
print(f'k = {k}: { math.sin(math.radians( (2 * k+1) * theta) ) ** 2 }')
# H R H, where R = 2|0><0| - I
# A R A^(-1)
def initAACircuit(n):
circuit = QuantumCircuit(n, n)
circuit.x(0)
circuit.h(1)
circuit.z(1)
circuit.h(0)
circuit.barrier()
return circuit
inputAACircuit = initAACircuit(2)
inputAACircuit.draw(output='mpl')
A = Operator(initAACircuit(2))
np.allclose(A.data @ Dag(A.data), np.eye(4))
inputAACircuit.measure([0, 1], [0, 1])
job = execute(inputAACircuit, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(inputAACircuit)
print(counts)
plot_histogram(counts, figsize=(7, 5), color="#CCCC66", title="measurements result of A")
oracleCircuit_3 = createOracle_3()
oracleCircuit_3.draw(output='mpl')
def createAADiffuser():
circuit = QuantumCircuit(2, 2)
circuit.append(A, [0, 1])
circuit = circuit.compose(createR_2q())
circuit.append(A.conjugate(), [0, 1])
circuit.barrier()
return circuit
diffuserAACircuit = createAADiffuser()
diffuserAACircuit.draw(output='mpl')
aaGroverIteration = createGroverIteration(createOracle_3(), createAADiffuser())
aaGroverIteration.draw(output='mpl')
incorrectGroverIteration = createGroverIteration(createOracle_3(), createDiffuser_2q())
grover_incorrect_diffuser = initAACircuit(2).compose(incorrectGroverIteration)
grover_incorrect_diffuser.draw(output='mpl')
grover_incorrect_diffuser.measure([0, 1], [0, 1])
job = execute(grover_incorrect_diffuser, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(grover_incorrect_diffuser)
print(counts)
plot_histogram(counts, figsize=(1, 5), color="#99CC33", title="using incorrect diffuser - find 3")
grover_correct_diffuser = initAACircuit(2).compose(aaGroverIteration)
grover_correct_diffuser.draw(output='mpl')
grover_correct_diffuser.measure([0, 1], [0, 1])
job = execute(grover_correct_diffuser, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(grover_correct_diffuser)
print(counts)
plot_histogram(counts, figsize=(1, 5), color="#339933", title="using correct diffuser - find 3")
inputCircuit_2q = initCircuit(2)
inputCircuit_2q.draw(output='mpl')
def createEvenOracle():
circuit = QuantumCircuit(2, 2)
circuit.x(0)
circuit.x(1)
circuit.cz(0, 1)
circuit.x(1)
circuit.cz(0, 1)
circuit.x(0)
circuit.barrier()
return circuit
evenOracle = createEvenOracle()
evenOracle.draw(output='mpl')
Operator(evenOracle).data # find 0 and 2
diffuserCircuit_2q = createDiffuser_2q()
diffuserCircuit_2q.draw(output='mpl')
grover_even = initCircuit(2).compose(createEvenOracle()).compose(createDiffuser_2q())
grover_even.draw(output='mpl')
grover_even.measure([0, 1], [0, 1])
job = execute(grover_even, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(grover_even)
print(counts)
plot_histogram(counts, figsize=(5, 5), color="#66CCCC", title="origin grover - find evens")
initState = Kron(
state_0, state_0, state_0, state_0, state_0,
state_0, state_0, state_0, state_0, state_0
)
H = np.array([[1,1], [1,-1]]) / (np.sqrt(2))
H_9 = Kron(H, H, H, H, H, H, H, H, H)
H_10 = Kron(H, H, H, H, H, H, H, H, H, H)
def createTargetState(n):
states = []
s = bin(n)[2:].rjust(10, "0")
for i in list(s):
if i == '0':
states.append(state_0)
else:
states.append(state_1)
return Kron(*states)
def createTargetStates(p):
n = math.floor(p * 1024)
state = createTargetState(0)
for i in range(1, n):
state = state + createTargetState(i)
return state / (np.sqrt(n))
target_states = [
[createTargetStates(0.05), 0.05], # 0.05
[createTargetStates(0.1), 0.1], # 0.1
[createTargetStates(0.15), 0.15], # 0.15
[createTargetStates(0.2), 0.2], # 0.2
[createTargetStates(0.25), 0.25], # 0.25
[createTargetStates(0.3), 0.3], # 0.3
[createTargetStates(0.35), 0.35], # 0.35
[createTargetStates(0.4), 0.4], # 0.4
[createTargetStates(0.45), 0.45], # 0.45
[createTargetStates(0.5), 0.5], # 0.5
[createTargetStates(0.55), 0.55], # 0.55
[createTargetStates(0.6), 0.6], # 0.6
[createTargetStates(0.65), 0.65], # 0.65
[createTargetStates(0.7), 0.7], # 0.7
[createTargetStates(0.75), 0.75], # 0.75
[createTargetStates(0.8), 0.8], # 0.8
[createTargetStates(0.85), 0.85], # 0.85
[createTargetStates(0.9), 0.9], # 0.9
[createTargetStates(0.95), 0.95], # 0.95
[createTargetStates(1), 1] # 1
]
def createOriginalOracle(target_state):
N = 1024
O = np.eye(N) - 2 * ( Dag(target_state).reshape(N, 1) @ target_state.reshape(1, N) )
return O
def createOriginalDiffuser():
N = 1024
R = 2 * (
Dag(initState).reshape(N, 1) @
initState.reshape(1, N)
) - np.eye(N)
return H_10 @ R @ Dag(H_10)
def createHalfPIOracle(target_state):
N = 1024
alpha = np.pi / 2
alpha_phase = np.exp(alpha * 1j)
# Oracle = I - (1 - e^(αi))|target><target|
O = np.eye(N) - (1 - alpha_phase) * \
( Dag(target_state).reshape(N, 1) @ target_state.reshape(1, N) )
return O
def createHalfPIDiffuser():
N = 1024
beta = -np.pi / 2
beta_phase = np.exp(beta * 1j)
# R = (1 - e^(βi))|0><0| + e^(βi)I
R = (1 - beta_phase) * (
Dag(initState).reshape(N, 1) @
initState.reshape(1, N)
) + beta_phase * np.eye(N)
return H_10 @ R @ Dag(H_10)
def createOneTenthPIOracle(target_state):
N = 1024
alpha = np.pi / 10
alpha_phase = np.exp(alpha * 1j)
# Oracle = I - (1 - e^(αi))|target><target|
O = np.eye(N) - (1 - alpha_phase) * \
( Dag(target_state).reshape(N, 1) @ target_state.reshape(1, N) )
return O
def createOneTenthPIDiffuser():
N = 1024
beta = -np.pi / 10
beta_phase = np.exp(beta * 1j)
# R = (1 - e^(βi))|0><0| + e^(βi)I
R = (1 - beta_phase) * (
Dag(initState).reshape(N, 1) @
initState.reshape(1, N)
) + beta_phase * np.eye(N)
return H_10 @ R @ Dag(H_10)
def createYouneOracle(n):
O = np.eye(1024)
for i in range(n):
O[i][i] = 0
O[i][i + 512] = 1
O[i + 512][i + 512] = 0
O[i + 512][i] = 1
return O
def createYouneDiffuser():
N = 512
R = (2 * Dag(initState).reshape(N * 2, 1) @
initState.reshape(1, N * 2) - np.eye(N * 2))
return Kron(np.eye(2), H_9) @ R @ Dag(Kron(np.eye(2), H_9))
measurements = getMeasurements(10)
# test: one grover iteration
x_o = []
y_o = []
for target_state, p in target_states:
n = math.floor(p * 1024)
O = createOriginalOracle(target_state)
diff = createOriginalDiffuser()
final_state = diff @ O @ H_10 @ initState
probability = 0.0
for i in range(1024):
if i < n:
probability = probability + measure(measurements[i], final_state)
# print(f'p={p}, probability={probability}')
x_o.append(p)
y_o.append(probability)
plt.title("Original Grover - apply one iterator")
plt.scatter(x_o, y_o, color="#66CCCC")
# test: best probability
x_o_best = []
y_o_best = []
for target_state, p in target_states:
n = math.floor(p * 1024)
O = createOriginalOracle(target_state)
diff = createOriginalDiffuser()
final_state = H_10 @ initState
theta = math.degrees( math.asin(math.sqrt(p)) )
k_tilde = math.floor( 180 / (4 * theta) - 0.5 )
for i in range(k_tilde):
final_state = diff @ O @ final_state
probability = 0.0
for i in range(1024):
if i < n:
probability = probability + measure(measurements[i], final_state)
final_state = diff @ O @ final_state
probability2 = 0.0
for i in range(1024):
if i < n:
probability2 = probability2 + measure(measurements[i], final_state)
# print(f'p={p}, probability={probability}')
x_o_best.append(p)
y_o_best.append(max(probability, probability2))
plt.title("Original Grover - best Probability")
x = np.arange(-0,1,0.01)
y = 1 - x
plt.plot(x, y, ls='--', color="#FFCC00")
plt.ylim(0, 1.05)
plt.scatter(x_o_best, y_o_best, color="#66CCCC")
# test: one grover iteration
x_half_pi = []
y_half_pi= []
for target_state, p in target_states:
n = math.floor(p * 1024)
O = createHalfPIOracle(target_state)
diff = createHalfPIDiffuser()
final_state = diff @ O @ H_10 @ initState
probability = 0.0
for i in range(1024):
if i < n:
probability = probability + measure(measurements[i], final_state)
# print(f'p={p}, probability={probability}')
x_half_pi.append(p)
y_half_pi.append(probability)
plt.title("pi/2 Grover - apply one iterator")
plt.scatter(x_half_pi, y_half_pi, color="#66CCCC")
# one grover iteration - pi/2 vs origin
fig, ax = plt.subplots()
plt.title("Apply one iteration")
plt.axvline(1/3, linestyle='--', color="#FFCCCC", label="t/N = 1/3")
plt.axhline(0.925, linestyle='--', color="#FFCC00", label="P=0.925")
plt.scatter(x_o, y_o, color="#66CCCC", label="Original Grover")
plt.scatter(x_half_pi, y_half_pi, color="#FF6666", label="pi/2 phase based Grover")
ax.legend()
# test: one grover iteration
x_ot_pi = []
y_ot_pi= []
for target_state, p in target_states:
n = math.floor(p * 1024)
O = createOneTenthPIOracle(target_state)
diff = createOneTenthPIDiffuser()
final_state = diff @ O @ H_10 @ initState
probability = 0.0
for i in range(1024):
if i < n:
probability = probability + measure(measurements[i], final_state)
# print(f'p={p}, probability={probability}')
x_ot_pi.append(p)
y_ot_pi.append(probability)
plt.title("0.1pi Grover - apply one iteration")
plt.scatter(x_ot_pi, y_ot_pi, color="#66CCCC")
# test: best probability
x_ot_best = []
y_ot_best = []
for target_state, p in target_states:
n = math.floor(p * 1024)
O = createOneTenthPIOracle(target_state)
diff = createOneTenthPIDiffuser()
final_state = H_10 @ initState
p_best = 0.0
k_tilde = math.floor( 5 * np.sqrt(1024) )
for i in range(k_tilde):
final_state = diff @ O @ final_state
probability = 0.0
for i in range(1024):
if i < n:
probability = probability + measure(measurements[i], final_state)
p_best = max(p_best, probability)
# print(f'p={p}, probability={probability}')
x_ot_best.append(p)
y_ot_best.append(p_best)
plt.title("0.1pi Grover - best Probability")
plt.ylim(0, 1)
plt.scatter(x_ot_best, y_ot_best, color="#66CCCC")
# best probability - 0.1pi vs origin
fig, ax = plt.subplots()
plt.title("Best Probability")
x = np.arange(-0,1,0.01)
y = 1 - x
plt.plot(x, y, ls='--', color="#FFCC00")
plt.ylim(0, 1.05)
plt.scatter(x_o_best, y_o_best, color="#66CCCC", label="Original Grover")
plt.scatter(x_ot_best, y_ot_best, color="#FF6666", label="0.1pi phase based Grover")
ax.legend()
# test: best probability
x_y_best = []
y_y_best = []
for _, p in target_states:
n = math.floor(p * 512)
O = createYouneOracle(n)
diff = createYouneDiffuser()
final_state = Kron( np.eye(2), H_9) @ initState
p_best = 0.0
k_tilde = math.floor(np.pi / (2 * np.sqrt(2)) * np.sqrt(512 / n))
for i in range(k_tilde):
final_state = diff @ O @ final_state
probability = 0.0
for i in range(512):
if i < n:
probability = probability + measure(measurements[i], final_state) + measure(measurements[i + 512], final_state)
# print(f'p={p}, probability={probability}')
x_y_best.append(p)
y_y_best.append(probability)
fig, ax = plt.subplots()
plt.title("Best Probability")
x = np.arange(-0, 1, 0.01)
y = 1 - x
plt.plot(x, y, ls='--', color="#FFCC00")
plt.axhline(0.8472, linestyle='--', color="#99CCFF", label="P=0.8472")
plt.axvline(0.308, linestyle='--', color="#FFCCCC", label="P=0.308")
plt.ylim(0, 1.05)
plt.scatter(x_y_best, y_y_best, color="#FF6666", label="Youne")
plt.scatter(x_o_best, y_o_best, color="#66CCCC", label="Original Grover")
ax.legend()
def createYouneInitCircuit():
circuit = QuantumCircuit(3, 2)
circuit.h(0)
circuit.h(1)
circuit.barrier()
return circuit
youneInitCircuit = createYouneInitCircuit()
youneInitCircuit.draw(output='mpl')
def createYouneOracle():
circuit = QuantumCircuit(3, 2)
circuit.x(0)
circuit.x(1)
circuit.ccx(0, 1, 2)
circuit.x(0)
circuit.x(1)
circuit.barrier()
circuit.x(0)
circuit.ccx(0, 1, 2)
circuit.x(0)
circuit.barrier()
return circuit
youneOracle = createYouneOracle()
youneOracle.draw(output='mpl')
def createYouneDiffuser():
circuit = QuantumCircuit(3, 2)
circuit.h(0)
circuit.h(1)
circuit.barrier(2)
circuit.x(2)
circuit.x(0)
circuit.x(1)
circuit.h(2)
circuit.ccx(0, 1, 2)
circuit.barrier(0)
circuit.barrier(1)
circuit.h(2)
circuit.x(2)
circuit.x(0)
circuit.x(1)
circuit.h(0)
circuit.h(1)
# circuit.h(2)
circuit.barrier()
return circuit
youneDiffuser = createYouneDiffuser()
youneDiffuser.draw(output='mpl')
youneGroverIteration = createYouneOracle().compose(createYouneDiffuser())
grover_youne = createYouneInitCircuit().compose(youneGroverIteration.copy())
grover_youne.draw(output='mpl')
grover_youne.measure([0, 1], [0, 1])
job = execute(grover_youne, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(grover_youne)
print(counts)
plot_histogram(counts, figsize=(4, 5), color="#0099CC", title="youne grover - find evens")
def createYouneOracle2():
circuit = QuantumCircuit(3, 2)
circuit.x(0)
circuit.cx(0, 2)
circuit.x(0)
circuit.barrier()
return circuit
youneOracle2 = createYouneOracle2()
youneOracle2.draw(output='mpl')
# 0 => 4 2 => 6
Operator(youneOracle2).data
youneGroverIteration2 = createYouneOracle2().compose(createYouneDiffuser())
grover_youne2 = createYouneInitCircuit().compose(youneGroverIteration2.copy())
grover_youne2.draw(output='mpl')
grover_youne2.measure([0, 1], [0, 1])
job = execute(grover_youne2, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(grover_youne2)
print(counts)
plot_histogram(counts, figsize=(4, 5), color="#66CCFF", title="youne grover(using another Oracle) - find evens")
# https://towardsdatascience.com/behind-oracles-grovers-algorithm-amplitude-amplification-46b928b46f1e
def createSATInitCircuit(var, clause):
# input + workspace(clause) + checker(1)
circuit = QuantumCircuit(var + clause + 1, var)
for i in range(var):
circuit.h(i)
circuit.barrier()
return circuit
SATInitCircuit = createSATInitCircuit(4, 3)
SATInitCircuit.draw(output='mpl')
def createSATOracle(var, clause):
circuit = QuantumCircuit(var + clause + 1, var)
# (a ∧ b ∧ ¬c)
circuit.x(2)
circuit.mcx([0, 1, 2], 4)
circuit.x(2)
circuit.barrier()
# (¬b ∧d )
circuit.x(1)
circuit.mcx([1, 3], 5)
circuit.x(1)
circuit.barrier()
# ¬d
circuit.x(3)
circuit.cx(3, 6)
circuit.x(3)
circuit.barrier()
# (a ∧ b ∧ ¬c) ∧ ¬(¬b ∧d ) ∧ ¬d
circuit.x(5)
circuit.mcx([4, 5, 6], 7)
circuit.x(5)
circuit.barrier()
# uncomputation
# ¬d
circuit.x(3)
circuit.cx(3, 6)
circuit.x(3)
circuit.barrier()
# (¬b ∧d )
circuit.x(1)
circuit.mcx([1, 3], 5)
circuit.x(1)
circuit.barrier()
# (a ∧ b ∧ ¬c)
circuit.x(2)
circuit.mcx([0, 1, 2], 4)
circuit.x(2)
circuit.barrier()
return circuit
SATOracleCircuit = createSATOracle(4, 3)
SATOracleCircuit.draw(output='mpl')
def createSATDiffuser(var, clause):
circuit = QuantumCircuit(var + clause + 1, var)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.h(3)
circuit.x(0)
circuit.x(1)
circuit.x(2)
circuit.x(3)
circuit.mcx([0, 1, 2, 3], var + clause)
circuit.x(0)
circuit.x(1)
circuit.x(2)
circuit.x(3)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.h(3)
return circuit
SATDiffuserCircuit = createSATDiffuser(4, 3)
SATDiffuserCircuit.draw(output='mpl')
SATCircuit = createSATInitCircuit(4, 3).compose(createSATOracle(4, 3)).compose(createSATDiffuser(4, 3))
SATCircuit.draw(output='mpl')
SATCircuit.measure([0, 1, 2, 3], [0, 1, 2, 3])
job = execute(SATCircuit, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(SATCircuit)
print(counts)
plot_histogram(counts, figsize=(12, 5), color="#CCCCFF", title="SAT - solving (a ∧ b ∧ ¬c) ∧ ¬(¬b ∧d ) ∧ ¬d, k = 1")
SATIteration = Operator(createSATOracle(4, 3).compose(createSATDiffuser(4, 3)))
SATCircuit2 = createSATInitCircuit(4, 3)
SATCircuit2.append(SATIteration, list(range(8)))
SATCircuit2.append(SATIteration, list(range(8)))
SATCircuit2.append(SATIteration, list(range(8)))
SATCircuit2.draw(output='mpl')
SATCircuit2.measure([0, 1, 2, 3], [0, 1, 2, 3])
job = execute(SATCircuit2, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(SATCircuit2)
print(counts)
plot_histogram(counts, figsize=(12, 5), color="#6666FF", title="SAT - solving (a ∧ b ∧ ¬c) ∧ ¬(¬b ∧d ) ∧ ¬d, k = 3")
import math
math.degrees( math.asin(1 / 4))
for k in range(1, 5):
print(f'k = {k}: { math.sin(math.radians( (2 * k+1) * 14.47) ) ** 2 }')
# https://arxiv.org/pdf/quant-ph/9605034.pdf
inputCircuit_8q = initCircuit(8)
inputCircuit_8q.draw(output='mpl')
def createOracle_255():
circuit = QuantumCircuit(8, 8)
circuit.h(7)
circuit.mcx(list(range(7)), 7)
circuit.h(7)
circuit.barrier()
return circuit
oracleCircuit_255 = createOracle_255()
oracleCircuit_255.draw(output='mpl')
Operator(oracleCircuit_255).data
for index, row in enumerate(Operator(oracleCircuit_255).data):
if abs(row[index] - -1) < 1e-6:
print(index)
def createR_8q():
circuit = QuantumCircuit(8, 8)
circuit.x(7)
circuit.x(6)
circuit.x(5)
circuit.x(4)
circuit.x(3)
circuit.x(2)
circuit.x(0)
circuit.x(1)
circuit.h(7)
circuit.mcx(list(range(7)), 7)
circuit.barrier(0)
circuit.barrier(1)
circuit.barrier(2)
circuit.barrier(3)
circuit.barrier(4)
circuit.barrier(5)
circuit.barrier(6)
circuit.h(7)
circuit.x(2)
circuit.x(0)
circuit.x(1)
circuit.x(5)
circuit.x(4)
circuit.x(3)
circuit.x(7)
circuit.x(6)
return circuit
R_8q = createR_8q()
R_8q.draw(output='mpl')
def createDiffuser_8q():
circuit = QuantumCircuit(8, 8)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.h(3)
circuit.h(4)
circuit.h(5)
circuit.h(6)
circuit.h(7)
circuit = circuit.compose(createR_8q())
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.h(3)
circuit.h(4)
circuit.h(5)
circuit.h(6)
circuit.h(7)
circuit.barrier()
return circuit
diffuserCircuit_8q = createDiffuser_8q()
diffuserCircuit_8q.draw(output='mpl')
groverIteration_8q = createGroverIteration(createOracle_255(), createDiffuser_8q())
groverIteration_8q.draw(output='mpl')
fullCircuit_8q = initCircuit(8).compose(groverIteration_8q)
fullCircuit_8q.draw(output='mpl')
degree = math.degrees( math.asin(1 / np.sqrt(256)) )
degree
for k in range(1, 15):
print(f'k = {k}: { math.sin(math.radians( (2 * k+1) * degree) ) ** 2 }')
def groverMeasurements(k):
circuit = initCircuit(8)
for i in range(k):
circuit = circuit.compose(groverIteration_8q.copy())
circuit.measure(list(range(8)), list(range(8)))
job = execute(circuit, simulator, shots = 1)
results = job.result()
counts = results.get_counts(circuit)
return list(counts)[0]
from random import randrange
def solutionFinding(limit):
m = 1
lam = 6 / 5
count = 0 # iteration times
while count <= limit * (9/4):
if m > 1:
j = randrange(0, math.floor(m))
if j != 0:
count += j
answer = groverMeasurements(j)
if answer == '11111111':
# print(f'Find! - total times: {count}')
return count, True
m = min(lam * m, limit)
# print(f'Not find! - total times: {count}')
return count, False
times = 0
best = 1000
worst = 0
success = 0
for i in range(1000):
time, flag = solutionFinding(np.sqrt(256)) # √N
times += time
best = min(best, time)
worst = max(worst, time)
if flag:
success += 1
print(f'total test times: {1000}')
print('--------------------------')
print(f'Average run times: {times / 1000}')
print(f'best run times: {best}')
print(f'worst run times: {worst}')
print(f'Success rate: {success / 1000 * 100:.2f}%')
|
https://github.com/westernquantumclub/qiskit-intro
|
westernquantumclub
|
#In case you don't have qiskit, install it now
%pip install qiskit --quiet
#Installing/upgrading pylatexenc seems to have fixed my mpl issue
#If you try this and it doesn't work, try also restarting the runtime/kernel
%pip install pylatexenc --quiet
!pip install -Uqq ipdb
!pip install qiskit_optimization
import networkx as nx
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import BasicAer
from qiskit.compiler import transpile
from qiskit.quantum_info.operators import Operator, Pauli
from qiskit.quantum_info import process_fidelity
from qiskit.extensions.hamiltonian_gate import HamiltonianGate
from qiskit.extensions import RXGate, XGate, CXGate
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute
import numpy as np
from qiskit.visualization import plot_histogram
import ipdb
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
#quadratic optimization
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.converters import QuadraticProgramToQubo
%pdb on
# def ApplyCost(qc, gamma):
# Ix = np.array([[1,0],[0,1]])
# Zx= np.array([[1,0],[0,-1]])
# Xx = np.array([[0,1],[1,0]])
# Temp = (Ix-Zx)/2
# T = Operator(Temp)
# I = Operator(Ix)
# Z = Operator(Zx)
# X = Operator(Xx)
# FinalOp=-2*(T^I^T)-(I^T^T)-(T^I^I)+2*(I^T^I)-3*(I^I^T)
# ham = HamiltonianGate(FinalOp,gamma)
# qc.append(ham,[0,1,2])
task = QuadraticProgram(name = 'QUBO on QC')
task.binary_var(name = 'x')
task.binary_var(name = 'y')
task.binary_var(name = 'z')
task.minimize(linear = {"x":-1,"y":2,"z":-3}, quadratic = {("x", "z"): -2, ("y", "z"): -1})
qubo = QuadraticProgramToQubo().convert(task) #convert to QUBO
operator, offset = qubo.to_ising()
print(operator)
# ham = HamiltonianGate(operator,0)
# print(ham)
Ix = np.array([[1,0],[0,1]])
Zx= np.array([[1,0],[0,-1]])
Xx = np.array([[0,1],[1,0]])
Temp = (Ix-Zx)/2
T = Operator(Temp)
I = Operator(Ix)
Z = Operator(Zx)
X = Operator(Xx)
FinalOp=-2*(T^I^T)-(I^T^T)-(T^I^I)+2*(I^T^I)-3*(I^I^T)
ham = HamiltonianGate(FinalOp,0)
print(ham)
#define PYBIND11_DETAILED_ERROR_MESSAGES
def compute_expectation(counts):
"""
Computes expectation value based on measurement results
Args:
counts: dict
key as bitstring, val as count
G: networkx graph
Returns:
avg: float
expectation value
"""
avg = 0
sum_count = 0
for bitstring, count in counts.items():
x = int(bitstring[2])
y = int(bitstring[1])
z = int(bitstring[0])
obj = -2*x*z-y*z-x+2*y-3*z
avg += obj * count
sum_count += count
return avg/sum_count
# We will also bring the different circuit components that
# build the qaoa circuit under a single function
def create_qaoa_circ(theta):
"""
Creates a parametrized qaoa circuit
Args:
G: networkx graph
theta: list
unitary parameters
Returns:
qc: qiskit circuit
"""
nqubits = 3
n,m=3,3
p = len(theta)//2 # number of alternating unitaries
qc = QuantumCircuit(nqubits,nqubits)
Ix = np.array([[1,0],[0,1]])
Zx= np.array([[1,0],[0,-1]])
Xx = np.array([[0,1],[1,0]])
Temp = (Ix-Zx)/2
T = Operator(Temp)
I = Operator(Ix)
Z = Operator(Zx)
X = Operator(Xx)
FinalOp=-2*(Z^I^Z)-(I^Z^Z)-(Z^I^I)+2*(I^Z^I)-3*(I^I^Z)
beta = theta[:p]
gamma = theta[p:]
# initial_state
for i in range(0, nqubits):
qc.h(i)
for irep in range(0, p):
#ipdb.set_trace(context=6)
# problem unitary
# for pair in list(G.edges()):
# qc.rzz(2 * gamma[irep], pair[0], pair[1])
#ApplyCost(qc,2*0)
ham = HamiltonianGate(operator,2 * gamma[irep])
qc.append(ham,[0,1,2])
# mixer unitary
for i in range(0, nqubits):
qc.rx(2 * beta[irep], i)
qc.measure(qc.qubits[:n],qc.clbits[:m])
return qc
# Finally we write a function that executes the circuit on the chosen backend
def get_expectation(shots=512):
"""
Runs parametrized circuit
Args:
G: networkx graph
p: int,
Number of repetitions of unitaries
"""
backend = Aer.get_backend('qasm_simulator')
backend.shots = shots
def execute_circ(theta):
qc = create_qaoa_circ(theta)
# ipdb.set_trace(context=6)
counts = {}
job = execute(qc, backend, shots=1024)
result = job.result()
counts=result.get_counts(qc)
return compute_expectation(counts)
return execute_circ
from scipy.optimize import minimize
expectation = get_expectation()
res = minimize(expectation, [1, 1], method='COBYLA')
expectation = get_expectation()
res = minimize(expectation, res.x, method='COBYLA')
res
from qiskit.visualization import plot_histogram
backend = Aer.get_backend('aer_simulator')
backend.shots = 512
qc_res = create_qaoa_circ(res.x)
backend = Aer.get_backend('qasm_simulator')
job = execute(qc_res, backend, shots=1024)
result = job.result()
counts=result.get_counts(qc_res)
plot_histogram(counts)
|
https://github.com/CapacitorSet/qiskit-fast-shor
|
CapacitorSet
|
"""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/DLR-RB/QUEASARS
|
DLR-RB
|
from pathlib import Path
import os
import sys
main_directory = Path(os.path.abspath("")).parent
sys.path.append(str(main_directory))
from queasars.job_shop_scheduling.problem_instances import Machine, Operation, Job, JobShopSchedulingProblemInstance
machines = (Machine(name="m0"), Machine(name="m1"), Machine("m2"))
j0op1 = Operation(name="j0op0", machine=machines[2], processing_duration=1, job_name="j0")
j0op2 = Operation(name="j0op1", machine=machines[0], processing_duration=1, job_name="j0")
j0op3 = Operation(name="j0op2", machine=machines[1], processing_duration=2, job_name="j0")
job0 = Job(name="j0", operations=(j0op1, j0op2, j0op3))
j1op1 = Operation(name="j1op1", machine=machines[2], processing_duration=2, job_name="j1")
j1op2 = Operation(name="j1op2", machine=machines[0], processing_duration=1, job_name="j1")
j1op3 = Operation(name="j1op3", machine=machines[1], processing_duration=1, job_name="j1")
job1 = Job(name="j1", operations=(j1op1, j1op2, j1op3))
jssp_instance = JobShopSchedulingProblemInstance(name="2_jobs_3_machines_seed_121", machines=machines, jobs=(job0, job1))
from queasars.job_shop_scheduling.visualization import plot_jssp_problem_instance_gantt
plot = plot_jssp_problem_instance_gantt(problem_instance=jssp_instance)
from queasars.job_shop_scheduling.domain_wall_hamiltonian_encoder import JSSPDomainWallHamiltonianEncoder
encoder = JSSPDomainWallHamiltonianEncoder(jssp_instance=jssp_instance, makespan_limit=6, max_opt_value=100, opt_all_operations_share=0.19, encoding_penalty=319, overlap_constraint_penalty=319, precedence_constraint_penalty=275)
print("needed qubits: ", encoder.n_qubits)
hamiltonian = encoder.get_problem_hamiltonian()
from qiskit_aer.primitives import Sampler
from qiskit_algorithms.optimizers import SPSA
from dask.distributed import LocalCluster
from queasars.minimum_eigensolvers.base.termination_criteria import BestIndividualRelativeChangeTolerance
from queasars.utility.spsa_termination import SPSATerminationChecker
from queasars.minimum_eigensolvers.evqe.evqe import EVQEMinimumEigensolverConfiguration
# The EVQEMinimumEigensolver needs at least a sampler and can also use an estimator.
# Here we only use a sampler, as the Critical Value at Risk objective value can
# can only be used when only using the sampler.
sampler_primitive = Sampler()
estimator_primitive = None
# If only a sampler is used, the expectation value with respect to the Hamiltonian
# is calculated using the measurement distribution provided by the sampler. This
# expectation value can also be calculated over only the lower tail of that distribution.
# In that case the objective score is also called the Critical Value at Risk.
distribution_alpha_tail = 0.5
# The EVQEMinimumEigensolver also needs a qiskit optimizer. It should be
# configured to terminate quickly, so that mutations are not overtly expensive.
# Here we use the SPSA optimizer with a very limited amount of iterations and a
# large step size.
termination_checker = SPSATerminationChecker(minimum_relative_change=0.01, allowed_consecutive_violations=2)
optimizer = SPSA(maxiter=33, perturbation=0.35, learning_rate=0.43, trust_region=True, last_avg=1, resamplings=1, termination_checker=termination_checker.termination_check)
# To help the EVQEMinimumEigensolver deal correctly with terminations based
# on the amount of circuit evaluations used, an estimate can be given for how
# many circuit evaluations the optimizer uses per optimization run.
# SPSA makes two measurements per gradient approximation, which means in total it will
# need 66 circuit evaluations for 33 iterations.
optimizer_n_circuit_evaluations = 66
# To specify when the EVQEMinimumEigensolver should terminate either max_generations,
# max_circuit_evaluations or a termination_criterion should be given.
max_generations = None
max_circuit_evaluations = None
termination_criterion = BestIndividualRelativeChangeTolerance(minimum_relative_change=0.01, allowed_consecutive_violations=1)
# A random seed can be provided to control the randomness of the evolutionary process.
random_seed = None
# The population size determines how many individuals are evaluated each generation.
# With a higher population size, fewer generations might be needed, but this also
# makes each generation more expensive to evaluate. A reasonable range might be
# 10 - 100 individuals per population.
population_size = 10
# The initial individuals in the starting population can be initialized with
# an arbitrary amount of layers and fully randomized parameter values. This
# can be particularly useful if the state |0 .. 0> is a local minima and
# the individuals should not start in that state
n_initial_layers = 2
randomize_initial_parameter_values = True
# Determines how many circuit layers apart two individuals need to be, to be considered to
# be of a different species. Reasonable values might be in the range 1 - 5.
speciation_genetic_distance_threshold = 1
# This implementation of EVQE offers both roulette wheel selection and tournament selection.
# Since tournament selection is more robust, we use it here.
use_tournament_selection = True
tournament_size = 2
# The alpha and beta penalties penalize quantum circuits of increasing depth (alpha) and
# increasing amount of controlled rotations (beta). increase them if the quantum circuits get to
# deep or complicated.
selection_alpha_penalty = 0.15
selection_beta_penalty = 0.02
# The parameter search probability determines how likely an individual is mutated by optimizing
# all it's parameter values. This should not be too large as this is costly.
parameter_search_probability = 0.39
# The topological search probability determines how likely a circuit layer is added to an individual
# as a mutation.
topological_search_probability = 0.79
# The layer removal probability determines how likely circuit layers are removed from an individual
# as a mutation. This is a very disruptive mutation and should only be used sparingly to counteract
# circuit growth.
layer_removal_probability = 0.02
# An executor for launching parallel computation can be specified.
# This can be a dask Client or a python ThreadPoolExecutor. If None is
# specified a ThreadPoolExecutor with population_size many threads will
# be used
parallel_executor = LocalCluster(n_workers=10, processes=True, threads_per_worker=1).get_client()
# Discerns whether to only allow mutually exclusive access to the Sampler and
# Estimator primitive respectively. This is needed if the Sampler or Estimator are not threadsafe and
# a ThreadPoolExecutor with more than one thread or a Dask Client with more than one thread per process is used.
# For safety reasons this is enabled by default. If the sampler and estimator are threadsafe disabling this
# option may lead to performance improvements
mutually_exclusive_primitives = False
configuration = EVQEMinimumEigensolverConfiguration(
sampler=sampler_primitive,
estimator=estimator_primitive,
distribution_alpha_tail=distribution_alpha_tail,
optimizer=optimizer,
optimizer_n_circuit_evaluations=optimizer_n_circuit_evaluations,
max_generations=max_generations,
max_circuit_evaluations=max_circuit_evaluations,
termination_criterion=termination_criterion,
random_seed=random_seed,
population_size=population_size,
n_initial_layers=n_initial_layers,
randomize_initial_population_parameters=randomize_initial_parameter_values,
speciation_genetic_distance_threshold=speciation_genetic_distance_threshold,
use_tournament_selection=use_tournament_selection,
tournament_size=tournament_size,
selection_alpha_penalty=selection_alpha_penalty,
selection_beta_penalty=selection_beta_penalty,
parameter_search_probability=parameter_search_probability,
topological_search_probability=topological_search_probability,
layer_removal_probability=layer_removal_probability,
parallel_executor=parallel_executor,
mutually_exclusive_primitives=mutually_exclusive_primitives,
)
from queasars.minimum_eigensolvers.evqe.evqe import EVQEMinimumEigensolver
eigensolver = EVQEMinimumEigensolver(configuration=configuration)
import logging
logger = logging.getLogger("queasars.minimum_eigensolvers.base.evolving_ansatz_minimum_eigensolver")
handler = logging.StreamHandler()
logger.setLevel(logging.INFO)
logger.addHandler(handler)
result = eigensolver.compute_minimum_eigenvalue(operator=hamiltonian)
quasi_distribution = result.eigenstate.binary_probabilities()
from qiskit.visualization import plot_distribution
plot_distribution(quasi_distribution, number_to_keep=10)
solutions = []
for bitstring, probability in quasi_distribution.items():
if probability < 0.05:
continue
solution = encoder.translate_result_bitstring(bitstring=bitstring)
print("probability: ", probability, "is valid: ", solution.is_valid)
print(solution)
if solution.is_valid:
solutions.append(solution)
from queasars.job_shop_scheduling.visualization import plot_jssp_problem_solution_gantt
for solution in solutions:
plot = plot_jssp_problem_solution_gantt(result=solution)
|
https://github.com/DLR-RB/QUEASARS
|
DLR-RB
|
from pathlib import Path
import os
import sys
main_directory = Path(os.path.abspath("")).parent
sys.path.append(str(main_directory))
from docplex.mp.model import Model
# set up the model for optimization in docplex
optimization_problem = Model()
# add the needed variables
x = optimization_problem.integer_var(0, 15, "x")
y = optimization_problem.integer_var(0, 15, "y")
a = optimization_problem.binary_var("a")
b = optimization_problem.binary_var("b")
# formally describe the minimization task
optimization_problem.minimize((2*x-y)**2 + 100*a*x - 100*b*y + (a + b - 1)**2)
from qiskit_optimization.translators import from_docplex_mp, to_ising
from qiskit_optimization.converters import IntegerToBinary
# convert to a quadratic program
quadratic_program = from_docplex_mp(model=optimization_problem)
# some variables are still integers, convert them to binary variables
integer_converter = IntegerToBinary()
quadratic_program = integer_converter.convert(problem=quadratic_program)
# convert the quadratic program to an ising hamiltonian
hamiltonian, offset = to_ising(quad_prog=quadratic_program)
from qiskit_aer.primitives import Sampler, Estimator
from qiskit_algorithms.optimizers import SPSA
from queasars.minimum_eigensolvers.base.termination_criteria import BestIndividualRelativeChangeTolerance
from queasars.minimum_eigensolvers.evqe.evqe import EVQEMinimumEigensolverConfiguration
# The EVQEMinimumEigensolver needs a sampler and can also use an estimator.
# Here we use the sampler and estimator provided by the qiskit_aer simulator.
sampler_primitive = Sampler()
estimator_primitive = Estimator()
# The EVQEMinimumEigensolver also needs a qiskit optimizer. It should be
# configured to terminate quickly, so that mutations are not overtly expensive.
# Here we use the SPSA optimizer with a very limited amount of iterations and a
# large step size.
optimizer = SPSA(maxiter=10, perturbation=0.2, learning_rate=0.2, trust_region=True)
# To help the EVQEMinimumEigensolver deal correctly with terminations based
# on the amount of circuit evaluations used, an estimate can be given for how
# many circuit evaluations the optimizer uses per optimization run.
# SPSA makes two measurements per iteration, which means in total it will
# need 20 circuit evaluations for 10 iterations.
optimizer_n_circuit_evaluations = 20
# To specify when the EVQEMinimumEigensolver should terminate either max_generations,
# max_circuit_evaluations or a termination_criterion should be given.
# Here we choose to terminate once the expectation value of the best individual of a generation
# changes by less than 0.5% between generations.
max_generations = None
max_circuit_evaluations = None
termination_criterion = BestIndividualRelativeChangeTolerance(minimum_relative_change=0.005)
# A random seed can be provided to control the randomness of the evolutionary process.
random_seed = 0
# The population size determines how many individuals are evaluated each generation.
# With a higher population size, fewer generations might be needed, but this also
# makes each generation more expensive to evaluate. A reasonable range might be
# 10 - 100 individuals per population. Here we use a population size of 25.
population_size = 25
# If the optimization algorithm can't deal with parameter values of 0 at the beginning
# of the optimization, they can be randomized here. For this example we don't need this.
randomize_initial_population_parameters = False
# Determines how many circuit layers apart two individuals need to be, to be considered to
# be of a different species. Reasonable values might be in the range 2 - 5. Here we use 3.
speciation_genetic_distance_threshold = 3
# The alpha and beta penalties penalize quantum circuits of increasing depth (alpha) and
# increasing amount of controlled rotations (beta). increase them if the quantum circuits get to
# deep or complicated. For now we will use values of 0.1 for both penalties.
selection_alpha_penalty = 0.1
selection_beta_penalty = 0.1
# The parameter search probability determines how likely an individual is mutated by optimizing
# all it's parameter values. This should not be too large as this is costly. Here we will use
# a probability of 0.25.
parameter_search_probability = 0.25
# The topological search probability determines how likely a circuit layer is added to an individual
# as a mutation. This should be a higher probability to encourage exploration of different circuits.
# Here we will use a likelihood of 0.5
topological_search_probability = 0.5
# The layer removal probability determines how likely circuit layers are removed from an individual
# as a mutation. This is a very disruptive mutation and should only be used sparingly to counteract
# circuit growth. Here we will use a probability of 0.1
layer_removal_probability = 0.1
# An executor for launching parallel computation can be specified.
# This can be a dask Client or a python ThreadPoolExecutor. If None is
# specified a ThreadPoolExecutor with population_size many threads will
# be used
parallel_executor = None
# Discerns whether to only allow mutually exclusive access to the Sampler and
# Estimator primitive respectively. This is needed if the Sampler or Estimator are not threadsafe and
# a ThreadPoolExecutor with more than one thread or a Dask Client with more than one thread per process is used.
# For safety reasons this is enabled by default. If the sampler and estimator are threadsafe disabling this
# option may lead to performance improvements
mutually_exclusive_primitives = True
configuration = EVQEMinimumEigensolverConfiguration(
sampler=sampler_primitive,
estimator=estimator_primitive,
optimizer=optimizer,
optimizer_n_circuit_evaluations=optimizer_n_circuit_evaluations,
max_generations=max_generations,
max_circuit_evaluations=max_circuit_evaluations,
termination_criterion=termination_criterion,
random_seed=random_seed,
population_size=population_size,
randomize_initial_population_parameters=randomize_initial_population_parameters,
speciation_genetic_distance_threshold=speciation_genetic_distance_threshold,
selection_alpha_penalty=selection_alpha_penalty,
selection_beta_penalty=selection_beta_penalty,
parameter_search_probability=parameter_search_probability,
topological_search_probability=topological_search_probability,
layer_removal_probability=layer_removal_probability,
parallel_executor=parallel_executor,
mutually_exclusive_primitives=mutually_exclusive_primitives,
)
from queasars.minimum_eigensolvers.evqe.evqe import EVQEMinimumEigensolver
eigensolver = EVQEMinimumEigensolver(configuration=configuration)
import logging
logger = logging.getLogger("queasars.minimum_eigensolvers.base.evolving_ansatz_minimum_eigensolver")
handler = logging.StreamHandler()
logger.setLevel(logging.INFO)
logger.addHandler(handler)
result = eigensolver.compute_minimum_eigenvalue(operator=hamiltonian)
quasi_distribution = result.eigenstate.binary_probabilities()
from qiskit.visualization import plot_distribution
plot_distribution(quasi_distribution, number_to_keep=10)
for bitstring, probability in quasi_distribution.items():
if probability < 0.05:
continue
bitlist = [int(char) for char in bitstring][::-1]
converted_variables = integer_converter.interpret(bitlist)
print("probability: ", probability)
print("variable values: ", converted_variables)
print("")
|
https://github.com/DLR-RB/QUEASARS
|
DLR-RB
|
from pathlib import Path
import os
import sys
main_directory = Path(os.path.abspath("")).parent
sys.path.append(str(main_directory))
from queasars.job_shop_scheduling.problem_instances import Machine, Operation, Job, JobShopSchedulingProblemInstance
machines = (Machine(name="m0"), Machine(name="m1"))
j0op1 = Operation(name="j0op0", machine=machines[0], processing_duration=2, job_name="j0")
j0op2 = Operation(name="j0op1", machine=machines[1], processing_duration=1, job_name="j0")
job0 = Job(name="j0", operations=(j0op1, j0op2))
j1op1 = Operation(name="j1op1", machine=machines[0], processing_duration=1, job_name="j1")
j1op2 = Operation(name="j1op2", machine=machines[1], processing_duration=2, job_name="j1")
job1 = Job(name="j1", operations=(j1op1, j1op2))
jssp_instance = JobShopSchedulingProblemInstance(name="Simple Instance", machines=machines, jobs=(job0, job1))
from queasars.job_shop_scheduling.visualization import plot_jssp_problem_instance_gantt
plot = plot_jssp_problem_instance_gantt(problem_instance=jssp_instance)
from queasars.job_shop_scheduling.domain_wall_hamiltonian_encoder import JSSPDomainWallHamiltonianEncoder
encoder = JSSPDomainWallHamiltonianEncoder(jssp_instance=jssp_instance, makespan_limit=5, opt_all_operations_share=0.19, max_opt_value=100, encoding_penalty=319, overlap_constraint_penalty=319, precedence_constraint_penalty=275)
print("needed qubits: ", encoder.n_qubits)
hamiltonian = encoder.get_problem_hamiltonian()
from qiskit import QuantumCircuit
from qiskit.primitives import SamplerResult
from qiskit.primitives.base import BaseSamplerV1
from qiskit.primitives.primitive_job import PrimitiveJob
from qiskit.transpiler import PassManager
# Sampler Primitive Wrapper to adjust for qiskit_ibm_runtime_primitives no longer
# offering cloud transpilation for free
class TranspilingSampler(BaseSamplerV1):
def __init__(self, sampler: BaseSamplerV1, pass_manager: PassManager):
super().__init__()
self._sampler = sampler
self._pass_manager = pass_manager
def _run(
self, circuits: tuple[QuantumCircuit, ...], parameter_values: tuple[tuple[float, ...], ...], **run_options
) -> PrimitiveJob[SamplerResult]:
applied_circuits = [circuit.assign_parameters(params) for circuit, params in zip(circuits, parameter_values)]
transpiled_circuits = self._pass_manager.run(applied_circuits)
return self._sampler.run(transpiled_circuits, **run_options)
import logging
from qiskit_algorithms.optimizers import SPSA
from qiskit_ibm_runtime import QiskitRuntimeService, Batch, Sampler
from qiskit_ibm_runtime.fake_provider.backends import FakeOsaka
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from queasars.utility.spsa_termination import SPSATerminationChecker
from queasars.minimum_eigensolvers.evqe.evqe import EVQEMinimumEigensolverConfiguration, EVQEMinimumEigensolver
# Connect to the runtime service using your IBM quantum token
runtime_service = QiskitRuntimeService(channel="ibm_quantum", token="Your token here!")
# Uncomment the second line and replace the backend name accordingly if you want to use real Quantum Hardware!
backend = FakeOsaka()
#backend = runtime_service.backend("ibm_kyoto")
# setup a pass manager to setup the transpilation process
pass_manager = generate_preset_pass_manager(optimization_level=1, backend=backend)
# Set up a session so that consecutive jobs may run in short succession.
with Batch(service=runtime_service, backend=backend) as batch:
# The EVQEMinimumEigensolver needs at least a sampler and can also use an estimator.
# Here we only use a sampler, as the Critical Value at Risk objective value can
# can only be used when only using the sampler.
sampler = Sampler(session=batch, options={"shots": 512, "optimization_level": 0, "resilience_level": 0})
sampler = TranspilingSampler(sampler, pass_manager)
estimator = None
# If only a sampler is used, the expectation value with respect to the Hamiltonian
# is calculated using the measurement distribution provided by the sampler. This
# expectation value can also be calculated over only the lower tail of that distribution.
# In that case the objective score is also called the Critical Value at Risk.
distribution_alpha_tail = 0.5
# The EVQEMinimumEigensolver also needs a qiskit optimizer. It should be
# configured to terminate quickly, so that mutations are not overtly expensive.
# Here we use the SPSA optimizer with a very limited amount of iterations and a
# large step size.
termination_checker = SPSATerminationChecker(minimum_relative_change=0.01, allowed_consecutive_violations=2)
optimizer = SPSA(maxiter=33, perturbation=0.35, learning_rate=0.43, trust_region=True, last_avg=1, resamplings=1, termination_checker=termination_checker.termination_check)
# To help the EVQEMinimumEigensolver deal correctly with terminations based
# on the amount of circuit evaluations used, an estimate can be given for how
# many circuit evaluations the optimizer uses per optimization run.
# SPSA makes two measurements per gradient approximation, which means in total it will
# need 66 circuit evaluations for 33 iterations.
optimizer_n_circuit_evaluations = 66
# To specify when the EVQEMinimumEigensolver should terminate either max_generations,
# max_circuit_evaluations or a termination_criterion should be given.
# Here we set a fixed generation limit, to reduce the runtime usage.
max_generations = 3
max_circuit_evaluations = None
termination_criterion = None
# A random seed can be provided to control the randomness of the evolutionary process.
random_seed = None
# The population size determines how many individuals are evaluated each generation.
# With a higher population size, fewer generations might be needed, but this also
# makes each generation more expensive to evaluate.
population_size = 5
# The initial individuals in the starting population can be initialized with
# an arbitrary amount of layers and fully randomized parameter values. This
# can be particularly useful if the state |0 .. 0> is a local minima and
# the individuals should not start in that state
n_initial_layers = 1
randomize_initial_parameter_values = True
# Determines how many circuit layers apart two individuals need to be, to be considered to
# be of a different species. Reasonable values might be in the range 1 - 5.
speciation_genetic_distance_threshold = 1
# This implementation of EVQE offers both roulette wheel selection and tournament selection.
# Since tournament selection is more robust, we use it here.
use_tournament_selection = True
tournament_size = 2
# The alpha and beta penalties penalize quantum circuits of increasing depth (alpha) and
# increasing amount of controlled rotations (beta). increase them if the quantum circuits get to
# deep or complicated.
selection_alpha_penalty = 0.15
selection_beta_penalty = 0.02
# The parameter search probability determines how likely an individual is mutated by optimizing
# all it's parameter values. This should not be too large as this is costly.
parameter_search_probability = 0.39
# The topological search probability determines how likely a circuit layer is added to an individual
# as a mutation. This should be a higher probability to encourage exploration of different circuits.
topological_search_probability = 0.79
# The layer removal probability determines how likely circuit layers are removed from an individual
# as a mutation. This is a very disruptive mutation and should only be used sparingly to counteract
# circuit growth.
layer_removal_probability = 0.02
# An executor for launching parallel computation can be specified.
# This can be a dask Client or a python ThreadPoolExecutor. If None is
# specified a ThreadPoolExecutor with population_size many threads will
# be used
parallel_executor = None
# Discerns whether to only allow mutually exclusive access to the Sampler and
# Estimator primitive respectively. This is needed if the Sampler or Estimator are not threadsafe and
# a ThreadPoolExecutor with more than one thread or a Dask Client with more than one thread per process is used.
# For safety reasons this is enabled by default. If the sampler and estimator are threadsafe disabling this
# option may lead to performance improvements
mutually_exclusive_primitives = True
configuration = EVQEMinimumEigensolverConfiguration(
sampler=sampler,
estimator=estimator,
distribution_alpha_tail=distribution_alpha_tail,
optimizer=optimizer,
optimizer_n_circuit_evaluations=optimizer_n_circuit_evaluations,
max_generations=max_generations,
max_circuit_evaluations=max_circuit_evaluations,
termination_criterion=termination_criterion,
random_seed=random_seed,
population_size=population_size,
n_initial_layers=n_initial_layers,
randomize_initial_population_parameters=randomize_initial_parameter_values,
speciation_genetic_distance_threshold=speciation_genetic_distance_threshold,
use_tournament_selection=use_tournament_selection,
tournament_size=tournament_size,
selection_alpha_penalty=selection_alpha_penalty,
selection_beta_penalty=selection_beta_penalty,
parameter_search_probability=parameter_search_probability,
topological_search_probability=topological_search_probability,
layer_removal_probability=layer_removal_probability,
parallel_executor=parallel_executor,
mutually_exclusive_primitives=mutually_exclusive_primitives,
)
eigensolver = EVQEMinimumEigensolver(configuration=configuration)
logger = logging.getLogger("queasars.minimum_eigensolvers.base.evolving_ansatz_minimum_eigensolver")
handler = logging.StreamHandler()
logger.setLevel(logging.INFO)
logger.addHandler(handler)
result = eigensolver.compute_minimum_eigenvalue(operator=hamiltonian)
from json import dump
from queasars.minimum_eigensolvers.base.serialization import EvolvingAnsatzMinimumEigensolverResultJSONEncoder
file_path = Path(main_directory, "examples", "queasars_result.json")
with open(file_path, "w") as file:
dump(obj=result, fp=file, indent=2, cls=EvolvingAnsatzMinimumEigensolverResultJSONEncoder)
from qiskit.visualization import plot_distribution
quasi_distribution = result.eigenstate.binary_probabilities()
plot_distribution(quasi_distribution, number_to_keep=10)
solutions = []
for bitstring, probability in quasi_distribution.items():
if probability < 0.1:
continue
solution = encoder.translate_result_bitstring(bitstring=bitstring)
print("probability: ", probability)
print(solution)
solutions.append(solution)
from queasars.job_shop_scheduling.visualization import plot_jssp_problem_solution_gantt
for solution in solutions:
if solution.is_valid:
plot = plot_jssp_problem_solution_gantt(result=solution)
|
https://github.com/KathrinKoenig/QuantumTopologicalDataAnalysis
|
KathrinKoenig
|
import numpy as np
import qtda_module as qtda
from qiskit.visualization import plot_histogram
import matplotlib.pyplot as plt
from scipy.spatial import distance_matrix
from qiskit import ClassicalRegister, Aer, execute
def generate_circles():
phi_values = np.linspace(0, 2*np.pi, 10)
small_circle = [[np.cos(phi), np.sin(phi)] for phi in phi_values]
phi_values = np.linspace(0, 2*np.pi, 12)
large_circle = [[3 + 2*np.cos(phi), 2*np.sin(phi)] for phi in phi_values]
return np.array(small_circle + large_circle)
point_data = generate_circles()
plt.scatter(point_data[:,0], point_data[:,1])
# alternatively a distance matrix (here generated from the point data for exemplification)
# can be used
dist_mat = distance_matrix(point_data, point_data)
filtration = qtda.DataFiltration(
data=point_data,
# distance_matrix=dist_mat,
max_dimension=4,
max_edge_length=10
)
filtration.plot_persistence_diagram()
n_vertices = 4 # number of qubits to represent the simplicial complex
num_eval_qubits = 5 # number of numerical evaluation qubits for the QPE algorithm
S0 = [(0,0,0,1),(0,0,1,0), (0,1,0,0),(1,0,0,0)] # 0-simplex: points in the graph
S1 = [(0,0,1,1),(0,1,1,0),(1,1,0,0),(1,0,0,1),(1,0,1,0)] # 1-simplex: connection lines between points
S2 = [(1,0,1,1)] # 2-simplex: filled triangle
S3 = []
state_dict = {0: S0, 1: S1, 2: S2, 3: S3}
k = 1 # order of the combinatorial Laplacian
qc = qtda.QTDAalgorithm(num_eval_qubits, k, state_dict)
qc.draw('mpl')
qc.add_register(ClassicalRegister(num_eval_qubits)) #add classical register to measure evaluation qubits
for q in qc.eval_qubits:
qc.measure(q,q)
shots = 1000
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=shots)
counts = job.result().get_counts(qc)
dim = len(state_dict[1]) # dimension of 1-simplex space
prob = counts.get("0"*num_eval_qubits)/shots # probability of eigenvalue 0
print('The number of 1-holes is', dim * prob)
plot_histogram(counts)
shots = 1000
num_eval_qubits = 10
data = qtda.Q_top_spectra(state_dict, num_eval_qubits, shots)
spectra = data.get_spectra()
for top_order in spectra.keys():
print()
print('Topological order: ', top_order)
print('Number of holes: ', spectra[top_order][0.0])
print('Dimension of the k-simplex subspace: ', len(data.state_dict[top_order]))
print('Eigenvalues of the combinatorial laplacian with dimension of corresponding eigenspaces: ')
print(spectra[top_order])
display(plot_histogram(data.get_counts()[top_order]))
n_vertices = 4
S0 = [(0,0,0,1),(0,0,1,0), (0,1,0,0),(1,0,0,0)]
S1 = [(0,0,1,1),(0,1,1,0),(1,1,0,0),(1,0,0,1),(1,0,1,0)]
S2 = []
S3 = []
state_dict = {0: S0, 1: S1, 2: S2, 3: S3}
shots = 1000
num_eval_qubits = 10
data = qtda.Q_top_spectra(state_dict, num_eval_qubits, shots)
spectra = data.get_spectra()
for top_order in spectra.keys():
print()
print('Topological order: ', top_order)
print('Number of holes: ', spectra[top_order][0.0])
print('Dimension of the k-simplex subspace: ', len(data.state_dict[top_order]))
print('Eigenvalues of the combinatorial laplacian with dimension of corresponding eigenspaces: ')
print(spectra[top_order])
display(plot_histogram(data.get_counts()[top_order]))
import qiskit
qiskit.__qiskit_version__
|
https://github.com/KathrinKoenig/QuantumTopologicalDataAnalysis
|
KathrinKoenig
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 24 11:04:02 2021
@author: Eric Brunner, Kathrin König, Andreas Woitzik
"""
import itertools as it
import numpy as np
import gudhi as gd
from scipy.sparse import csr_matrix
from scipy.linalg import expm
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import Aer
from qiskit import execute
from qiskit.extensions import UnitaryGate
def vec_to_state(vec):
'''converts vec to state'''
n_vertices = int(np.log2(len(vec)))
basis_list = list(it.product(range(2), repeat=n_vertices))
indices = np.nonzero(vec)[0]
return {basis_list[i]: vec[i] for i in indices}
def state_to_vec(state):
'''state is a list of state'''
n_vertices = len(state[0])
basis_list = list(it.product(range(2), repeat=n_vertices))
basis_dict = {basis_list[i]: i for i in range(2**n_vertices)}
vec = np.zeros(2**n_vertices)
for stat in state:
vec[basis_dict[stat]] = 1
return vec
def boundary_operator(x_tuple):
'''calculates the boundary of a simplex desribed by x_tuple'''
x_np = np.array(x_tuple)
indices = np.nonzero(x_np)[0]
dictionary = {}
k = len(indices)
for i in range(k):
helper = x_np.copy()
helper[indices[k-1-i]] = 0.0
dictionary[tuple(helper)] = (-1.)**(i)
return dictionary
def boundary_operator_dict(n_vertices):
'''
returns the boundary operator on n vertices as a dictionary
'''
dictionary = {}
dictionary[
(
tuple([0]*n_vertices),
tuple([0]*n_vertices)
)
] = 0
for bound in it.product(range(2), repeat=n_vertices):
helper = boundary_operator(bound)
for key in helper:
dictionary[(tuple(bound), key)] = helper[key]
return dictionary
def boundary_operator_dict_k(n_vertices, k):
'''
returns the boundary operator of order k on n vertices as a dictionary
'''
dictionary = {}
dictionary[
(
tuple([0]*n_vertices),
tuple([0]*n_vertices)
)
] = 0
for bound in it.product(range(2), repeat=n_vertices):
if np.sum(bound) == k+1:
helper = boundary_operator(bound)
for key in helper:
dictionary[(tuple(bound), key)] = helper[key]
return dictionary
def boundary_operator_crsmat(n_vertices):
'''
returns boundary operator on n vertices as sparse crs matrix
'''
dictionary = boundary_operator_dict(n_vertices)
basis_list = list(it.product(range(2), repeat=n_vertices))
basis_dict = {basis_list[i]: i for i in range(2**n_vertices)}
col = np.array([basis_dict[index[0]] for index in dictionary])
row = np.array([basis_dict[index[1]] for index in dictionary])
data = np.array(list(dictionary.values()))
return csr_matrix((data, (row, col)), shape=(2**n_vertices, 2**n_vertices))
def boundary_operator_crsmat_k(n_vertices, k):
'''
returns boundary operator of order k on n vertices as sparse crs matrix
'''
dictionary = boundary_operator_dict_k(n_vertices, k)
basis_list = list(it.product(range(2), repeat=n_vertices))
basis_dict = {basis_list[i]: i for i in range(2**n_vertices)}
col = np.array([basis_dict[index[0]] for index in dictionary])
row = np.array([basis_dict[index[1]] for index in dictionary])
data = np.array(list(dictionary.values()))
return csr_matrix((data, (row, col)), shape=(2**n_vertices, 2**n_vertices))
def combinatorial_laplacian(n_vertices, k):
'''
returns combinatorial Laplacian of order k on n vertices
as sparse crs matrix
'''
delta_k = boundary_operator_crsmat_k(n_vertices, k)
delta_kplus1 = boundary_operator_crsmat_k(n_vertices, k+1)
return delta_k.conj().T @ delta_k + delta_kplus1 @ delta_kplus1.conj().T
def projector_onto_state(n_vertices, state):
'''projector onto simplex state'''
basis_list = list(it.product(range(2), repeat=n_vertices))
basis_dict = {basis_list[i]: i for i in range(2**n_vertices)}
indices = [basis_dict[s] for s in state]
return csr_matrix(
(np.ones(len(indices)), (indices, indices)),
shape=(2**n_vertices, 2**n_vertices)
)
def projected_combinatorial_laplacian(n_vertices, k, state_dict):
'''
returns the projected combinatorial Laplacian of order k on n vertices
as sparse crs matrix
'''
p_k = projector_onto_state(n_vertices, state_dict[k])
p_kp1 = projector_onto_state(n_vertices, state_dict[k+1])
delta_k = boundary_operator_crsmat_k(n_vertices, k) @ p_k
delta_kplus1 = boundary_operator_crsmat_k(n_vertices, k+1) @ p_kp1
return delta_k.conj().T @ delta_k + delta_kplus1 @ delta_kplus1.conj().T
def initialize_projector(
state,
circuit=None,
initialization_qubits=None,
circuit_name=None
):
'''
initializes projector onto subspace spanned by list of states
input circuit has to have classical register
'''
if circuit is None:
n_vertices = len(state[0])
qr1 = QuantumRegister(n_vertices, name="state_reg")
copy_reg = QuantumRegister(n_vertices, name="copy_reg")
quantum_circuit = QuantumCircuit(qr1, copy_reg)
state_vec = state_to_vec(state)
state_vec = state_vec/np.linalg.norm(state_vec)
quantum_circuit.initialize(state_vec, qr1)
# quantum_circuit.barrier()
for k in range(n_vertices):
quantum_circuit.cx(qr1[k], copy_reg[k])
# quantum_circuit.barrier()
else:
n_vertices = len(state[0])
qr1 = QuantumRegister(n_vertices, name="state_reg")
copy_reg = QuantumRegister(n_vertices, name="copy_reg")
if circuit.num_qubits - n_vertices > 0:
anr = QuantumRegister(
circuit.num_qubits - n_vertices,
name="an_reg"
)
quantum_circuit = QuantumCircuit(anr, qr1, copy_reg)
else:
quantum_circuit = QuantumCircuit(qr1, copy_reg)
state_vec = state_to_vec(state)
state_vec = state_vec/np.linalg.norm(state_vec)
quantum_circuit.initialize(state_vec, qr1)
# quantum_circuit.barrier()
for k in range(n_vertices):
quantum_circuit.cx(qr1[k], copy_reg[k])
# quantum_circuit.barrier()
if initialization_qubits is None:
init = list(range(n_vertices))
else:
init = initialization_qubits
rest = list(set(range(circuit.num_qubits)) - set(init))
sub_inst = circuit.to_instruction()
if circuit_name is not None:
sub_inst.name = circuit_name
quantum_circuit.append(sub_inst, rest + init)
return quantum_circuit
def simplices_to_states(test_list, n_vertices):
'''
converts the simplices to a matrix
'''
n_states = len(test_list)
arr = np.zeros((n_states, n_vertices))
for k in range(n_states):
arr[k, test_list[k]] = 1
return arr
class DataFiltration:
'''
data: point data given by (number_data_points x dim_points)-numpy-array
distance_matrix: (n x n)-numpy-array describing the pair-wise
distances of n data points
Either one of them has to be given!
'''
def __init__(
self,
data=None,
distance_matrix=None,
max_dimension=None,
max_edge_length=None
):
if data is not None:
self.skeleton = gd.RipsComplex(
points=data,
max_edge_length=max_edge_length
)
elif distance_matrix is not None:
self.skeleton = gd.RipsComplex(
distance_matrix=distance_matrix,
max_edge_length=max_edge_length
)
else:
print('Either point data or distance matrix has to be provided!')
self.Rips_simplex_tree = self.skeleton.create_simplex_tree(
max_dimension=max_dimension
)
self.num_vertices = self.Rips_simplex_tree.num_vertices()
self.num_simplices = self.Rips_simplex_tree.num_simplices()
self.filtration = list(self.Rips_simplex_tree.get_filtration())
def get_filtration_states(self, epsilons=None):
'''
epsilons: different radia for the filtration
returns a dictionary of the filtration
'''
if epsilons is None:
epsilons = set([x[1] for x in self.filtration])
filt_dict = {}
for eps in epsilons:
helper_list = [x[0] for x in self.filtration if x[1] <= eps]
filt_dict[eps] = simplices_to_states(
helper_list, self.num_vertices
)
return filt_dict
def plot_persistence_diagram(self):
''' plots a diagram for the persistent topologial features '''
bar_codes = self.Rips_simplex_tree.persistence()
gd.plot_persistence_diagram(bar_codes, legend=True)
def controled_u(unitary, quantum_circuit, num_eval_qubits, n_vertices): # , k, state_dict):
'''
returns a quantum circuit with the controled unitary for the
quantum phase estimation routine.
'''
unit = unitary
gate = UnitaryGate(unit)
for counting_qubit in range(num_eval_qubits):
quantum_circuit.append(
gate.control(1),
[counting_qubit] + list(
range(num_eval_qubits, num_eval_qubits+n_vertices)
)
)
unit = unit@unit
gate = UnitaryGate(unit)
return quantum_circuit
def qft_dagger(quantum_circuit, num):
"""n-qubit QFTdagger the first n qubits in circ"""
# Don't forget the Swaps!
for qubit in range(num//2):
quantum_circuit.swap(qubit, num-qubit-1)
for j in range(num):
for k in range(j):
quantum_circuit.cp(-np.pi/float(2**(j-k)), k, j)
quantum_circuit.h(j)
def qpe_total(num_eval_qubits, n_vertices, unitary): # , k, state_dict):
'''
returns the full circuit of the quantum phase estimation
'''
quantum_circuit = QuantumCircuit(num_eval_qubits + n_vertices)
for qubit in range(num_eval_qubits):
quantum_circuit.h(qubit)
controled_u(unitary, quantum_circuit, num_eval_qubits, n_vertices) # , k, state_dict)
# Apply inverse QFT
qft_dagger(quantum_circuit, num_eval_qubits)
return quantum_circuit
class QTDAalgorithm(QuantumCircuit):
'''
Class that contains the QTDA algorithm.
num_eval_qubits: number of qubits for the evaluation in the quantum phase
estimation
top_order: the topological order
state_dict: the dictionary of states
'''
def __init__(self, num_eval_qubits, top_order, state_dict, name='QTDA'):
n_vertices = len(state_dict[0][0])
qr_eval = QuantumRegister(num_eval_qubits, 'eval')
qr_state = QuantumRegister(n_vertices, 'state')
qr_copy = QuantumRegister(n_vertices, 'copy')
super().__init__(qr_eval, qr_state, qr_copy, name=name)
unitary = expm(
1j*projected_combinatorial_laplacian(
n_vertices, top_order, state_dict
).toarray()
)
'''
we can also directly use the PhaseEstimation routine from Qiskit,
which, however, leads to a larger circuit depth than our designed
qpe_total implementation
'''
# gate = UnitaryGate(unitary)
# qpe = qiskit.circuit.library.PhaseEstimation(
# num_eval_qubits, unitary=gate, iqft=None, name='QPE'
# )
qpe = qpe_total(num_eval_qubits, n_vertices, unitary)
sub_inst = qpe.to_instruction()
sub_inst.name = ' QPE '
state_vec = state_to_vec(state_dict[top_order])
state_vec = state_vec/np.linalg.norm(state_vec)
self.initialize(state_vec, qr_state)
# for a better visualisation one can imput barriers, but they slow
# down the computation.
# self.barrier()
for k in range(n_vertices):
self.cx(qr_state[k], qr_copy[k])
# self.barrier()
self.append(sub_inst, list(range(num_eval_qubits + n_vertices)))
self.eval_qubits = list(range(num_eval_qubits))
class Q_top_spectra:
'''
data: point data given by (number_data_points x dim_points)-numpy-array
distance_matrix: (n x n)-numpy-array describing the pair-wise
distances of n data points
Either one of them has to be given!
'''
def __init__(self, state_dict, num_eval_qubits=6, shots=1000):
self.shots = shots
self.state_dict = state_dict
self.counts = {}
for top_order in self.state_dict:
print('Topological order: ', top_order)
if len(self.state_dict[top_order]) == 0:
print(
"calculation terminated because no simplex of dimension %s" % (top_order)
)
break
quantum_circuit = QTDAalgorithm(num_eval_qubits, top_order, self.state_dict)
quantum_circuit.add_register(ClassicalRegister(num_eval_qubits, name="phase"))
for qubit in quantum_circuit.eval_qubits:
quantum_circuit.measure(qubit, qubit)
backend = Aer.get_backend('qasm_simulator')
job = execute(quantum_circuit, backend, shots=self.shots)
self.counts[top_order] = job.result().get_counts(quantum_circuit)
def get_counts(self):
'''
returns the number of counts
'''
return self.counts
def get_spectra(self, chop=None):
'''
defaul chop: eigenvalues with less then 2% of all shots are regarded
as noise (can be adjusted)
exception: the eigenspace of eigenvalue 0 is important, even if it is
0-dimensional; hence, this is always included
'''
if chop is None:
chop = self.shots/50
eigenvalue_dict = {}
for top_order in self.counts:
eigenvalue_dict[top_order] = {}
eigenvalue_dict[top_order][0.0] = 0
vals = np.fromiter(self.counts[top_order].values(), dtype=float)
keys = list(self.counts[top_order].keys())
indices = np.where(vals >= chop)
new_vals = vals[indices]
new_keys = [keys[i] for i in indices[0]]
for i in range(len(new_keys)):
eigenvalue_dict[top_order][
2*np.pi*int(new_keys[i], 2)/int(len(new_keys[i])*'1', 2)
] = (
new_vals[i]
* len(self.state_dict[top_order])
/ self.shots
)
return eigenvalue_dict
class Q_persistent_top_spectra:
'''
data: point data given by (number_data_points x dim_points)-numpy-array
distance_matrix: (n x n)-numpy-array describing the pair-wise
distances of n data points
Either one of them has to be given!
'''
def __init__(
self,
data=None,
distance_matrix=None,
max_dimension=None,
max_edge_length=None,
num_eval_qubits=6,
shots=1000,
epsilons=None
):
self.shots = shots
self.filt_dict = DataFiltration(
data=data,
distance_matrix=distance_matrix,
max_dimension=max_dimension,
max_edge_length=max_edge_length
).get_filtration_states(epsilons=epsilons)
self.state_dict = {}
for key in sorted(self.filt_dict.keys()):
self.state_dict[key] = {}
for k in range(1, max_dimension+1):
mask = np.sum(self.filt_dict[key], axis=1) == k
self.state_dict[key][k-1] = [
tuple(s)
for s in self.filt_dict[key][mask, :]
]
self.state_dict[key][max_dimension] = [] # an empty state has to be included
# on order max_dimension for consistency
self.counts = {}
for eps in self.state_dict:
print()
print('Filtration scale: ', eps)
print()
self.counts[eps] = {}
for top_order in self.state_dict[eps]:
print('Topological order: ', top_order)
if len(self.state_dict[eps][top_order]) == 0:
print(
"calculation terminated because no simplex of dimension %s" % (top_order)
)
break
quantum_circuit = QTDAalgorithm(
num_eval_qubits,
top_order,
self.state_dict[eps]
)
quantum_circuit.add_register(
ClassicalRegister(num_eval_qubits, name="phase")
)
for qubit in quantum_circuit.eval_qubits:
quantum_circuit.measure(qubit, qubit)
backend = Aer.get_backend('qasm_simulator')
job = execute(quantum_circuit, backend, shots=self.shots)
self.counts[eps][top_order] = job.result().get_counts(quantum_circuit)
def get_counts(self):
'''
returns the number of counts
'''
return self.counts
def get_eigenvalues(self, chop=None):
'''
defaul chop: eigenvalues with less then 2% of all shots are regarded
as noise (can be adjusted)
exception: the eigenspace of eigenvalue 0 is important, even if it is
0-dimensional; hence, this is always included
'''
if chop is None:
chop = self.shots/50
eigenvalue_dict = {}
for eps in self.counts:
eigenvalue_dict[eps] = {}
for top_order in self.counts[eps]:
eigenvalue_dict[eps][top_order] = {}
eigenvalue_dict[eps][top_order][0.0] = 0
vals = np.fromiter(
self.counts[eps][top_order].values(), dtype=float
)
keys = list(self.counts[eps][top_order].keys())
indices = np.where(vals >= chop)
new_vals = vals[indices]
new_keys = [keys[i] for i in indices[0]]
for i, key in enumerate(new_keys):
eigenvalue_dict[eps][top_order][
2*np.pi*int(key, 2)/int(len(new_keys[i])*'1', 2)
] = (
new_vals[i]
* len(self.state_dict[eps][top_order])
/ self.shots
)
return eigenvalue_dict
|
https://github.com/KathrinKoenig/QuantumTopologicalDataAnalysis
|
KathrinKoenig
|
import numpy as np
import qtda_module as qtda
from qiskit.visualization import plot_histogram
point_data = np.array([
[0.,0.],
[1.,0.],
[1.,1.],
[0.,1.],
])
# alternatively a distance matrix (here generated from the point data for exemplification)
# can be used
from scipy.spatial import distance_matrix
dist_mat = distance_matrix(point_data, point_data)
filtration = qtda.DataFiltration(
data=point_data,
# distance_matrix=dist_mat,
max_dimension=3,
max_edge_length=2
)
filtration.plot_persistence_diagram()
shots = 1000
num_eval_qubits = 10
# epsilons = [0.1, 1.1, 1.5]
data = qtda.Q_persistent_top_spectra(
data = point_data,
# distance_matrix=distance_matrix,
max_dimension=3,
max_edge_length=2,
num_eval_qubits=num_eval_qubits,
shots=shots)
eigenvalue_dict = data.get_eigenvalues()
for eps in eigenvalue_dict.keys():
print()
print()
print('Filtration scale: ', eps)
for top_order in eigenvalue_dict[eps].keys():
print()
print('Topological order: ', top_order)
print('Number of holes: ', eigenvalue_dict[eps][top_order][0.0])
print('Dimension of the k-simplex subspace: ', len(data.state_dict[eps][top_order]))
print('Eigenvalues of the combinatorial laplacian with dimension of corresponding eigenspaces: ')
print(eigenvalue_dict[eps][top_order])
display(plot_histogram(data.get_counts()[eps][top_order]))
import qiskit
qiskit.__qiskit_version__
|
https://github.com/KathrinKoenig/QuantumTopologicalDataAnalysis
|
KathrinKoenig
|
import numpy as np
import qtda_module as qtda
from qiskit.visualization import plot_histogram
from qiskit import IBMQ
from qiskit import execute, QuantumRegister, QuantumCircuit, ClassicalRegister, Aer
from qiskit.compiler import transpile
provider = IBMQ.load_account()
accountProvider = IBMQ.get_provider(hub='ibm-q-fraunhofer',group = 'fhg-all',project = 'ticket')
backend = accountProvider.get_backend('ibmq_brooklyn')
n_vertices = 3 # number of vertices
num_eval_qubits = 3 # number of evaluation qubits
S0 = [(0,0,1),(0,1,0), (1,0,0)] # points
S1 = [(1,0,1),(0,1,1),(1,1,0)] # lines
S2 = []
state_dict = {0: S0, 1: S1, 2: S2}
k = 1 # order of the combinatorial Laplacian
qc = qtda.QTDAalgorithm(num_eval_qubits, k, state_dict)
qc.add_register(ClassicalRegister(num_eval_qubits)) # adding a classical register for measuring
for q in qc.eval_qubits: # measure all evaluation qubits
qc.measure(q,q)
qc.draw('mpl')
qcc = transpile(qc, basis_gates=['id', 'rz', 'sx', 'x', 'cx'], layout_method='sabre',optimization_level=3)
qa = transpile(qc, backend=backend, basis_gates=['id', 'rz', 'sx', 'x', 'cx'],layout_method='sabre',optimization_level=3)
qa.depth() # depth of ibmq_brooklyn
qcc.depth() # depth of an arbitrary backend
shots = 8192
job = execute(qa, backend, shots=shots)
counts = job.result().get_counts(qa)
dim = len(state_dict[1]) # dimension of 1-simplex space
prob = counts.get("0"*num_eval_qubits)/shots # probability of eigenvalue 0
print('The number of 1-holes is', dim * prob)
plot_histogram(counts)
import qiskit
qiskit.__qiskit_version__
|
https://github.com/AbeerVaishnav13/Quantum-Programs
|
AbeerVaishnav13
|
##The following statement imports Qiskit libraries in the notebook!
import qiskit
##To create a Quantum Circuit with 1 qubit
from qiskit import QuantumCircuit as qc
cirq = qc(1)
##To plot the circuit using MatplotLib
cirq.draw('mpl')
#To make a state vector and see it
from qiskit.quantum_info import Statevector
sv = Statevector.from_label('0')
sv
#To see the specific Array data
sv.data
#To apply the new state vector over the constructed circuit
new_sv = sv.evolve(cirq)
new_sv
#To check the State Fidelity
from qiskit.quantum_info import state_fidelity
state_fidelity(sv , new_sv)
#To plot the Q-Sphere
from qiskit.visualization import plot_state_qsphere
plot_state_qsphere(new_sv.data)
#Adding an X gate for qubit flip
cirq1 = qc(1)
cirq1.x(0)
cirq1.draw('mpl')
#Adding a hadamard gate to create a superposition
cirq2 = qc(1)
cirq2.h(0)
cirq2.draw('mpl')
#Adding a t gate
cirq3 = qc(1)
cirq3.t(0)
cirq3.draw('mpl')
#Adding a s gate
cirq4 = qc(1)
cirq4.s(0)
cirq4.draw('mpl')
#Creating a multi state vector |00>
sv = Statevector.from_label('10010')
plot_state_qsphere(sv.data)
my_cirq = qc(3, 3)
my_sv = Statevector.from_label('000')
my_cirq.h(0)
my_cirq.cx(0 , 1)
my_cirq.cx(0 , 2)
display(my_cirq.draw('mpl'))
print(my_sv)
new_my_sv = my_sv.evolve(my_cirq)
print(new_my_sv)
plot_state_qsphere(new_my_sv.data)
##Setting numer of shots and plotting the Histogram
counts = new_my_sv.sample_counts(shots = 1000)
from qiskit.visualization import *
from matplotlib import style
style.use('bmh')
style.use('dark_background')
plot_histogram(counts)
plot_state_city(my_sv)
my_cirq.measure([0,1], [0,1])
my_cirq.draw('mpl')
from qiskit import *
#SIMULATION
simulator = Aer.get_backend('qasm_simulator')
result = execute(my_cirq, simulator, shots=10000).result()
count = result.get_counts(my_cirq)
plot_histogram(count)
|
https://github.com/AbeerVaishnav13/Quantum-Programs
|
AbeerVaishnav13
|
from qiskit import *
%matplotlib inline
import numpy as np
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.draw('mpl')
from qiskit.visualization import plot_state_hinton
sim = Aer.get_backend('statevector_simulator') # qasm_simulator, statevector_simulator, unitary_simulator
result = execute(qc, backend=sim).result()
state = result.get_statevector(qc)
plot_state_hinton(state)
from qiskit.visualization import *
from matplotlib import style
style.use('bmh')
style.use('dark_background')
plot_state_city(state)
plot_state_paulivec(result.get_statevector(qc))
from qiskit import IBMQ
IBMQ.load_account()
from qiskit.tools.monitor import job_monitor
provider = IBMQ.get_provider(hub='ibm-q', group='open')
backend = provider.get_backend('ibmq_santiago')
job = execute(qc, backend=backend, shots=8192)
job_monitor(job)
from qiskit.visualization import plot_histogram
result = job.result()
plot_histogram(result.get_counts(qc))
|
https://github.com/AbeerVaishnav13/Quantum-Programs
|
AbeerVaishnav13
|
from qiskit import *
%matplotlib inline
from qiskit.tools.visualization import plot_histogram
secretnumber = '101101'
circuit = QuantumCircuit(6+1, 6)
circuit.h([0,1,2,3,4,5])
circuit.x([6])
circuit.h([6])
circuit.barrier()
circuit.cx(5, 6)
circuit.cx(3, 6)
circuit.cx(2, 6)
circuit.cx(0, 6)
circuit.barrier()
circuit.h([0,1,2,3,4,5])
circuit.barrier()
circuit.measure([0,1,2,3,4,5], [0,1,2,3,4,5])
circuit.draw('mpl')
from matplotlib import style
style.use('bmh')
style.use('dark_background')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit, backend = simulator, shots = 1).result()
counts = result.get_counts()
print(counts)
plot_histogram(counts)
|
https://github.com/AbeerVaishnav13/Quantum-Programs
|
AbeerVaishnav13
|
from qiskit import *
import numpy as np
%matplotlib inline
from matplotlib import style
style.use('bmh')
style.use('dark_background')
def dj_oracle(case, n):
# We need to make a QuantumCircuit object to return
# This circuit has n+1 qubits: the size of the input,
# plus one output qubit
oracle_qc = QuantumCircuit(n+1)
# First, let's deal with the case in which oracle is balanced
if case == "balanced":
# First generate a random number that tells us which CNOTs to
# wrap in X-gates:
b = np.random.randint(1,2**n)
# Next, format 'b' as a binary string of length 'n', padded with zeros:
b_str = format(b, '0'+str(n)+'b')
# Next, we place the first X-gates. Each digit in our binary string
# corresponds to a qubit, if the digit is 0, we do nothing, if it's 1
# we apply an X-gate to that qubit:
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Do the controlled-NOT gates for each qubit, using the output qubit
# as the target:
for qubit in range(n):
oracle_qc.cx(qubit, n)
# Next, place the final X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Case in which oracle is constant
if case == "constant":
# First decide what the fixed output of the oracle will be
# (either always 0 or always 1)
output = np.random.randint(2)
if output == 1:
oracle_qc.x(n)
oracle_gate = oracle_qc.to_gate()
oracle_gate.name = "Oracle" # To show when we display the circuit
display(oracle_qc.draw('mpl'))
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('constant', n)
dj_circuit = dj_algorithm(oracle_gate, n)
dj_circuit.draw('mpl')
from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
results = execute(dj_circuit, backend=backend, shots=1024).result()
answer = results.get_counts()
plot_histogram(answer)
# Load our saved IBMQ accounts and get the least busy backend device with greater than or equal to (n+1) qubits
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_ourense')
# 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(dj_circuit, backend=backend, shots=shots, optimization_level=3)
job_monitor(job)
# Get the results of the computation
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/AbeerVaishnav13/Quantum-Programs
|
AbeerVaishnav13
|
from qiskit import *
%matplotlib inline
from matplotlib import style
style.use('bmh')
style.use('dark_background')
from math import pi, log
def new_mcrz(qc, theta, q_controls, q_target):
n = len(q_controls)
newtheta = -theta/2**n
a = lambda n: log(n-(n&(n-1)), 2)
qc.cx(q_controls[n-1], q_target)
qc.u1(newtheta, q_target)
for i in range(1, 2**n):
qc.cx(q_controls[int(a(i))], q_target)
qc.u1((-1)**i*newtheta,q_target)
QuantumCircuit.new_mcrz = new_mcrz
def new_mcz(qc, q_controls, q_target):
L = q_controls + [q_target]
n = len(L)
qc.u1(pi/2**(n-1), L[0])
for i in range(2, n+1):
qc.new_mcrz(pi/2**(n-i), L[0:i-1], L[i-1])
QuantumCircuit.new_mcz = new_mcz
Search_key = '1010'
# Total number of qubits to represent the search space
num_qubits = len(Search_key)
# Search space size
search_space = 2**num_qubits
print('Number of Qubits:', num_qubits)
print('Search-space size:', search_space)
from math import sqrt, ceil
def Uw(qc, key):
ctrl_on = ''
if num_qubits % 4 == 0:
ctrl_on = '1'
elif num_qubits % 4 == 2:
ctrl_on = '0'
for i, bin_val in enumerate(reversed(key)):
if bin_val == ctrl_on:
qc.x(i)
qc.new_mcz([range(num_qubits-1)], num_qubits-1)
for i, bin_val in enumerate(reversed(key)):
if bin_val == ctrl_on:
qc.x(i)
return qc
def Us(qc):
qc.h(range(num_qubits))
qc.x(range(num_qubits))
qc.new_mcz([range(num_qubits-1)], num_qubits-1)
qc.x(range(num_qubits))
qc.h(range(num_qubits))
return qc
def GroverSearch(qc, key):
steps = 0
if num_qubits < 4:
steps = int(sqrt(search_space) * pi / 4)
else:
steps = ceil(sqrt(search_space) * pi / 4)
if len(key) > num_qubits:
print('Invalid length of key, please check the key input.')
return
qc.h(range(num_qubits))
for i in range(steps):
qc = Uw(qc, key)
qc = Us(qc)
return qc
qc = QuantumCircuit(num_qubits, num_qubits)
qc = GroverSearch(qc, Search_key)
qc.measure(range(num_qubits), range(num_qubits))
qc.draw(output='mpl')
print('Depth of Circuit:', qc.depth())
from qiskit.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, backend=simulator, shots=8192).result()
plot_histogram(result.get_counts(qc))
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q', group='open')
device = provider.get_backend('ibmq_ourense')
job = execute(qc, backend=device, shots=8192)
job_monitor(job)
result = job.result()
plot_histogram(result.get_counts(qc))
provider = IBMQ.get_provider(hub='ibm-q', group='open')
device = provider.get_backend('ibmq_ourense')
job = execute(qc, backend=device, shots=8192)
job_monitor(job)
result = job.result()
plot_histogram(result.get_counts(qc))
|
https://github.com/AbeerVaishnav13/Quantum-Programs
|
AbeerVaishnav13
|
from qiskit.quantum_info import Operator
from qiskit import QuantumCircuit, Aer, execute
import numpy as np
from qiskit.visualization import plot_state_qsphere
def phase_oracle(n, indices_to_mark, name = 'Oracle'):
# create a qAertum circuit on n qubits
qc = QuantumCircuit(n, name=name)
### WRITE YOUR CODE BETWEEN THESE LINES - START
oracle_matrix = np.identity(2**n)
for i in indices_to_mark:
oracle_matrix[i][i] = -1
### WRITE YOUR CODE BETWEEN THESE LINES - END
# convert your matrix (called oracle_matrix) into an operator, and add it to the quantum circuit
qc.unitary(Operator(oracle_matrix), range(n))
return qc
def diffuser(n):
# create a quantum circuit on n qubits
qc = QuantumCircuit(n, name='Diffuser')
### WRITE YOUR CODE BETWEEN THESE LINES - START
qc.h(range(n))
qc.append(phase_oracle(n, [0]), range(n))
qc.h(range(n))
### WRITE YOUR CODE BETWEEN THESE LINES - END
return qc
def simulate_and_display(qc, step, it):
sim = Aer.get_backend('statevector_simulator')
res = execute(qc, backend=sim, shots=1).result()
display(plot_state_qsphere(res.get_statevector(qc)))#.savefig(('./pics/out_'+step+it+'.png'))
def Grover(n, indices_of_marked_elements):
# Create a quantum circuit on n qubits
qc = QuantumCircuit(n, n)
# Determine r
r = int(np.floor(np.pi/4*np.sqrt(2**n/len(indices_of_marked_elements))))
print(f'{n} qubits, basis states {indices_of_marked_elements} marked, {r} rounds')
# Display the initial state
simulate_and_display(qc, 'init', '0')
# step 1: apply Hadamard gates on all qubits
qc.h(range(n))
simulate_and_display(qc, 'hadamard', '0')
# step 2: apply r rounds of the phase oracle and the diffuser
for it in range(r):
qc.append(phase_oracle(n, indices_of_marked_elements), range(n))
simulate_and_display(qc, 'oracle', str(it))
qc.append(diffuser(n), range(n))
simulate_and_display(qc, 'diff', str(it))
# step 3: measure all qubits
qc.measure(range(n), range(n))
return qc
mycircuit = Grover(5, [2, 29])
mycircuit.draw(output='text')
from qiskit import Aer, execute
simulator = Aer.get_backend('qasm_simulator')
counts = execute(mycircuit, backend=simulator, shots=1000).result().get_counts(mycircuit)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
|
https://github.com/AbeerVaishnav13/Quantum-Programs
|
AbeerVaishnav13
|
from qiskit import QuantumCircuit
alice_key = '11100100010001001001001000001111111110100100100100010010010001010100010100100100101011111110001010100010010001001010010010110010'
alice_bases = '11000110011000100001100101110000111010011001111111110100010111010100000100011001101010100001010010101011010001011001110011111111'
def alice_prepare_qubit(qubit_index):
## WRITE YOUR CODE HERE
qc = QuantumCircuit(1, 1)
if alice_key[qubit_index] == '1':
qc.x(0)
if alice_bases[qubit_index] == '1':
qc.h(0)
return qc
## WRITE YOUR CODE HERE
|
https://github.com/AbeerVaishnav13/Quantum-Programs
|
AbeerVaishnav13
|
import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, Aer, transpile, assemble
from qiskit.visualization import plot_histogram, plot_bloch_multivector
qc = QuantumCircuit(1,1)
# Alice prepares qubit in state |+>
qc.h(0)
qc.barrier()
# Alice now sends the qubit to Bob
# who measures it in the X-basis
qc.h(0)
qc.measure(0,0)
# Draw and simulate circuit
display(qc.draw())
aer_sim = Aer.get_backend('aer_simulator')
job = aer_sim.run(assemble(qc))
plot_histogram(job.result().get_counts())
qc = QuantumCircuit(1,1)
# Alice prepares qubit in state |+>
qc.h(0)
# Alice now sends the qubit to Bob
# but Eve intercepts and tries to read it
qc.measure(0, 0)
qc.barrier()
# Eve then passes this on to Bob
# who measures it in the X-basis
qc.h(0)
qc.measure(0,0)
# Draw and simulate circuit
display(qc.draw())
aer_sim = Aer.get_backend('aer_simulator')
job = aer_sim.run(assemble(qc))
plot_histogram(job.result().get_counts())
n = 100
## Step 1
# Alice generates bits.
alice_bits = np.random.randint(0,2,n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = np.random.randint(0,2,n)
# Function to compare the bits & bases generated by alice, and then 'encode' the message. Basically determines the state of the qubit/photon to send.
def encode_message(bits, bases):
message = []
for i in range(n):
qc = QuantumCircuit(1,1)
if bases[i] == 0: # Prepare qubit in Z-basis
if bits[i] == 0:
pass
else:
qc.x(0)
else: # Prepare qubit in X-basis
if bits[i] == 0:
qc.h(0)
else:
qc.x(0)
qc.h(0)
qc.barrier()
message.append(qc)
return message
# Alice computes the encoded message using the function defined above.
message = encode_message(alice_bits, alice_bases)
## Step 3
# Decide which basis to measure in:
bob_bases = np.random.randint(0,2,n)
# Function to decode the message sent by alice by comparing qubit/photon states with Bob's generated bases.
def measure_message(message, bases):
backend = Aer.get_backend('aer_simulator')
measurements = []
for q in range(n):
if bases[q] == 0: # measuring in Z-basis
message[q].measure(0,0)
if bases[q] == 1: # measuring in X-basis
message[q].h(0)
message[q].measure(0,0)
aer_sim = Aer.get_backend('aer_simulator')
qobj = assemble(message[q], shots=1, memory=True)
result = aer_sim.run(qobj).result()
measured_bit = int(result.get_memory()[0])
measurements.append(measured_bit)
return measurements
# Decode the message according to his bases
bob_results = measure_message(message, bob_bases)
## Step 4
# Function to perform sifting i.e. disregard the bits for which Bob's & A;ice's bases didnot match.
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
# Performing sifting for Alice's and Bob's bits.
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
print("Alice's key after sifting (without interception)", alice_key)
print("Bob's key after sifting (without interception) ", bob_key)
# # Step 5
# # Function for parameter estimation i.e. determining the error rate by comparing subsets taen from both Alice's key & Bob's key.
# def sample_bits(bits, selection):
# sample = []
# for i in selection:
# # use np.mod to make sure the
# # bit we sample is always in
# # the list range
# i = np.mod(i, len(bits))
# # pop(i) removes the element of the
# # list at index 'i'
# sample.append(bits.pop(i))
# return sample
# # Performing parameter estimation & disregarding the bits used for comparison from Alice's & Bob's key.
# sample_size = 15
# bit_selection = np.random.randint(0,n,size=sample_size)
# bob_sample = sample_bits(bob_key, bit_selection)
# alice_sample = sample_bits(alice_key, bit_selection)
num = 0
for i in range(0,len(bob_key)):
if alice_key[i] == bob_key[i]:
num = num + 1
matching_bits = (num/len(bob_key))*100
print(matching_bits,"% of the bits match.")
## Step 1
alice_bits = np.random.randint(2, size=n)
## Step 2
alice_bases = np.random.randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Interception!!
eve_bases = np.random.randint(2, size=n)
intercepted_message = measure_message(message, eve_bases)
## Step 3
bob_bases = np.random.randint(2, size=n)
bob_results = measure_message(message, bob_bases)
## Step 4
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
print("Alice's key after sifting (with interception)", alice_key)
print("Bob's key after sifting (with interception) ", bob_key)
# ## Step 5
# sample_size = 15
# bit_selection = np.random.randint(n, size=sample_size)
# bob_sample = sample_bits(bob_key, bit_selection)
# alice_sample = sample_bits(alice_key, bit_selection)
num = 0
for i in range(0,len(bob_key)):
if alice_key[i] == bob_key[i]:
num = num + 1
matching_bits = (num/len(bob_key))*100
print(matching_bits,"% of the bits match.")
plt.rcParams['axes.linewidth'] = 2
mpl.rcParams['font.family'] = ['Georgia']
plt.figure(figsize=(10.5,6))
ax=plt.axes()
ax.set_title('')
ax.set_xlabel('$n$ (Number of bits drawn from the sifted keys for determining error rate)',fontsize = 18,labelpad=10)
ax.set_ylabel(r'$P(Eve\ detected)$',fontsize = 18,labelpad=10)
ax.xaxis.set_tick_params(which='major', size=8, width=2, direction='in', top='on')
ax.yaxis.set_tick_params(which='major', size=8, width=2, direction='in', top='on')
ax.tick_params(axis='x', labelsize=20)
ax.tick_params(axis='y', labelsize=20)
ax. xaxis. label. set_size(20)
ax. yaxis. label. set_size(20)
n = 30
x = np.arange(n+1)
y = 1 - 0.75**x
ax.plot(x,y,color = plt.cm.rainbow(np.linspace(0, 1, 5))[0], marker = "s", markerfacecolor='r')
|
https://github.com/AbeerVaishnav13/Quantum-Programs
|
AbeerVaishnav13
|
import numpy as np
coeff_list = []
for y in range(16):
coeff = 0
coeff += np.exp(-np.pi * 1j * 3 * y / 8)
coeff += np.exp(-np.pi * 1j * 7 * y / 8)
coeff += np.exp(-np.pi * 1j * 11 * y / 8)
coeff += np.exp(-np.pi * 1j * 15 * y / 8)
if np.abs(coeff.real) > 1e-14 or np.abs(coeff.imag) > 1e-14:
coeff_list.append(coeff)
else:
coeff_list.append(0)
for c in range(len(coeff_list)):
print(f'{c} : {coeff_list[c]}')
|
https://github.com/AbeerVaishnav13/Quantum-Programs
|
AbeerVaishnav13
|
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import style
%matplotlib inline
style.use('bmh')
style.use('dark_background')
a = 13; N = 15; num_iter = 15
# Finding the period
values = []
for x in range(num_iter):
values.append((a**x) % N)
print(values)
plt.plot(values)
start = values[0]
period = 0
for i in range(1, len(values)):
if values[i] == start:
period = i
break
print('Period:', period)
a = 18; N = 77; num_iter = 80
# Finding the period
values = []
for x in range(num_iter):
values.append((a**x) % N)
print(values)
plt.plot(values)
start = values[0]
period = 0
for i in range(1, len(values)):
if values[i] == start:
period = i
break
print('Period:', period)
|
https://github.com/AbeerVaishnav13/Quantum-Programs
|
AbeerVaishnav13
|
# Do the necessary imports
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import IBMQ, Aer, transpile, assemble
from qiskit.visualization import plot_histogram, plot_bloch_multivector, array_to_latex
from qiskit.extensions import Initialize
from qiskit.ignis.verification import marginal_counts
from qiskit.quantum_info import random_statevector
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
## SETUP
# Protocol uses 3 qubits and 2 classical bits in 2 different registers
qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits
crz = ClassicalRegister(1, name="crz") # and 2 classical bits
crx = ClassicalRegister(1, name="crx") # in 2 different registers
teleportation_circuit = QuantumCircuit(qr, crz, crx)
def create_bell_pair(qc, a, b):
qc.h(a)
qc.cx(a,b)
qr = QuantumRegister(3, name="q")
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx")
teleportation_circuit = QuantumCircuit(qr, crz, crx)
create_bell_pair(teleportation_circuit, 1, 2)
teleportation_circuit.draw()
def alice_gates(qc, psi, a):
qc.cx(psi, a)
qc.h(psi)
qr = QuantumRegister(3, name="q")
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx")
teleportation_circuit = QuantumCircuit(qr, crz, crx)
## STEP 1
create_bell_pair(teleportation_circuit, 1, 2)
## STEP 2
teleportation_circuit.barrier() # Use barrier to separate steps
alice_gates(teleportation_circuit, 0, 1)
teleportation_circuit.draw()
def measure_and_send(qc, a, b):
"""Measures qubits a & b and 'sends' the results to Bob"""
qc.barrier()
qc.measure(a,0)
qc.measure(b,1)
qr = QuantumRegister(3, name="q")
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx")
teleportation_circuit = QuantumCircuit(qr, crz, crx)
create_bell_pair(teleportation_circuit, 1, 2)
teleportation_circuit.barrier() # Use barrier to separate steps
alice_gates(teleportation_circuit, 0, 1)
measure_and_send(teleportation_circuit, 0 ,1)
teleportation_circuit.draw()
def bob_gates(qc, qubit, crz, crx):
qc.x(qubit).c_if(crx, 1) # Apply gates if the registers
qc.z(qubit).c_if(crz, 1) # are in the state '1'
qr = QuantumRegister(3, name="q")
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx")
teleportation_circuit = QuantumCircuit(qr, crz, crx)
## STEP 1
create_bell_pair(teleportation_circuit, 1, 2)
## STEP 2
teleportation_circuit.barrier() # Use barrier to separate steps
alice_gates(teleportation_circuit, 0, 1)
## STEP 3
measure_and_send(teleportation_circuit, 0, 1)
## STEP 4
teleportation_circuit.barrier() # Use barrier to separate steps
bob_gates(teleportation_circuit, 2, crz, crx)
teleportation_circuit.draw()
# Create random 1-qubit state
psi = random_statevector(2)
# Display it nicely
display(array_to_latex(psi, prefix="|\\psi\\rangle ="))
# Show it on a Bloch sphere
plot_bloch_multivector(psi)
init_gate = Initialize(psi)
init_gate.label = "init"
## SETUP
qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits
crz = ClassicalRegister(1, name="crz") # and 2 classical registers
crx = ClassicalRegister(1, name="crx")
qc = QuantumCircuit(qr, crz, crx)
## STEP 0
# First, let's initialize Alice's q0
qc.append(init_gate, [0])
qc.barrier()
## STEP 1
# Now begins the teleportation protocol
create_bell_pair(qc, 1, 2)
qc.barrier()
## STEP 2
# Send q1 to Alice and q2 to Bob
alice_gates(qc, 0, 1)
## STEP 3
# Alice then sends her classical bits to Bob
measure_and_send(qc, 0, 1)
## STEP 4
# Bob decodes qubits
bob_gates(qc, 2, crz, crx)
# Display the circuit
qc.draw()
sim = Aer.get_backend('aer_simulator')
qc.save_statevector()
out_vector = sim.run(qc).result().get_statevector()
plot_bloch_multivector(out_vector)
|
https://github.com/ohadlev77/sat-circuits-engine
|
ohadlev77
|
# (1) Run this cell for obtaining the suitable Grover's operator for the defined satisfiability problem
from sat_circuits_engine import SATInterface
# Defining constraints and varibales in a high-level fashion
high_level_constraints_string = (
"(x0 != x1)," \
"(x3 != x4)," \
"(x1 != x3)," \
"(x3 != x5)," \
"(x5 != x6)," \
"(x0 != x2)," \
"(x1 != x6)," \
"(x4 != x6)"
)
high_level_vars = {"x0": 1, "x1": 1, "x2": 1, "x3": 2, "x4": 1, "x5": 1, "x6": 1}
# Initialization of the interface, `save_data=True` for exporting data into a dedicated directory
demo_1 = SATInterface(
high_level_constraints_string=high_level_constraints_string,
high_level_vars=high_level_vars,
name="demo_1",
save_data=True
)
# `obtain_grover_operator()` returns a dictionary of the form: `{
# 'operator': QC_OBJ,
# 'decomposed_operator': QC_OBJ,
# 'transpiled_operator': QC_OBJ,
# 'high_level_to_bit_indexes_map': MAP_OBJ
# }`.
# Transpilation is done according to the `transpile_kwargs` arg, which by default is set to:
# {'basis_gates': ['u', 'cx'], 'optimization_level': 3}.
grover_operator_data = demo_1.obtain_grover_operator(
transpile_kwargs={'basis_gates': ['u', 'cx'], 'optimization_level': 3}
)
demo_1.save_display_grover_operator(grover_operator_data, display=True)
# (2) Run this cell for obtaining the overall SAT circuit:
# A `QuantumCircuit` object that solves the satisfiability problem, ready for execution on a backend.
from qiskit_aer import AerSimulator
# The number of iterations over Grover's iterator (= operator + diffuser) depends on the number of solutions.
# If the number of solutions is known, it is best to provide it.
# If the number of solutions is unknown, `solutions_num=-1` will initiate an classical
# iterative stochastic process that looks for an adequate number of iterations for the problem.
# Needless to mention, this process add some computational overheads.
# `solutions_num=-2` will generate a dynamic circuit to overcome the need for providing the number of solutions.
# NOTE - this is a BETA feature which is currently under development. For now it failes
# to scale and works properly only for small circuits (~ < 15 qubits).
overall_circuit_data = demo_1.obtain_overall_sat_circuit(
grover_operator=grover_operator_data['operator'],
solutions_num=6,
backend=AerSimulator()
)
demo_1.save_display_overall_circuit(overall_circuit_data, display=True)
# (3) Run this cell for executing the overall SAT circuit and obtaining the results.
results_data = demo_1.run_overall_sat_circuit(
circuit=overall_circuit_data['circuit'],
backend=AerSimulator(),
shots=300
)
demo_1.save_display_results(results_data, display=True)
# (1) Run this cell to obtain Grover's operator for the defined constraints
from sat_circuits_engine import SATInterface
# Initialization of the interface, `save_data=False` = not saving and exporting data
demo_2 = SATInterface(
constraints_string="([4][3][2] == [0]),([2] == [3]),([3] == [4]),([0] != [1]),([8][7] == [3][2])",
num_input_qubits=9,
name="demo_2",
save_data=False
)
# Obtaining Grover's operator objects
grover_operator_data = demo_2.obtain_grover_operator(
transpile_kwargs={'basis_gates': ['u', 'cx'], 'optimization_level': 3}
)
operator = grover_operator_data['operator']
decomposed_operator = grover_operator_data['decomposed_operator']
transpiled_operator = grover_operator_data['transpiled_operator']
# Displaying results
print("The high level operator circuit diagram:")
display(operator.draw('mpl', fold=-1))
print("The decomposed operator circuit diagram:")
display(decomposed_operator.draw('mpl', fold=-1))
print(f"Gates count in the transpiled operator: {transpiled_operator.count_ops()}")
# Run this cell to initiate an interactive user interface
from sat_circuits_engine import SATInterface
SATInterface()
# (1) Run this cell for obtaining the suitable Grover's operator for the defined satisfiability problem
from sat_circuits_engine import SATInterface
# Defining constraints and varibales in a high-level fashion
high_level_constraints_string = (
"(x0 != x1)," \
"(x2 + 2 != x3)," \
"(x3 != x4)," \
"(x3 != x1)," \
"(x5 != x6)," \
"(x0 != x2)," \
"(x1 != x5)," \
"(x4 != x6)," \
"(x3 == 2)," \
"(x2 + x4 + x3 == 3)"
)
high_level_vars = {"x0": 1, "x1": 1, "x2": 1, "x3": 2, "x4": 1, "x5": 1, "x6": 1}
# Initialization of the interface, `save_data=True` for exporting data into a dedicated directory
benchmark_demo = SATInterface(
high_level_constraints_string=high_level_constraints_string,
high_level_vars=high_level_vars,
name="benchmark_demo",
save_data=True
)
grover_operator_data = benchmark_demo.obtain_grover_operator(
transpile_kwargs={'basis_gates': ['u', 'cx'], 'optimization_level': 3}
)
benchmark_demo.save_display_grover_operator(grover_operator_data, display=True)
# (2) Run this cell for obtaining the overall SAT circuit:
# a `QuantumCircuit` object that solves the satisfiability problem, ready for execution on a backend.
from qiskit_aer import AerSimulator
overall_circuit_data = benchmark_demo.obtain_overall_sat_circuit(
grover_operator=grover_operator_data['operator'],
solutions_num=1,
backend=AerSimulator()
)
benchmark_demo.save_display_overall_circuit(overall_circuit_data, display=True)
# (3) Run this cell for executing the overall SAT circuit and obtaining the results.
# WARNING: this specific circuit is heavy for a classical computer to simualte, it might take a while.
results_data = benchmark_demo.run_overall_sat_circuit(
circuit=overall_circuit_data['circuit'],
backend=AerSimulator(),
shots=50
)
benchmark_demo.save_display_results(results_data, display=True)
from sat_circuits_engine import SATInterface
SATInterface()
|
https://github.com/ohadlev77/sat-circuits-engine
|
ohadlev77
|
# Copyright 2022-2023 Ohad Lev.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0,
# or in the root directory of this package("LICENSE.txt").
# 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.
"""
GroverConstraintsOperator class.
"""
from itertools import chain
from typing import Optional
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.transpiler.passes import RemoveBarriers
from sat_circuits_engine.constraints_parse import ParsedConstraints
from sat_circuits_engine.circuit.single_constraint import SingleConstraintBlock
class GroverConstraintsOperator(QuantumCircuit):
"""
A quantum circuit implementation of Grover's operator constructed
for a specific combination of constraints defined by a user.
"""
def __init__(
self,
parsed_constraints: ParsedConstraints,
num_input_qubits: int,
insert_barriers: Optional[bool] = True,
) -> None:
"""
Args:
parsed_constraints (ParsedConstraints): a dict-like object that associates every (single)
constraint string (the keys) with its `SingleConstraintParsed` object (the values).
num_input_qubits (int): number of qubits in the input register.
insert_barriers (Optional[bool] = True): if True, barriers will be inserted
to separate between constraints.
"""
self.num_input_qubits = num_input_qubits
self.parsed_constraints = parsed_constraints
self.insert_barriers = insert_barriers
# Construction a `SingleConstraintBlock` object for every constraint. A few more
# attributes defined within self.constraints_blocks_build(), see its docstrings for details.
self.constraints_blocks_build()
# Initializing the quantum circuit that implements the Grover operator we seek for
self.input_reg = QuantumRegister(self.num_input_qubits, "input_reg")
self.comparison_aux_reg = QuantumRegister(self.comparison_aux_width, "comparison_aux_reg")
self.left_aux_reg = QuantumRegister(self.left_aux_width, "left_aux_reg")
self.right_aux_reg = QuantumRegister(self.right_aux_width, "right_aux_reg")
self.out_reg = QuantumRegister(self.out_qubits_amount, "out_reg")
self.ancilla = QuantumRegister(1, "ancilla")
super().__init__(
self.input_reg,
self.left_aux_reg,
self.right_aux_reg,
self.comparison_aux_reg,
self.out_reg,
self.ancilla,
name="Operator",
)
# Assembling `self` to a complete Grover operator
self.assemble()
def __repr__(self) -> str:
if self.parsed_constraints.high_level_constraints_string is not None:
repr_string = self.parsed_constraints.high_level_constraints_string
else:
repr_string = self.parsed_constraints.constraints_string
return f"{self.__class__.__name__}('{repr_string}')"
def constraints_blocks_build(self) -> None:
"""
Parses the `self.parsed_constraints` attribute and defines the attributes:
- `self.single_constraints_objects` (List[SingleConstraintBlock]): a list of
`SingleConstraintBlock` objects, each built from a single constraint string.
- `self.comparison_aux_qubits_needed` (List[int]): a list of auxiliary qubits needed
for implementing the comparison between the two sides of the constraint's equation.
- `self.left_aux_qubits_needed` (List[int]): a list of auxiliary qubits needed
for implementing arithmetics on the left side of the constraint's equation.
- `self.right_aux_qubits_needed` (List[int]): a list of auxiliary qubits needed
for implementing arithmetics on the right side of the constraint's equation.
- `self.comparison_aux_width` (int): Total number of comparison aux qubits.
- `self.left_aux_width` (int): Total number of left aux qubits.
- `self.right_aux_width` (int): Total number of right aux qubits.
- `self.out_qubits_amount` (int): the number of "out qubits" needed, while each "out qubit"
is used to write the result of applying a single constraint into (|1> if the constraint is
satisfied, |0> otherwise).
"""
# For each constraint we build a `SingleConstraintBlock` object
self.single_constraints_objects = list(
map(SingleConstraintBlock, self.parsed_constraints.values())
)
# Sorting the constraints such that the most costly ones will be the first and last
# (First and last constraint are not uncomputed - only when the whole operator is uncomputed).
self.single_constraints_objects.sort(key=lambda x: x.transpiled.count_ops()["cx"], reverse=True)
self.single_constraints_objects.append(self.single_constraints_objects[0])
self.single_constraints_objects.pop(0)
self.comparison_aux_qubits_needed = []
self.left_aux_qubits_needed = []
self.right_aux_qubits_needed = []
# For each we count which and how many aux qubits are needed
for constraint_block in self.single_constraints_objects:
if "comparison_aux" in constraint_block.regs.keys():
self.comparison_aux_qubits_needed.append(len(constraint_block.regs["comparison_aux"][0]))
else:
self.comparison_aux_qubits_needed.append(0)
self.left_aux_qubits_needed.append(len(constraint_block.regs["sides_aux"][0]))
self.right_aux_qubits_needed.append(len(constraint_block.regs["sides_aux"][1]))
# Total number of qubits for each type
self.comparison_aux_width = sum(self.comparison_aux_qubits_needed)
self.left_aux_width = sum(self.left_aux_qubits_needed)
self.right_aux_width = sum(self.right_aux_qubits_needed)
self.out_qubits_amount = len(self.single_constraints_objects)
def assemble(self) -> None:
"""
Assembles a whole Grover operator (`self`) by performing the following steps:
(1) Allocating qubits for each `SingleConstraintBlock` object
(from `self.single_constraints_objects`) - for input qubits, auxiliary qubits of
all kinds and a single "out" qubit for each constraint.
(2) Appending all the `SingleConstraintBlock` objects.
(3) Applying a "marking" operation by applying some controlled-not gate to the
ancilla qubit.
(4) Appending an uncomputation of the entire operation assembled in (1) + (2).
"""
# Iterating over constraints, appending one `SingleConstraintBlock` object in each iteration
for count, constraint_block in enumerate(self.single_constraints_objects):
# Defining the `qargs` paramater for the `constraint_block` to be appended to `self`
qargs = []
# Appending the input bits indexes from both sides of the constraint's equation to `qargs`
left_input_qubits = list(chain(*constraint_block.parsed_data.sides_bit_indexes[0]))
if left_input_qubits:
qargs += self.input_reg[left_input_qubits]
right_input_qubits = list(chain(*constraint_block.parsed_data.sides_bit_indexes[1]))
if right_input_qubits:
qargs += self.input_reg[right_input_qubits]
# Appending the various aux bits indexes to `qargs`
for aux_tuple in [
(self.left_aux_qubits_needed, self.left_aux_reg),
(self.right_aux_qubits_needed, self.right_aux_reg),
(self.comparison_aux_qubits_needed, self.comparison_aux_reg),
]:
if aux_tuple[0][count] != 0:
aux_bottom_index = sum(aux_tuple[0][0:count])
aux_top_index = aux_bottom_index + aux_tuple[0][count]
qargs += aux_tuple[1][aux_bottom_index:aux_top_index][::-1]
# Appending blocks of constraints to `self`
# First constraint
if count == 0:
qargs.append(self.out_reg[count])
self.append(instruction=constraint_block, qargs=qargs)
# If there is only one constraint
if self.out_qubits_amount == 1:
# Saving inverse for future uncomputation
qc_dagger = self.inverse()
qc_dagger.name = "Uncomputation"
# "Marking" states by writing to ancilla
self.cx(self.out_reg[count], self.ancilla)
# Last constraint
elif count == len(self.single_constraints_objects) - 1:
qargs.append(self.out_reg[count])
self.append(instruction=constraint_block, qargs=qargs)
# Barriers are used for visualization purposes and should be removed before transpiling
if self.insert_barriers:
self.barrier()
# Saving inverse for future uncomputation
qc_dagger = RemoveBarriers()(self.inverse())
qc_dagger.name = "Uncomputation"
# "Marking" states by writing to ancilla
self.ccx(self.out_reg[count - 1], self.out_reg[count], self.ancilla)
# Intermidate constraints
else:
qargs.append(self.out_reg[count + 1])
# Chaining constraints with RCCX gates, to avoid costly MCX gate all over the out qubits
self.append(instruction=constraint_block, qargs=qargs)
self.rccx(self.out_reg[count + 1], self.out_reg[count - 1], self.out_reg[count])
self.append(instruction=constraint_block.inverse(), qargs=qargs)
# Barriers are used for visualization purposes and should be removed before transpiling
if self.insert_barriers:
self.barrier()
# Applying uncomputation
self.append(instruction=qc_dagger, qargs=self.qubits)
|
https://github.com/ohadlev77/sat-circuits-engine
|
ohadlev77
|
# Copyright 2022-2023 Ohad Lev.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0,
# or in the root directory of this package("LICENSE.txt").
# 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.
"""
GroverDiffuser class.
"""
from typing import Optional
from qiskit import QuantumCircuit, QuantumRegister
class GroverDiffuser(QuantumCircuit):
"""
Implementation of Grover's diffuser operator.
"""
def __init__(self, num_input_qubits: int, num_ancilla_qubits: Optional[int] = 0) -> None:
"""
Initializes a `QuantumCircuit` object.
Implements the gate-combination needed for Grover's diffuser operator.
Args:
num_input_qubits (int): number of input qubits.
num_ancilla_qubits (Optional[int] = 0): number of ancilla qubits available, for the
purpose of decomposing the MCX gate needed for implementing Grover's diffuser, in
an efficient and shallow-as-possible manner.
"""
input_reg = QuantumRegister(num_input_qubits, "input_reg")
ancilla_reg = QuantumRegister(num_ancilla_qubits, "ancilla_reg")
super().__init__(input_reg, ancilla_reg, name="Diffuser")
# Pre-settings. Choosing the shallowest possible MCX decomposing mode
target_qubit = input_reg[num_input_qubits - 1]
if num_ancilla_qubits == 0:
mode = "noancilla"
elif num_ancilla_qubits < num_input_qubits - 2:
mode = "recursion"
else:
mode = "v-chain"
# Diffuser implementation
self.h(input_reg)
self.x(input_reg)
self.h(target_qubit)
self.mcx(
control_qubits=input_reg[list(range(num_input_qubits - 1))],
target_qubit=target_qubit,
ancilla_qubits=ancilla_reg,
mode=mode,
)
self.h(target_qubit)
self.x(input_reg)
self.h(input_reg)
|
https://github.com/ohadlev77/sat-circuits-engine
|
ohadlev77
|
# Copyright 2022-2023 Ohad Lev.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0,
# or in the root directory of this package("LICENSE.txt").
# 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.
"""
SATCircuit class.
"""
from typing import Optional
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from sat_circuits_engine.circuit.grover_constraints_operator import GroverConstraintsOperator
from sat_circuits_engine.circuit.grover_diffuser import GroverDiffuser
class SATCircuit(QuantumCircuit):
"""
Assembles an overall circuit for the given SAT problem from the building blocks:
- Input state preparation.
- Grover's iterator - consists of:
* `GroverConstraintsOperator` object (Grover's operator).
* `GroverDiffuser` object (Grover's diffuser).
- Measurement.
"""
def __init__(
self,
num_input_qubits: int,
grover_constraints_operator: GroverConstraintsOperator,
iterations: Optional[int] = None,
insert_barriers: Optional[bool] = True,
) -> None:
"""
Args:
num_input_qubits (int): the number of qubits in the input register.
grover_constraints_operator (GroverConstraintsOperator): a child object of `QuantumCircuit`
which is Grover's operator implementation for the specific constraints entered by the user.
iterations (Optional[int] = None): number of required iterations over Grover's iterator.
# If `None` (default) - the number of iterations is unknown and a dynamic
circuit approach should be applied (TODO THIS IS A FUTURE FEATURE).
insert_barriers (Optional[bool] = True): if True, barriers will be inserted
to separate between segments and iterations.
"""
self.num_input_qubits = num_input_qubits
self.operator = grover_constraints_operator
self.iterations = iterations
self.insert_barriers = insert_barriers
# Total number of auxiliary qubits (of all kinds)
self.total_aux_width = (
self.operator.comparison_aux_width
+ self.operator.left_aux_width
+ self.operator.right_aux_width
)
self.input_reg = QuantumRegister(num_input_qubits, "input_reg")
self.aux_reg = QuantumRegister(self.total_aux_width, "aux_reg")
self.out_reg = QuantumRegister(self.operator.out_qubits_amount, "out_reg")
self.ancilla = QuantumRegister(1, "ancilla")
self.results = ClassicalRegister(num_input_qubits, "results")
# Input, auxiliary and out Qubit objects stacked in one list
self.input_aux_out_qubits = self.input_reg[:] + self.aux_reg[:] + self.out_reg[:]
diffuser_ancillas = len(self.input_aux_out_qubits) - num_input_qubits
self.diffuser = GroverDiffuser(
num_input_qubits=num_input_qubits, num_ancilla_qubits=diffuser_ancillas
)
# No `iterations` specified = dynamic circuit
# TODO this feature is not supported yet and shouldn't be used
if iterations is None:
# Register to apply weak measurements with
self.probe = QuantumRegister(1, "probe")
self.probe_result = ClassicalRegister(1, "probe_result")
super().__init__(
self.input_reg,
self.aux_reg,
self.out_reg,
self.ancilla,
self.probe,
self.results,
self.probe_result,
)
# Initializing input state
self.set_init_state()
# Applying dynamic while loop over Grover's iterator coditioned by `probe`
self.dynamic_loop()
# `iterations` specified = static circuit
else:
super().__init__(
self.input_reg,
self.aux_reg,
self.out_reg,
self.ancilla,
self.results,
)
# Initializing input state
self.set_init_state()
# Appending `iterations` iterations over Grover's iterator
for _ in range(iterations):
self.add_iteration()
def dynamic_loop(self) -> None:
"""
TODO this feature is not supported yet and shouldn't be used.
"""
condition = (self.probe_result, 0)
qargs_with_probe = self.input_aux_out_qubits[:] + self.probe[:]
with self.while_loop(condition):
self.append(self.diffuser, qargs=self.input_aux_out_qubits)
self.add_iteration()
self.append(self.operator, qargs=qargs_with_probe)
self.measure(self.probe, self.probe_result)
def set_init_state(self) -> None:
"""
Setting the input register to 2^(self.num_input_qubits) = N equal superposition of states,
and the ancilla to an eigenstate of the NOT gate: |->.
"""
self.h(self.input_reg)
self.x(self.ancilla)
self.h(self.ancilla)
if self.insert_barriers:
self.barrier()
def add_iteration(self) -> None:
"""
Appends an iteration over Grover's iterator (`operator` + `diffuser`) to `self`.
"""
qargs_with_ancilla = self.input_aux_out_qubits[:] + self.ancilla[:]
self.append(self.operator, qargs=qargs_with_ancilla)
self.append(self.diffuser, qargs=self.input_aux_out_qubits)
if self.insert_barriers:
self.barrier()
def add_input_reg_measurement(self) -> None:
"""
Appends a final measurement of the input register to `self`.
"""
self.measure(self.input_reg, self.results)
|
https://github.com/ohadlev77/sat-circuits-engine
|
ohadlev77
|
# Copyright 2022-2023 Ohad Lev.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0,
# or in the root directory of this package("LICENSE.txt").
# 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.
"""
`SingleConstraintBlock` and `ArithmeticExprBlock` classes.
"""
from typing import Union, Optional, List, Dict, Any
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, transpile
from qiskit.circuit import Qubit
from qiskit.circuit.library import QFT
from sat_circuits_engine.constraints_parse import SingleConstraintParsed
from sat_circuits_engine.util.settings import TRANSPILE_KWARGS
class SingleConstraintBlock(QuantumCircuit):
"""
A quantum circuit implementation of a single constraint.
To be integrated as a block in a `GroverConstriantsOperator` object.
"""
def __init__(
self, parsed_data: SingleConstraintParsed, transpile_kwargs: Optional[Dict[str, Any]] = None
) -> None:
"""
Args:
parsed_data (SingleConstraintParsed): an object contains all necessary
information for a single constraint, in a specific API (see `help(SingleConstraintParsed)`
for API annotation).
transpile_kwargs (Optional[Dict[str, Any]] = None): keyword arguments for self-transpilation
that takes place in this class. If None (default) - `TRANSPILE_KWARGS` constant is used.
"""
self.parsed_data = parsed_data
self.constraint_index = self.parsed_data.constraint_index
if transpile_kwargs is None:
transpile_kwargs = TRANSPILE_KWARGS
self.transpile_kwargs = transpile_kwargs
# Handling arithmetic expressions and constructing the container - `self.regs`
self.handle_arithmetics()
# Creating a unified list of registers to unpack as args for `super().__init__`
regs_list = []
for item in self.regs.values():
regs_list.extend(item)
# Initializing circuit
super().__init__(*regs_list, name=self.parsed_data.string_to_show)
# Assembling a circuit implementation of the given constraint
self.assemble()
# Saving a transpiled version of `self`.
# Used by `GroverConstraintsOperator` to set the order of constraints.
self.transpiled = transpile(self, **self.transpile_kwargs)
def __repr__(self) -> str:
return f"{self.__class__.__name__}" f"('{self.parsed_data.string_to_show}')"
def handle_arithmetics(self) -> None:
"""
Handles arithmetic operations from both sides of the constraint's equation, if needed.
Initiates some of the quantum registers that compose the circuit (`self`).
The left side of the constraint's equation is indexed as 0, and the right side is inexed as 1.
Defines attributes:
self.regs (Dict[str, List[QuantumRegister]]): container for quantum registers.
self.arith_blocks (List[Optioanl[ArithmeticExprBlock] = None]): Indexed containter for
`ArithmeticExprBlock` objects. None (default) - if no artihmetics in a specific side.
self.integer_flags (List[bool]): Indexed container for boolean values. True for a side
that contains bare integer only, otherwise False.
"""
self.regs = {
# Initializing empty input registers
"inputs": [QuantumRegister(0, "input_left"), QuantumRegister(0, "input_right")],
# Initializing empty auxiliary register for performing arithmetics
"sides_aux": [
QuantumRegister(0, f"c{self.constraint_index}_aux_left"),
QuantumRegister(0, f"c{self.constraint_index}_aux_right"),
],
}
self.arith_blocks = [None, None]
self.integer_flags = [False, False]
# Iterating over the 2 sides of the constraint's equation and constructing the needed registers
for side, (bit_indexes, int_bitstring) in enumerate(
zip(self.parsed_data.sides_bit_indexes, self.parsed_data.sides_int_bitstrings)
):
# Case A - arithmetic expression
if (len(bit_indexes) > 1) or (len(bit_indexes) == 1 and int_bitstring is not None):
# Case A.1 -the other side of the equations is a bare integer
compared_value = None
if (
not self.parsed_data.sides_bit_indexes[side ^ 1]
and self.parsed_data.sides_int_bitstrings[side ^ 1]
):
compared_value = int(self.parsed_data.sides_int_bitstrings[side ^ 1], 2)
# Generating the arithmetic expression block
self.arith_blocks[side] = ArithmeticExprBlock(
bit_indexes, int_bitstring, compared_value=compared_value
)
# Creating an input register that fits with the arithmetic expression block
self.regs["inputs"][side] = QuantumRegister(
self.arith_blocks[side].total_operands_width, self.regs["inputs"][side].name
)
# Creating an auxiliary register for arithmetics
self.regs["sides_aux"][side] = QuantumRegister(
self.arith_blocks[side].result_reg_width, self.regs["sides_aux"][side].name
)
# Case B - single variable expression
elif len(bit_indexes) == 1 and int_bitstring is None:
self.regs["inputs"][side] = QuantumRegister(
len(bit_indexes[0]), self.regs["inputs"][side].name
)
# Case C - bare integer expression
else:
self.integer_flags[side] = True
def assemble(self) -> None:
"""
Assembles a complete circuit implementation of the given constraint.
"""
compare_operands = []
# Figuring the compared operand for each of the contraint's equation sides
for arith_block, input_reg, side_aux_reg, integer_flag, int_bitstring in zip(
self.arith_blocks,
self.regs["inputs"],
self.regs["sides_aux"],
self.integer_flags,
self.parsed_data.sides_int_bitstrings,
):
# Arithmetic block operand
if arith_block is not None:
# Appeding the arithmetic block to the `self`
self.append(arith_block, qargs=input_reg[:] + side_aux_reg[::-1])
compare_operands.append(side_aux_reg)
else:
# Integer bitstring operand
if integer_flag:
compare_operands.append(int_bitstring)
# A bundle of qubits (from the input register) operand
else:
compare_operands.append(input_reg)
# Applying the methods for the necessary comparison
if self.integer_flags[0]:
self.qubits_int_comparison(
qubits_bundle=compare_operands[1],
int_bitstring=compare_operands[0],
operator=self.parsed_data.operator,
)
elif self.integer_flags[1]:
self.qubits_int_comparison(
qubits_bundle=compare_operands[0],
int_bitstring=compare_operands[1],
operator=self.parsed_data.operator,
)
else:
self.unbalanced_qubits_comparison(
qubits_bundle_1=compare_operands[0],
qubits_bundle_2=compare_operands[1],
operator=self.parsed_data.operator,
)
def qubits_int_comparison(
self,
qubits_bundle: Union[List[Union[Qubit, int]], QuantumRegister],
int_bitstring: str,
*,
operator: Optional[str] = "==",
) -> None:
"""
Compares a bundle of qubits to an integer.
Args:
qubits_bundle (Union[List[Union[Qubit, int]], QuantumRegister]): compared qubits.
int_bitstring (str): compared integer (in a bitstring form).
operator (Optional[str] = "=="): comparison operator, default is "==",
and the other option is "!=".
Raises:
AssertionError: If `int_bitstring` is an integer larger than any integer
that can be possibly represented by `qubits_bundle`.
"""
# Adding an "out" qubit to write the result into
self.add_out_reg()
# Creating pointers for convenience
len_int = len(int_bitstring)
len_qubits_bundle = len(qubits_bundle)
# Catching non-logical input
assert len_int <= len_qubits_bundle, (
f"The integer ({int_bitstring}) length is longer than compared"
f"qubits ({qubits_bundle}), no solution."
)
# In the case the equation is unbalanced, filling the integer with zeros from the left
if len_int < len_qubits_bundle:
int_bitstring = int_bitstring.zfill(len_qubits_bundle)
# Setting `len_int` again after filling `int_bitstring` with zeros from the left
len_int = len(int_bitstring)
# Flipping bits in `qubits_bundle` in order to compare them to '0' digits in `int_bitstring`
flipping_zeros = QuantumCircuit(len_int, name=f"{int_bitstring}_encoding")
for digit, qubit in zip(int_bitstring, flipping_zeros.qubits):
if digit == "0":
flipping_zeros.x(qubit)
self.append(flipping_zeros, qargs=qubits_bundle)
# Writing results to the "out" qubit
# TODO need to generalize RCCX and RCCCX to the n-control qubits case
if len_qubits_bundle == 2:
self.rccx(qubits_bundle[0], qubits_bundle[1], self.regs["out"][0])
elif len_qubits_bundle == 3:
self.rcccx(qubits_bundle[0], qubits_bundle[1], qubits_bundle[2], self.regs["out"][0])
else:
self.mcx(qubits_bundle, self.regs["out"][0])
# Flipping outcome in the case the operator is "!="
if operator == "!=":
self.x(self.regs["out"][0])
# Uncomputing flipped bits
self.append(flipping_zeros, qargs=qubits_bundle)
def unbalanced_qubits_comparison(
self,
qubits_bundle_1: Union[List[Union[Qubit, int]], QuantumRegister],
qubits_bundle_2: Union[List[Union[Qubit, int]], QuantumRegister],
*,
operator: Optional[str] = "==",
) -> None:
"""
The most general case of comparing 2 bundles of qubits.
The bundles might be of the same length ("balanced") or not ("unbalanced").
Args:
qubits_bundle_1, qubits_bundle_2 (Union[List[Union[Qubit, int]], QuantumRegister]):
- Qubits of bundle_1 are compared to qubits of bundle_2.
operator (Optional[str] = "=="): comparison operator, default is "==",
and the other option is "!=".
"""
# Creating pointers for convenience
len_bundle_1 = len(qubits_bundle_1)
len_bundle_2 = len(qubits_bundle_2)
# The case where a comparison aux register is needed
if len_bundle_1 > 1 or len_bundle_2 > 1:
self.add_comparison_aux_reg(min(len_bundle_1, len_bundle_2))
# Adding an "out" qubit to write the result into
self.add_out_reg()
# In this case, only 2 qubits comparison is needed, and then the method's execution halts
if len_bundle_1 == 1 and len_bundle_2 == 1:
self.two_qubits_comparison(
qubits_bundle_1, qubits_bundle_2, self.regs["out"][0], operator=operator
)
return
# Setting short and long bundles and cutting the long bundle to 2 parts.
# The right part of the long bundle is comparble to the short bundle.
if len_bundle_1 > len_bundle_2:
long = qubits_bundle_1
short = qubits_bundle_2
long_right_cut = qubits_bundle_1[-len_bundle_2:]
else:
long = qubits_bundle_2
short = qubits_bundle_1
long_right_cut = qubits_bundle_2[-len_bundle_1:]
len_short = len(short)
len_long = len(long)
long_left_cut = long[: len_long - len_short]
# Comparing the rightmost bits in the longer bundle to the bits of the shorter bundle
self.balanced_qubits_comparison(
short, long_right_cut, self.regs["comparison_aux"][0][:len_short]
)
# Flipping the left bits in the longer bundle (in order to check whether they all zeros)
if long_left_cut:
self.x(long_left_cut)
# Writing results to the "out" qubit
# TODO need to generalize RCCX and RCCCX to the n-control qubits case
q = long_left_cut + self.regs["comparison_aux"][0][:]
if len(q) == 2:
self.rccx(q[0], q[1], self.regs["out"][0])
elif len(q) == 3:
self.rcccx(q[0], q[1], q[2], self.regs["out"][0])
else:
self.mcx(q, self.regs["out"][0])
# Flipping outcome in the case the operator is "!="
if operator == "!=":
self.x(self.regs["out"][0])
# Uncomputing flipping left bits in the longer bundle
if long_left_cut:
self.x(long_left_cut)
def balanced_qubits_comparison(
self,
qubits_bundle_1: Union[List[Union[Qubit, int]], QuantumRegister],
qubits_bundle_2: Union[List[Union[Qubit, int]], QuantumRegister],
aux_qubits: Union[List[Union[Qubit, int]], QuantumRegister],
out_qubit: Optional[Union[Qubit, QuantumRegister, int]] = None,
*,
operator: Optional[str] = "==",
) -> None:
"""
Comparing 2 bundles of qubits.
The bundles must be of the same length ("balanced").
Args:
qubits_bundle_1, qubits_bundle_2 (Union[List[Union[Qubit, int]], QuantumRegister]):
- Qubits of bundle_1 are compared to qubits of bundle_2.
aux_qubits (Union[List[Union[Qubit, int]], QuantumRegister]): auxiliary qubits for
comparing `qubits_bundle_1` with `qubits_bundle_2`.
out_qubit (Optional[Union[Qubit, QuantumRegister, int]] = None): A qubit
to write the result into. If None - not writing result, probably the method
is being used by another method and not intended to write results.
operator (Optional[str] = "=="): comparison operator, default is "==",
and the other option is "!=".
"""
# No auxilliary qubits = the case of comparing 1 single qubit from each side
if len(aux_qubits) == 0:
aux_qubits = out_qubit
# Implementation of: qubits_bundle_1 == qubits_bundle_2.
# Comparing each pair of qubits and writing results to auxilliary qubits.
for q1, q2, aux in zip(qubits_bundle_1, qubits_bundle_2, aux_qubits):
self.two_qubits_comparison(q1, q2, aux, operator="==")
if out_qubit is not None:
print("============ CHECK CHECK CHECK CHECK CHECK ======================")
# Writing overall outcome to the "out" qubit
# TODO need to generalize RCCX and RCCCX to the n-control qubits case
if len(aux) == 2:
self.rccx(aux[0], aux[1], out_qubit)
elif len(aux) == 3:
self.rcccx(aux[0], aux[1], aux[2], out_qubit)
else:
self.mcx(aux, out_qubit)
# Flipping outcome in the case the operator is "!="
if operator == "!=":
self.x(out_qubit)
def two_qubits_comparison(
self,
qubit_1: Union[Qubit, QuantumRegister, int],
qubit_2: Union[Qubit, QuantumRegister, int],
qubit_result: Union[Qubit, QuantumRegister, int],
*,
operator: Optional[str] = "==",
) -> None:
"""
Compares values of 2 qubits.
Args:
qubit_1 (Union[Qubit, QuantumRegister, int]): first qubit to compare.
qubit_2 (Union[Qubit, QuantumRegister, int]): second qubit to compare.
qubit_result (Union[Qubit, QuantumRegister, int]): qubit to write the results to.
operator (Optional[str] = "=="): comparison operator, default is "==",
and the other option is "!=".
"""
# XOR implementaion for qubit_1 != qubit_2
self.cx(qubit_1, qubit_result)
self.cx(qubit_2, qubit_result)
# Flipping the result for qubit_1 == qubit_2
if operator == "==":
self.x(qubit_result)
def add_comparison_aux_reg(self, width: int) -> None:
"""
Appends an auxilliary register for the comparison (between sides of equation) operations.
Adds it also to self.regs under the key "comparison_aux" (accessible
via `self.regs['comparison_aux'][0]).
Args:
width (int): number of qubits in the register.
"""
aux_reg = QuantumRegister(width, f"c{self.constraint_index}_aux_comparison")
self.add_register(aux_reg)
self.regs["comparison_aux"] = [aux_reg]
def add_out_reg(self) -> None:
"""
Appends a single-qubit "out" register to this object.
Adds it also to self.regs under the key "out" (accessible via `self.regs['out'][0]).
"""
out_reg = QuantumRegister(1, f"c{self.constraint_index}_out")
self.add_register(out_reg)
self.regs["out"] = [out_reg]
class ArithmeticExprBlock(QuantumCircuit):
"""
A quantum circuit implementation of an arithmetic expression.
To be integrated as a block in a `SingleConstraintBlock` object.
"""
def __init__(
self,
single_side_bits_indexes: List[List[int]],
single_side_integer_bitstring: Optional[str] = None,
compared_value: int = None,
block_name: Optional[str] = None,
) -> None:
"""
Args:
single_side_bits_indexes (List[List[int]]): A list of lists, each list contains bit
indexes that form a single bundle.
single_side_integer_bitstring (Optional[str] = None): If exists, the binary string
of the integer in an arithmetic expression.
compared_value (int = None):
- An integer value that the arithmetic expression is compared to (in the "other side"
of the constraint's equation).
- If defined - this class will try to reduce the width of its results
register using modular addition, after negating collisions possibilities.
block_name (Optional[str] = None): a name for this circuit block. If None, a meaningful
name is given by this class automatically.
"""
self.bits_indexes = single_side_bits_indexes
self.integer_bitstring = single_side_integer_bitstring
# Translating qubits bundles into a list of number of qubits in each bundle
self.operands_widths = list(map(lambda x: len(x), self.bits_indexes))
self.total_operands_width = sum(self.operands_widths)
# Computing the necessary width for the results aux register
self.result_reg_width = self.compute_addition_result_width(
self.operands_widths, self.integer_bitstring, compared_value
)
# Defining registers
self.bundles_regs = list(
map(lambda x: QuantumRegister(x[1], f"reg_bundle_{x[0]}"), enumerate(self.operands_widths))
)
self.result_reg = QuantumRegister(self.result_reg_width, "result_reg")
# Initiazling circuit
super().__init__(*self.bundles_regs, self.result_reg)
# Performing addition of all operands
self.add()
# Assigning name to this circuit block
if block_name is None:
block_name = f"Addition:{self.bits_indexes} + {self.integer_bitstring}"
self.name = block_name
def add(self) -> None:
"""
Performing addition of all operands.
NOTE: Supports only non-repeated values (VALID = [3][2] + [1] + 5, NOT VALID = [3][2] + [2][1]).
"""
# Assigning `default_bitstring` value to `results_qubits`
if self.integer_bitstring is None:
self.integer_bitstring = "".zfill(self.result_reg_width)
else:
self.integer_bitstring = self.integer_bitstring.zfill(self.result_reg_width)
for digit, result_qubit in zip(reversed(self.integer_bitstring), self.result_reg):
if digit == "1":
self.x(result_qubit)
# Performing "default addition" (= copying values of each bit with CNOTS) of one
# operand (the most suitable one) to `self.result_reg`, if possible (Before applying QFT).
default_added_operand_index = self.default_addition()
if default_added_operand_index is not None:
self.bundles_regs.pop(default_added_operand_index)
if self.bundles_regs:
# Transforming `results_qubits` to Fourier basis
self.append(QFT(self.result_reg_width), qargs=self.result_reg)
# Fourier addition of all bundles
for reg in self.bundles_regs:
self.fourier_add_single_bundle(reg, self.result_reg)
# Transforming `results_qubits` back to the computational basis
self.append(QFT(self.result_reg_width, inverse=True), qargs=self.result_reg)
def default_addition(self) -> int:
"""
Performs in bit-to-bit addition of one of the operands to `self.result_reg` if possible.
Returns:
(int): the index of the operand that has been added.
"""
# Counting the number of trailing zeros (i.e, number of available bits to copy values into)
try:
trailing_zeros_num = self.integer_bitstring[::-1].index("1")
except ValueError:
trailing_zeros_num = self.result_reg_width
# Finding the best operand to copy its value (the longest one that's shorter
# or equal in length to the number of trailing zeros).
operand_index = None
for num_zeros in reversed(range(1, trailing_zeros_num + 1)):
try:
operand_index = self.operands_widths.index(num_zeros)
trailing_zeros_num = num_zeros
break
except ValueError:
pass
# If possible, performing the optimal bit-to-bit addition
if operand_index is not None:
self.cx(self.bundles_regs[operand_index], self.result_reg[:trailing_zeros_num][::-1])
return operand_index
def fourier_add_single_bundle(
self,
qubits_to_add: Union[List[Union[Qubit, int]], QuantumRegister],
target_qubits: Union[List[Union[Qubit, int]], QuantumRegister],
) -> None:
"""
Perform an addition in Fourier basis.
Args:
qubits_to_add (Union[List[Union[Qubit, int]], QuantumRegister]): a bundle of qubits
to sum their values.
target_qubits (Union[List[Union[Qubit, int]], QuantumRegister]): qubits to write the result
into, must be already in Fourier basis.
"""
# `qubits_to_add` are reversed due to bits ordering issues (consistency with little-endian)
for control_index, control_q in enumerate(reversed(qubits_to_add)):
for target_index, target_q in enumerate(target_qubits):
k = len(target_qubits) - target_index
phase = (2 * np.pi * (2**control_index)) / (2**k)
# Phase shifts of 2pi multiples are indistinguishable = Breaking from the inner loop
if phase == 2 * np.pi:
break
self.cp(theta=phase, control_qubit=control_q, target_qubit=target_q)
@staticmethod
def compute_addition_result_width(
regs_widths: List[int],
default_bitstring: Optional[str] = None,
compared_value: Optional[int] = None,
) -> int:
"""
Calculates `width` - the (minimal) width of the register that should
contain the sum of values of the registers (whose widths are stored in `regs_width`)
with `default_bitstring`.
Args:
regs_widths (List[int]): number of bits in each of the summed registers.
default_bitstring (Optional[str] = None): integer bitstring operand.
compared_value (Optional[int] = None):
- An integer value that the arithmetic expression is compared to (in the "other side"
of the constraint's equation).
Returns:
(int) - `width`.
"""
if default_bitstring is None:
default_bitstring = "0"
# Just 1 operand = no addition
if len(regs_widths) == 1 and default_bitstring == "0":
return 0
# The maximum possible sum integer value
max_sum = sum(map(lambda x: (2**x) - 1, regs_widths)) + int(default_bitstring, 2)
# The bitstring length of the maximum possible sum
width = len(bin(max_sum)[2:])
# Trying to reduce width if modular addition can't cause collisions w.r.t to `compared_value`
if compared_value is not None:
if max_sum - compared_value < compared_value and width > len(bin(compared_value)[2:]):
width -= 1
return width
|
https://github.com/ohadlev77/sat-circuits-engine
|
ohadlev77
|
# Copyright 2022-2023 Ohad Lev.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0,
# or in the root directory of this package("LICENSE.txt").
# 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.
"""
`calc_iterations`, `find_iterations_unknown` functions.
`is_circuit_match` and `randint_exclude` functions can be considered
as sub-functions of `find_iterations_unknown`.
"""
import random
import copy
from typing import Tuple, Optional
import numpy as np
from qiskit import transpile, QuantumCircuit
from qiskit.providers.backend import Backend
from sat_circuits_engine.util import timer_dec
from sat_circuits_engine.util.settings import BACKENDS
from sat_circuits_engine.circuit import SATCircuit, GroverConstraintsOperator
from sat_circuits_engine.classical_processing.classical_verifier import ClassicalVerifier
from sat_circuits_engine.constraints_parse import ParsedConstraints, SATNoSolutionError
def calc_iterations(num_input_qubits: int, num_solutions: int) -> int:
"""
Simple classical calculation of the number of iterations over Grover's iterator
when the number of solutions for the SAT problem is known.
Args:
num_input_qubits (int): number of input qubits.
num_solutions (int): known number of solutions to the SAT problem.
Returns:
(int): the exact number of iterations needed for the given SAT problem.
"""
# N is the dimension of the Hilbert space spanned by `num_input_qubits`
N = 2**num_input_qubits
# The formula for calculating the number of iterations
iterations = int((np.pi / 4) * np.sqrt(N / num_solutions))
return iterations
@timer_dec("Found number of iterations in ")
def find_iterations_unknown(
num_input_qubits: int,
grover_constraints_operator: GroverConstraintsOperator,
parsed_constraints: ParsedConstraints,
precision: Optional[int] = 10,
backend: Optional[Backend] = BACKENDS(0),
step: Optional[float] = 6 / 5,
) -> Tuple[SATCircuit, int]:
"""
Finds an adequate (optimal or near optimal) number of iterations suitable for a given SAT problem
when the number of "solutions" or "marked states" is unknown.
The method being used is described in https://arxiv.org/pdf/quant-ph/9605034.pdf (section 4).
- In short, the original method steps are:
* Drawing a random number of iterations which is smaller than some number M.
* Executing the circuit.
* If a solution has been found (easy to verify classically) - done.
* If not - M is being multiplied by a fixed step size.
* Repeat.
- Here we implement a variation of the described method above - with the goal of finding
ad adequate number of iterations for the SAT problem, and not just a single solution.
* Instead of exiting the process when finding a solution, we then
execute the circuit `precision` times.
* If `precision` execution shots gives 100% "good" solutions - done, we have found
a number of iterations precise enough.
* If not - we continue with the original method scheme.
* If we couldn't find an adequate number of iterations for the given `precision`,
the precision is decremented and we iterate over the process again with a lower precision.
* If `precision` has been decremented to 0 - then we halt,
and probably the SAT problem has no solution.
- `precision` can be thought as the degree of accuracy - for large values of `precision`
more optimal results will be obtained, in a price of extra computational overhead.
Args:
num_input_qubits (int): number of input qubits.
grover_constraints_operator (GroverConstraintsOperator): Grover's operator for the SAT problem.
parsed_constraints (ParsedConstraints): a series of constraints,
already parsed to a specific format.
precision (Optional[int] = 10): number of "valid solutions" which is
enough to determine ad adequate number of iterations for the SAT problem.
backend (Optional[Backend] = BACKENDS(0)): a backend to run the circuits upon.
Default is the local AerSimulator (BACKENDS(0)).
step (Optional[float] = 6/5): step size to increment M in each iteration.
Returns: Tuple[SATCircuit, int]:
(SATCircuit): the overall SAT circuit obtained after finding number of iterations.
(int): the calculated number of iterations for the given SAT problem.
Raises:
SATNoSolutionError - if no adequate number of iterations has been found for
any level of precision.
"""
verifier = ClassicalVerifier(parsed_constraints)
# Diemnsion of the Hilbert space spanned by the input qubits
N = 2**num_input_qubits
# A container for SATCircuit objects with various numbers of iterations
qc_storage = {}
# If `precision == 0`` then probably there is no solution
while precision > 0:
# M is the upper limit for drawing a random number of iterations
M = 1
checked_iterations = set()
# For each level of precision we are looking for an adequate number of iterations
print(f"\nChecking iterations for precision = {precision}:")
while M <= np.sqrt(N):
# Figuring a guess for the number of iterations
iterations = False
while not iterations:
M = step * M
iterations = randint_exclude(start=0, end=int(M), exclude=checked_iterations)
print(f" Checking iterations = {iterations}")
# Obtaining the necessary SATCircuit object (preferably from the `qc_storage`)
if iterations in qc_storage.keys():
qc = qc_storage[iterations]
else:
qc = SATCircuit(num_input_qubits, grover_constraints_operator, iterations)
qc.add_input_reg_measurement()
qc_storage[iterations] = copy.deepcopy(qc)
# Checking whether `qc` with `iterations` iterations gives 100% correct solutions (= match)
match = is_circuit_match(qc, verifier, precision, backend)
if match:
return qc, iterations
checked_iterations.add(iterations)
# Degrading precision if failed to find an adequate number of iterations
precision -= 2
if precision <= 0:
raise SATNoSolutionError(
"Didn't find an suitable number of iterations."
"Probably the SAT problem has no solution."
)
def randint_exclude(start, end, exclude):
"""
Guessing a number of iterations which haven't been tried yet.
If it fails (`count >= 50`), returns False.
"""
randint = random.randint(start, end)
count = 0
while randint in exclude:
randint = random.randint(start, end)
count += 1
if count >= 50:
return False
return randint
def is_circuit_match(
qc: QuantumCircuit, verifier: ClassicalVerifier, precision: int, backend: Backend
) -> bool:
"""
Checks classically whether running `qc` `precision` times gives `precision` correct solutions.
Args:
qc (QuantumCircuit): the quantum circuit to run.
verifier (ClassicalVerifier): classical verifier object to verify solutions with.
precision (int): number of correct solutions required.
backend (Backend): backend to run circuits upon.
Returns:
(bool): True if the execution of `qc` yielded 100% correct solutions (`precision` times).
False otherwise.
"""
job = backend.run(transpile(qc, backend), shots=precision, memory=True)
outcomes = job.result().get_memory()
# In `outcomes` we have `precision` results - If all of them are solutions, we have a match.
match = True
for outcome in outcomes:
match = verifier.verify(outcome)
if not match:
break
return match
|
https://github.com/ohadlev77/sat-circuits-engine
|
ohadlev77
|
# Copyright 2022-2023 Ohad Lev.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0,
# or in the root directory of this package("LICENSE.txt").
# 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.
"""
`SATInterface` class.
"""
import os
import json
from typing import List, Tuple, Union, Optional, Dict, Any
from sys import stdout
from datetime import datetime
from hashlib import sha256
from qiskit import transpile, QuantumCircuit, qpy
from qiskit.result.counts import Counts
from qiskit.visualization.circuit.text import TextDrawing
from qiskit.providers.backend import Backend
from qiskit.transpiler.passes import RemoveBarriers
from IPython import display
from matplotlib.figure import Figure
from sat_circuits_engine.util import timer_dec, timestamp, flatten_circuit
from sat_circuits_engine.util.settings import DATA_PATH, TRANSPILE_KWARGS
from sat_circuits_engine.circuit import GroverConstraintsOperator, SATCircuit
from sat_circuits_engine.constraints_parse import ParsedConstraints
from sat_circuits_engine.interface.circuit_decomposition import decompose_operator
from sat_circuits_engine.interface.counts_visualization import plot_histogram
from sat_circuits_engine.interface.translator import ConstraintsTranslator
from sat_circuits_engine.classical_processing import (
find_iterations_unknown,
calc_iterations,
ClassicalVerifier,
)
from sat_circuits_engine.interface.interactive_inputs import (
interactive_operator_inputs,
interactive_solutions_num_input,
interactive_run_input,
interactive_backend_input,
interactive_shots_input,
)
# Local globlas for visualization of charts and diagrams
IFRAME_WIDTH = "100%"
IFRAME_HEIGHT = "700"
class SATInterface:
"""
An interface for building, running and mining data from n-SAT problems quantum circuits.
There are 2 options to use this class:
(1) Using an interactive interface (intuitive but somewhat limited) - for this
just initiate a bare instance of this class: `SATInterface()`.
(2) Using the API defined by this class, that includes the following methods:
* The following descriptions are partial, for full annotations see the methods' docstrings.
- `__init__`: an instance of `SATInterface must be initiated with exactly 1 combination:
(a) (high_level_constraints_string + high_level_vars) - for constraints
in a high-level format.
(b) (num_input_qubits + constraints_string) - for constraints
in a low-level foramt.
* For formats annotations see `constriants_format.ipynb` in the main directory.
- `obtain_grover_operator`: obtains the suitable grover operator for the constraints.
- `save_display_grover_operator`: saves and displays data generated
by the `obtain_grover_operator` method.
- `obtain_overall_circuit`: obtains the suitable overall SAT circuit.
- `save_display_overall_circuit: saves and displays data generated
by the `obtain_overall_circuit` method.
- `run_overall_circuit`: executes the overall SAT circuit.
- `save_display_results`: saves and displays data generated
by the `run_overall_circuit` method.
It is very recommended to go through `demos.ipynb` that demonstrates the various optional uses
of this class, in addition to reading `constraints_format.ipynb`, which is a must for using
this package properly. Both notebooks are in ther main directory.
"""
def __init__(
self,
num_input_qubits: Optional[int] = None,
constraints_string: Optional[str] = None,
high_level_constraints_string: Optional[str] = None,
high_level_vars: Optional[Dict[str, int]] = None,
name: Optional[str] = None,
save_data: Optional[bool] = True,
) -> None:
"""
Accepts the combination of paramters:
(high_level_constraints_string + high_level_vars) or (num_input_qubits + constraints_string).
Exactly one combination is accepted.
In other cases either an iteractive user interface will be called to take user's inputs,
or an exception will be raised due to misuse of the API.
Args:
num_input_qubits (Optional[int] = None): number of input qubits.
constraints_string (Optional[str] = None): a string of constraints in a low-level format.
high_level_constraints_string (Optional[str] = None): a string of constraints in a
high-level format.
high_level_vars (Optional[Dict[str, int]] = None): a dictionary that configures
the high-level variables - keys are names and values are bits-lengths.
name (Optional[str] = None): a name for this object, if None than the
generic name "SAT" is given automatically.
save_data (Optional[bool] = True): if True, saves all data and metadata generated by this
class to a unique data folder (by using the `save_XXX` methods of this class).
Raises:
SyntaxError - if a forbidden combination of arguments has been provided.
"""
if name is None:
name = "SAT"
self.name = name
# Creating a directory for data to be saved
if save_data:
self.time_created = timestamp(datetime.now())
self.dir_path = f"{DATA_PATH}{self.time_created}_{self.name}/"
os.mkdir(self.dir_path)
print(f"Data will be saved into '{self.dir_path}'.")
# Initial metadata, more to be added by this class' `save_XXX` methods
self.metadata = {
"name": self.name,
"datetime": self.time_created,
"num_input_qubits": num_input_qubits,
"constraints_string": constraints_string,
"high_level_constraints_string": high_level_constraints_string,
"high_level_vars": high_level_vars,
}
self.update_metadata()
# Identifying user's platform, for visualization purposes
self.identify_platform()
# In the case of low-level constraints format, that is the default value
self.high_to_low_map = None
# Case A - interactive interface
if (num_input_qubits is None or constraints_string is None) and (
high_level_constraints_string is None or high_level_vars is None
):
self.interactive_interface()
# Case B - API
else:
self.high_level_constraints_string = high_level_constraints_string
self.high_level_vars = high_level_vars
# Case B.1 - high-level format constraints inputs
if num_input_qubits is None or constraints_string is None:
self.num_input_qubits = sum(self.high_level_vars.values())
self.high_to_low_map, self.constraints_string = ConstraintsTranslator(
self.high_level_constraints_string, self.high_level_vars
).translate()
# Case B.2 - low-level format constraints inputs
elif num_input_qubits is not None and constraints_string is not None:
self.num_input_qubits = num_input_qubits
self.constraints_string = constraints_string
# Misuse
else:
raise SyntaxError(
"SATInterface accepts the combination of paramters:"
"(high_level_constraints_string + high_level_vars) or "
"(num_input_qubits + constraints_string). "
"Exactly one combination is accepted, not both."
)
self.parsed_constraints = ParsedConstraints(
self.constraints_string, self.high_level_constraints_string
)
def update_metadata(self, update_metadata: Optional[Dict[str, Any]] = None) -> None:
"""
Updates the metadata file (in the unique data folder of a given `SATInterface` instance).
Args:
update_metadata (Optional[Dict[str, Any]] = None):
- If None - just dumps `self.metadata` into the metadata JSON file.
- If defined - updates the `self.metadata` attribute and then dumps it.
"""
if update_metadata is not None:
self.metadata.update(update_metadata)
with open(f"{self.dir_path}metadata.json", "w") as metadata_file:
json.dump(self.metadata, metadata_file, indent=4)
def identify_platform(self) -> None:
"""
Identifies user's platform.
Writes True to `self.jupyter` for Jupyter notebook, False for terminal.
"""
# If True then the platform is a terminal/command line/shell
if stdout.isatty():
self.jupyter = False
# If False, we assume the platform is a Jupyter notebook
else:
self.jupyter = True
def output_to_platform(
self,
*,
title: str,
output_terminal: Union[TextDrawing, str],
output_jupyter: Union[Figure, str],
display_both_on_jupyter: Optional[bool] = False,
) -> None:
"""
Displays output to user's platform.
Args:
title (str): a title for the output.
output_terminal (Union[TextDrawing, str]): text to print for a terminal platform.
output_jupyter: (Union[Figure, str]): objects to display for a Jupyter notebook platform.
can handle `Figure` matplotlib objects or strings of paths to IFrame displayable file,
e.g PDF files.
display_both_on_jupyter (Optional[bool] = False): if True, displays both
`output_terminal` and `output_jupyter` in a Jupyter notebook platform.
Raises:
TypeError - in the case of misusing the `output_jupyter` argument.
"""
print()
print(title)
if self.jupyter:
if isinstance(output_jupyter, str):
display.display(display.IFrame(output_jupyter, width=IFRAME_WIDTH, height=IFRAME_HEIGHT))
elif isinstance(output_jupyter, Figure):
display.display(output_jupyter)
else:
raise TypeError("output_jupyter must be an str (path to image file) or a Figure object.")
if display_both_on_jupyter:
print(output_terminal)
else:
print(output_terminal)
def interactive_interface(self) -> None:
"""
An interactive CLI that allows exploiting most (but not all) of the package's features.
Uses functions of the form `interactive_XXX_inputs` from the `interactive_inputs.py` module.
Divided into 3 main stages:
1. Obtaining Grover's operator for the SAT problem.
2. Obtaining the overall SAT cirucit.
3. Executing the circuit and parsing the results.
The interface is built in a modular manner such that a user can halt at any stage.
The defualt settings for the interactive user intreface are:
1. `name = "SAT"`.
2. `save_data = True`.
3. `display = True`.
4. `transpile_kwargs = {'basis_gates': ['u', 'cx'], 'optimization_level': 3}`.
5. Backends are limited to those defined in the global-constant-like function `BACKENDS`:
- Those are the local `aer_simulator` and the remote `ibmq_qasm_simulator` for now.
Due to these default settings the interactive CLI is somewhat restrictive,
for full flexibility a user should use the API and not the CLI.
"""
# Handling operator part
operator_inputs = interactive_operator_inputs()
self.num_input_qubits = operator_inputs["num_input_qubits"]
self.high_to_low_map = operator_inputs["high_to_low_map"]
self.constraints_string = operator_inputs["constraints_string"]
self.high_level_constraints_string = operator_inputs["high_level_constraints_string"]
self.high_level_vars = operator_inputs["high_level_vars"]
self.parsed_constraints = ParsedConstraints(
self.constraints_string, self.high_level_constraints_string
)
self.update_metadata(
{
"num_input_qubits": self.num_input_qubits,
"constraints_string": self.constraints_string,
"high_level_constraints_string": self.high_level_constraints_string,
"high_level_vars": self.high_level_vars,
}
)
obtain_grover_operator_output = self.obtain_grover_operator()
self.save_display_grover_operator(obtain_grover_operator_output)
# Handling overall circuit part
solutions_num = interactive_solutions_num_input()
if solutions_num is not None:
backend = None
if solutions_num == -1:
backend = interactive_backend_input()
overall_circuit_data = self.obtain_overall_sat_circuit(
obtain_grover_operator_output["operator"], solutions_num, backend
)
self.save_display_overall_circuit(overall_circuit_data)
# Handling circuit execution part
if interactive_run_input():
if backend is None:
backend = interactive_backend_input()
shots = interactive_shots_input()
counts_parsed = self.run_overall_sat_circuit(
overall_circuit_data["circuit"], backend, shots
)
self.save_display_results(counts_parsed)
print()
print(f"Done saving data into '{self.dir_path}'.")
def obtain_grover_operator(
self, transpile_kwargs: Optional[Dict[str, Any]] = None
) -> Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]]:
"""
Obtains the suitable `GroverConstraintsOperator` object for the constraints,
decomposes it using the `circuit_decomposition.py` module and transpiles it
according to `transpile_kwargs`.
Args:
transpile_kwargs (Optional[Dict[str, Any]]): kwargs for Qiskit's transpile function.
The defualt is set to the global constant `TRANSPILE_KWARGS`.
Returns:
(Dict[str, Union[GroverConstraintsOperator, QuantumCircuit, Dict[str, List[int]]]]):
- 'operator' (GroverConstraintsOperator):the high-level blocks operator.
- 'decomposed_operator' (QuantumCircuit): decomposed to building-blocks operator.
* For annotations regarding the decomposition method see the
`circuit_decomposition` module.
- 'transpiled_operator' (QuantumCircuit): the transpiled operator.
*** The high-level operator and the decomposed operator are generated with barriers
between constraints as default for visualizations purposes. The barriers are stripped
off before transpiling so the the transpiled operator object contains no barriers. ***
- 'high_level_to_bit_indexes_map' (Optional[Dict[str, List[int]]] = None):
A map of high-level variables with their allocated bit-indexes in the input register.
"""
print()
print(
"The system synthesizes and transpiles a Grover's "
"operator for the given constraints. Please wait.."
)
if transpile_kwargs is None:
transpile_kwargs = TRANSPILE_KWARGS
self.transpile_kwargs = transpile_kwargs
operator = GroverConstraintsOperator(
self.parsed_constraints, self.num_input_qubits, insert_barriers=True
)
decomposed_operator = decompose_operator(operator)
no_baerriers_operator = RemoveBarriers()(operator)
transpiled_operator = transpile(no_baerriers_operator, **transpile_kwargs)
print("Done.")
return {
"operator": operator,
"decomposed_operator": decomposed_operator,
"transpiled_operator": transpiled_operator,
"high_level_to_bit_indexes_map": self.high_to_low_map,
}
def save_display_grover_operator(
self,
obtain_grover_operator_output: Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]],
display: Optional[bool] = True,
) -> None:
"""
Handles saving and displaying data generated by the `self.obtain_grover_operator` method.
Args:
obtain_grover_operator_output(Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]]):
the dictionary returned upon calling the `self.obtain_grover_operator` method.
display (Optional[bool] = True) - If true, displays objects to user's platform.
"""
# Creating a directory to save operator's data
operator_dir_path = f"{self.dir_path}grover_operator/"
os.mkdir(operator_dir_path)
# Titles for displaying objects, by order of `obtain_grover_operator_output`
titles = [
"The operator diagram - high level blocks:",
"The operator diagram - decomposed:",
f"The transpiled operator diagram saved into '{operator_dir_path}'.\n"
f"It's not presented here due to its complexity.\n"
f"Please note that barriers appear in the high-level diagrams above only for convenient\n"
f"visual separation between constraints.\n"
f"Before transpilation all barriers are removed to avoid redundant inefficiencies.",
]
for index, (op_name, op_obj) in enumerate(obtain_grover_operator_output.items()):
# Generic path and name for files to be saved
files_path = f"{operator_dir_path}{op_name}"
# Generating a circuit diagrams figure
figure_path = f"{files_path}.pdf"
op_obj.draw("mpl", filename=figure_path, fold=-1)
# Generating a QPY serialization file for the circuit object
qpy_file_path = f"{files_path}.qpy"
with open(qpy_file_path, "wb") as qpy_file:
qpy.dump(op_obj, qpy_file)
# Original high-level operator and decomposed operator
if index < 2 and display:
# Displaying to user
self.output_to_platform(
title=titles[index], output_terminal=op_obj.draw("text"), output_jupyter=figure_path
)
# Transpiled operator
elif index == 2:
# Output to user, not including the circuit diagram
print()
print(titles[index])
print()
print(f"The transpilation kwargs are: {self.transpile_kwargs}.")
transpiled_operator_depth = op_obj.depth()
transpiled_operator_gates_count = op_obj.count_ops()
print(f"Transpiled operator depth: {transpiled_operator_depth}.")
print(f"Transpiled operator gates count: {transpiled_operator_gates_count}.")
print(f"Total number of qubits: {op_obj.num_qubits}.")
# Generating QASM 2.0 file only for the (flattened = no registers) tranpsiled operator
qasm_file_path = f"{files_path}.qasm"
flatten_circuit(op_obj).qasm(filename=qasm_file_path)
# Index 3 is 'high_level_to_bit_indexes_map' so it's time to break from the loop
break
# Mapping from high-level variables to bit-indexes will be displayed as well
mapping = obtain_grover_operator_output["high_level_to_bit_indexes_map"]
if mapping:
print()
print(f"The high-level variables mapping to bit-indexes:\n{mapping}")
print()
print(
f"Saved into '{operator_dir_path}':\n",
" Circuit diagrams for all levels.\n",
" QPY serialization exports for all levels.\n",
" QASM 2.0 export only for the transpiled level.",
)
with open(f"{operator_dir_path}operator.qpy", "rb") as qpy_file:
operator_qpy_sha256 = sha256(qpy_file.read()).hexdigest()
self.update_metadata(
{
"high_level_to_bit_indexes_map": self.high_to_low_map,
"transpile_kwargs": self.transpile_kwargs,
"transpiled_operator_depth": transpiled_operator_depth,
"transpiled_operator_gates_count": transpiled_operator_gates_count,
"operator_qpy_sha256": operator_qpy_sha256,
}
)
def obtain_overall_sat_circuit(
self,
grover_operator: GroverConstraintsOperator,
solutions_num: int,
backend: Optional[Backend] = None,
) -> Dict[str, SATCircuit]:
"""
Obtains the suitable `SATCircuit` object (= the overall SAT circuit) for the SAT problem.
Args:
grover_operator (GroverConstraintsOperator): Grover's operator for the SAT problem.
solutions_num (int): number of solutions for the SAT problem. In the case the number
of solutions is unknown, specific negative values are accepted:
* '-1' - for launching a classical iterative stochastic process that finds an adequate
number of iterations - by calling the `find_iterations_unknown` function (see its
docstrings for more information).
* '-2' - for generating a dynamic circuit that iterates over Grover's iterator until
a solution is obtained, using weak measurements. TODO - this feature isn't ready yet.
backend (Optional[Backend] = None): in the case of a '-1' value given to `solutions_num`,
a backend object to execute the depicted iterative prcess upon should be provided.
Returns:
(Dict[str, SATCircuit]):
- 'circuit' key for the overall SAT circuit.
- 'concise_circuit' key for the overall SAT circuit, with only 1 iteration over Grover's
iterator (operator + diffuser). Useful for visualization purposes.
*** The concise circuit is generated with barriers between segments as default
for visualizations purposes. In the actual circuit there no barriers. ***
"""
# -1 = Unknown number of solutions - iterative stochastic process
print()
if solutions_num == -1:
assert backend is not None, "Need to specify a backend if `solutions_num == -1`."
print("Please wait while the system checks various solutions..")
circuit, iterations = find_iterations_unknown(
self.num_input_qubits,
grover_operator,
self.parsed_constraints,
precision=10,
backend=backend,
)
print()
print(f"An adequate number of iterations found = {iterations}.")
# -2 = Unknown number of solutions - implement a dynamic circuit
# TODO this feature isn't fully implemented yet
elif solutions_num == -2:
print("The system builds a dynamic circuit..")
circuit = SATCircuit(self.num_input_qubits, grover_operator, iterations=None)
circuit.add_input_reg_measurement()
iterations = None
# Known number of solutions
else:
print("The system builds the overall circuit..")
iterations = calc_iterations(self.num_input_qubits, solutions_num)
print(f"\nFor {solutions_num} solutions, {iterations} iterations needed.")
circuit = SATCircuit(
self.num_input_qubits, grover_operator, iterations, insert_barriers=False
)
circuit.add_input_reg_measurement()
self.iterations = iterations
# Obtaining a SATCircuit object with one iteration for concise representation
concise_circuit = SATCircuit(
self.num_input_qubits, grover_operator, iterations=1, insert_barriers=True
)
concise_circuit.add_input_reg_measurement()
return {"circuit": circuit, "concise_circuit": concise_circuit}
def save_display_overall_circuit(
self, obtain_overall_sat_circuit_output: Dict[str, SATCircuit], display: Optional[bool] = True
) -> None:
"""
Handles saving and displaying data generated by the `self.obtain_overall_sat_circuit` method.
Args:
obtain_overall_sat_circuit_output(Dict[str, SATCircuit]):
the dictionary returned upon calling the `self.obtain_overall_sat_circuit` method.
display (Optional[bool] = True) - If true, displays objects to user's platform.
"""
circuit = obtain_overall_sat_circuit_output["circuit"]
concise_circuit = obtain_overall_sat_circuit_output["concise_circuit"]
# Creating a directory to save overall circuit's data
overall_circuit_dir_path = f"{self.dir_path}overall_circuit/"
os.mkdir(overall_circuit_dir_path)
# Generating a figure of the overall SAT circuit with just 1 iteration (i.e "concise")
concise_circuit_fig_path = f"{overall_circuit_dir_path}overall_circuit_1_iteration.pdf"
concise_circuit.draw("mpl", filename=concise_circuit_fig_path, fold=-1)
# Displaying the concise circuit to user
if display:
if self.iterations:
self.output_to_platform(
title=(
f"The high level circuit contains {self.iterations}"
f" iterations of the following form:"
),
output_terminal=concise_circuit.draw("text"),
output_jupyter=concise_circuit_fig_path,
)
# Dynamic circuit case - TODO NOT FULLY IMPLEMENTED YET
else:
dynamic_circuit_fig_path = f"{overall_circuit_dir_path}overall_circuit_dynamic.pdf"
circuit.draw("mpl", filename=dynamic_circuit_fig_path, fold=-1)
self.output_to_platform(
title="The dynamic circuit diagram:",
output_terminal=circuit.draw("text"),
output_jupyter=dynamic_circuit_fig_path,
)
if self.iterations:
transpiled_overall_circuit = transpile(flatten_circuit(circuit), **self.transpile_kwargs)
print()
print(f"The transpilation kwargs are: {self.transpile_kwargs}.")
transpiled_overall_circuit_depth = transpiled_overall_circuit.depth()
transpiled_overall_circuit_gates_count = transpiled_overall_circuit.count_ops()
print(f"Transpiled overall-circuit depth: {transpiled_overall_circuit_depth}.")
print(f"Transpiled overall-circuit gates count: {transpiled_overall_circuit_gates_count}.")
print(f"Total number of qubits: {transpiled_overall_circuit.num_qubits}.")
print()
print("Exporting the full overall SAT circuit object..")
export_files_path = f"{overall_circuit_dir_path}overall_circuit"
with open(f"{export_files_path}.qpy", "wb") as qpy_file:
qpy.dump(circuit, qpy_file)
if self.iterations:
transpiled_overall_circuit.qasm(filename=f"{export_files_path}.qasm")
print()
print(
f"Saved into '{overall_circuit_dir_path}':\n",
" A concised (1 iteration) circuit diagram of the high-level overall SAT circuit.\n",
" QPY serialization export for the full overall SAT circuit object.",
)
if self.iterations:
print(" QASM 2.0 export for the transpiled full overall SAT circuit object.")
metadata_update = {
"num_total_qubits": circuit.num_qubits,
"num_iterations": circuit.iterations,
}
if self.iterations:
metadata_update["transpiled_overall_circuit_depth"] = (transpiled_overall_circuit_depth,)
metadata_update[
"transpiled_overall_circuit_gates_count"
] = transpiled_overall_circuit_gates_count
self.update_metadata(metadata_update)
@timer_dec("Circuit simulation execution time = ")
def run_overall_sat_circuit(
self, circuit: QuantumCircuit, backend: Backend, shots: int
) -> Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]:
"""
Executes a `circuit` on `backend` transpiled w.r.t backend, `shots` times.
Args:
circuit (QuantumCircuit): `QuantumCircuit` object or child-object (a.k.a `SATCircuit`)
to execute.
backend (Backend): backend to execute `circuit` upon.
shots (int): number of execution shots.
Returns:
(Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]):
dict object returned by `self.parse_counts` - see this method's docstrings for annotations.
"""
# Defines also instance attributes to use in other methods
self.backend = backend
self.shots = shots
print()
print(f"The system is running the circuit {shots} times on {backend}, please wait..")
print("This process might take a while.")
job = backend.run(transpile(circuit, backend), shots=shots)
counts = job.result().get_counts()
print("Done.")
parsed_counts = self.parse_counts(counts)
return parsed_counts
def parse_counts(
self, counts: Counts
) -> Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]:
"""
Parses a `Counts` object into several desired datas (see 'Returns' section).
Args:
counts (Counts): the `Counts` object to parse.
Returns:
(Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]):
'counts' (Counts) - the original `Counts` object.
'counts_sorted' (List[Tuple[Union[str, int]]]) - results sorted in a descending order.
'distilled_solutions' (List[str]): list of solutions (bitstrings).
'high_level_vars_values' (List[Dict[str, int]]): list of solutions (each solution is a
dictionary with variable-names as keys and their integer values as values).
"""
# Sorting results in an a descending order
counts_sorted = sorted(counts.items(), key=lambda x: x[1], reverse=True)
# Generating a set of distilled verified-only solutions
verifier = ClassicalVerifier(self.parsed_constraints)
distilled_solutions = set()
for count_item in counts_sorted:
if not verifier.verify(count_item[0]):
break
distilled_solutions.add(count_item[0])
# In the case of high-level format in use, translating `distilled_solutions` into integer values
high_level_vars_values = None
if self.high_level_constraints_string and self.high_level_vars:
# Container for dictionaries with variables integer values
high_level_vars_values = []
for solution in distilled_solutions:
# Keys are variable-names and values are their integer values
solution_vars = {}
for var, bits_bundle in self.high_to_low_map.items():
reversed_solution = solution[::-1]
var_bitstring = ""
for bit_index in bits_bundle:
var_bitstring += reversed_solution[bit_index]
# Translating to integer value
solution_vars[var] = int(var_bitstring, 2)
high_level_vars_values.append(solution_vars)
return {
"counts": counts,
"counts_sorted": counts_sorted,
"distilled_solutions": distilled_solutions,
"high_level_vars_values": high_level_vars_values,
}
def save_display_results(
self,
run_overall_sat_circuit_output: Dict[
str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]
],
display: Optional[bool] = True,
) -> None:
"""
Handles saving and displaying data generated by the `self.run_overall_sat_circuit` method.
Args:
run_overall_sat_circuit_output (Dict[str, Union[Counts, List[Tuple[Union[str, int]]],
List[str], List[Dict[str, int]]]]): the dictionary returned upon calling
the `self.run_overall_sat_circuit` method.
display (Optional[bool] = True) - If true, displays objects to user's platform.
"""
counts = run_overall_sat_circuit_output["counts"]
counts_sorted = run_overall_sat_circuit_output["counts_sorted"]
distilled_solutions = run_overall_sat_circuit_output["distilled_solutions"]
high_level_vars_values = run_overall_sat_circuit_output["high_level_vars_values"]
# Creating a directory to save results data
results_dir_path = f"{self.dir_path}results/"
os.mkdir(results_dir_path)
# Defining custom dimensions for the custom `plot_histogram` of this package
histogram_fig_width = max((len(counts) * self.num_input_qubits * (10 / 72)), 7)
histogram_fig_height = 5
histogram_figsize = (histogram_fig_width, histogram_fig_height)
histogram_path = f"{results_dir_path}histogram.pdf"
plot_histogram(counts, figsize=histogram_figsize, sort="value_desc", filename=histogram_path)
if display:
# Basic output text
output_text = (
f"All counts:\n{counts_sorted}\n"
f"\nDistilled solutions ({len(distilled_solutions)} total):\n"
f"{distilled_solutions}"
)
# Additional outputs for a high-level constraints format
if high_level_vars_values:
# Mapping from high-level variables to bit-indexes will be displayed as well
output_text += (
f"\n\nThe high-level variables mapping to bit-indexes:" f"\n{self.high_to_low_map}"
)
# Actual integer solutions will be displayed as well
additional_text = ""
for solution_index, solution in enumerate(high_level_vars_values):
additional_text += f"Solution {solution_index + 1}: "
for var_index, (var, value) in enumerate(solution.items()):
additional_text += f"{var} = {value}"
if var_index != len(solution) - 1:
additional_text += ", "
else:
additional_text += "\n"
output_text += f"\n\nHigh-level format solutions: \n{additional_text}"
self.output_to_platform(
title=f"The results for {self.shots} shots are:",
output_terminal=output_text,
output_jupyter=histogram_path,
display_both_on_jupyter=True,
)
results_dict = {
"high_level_to_bit_indexes_map": self.high_to_low_map,
"solutions": list(distilled_solutions),
"high_level_solutions": high_level_vars_values,
"counts": counts_sorted,
}
with open(f"{results_dir_path}results.json", "w") as results_file:
json.dump(results_dict, results_file, indent=4)
self.update_metadata(
{
"num_solutions": len(distilled_solutions),
"backend": str(self.backend),
"shots": self.shots,
}
)
|
https://github.com/ohadlev77/sat-circuits-engine
|
ohadlev77
|
# Copyright 2022-2023 Ohad Lev.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0,
# or in the root directory of this package("LICENSE.txt").
# 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.
"""
Global constants and settings.
"""
from qiskit.providers.backend import Backend
from qiskit import IBMQ
from qiskit_aer import AerSimulator
def BACKENDS(index: int) -> Backend:
"""
Returns a backend object according to `index`.
This "constants" are assembled as a function in order to avoid errors that may raise
from an `IBMQ.load_account()` command if an IBMQ API token isn't saved on the machine.
Raises:
(ValueError) - if the index entered isn't associated with a backend.
"""
if index == 0:
return AerSimulator()
if index == 1:
provider = IBMQ.load_account()
return provider.get_backend("ibmq_qasm_simulator")
raise ValueError(f"No backends are defined for index {index}.")
# Paths constants
CONSTRAINTS_FORMAT_PATH = "sat_circuits_engine/data/constraints_format.md"
DATA_PATH = "sat_circuits_engine/data/generated_data/"
TEST_DATA_PATH = "sat_circuits_engine/data/test_data.json"
# Default kwargs for Qiskit's transpile
TRANSPILE_KWARGS = {"basis_gates": ["u", "cx"], "optimization_level": 3}
|
https://github.com/ohadlev77/sat-circuits-engine
|
ohadlev77
|
import json
import logging
import numpy as np
import warnings
from functools import wraps
from typing import Any, Callable, Optional, Tuple, Union
from qiskit import IBMQ, QuantumCircuit, assemble
from qiskit.circuit import Barrier, Gate, Instruction, Measure
from qiskit.circuit.library import UGate, U3Gate, CXGate
from qiskit.providers.ibmq import AccountProvider, IBMQProviderError
from qiskit.providers.ibmq.job import IBMQJob
def get_provider() -> AccountProvider:
with warnings.catch_warnings():
warnings.simplefilter('ignore')
ibmq_logger = logging.getLogger('qiskit.providers.ibmq')
current_level = ibmq_logger.level
ibmq_logger.setLevel(logging.ERROR)
# get provider
try:
provider = IBMQ.get_provider()
except IBMQProviderError:
provider = IBMQ.load_account()
ibmq_logger.setLevel(current_level)
return provider
def get_job(job_id: str) -> Optional[IBMQJob]:
try:
job = get_provider().backends.retrieve_job(job_id)
return job
except Exception:
pass
return None
def circuit_to_json(qc: QuantumCircuit) -> str:
class _QobjEncoder(json.encoder.JSONEncoder):
def default(self, obj: Any) -> Any:
if isinstance(obj, np.ndarray):
return obj.tolist()
if isinstance(obj, complex):
return (obj.real, obj.imag)
return json.JSONEncoder.default(self, obj)
return json.dumps(circuit_to_dict(qc), cls=_QobjEncoder)
def circuit_to_dict(qc: QuantumCircuit) -> dict:
qobj = assemble(qc)
return qobj.to_dict()
def get_job_urls(job: Union[str, IBMQJob]) -> Tuple[bool, Optional[str], Optional[str]]:
try:
job_id = job.job_id() if isinstance(job, IBMQJob) else job
download_url = get_provider()._api_client.account_api.job(job_id).download_url()['url']
result_url = get_provider()._api_client.account_api.job(job_id).result_url()['url']
return download_url, result_url
except Exception:
return None, None
def cached(key_function: Callable) -> Callable:
def _decorator(f: Any) -> Callable:
f.__cache = {}
@wraps(f)
def _decorated(*args: Any, **kwargs: Any) -> int:
key = key_function(*args, **kwargs)
if key not in f.__cache:
f.__cache[key] = f(*args, **kwargs)
return f.__cache[key]
return _decorated
return _decorator
def gate_key(gate: Gate) -> Tuple[str, int]:
return gate.name, gate.num_qubits
@cached(gate_key)
def gate_cost(gate: Gate) -> int:
if isinstance(gate, (UGate, U3Gate)):
return 1
elif isinstance(gate, CXGate):
return 10
elif isinstance(gate, (Measure, Barrier)):
return 0
return sum(map(gate_cost, (g for g, _, _ in gate.definition.data)))
def compute_cost(circuit: Union[Instruction, QuantumCircuit]) -> int:
print('Computing cost...')
circuit_data = None
if isinstance(circuit, QuantumCircuit):
circuit_data = circuit.data
elif isinstance(circuit, Instruction):
circuit_data = circuit.definition.data
else:
raise Exception(f'Unable to obtain circuit data from {type(circuit)}')
return sum(map(gate_cost, (g for g, _, _ in circuit_data)))
def uses_multiqubit_gate(circuit: QuantumCircuit) -> bool:
circuit_data = None
if isinstance(circuit, QuantumCircuit):
circuit_data = circuit.data
elif isinstance(circuit, Instruction) and circuit.definition is not None:
circuit_data = circuit.definition.data
else:
raise Exception(f'Unable to obtain circuit data from {type(circuit)}')
for g, _, _ in circuit_data:
if isinstance(g, (Barrier, Measure)):
continue
elif isinstance(g, Gate):
if g.num_qubits > 1:
return True
elif isinstance(g, (QuantumCircuit, Instruction)) and uses_multiqubit_gate(g):
return True
return False
|
https://github.com/ohadlev77/sat-circuits-engine
|
ohadlev77
|
# Copyright 2022-2023 Ohad Lev.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0,
# or in the root directory of this package("LICENSE.txt").
# 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.
"""Tests for `util.py` module."""
import unittest
from datetime import datetime
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from sat_circuits_engine.util import flatten_circuit, timestamp
class UtilTest(unittest.TestCase):
def test_timestamp(self):
"""Test for the `timestamp` function."""
self.assertEqual(timestamp(datetime(2022, 12, 3, 17, 0, 45, 0)), "D03.12.22_T17.00.45")
def test_flatten_circuit(self):
"""Test for the `flatten_circuit` function."""
bits_1 = 2
bits_2 = 3
qreg_1 = QuantumRegister(bits_1)
qreg_2 = QuantumRegister(bits_2)
creg_1 = ClassicalRegister(bits_1)
creg_2 = ClassicalRegister(bits_2)
circuit = QuantumCircuit(qreg_1, qreg_2, creg_1, creg_2)
self.assertEqual(circuit.num_qubits, bits_1 + bits_2)
self.assertEqual(circuit.num_clbits, bits_1 + bits_2)
self.assertEqual(len(circuit.qregs), 2)
self.assertEqual(len(circuit.cregs), 2)
flat_circuit = flatten_circuit(circuit)
self.assertEqual(flat_circuit.num_qubits, bits_1 + bits_2)
self.assertEqual(flat_circuit.num_clbits, bits_1 + bits_2)
self.assertEqual(len(flat_circuit.qregs), 1)
self.assertEqual(len(flat_circuit.cregs), 1)
if __name__ == "__main__":
unittest.main()
|
https://github.com/agaviniv/qaoa-maxcut-qiskit
|
agaviniv
|
from qiskit import Aer, IBMQ, execute
from qiskit import transpile, assemble
from qiskit.tools.monitor import job_monitor
from qiskit.tools.monitor import job_monitor
import matplotlib.pyplot as plt
from qiskit.visualization import plot_histogram, plot_state_city
"""
Qiskit backends to execute the quantum circuit
"""
def simulator(qc):
"""
Run on local simulator
:param qc: quantum circuit
:return:
"""
backend = Aer.get_backend("qasm_simulator")
shots = 2048
tqc = transpile(qc, backend)
qobj = assemble(tqc, shots=shots)
job_sim = backend.run(qobj)
qc_results = job_sim.result()
return qc_results, shots
def simulator_state_vector(qc):
"""
Select the StatevectorSimulator from the Aer provider
:param qc: quantum circuit
:return:
statevector
"""
simulator = Aer.get_backend('statevector_simulator')
# Execute and get counts
result = execute(qc, simulator).result()
state_vector = result.get_statevector(qc)
return state_vector
def real_quantum_device(qc):
"""
Use the IBMQ essex device
:param qc: quantum circuit
:return:
"""
provider = IBMQ.load_account()
backend = provider.get_backend('ibmq_santiago')
shots = 2048
TQC = transpile(qc, backend)
qobj = assemble(TQC, shots=shots)
job_exp = backend.run(qobj)
job_monitor(job_exp)
QC_results = job_exp.result()
return QC_results, shots
def counts(qc_results):
"""
Get counts representing the wave-function amplitudes
:param qc_results:
:return: dict keys are bit_strings and their counting values
"""
return qc_results.get_counts()
def plot_results(qc_results):
"""
Visualizing wave-function amplitudes in a histogram
:param qc_results: quantum circuit
:return:
"""
plt.show(plot_histogram(qc_results.get_counts(), figsize=(8, 6), bar_labels=False))
def plot_state_vector(state_vector):
"""Visualizing state vector in the density matrix representation"""
plt.show(plot_state_city(state_vector))
|
https://github.com/agaviniv/qaoa-maxcut-qiskit
|
agaviniv
|
from math import sqrt, pi
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
import oracle_simple
import composed_gates
def get_circuit(n, oracles):
"""
Build the circuit composed by the oracle black box and the other quantum gates.
:param n: The number of qubits (not including the ancillas)
:param oracles: A list of black box (quantum) oracles; each of them selects a specific state
:returns: The proper quantum circuit
:rtype: qiskit.QuantumCircuit
"""
cr = ClassicalRegister(n)
## Testing
if n > 3:
#anc = QuantumRegister(n - 1, 'anc')
# n qubits for the real number
# n - 1 qubits for the ancillas
qr = QuantumRegister(n + n - 1)
qc = QuantumCircuit(qr, cr)
else:
# We don't need ancillas
qr = QuantumRegister(n)
qc = QuantumCircuit(qr, cr)
## /Testing
print("Number of qubits is {0}".format(len(qr)))
print(qr)
# Initial superposition
for j in range(n):
qc.h(qr[j])
# The length of the oracles list, or, in other words, how many roots of the function do we have
m = len(oracles)
# Grover's algorithm is a repetition of an oracle box and a diffusion box.
# The number of repetitions is given by the following formula.
print("n is ", n)
r = int(round((pi / 2 * sqrt((2**n) / m) - 1) / 2))
print("Repetition of ORACLE+DIFFUSION boxes required: {0}".format(r))
oracle_t1 = oracle_simple.OracleSimple(n, 5)
oracle_t2 = oracle_simple.OracleSimple(n, 0)
for j in range(r):
for i in range(len(oracles)):
oracles[i].get_circuit(qr, qc)
diffusion(n, qr, qc)
for j in range(n):
qc.measure(qr[j], cr[j])
return qc, len(qr)
def diffusion(n, qr, qc):
"""
The Grover diffusion operator.
Given the arry of qiskit QuantumRegister qr and the qiskit QuantumCircuit qc, it adds the diffusion operator to the appropriate qubits in the circuit.
"""
for j in range(n):
qc.h(qr[j])
# D matrix, flips state |000> only (instead of flipping all the others)
for j in range(n):
qc.x(qr[j])
# 0..n-2 control bits, n-1 target, n..
if n > 3:
composed_gates.n_controlled_Z_circuit(
qc, [qr[j] for j in range(n - 1)], qr[n - 1],
[qr[j] for j in range(n, n + n - 1)])
else:
composed_gates.n_controlled_Z_circuit(
qc, [qr[j] for j in range(n - 1)], qr[n - 1], None)
for j in range(n):
qc.x(qr[j])
for j in range(n):
qc.h(qr[j])
|
https://github.com/thyung/qiskit_factorization
|
thyung
|
import numpy as np
from numpy import pi
from qiskit import QuantumCircuit, Aer, transpile
from qiskit.visualization import plot_histogram, plot_bloch_multivector
from qiskit.circuit import QuantumRegister, ClassicalRegister
from qiskit.circuit.library import QFT
sim = Aer.get_backend('statevector_simulator')
init_state = '101'
qc1 = QuantumCircuit(3)
qc1.initialize(init_state)
qc1.append(QFT(num_qubits=3), [0, 1, 2])
display(qc1.draw())
sv1 = sim.run(transpile(qc1, sim)).result().get_statevector()
plot_bloch_multivector(sv1)
sim = Aer.get_backend('statevector_simulator')
init_state = '101'
qc2 = QuantumCircuit(3)
qc2.initialize(init_state)
qc2.barrier()
qc2.h(2)
qc2.cp(pi/2, 1, 2)
qc2.cp(pi/4, 0, 2)
qc2.h(1)
qc2.cp(pi/2, 0, 1)
qc2.h(0)
qc2.swap(0, 2)
display(qc2.draw())
sv2 = sim.run(qc2).result().get_statevector()
plot_bloch_multivector(sv2)
# implement general QFT
def create_qft(n, draw=False):
qc = QuantumCircuit(n)
for i in reversed(range(n)):
qc.h(i)
for e, j in enumerate(reversed(range(i))):
qc.cp(pi/2**(e+1), j, i)
for i in range(n//2):
qc.swap(i, n-i-1)
if draw:
display(qc.draw())
return qc.to_gate(label='myqft{}'.format(n))
sim = Aer.get_backend('statevector_simulator')
init_state = '101'
qc3 = QuantumCircuit(3)
qc3.initialize(init_state)
qc3.append(create_qft(3, True), [0, 1, 2])
display(qc3.draw())
sv3 = sim.run(transpile(qc3, sim)).result().get_statevector()
plot_bloch_multivector(sv3)
def create_carrier_orig(name=None, draw=False):
c0 = QuantumRegister(1, 'c0')
a0 = QuantumRegister(1, 'a0')
b0 = QuantumRegister(1, 'b0')
c1 = QuantumRegister(1, 'c1')
qc = QuantumCircuit(c0, a0, b0, c1)
qc.toffoli(1, 2, 3)
qc.cx(1, 2)
qc.toffoli(0, 2, 3)
if draw:
display(qc.draw())
return qc.to_gate(label=name or 'carrier_orig')
def create_carrier_orig_inv(name=None):
qc = QuantumCircuit(4)
qc.append(create_carrier_orig().inverse(), range(4))
return qc.to_gate(label=name or 'carrier_orig_inv')
create_carrier_orig('carrier', True)
def create_carrier(name=None, draw=False):
c0 = QuantumRegister(1, 'c0')
a0 = QuantumRegister(1, 'a0')
b0 = QuantumRegister(1, 'b0')
c1 = QuantumRegister(1, 'c1')
qc = QuantumCircuit(c0, a0, b0, c1)
qc.toffoli(1, 2, 3)
qc.cx(1, 2)
qc.toffoli(0, 2, 3)
qc.cx(1, 2)
if draw:
display(qc.draw())
return qc.to_gate(label=name or 'carrier')
def create_carrier_inv(name=None):
qc = QuantumCircuit(4)
qc.append(create_carrier().inverse(), range(4))
return qc.to_gate(label=name or 'carrier_inv')
create_carrier('carrier', True)
def create_sum(name=None, draw=False):
c0 = QuantumRegister(1, 'c0')
a0 = QuantumRegister(1, 'a0')
b0 = QuantumRegister(1, 'b0')
qc = QuantumCircuit(c0, a0, b0)
qc.cx(a0, b0)
qc.cx(c0, b0)
if draw:
display(qc.draw())
return qc.to_gate(label=name or 'sum')
def create_sum_inv(name=None):
qc = QuantumCircuit(3)
qc.append(create_sum().inverse(), range(3))
return qc.to_gate(label=name or 'sum_inv')
create_sum('sum', True)
a = QuantumRegister(3, 'a')
b = QuantumRegister(4, 'b')
c = QuantumRegister(3, 'c')
creg = ClassicalRegister(4, 'creg')
qc = QuantumCircuit(a, b, c, creg)
qc.x(a[0]) # a = 101(2)
qc.x(a[2])
qc.x(b[1]) # b = 110(2)
qc.x(b[2])
qc.append(create_carrier_orig(), [c[0], a[0], b[0], c[1]])
qc.append(create_carrier_orig(), [c[1], a[1], b[1], c[2]])
qc.append(create_carrier_orig(), [c[2], a[2], b[2], b[3]])
qc.cx(a[2], b[2])
qc.append(create_sum(), [c[2], a[2], b[2]])
qc.append(create_carrier_orig_inv(), [c[1], a[1], b[1], c[2]])
qc.append(create_sum(), [c[1], a[1], b[1]])
qc.append(create_carrier_orig_inv(), [c[0], a[0], b[0], c[1]])
qc.append(create_sum(), [c[0], a[0], b[0]])
qc.barrier()
qc.measure(b, creg)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
a = QuantumRegister(3, 'a')
b = QuantumRegister(4, 'b')
c = QuantumRegister(3, 'c')
creg = ClassicalRegister(4, 'creg')
qc = QuantumCircuit(a, b, c, creg)
qc.x(a[0]) # a = 101(2)
qc.x(a[2])
qc.x(b[1]) # b = 110(2)
qc.x(b[2])
qc.append(create_carrier(), [c[0], a[0], b[0], c[1]])
qc.append(create_carrier(), [c[1], a[1], b[1], c[2]])
qc.append(create_carrier(), [c[2], a[2], b[2], b[3]])
# qc.cx(a[2], b[2]) # this was put into create_carrier()
qc.append(create_sum(), [c[2], a[2], b[2]])
qc.append(create_carrier_inv(), [c[1], a[1], b[1], c[2]])
qc.append(create_sum(), [c[1], a[1], b[1]])
qc.append(create_carrier_inv(), [c[0], a[0], b[0], c[1]])
qc.append(create_sum(), [c[0], a[0], b[0]])
qc.barrier()
qc.measure(b, creg)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
def create_adder(n, name=None, draw=False):
"""create adder with n bits a, n+1 bits b and n bits carrier"""
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
qc = QuantumCircuit(a, b, c)
for i in range(n-1):
qc.append(create_carrier(), [c[i], a[i], b[i], c[i+1]])
qc.append(create_carrier(), [c[n-1], a[n-1], b[n-1], b[n]])
qc.append(create_sum(), [c[n-1], a[n-1], b[n-1]])
for i in reversed(range(n-1)):
qc.append(create_carrier_inv(), [c[i], a[i], b[i], c[i+1]])
qc.append(create_sum(), [c[i], a[i], b[i]])
if draw:
display(qc.draw())
return qc.to_gate(label=name or 'adder')
def create_adder_inv(n, name=None):
qc = QuantumCircuit(3*n+1)
qc.append(create_adder(n).inverse(), range(3*n+1))
return qc.to_gate(label=name or 'adder_inv')
create_adder(3, 'adder', True)
a = QuantumRegister(3, 'a')
b = QuantumRegister(4, 'b')
c = QuantumRegister(3, 'c')
creg = ClassicalRegister(4, 'creg')
qc = QuantumCircuit(a, b, c, creg)
qc.x(a[0]) # a = 5
qc.x(a[2])
qc.x(b[1]) # b = 6
qc.x(b[2])
qc.append(create_adder(3), range(10))
qc.measure(b, creg)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
def create_adder_mod(n, bigN, name=None, draw=False):
"""
:param n: number of bits for a, c and bigN; b has n+1 bits
:param bigN: mod number
:return: Gate of 4n+2 qubits
0 to n-1 (n qubits) for a
n to 2n (n+1 qubits) for b
2n+1 to 3n (n qubits) for c (init to 0)
3n+1 to 4n (n qubits) for bigN (init to bigN when use)
4n+1 (1 qubit) for temp (init to 0)
"""
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bigN')
t = QuantumRegister(1, 't')
qc = QuantumCircuit(a, b, c, bN, t)
# block 1
qc.append(create_adder(n), list(a)+list(b)+list(c))
for i in range(n):
qc.swap(a[i], bN[i])
qc.append(create_adder_inv(n), list(a)+list(b)+list(c))
qc.x(b[n])
qc.cx(b[n], t[0])
qc.x(b[n])
tempN = bigN
i = 0
while tempN != 0:
if tempN % 2 != 0:
qc.cx(t[0], a[i])
i = i + 1
tempN = tempN // 2
qc.append(create_adder(n), list(a)+list(b)+list(c))
tempN = bigN
i = 0
while tempN != 0:
if tempN % 2 != 0:
qc.cx(t[0], a[i])
i = i + 1
tempN = tempN // 2
for i in range(n):
qc.swap(a[i], bN[i])
# block 2
qc.append(create_adder_inv(n), list(a)+list(b)+list(c))
qc.cx(b[n], t[0])
qc.append(create_adder(n), list(a)+list(b)+list(c))
if draw:
display(qc.draw())
return qc.to_gate(label=name or 'adder_mod')
create_adder_mod(3, 5, 'adder_mod', True)
n = 3
bigN = 5
#qc = QuantumCircuit(4*n+2)
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bigN')
t = QuantumRegister(1, 't')
creg = ClassicalRegister(4, 'creg')
qc = QuantumCircuit(a, b, c, bN, t, creg)
qc.x(a[2]) # a = 4
qc.x(b[2]) # b = 4
qc.x(bN[0]) # bN = 5
qc.x(bN[2])
qc.append(create_adder_mod(n, bigN), list(a) + list(b) + list(c) + list(bN) + list(t))
qc.measure(b, creg)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
def create_ctrl_mult_mod(n, bigN, m, name=None, draw=False):
"""
Calculate zm mod N and output to b
:param n: number of bits for a, c and bigN; b has n+1 bits
:param bigN: mod number
:param m: multiplier
:return: Gate of 4n+2 qubits
0 (1 qubit) for x
1 to n (n qubits) for z
n+1 to 2n (n qubits) for a
2n+1 to 3n+1 (n+1 qubits) for b
3n+2 to 4n+1 (n qubits) for c (init to 0)
4n+2 to 5n+1 (n qubits) for bigN (init to bigN when use)
5n+2 (1 qubit) for temp (init to 0)
"""
x = QuantumRegister(1, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
qc = QuantumCircuit(x, z, a, b, c, bN, t)
next_mod = m # m 2^0 mod N
for j in range(n):
temp_mod = next_mod
i = 0
while temp_mod != 0:
if temp_mod % 2 != 0:
qc.ccx(x[0], z[j], a[i])
i = i + 1
temp_mod = temp_mod // 2
qc.append(create_adder_mod(n, bigN), list(a) + list(b) + list(c) + list(bN) + list(t))
temp_mod = next_mod
i = 0
while temp_mod != 0:
if temp_mod % 2 != 0:
qc.ccx(x[0], z[j], a[i])
i = i + 1
temp_mod = temp_mod // 2
next_mod = (next_mod * 2) % bigN # update for m 2^i+1 mod N
# seems no need to copy z to b if x=0. may try to remove this block and test
# qc.x(x[0])
# for j in range(n):
# qc.ccx(x[0], z[j], b[j])
# qc.x(x[0])
if draw:
display(qc.draw())
return qc.to_gate(label=name or 'ctrl_mult_mod')
def create_ctrl_mult_mod_inv(n, bigN, m):
qc = QuantumCircuit(5*n+3)
qc.append(create_ctrl_mult_mod(n, bigN, m).inverse(), range(5*n+3))
return qc.to_gate(label='ctrl_mult_mod_inv')
create_ctrl_mult_mod(3, 5, 3, 'ctrl_mult_mod', True)
n = 3
bigN = 5
m = 3
x = QuantumRegister(1, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
creg = ClassicalRegister(n, 'creg')
qc = QuantumCircuit(x, z, a, b, c, bN, t, creg)
qc.x(x[0]) # x = 1
qc.x(z[0]) # z = 3
qc.x(z[1])
qc.x(bN[0]) # bN = 5
qc.x(bN[2])
qc.append(create_ctrl_mult_mod(n, bigN, m), list(x) + z[:] + list(a) + list(b) + list(c) + list(bN) + list(t))
# for i in range(n):
# qc.measure(b[i], creg[i])
qc.measure(b[0:n], creg)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
from sympy import mod_inverse
def create_mod_exp(n, bigN, y, nx, name=None, draw=False):
"""
Calculate y^x mod N and output to z
:param n: number of bits for z, a, c and bigN; b has n+1 bits
:param bigN: mod number
:param y: multiplier
:param nx: number of bits for x
:return: Gate of 4n+2 qubits
0 to nx-1 (n qubit) for x
nx to nx+n-1 (n qubits) for z (init to 1 when use)
nx+n to nx+2n-1 (n qubits) for a (init to 0)
nx+2n to nx+3n (n+1 qubits) for b (init to 0)
nx+3n+1 to nx+4n (n qubits) for c (init to 0)
nx+4n+1 to nx+5n (n qubits) for bigN (init to bigN when use)
nx+5n+1 (1 qubit) for temp (init to 0)
"""
x = QuantumRegister(nx, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
qc = QuantumCircuit(x, z, a, b, c, bN, t)
m = y
for i in range(nx):
qc.append(create_ctrl_mult_mod(n, bigN, m),
[x[i]] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
for j in range(n):
qc.cswap(x[i], z[j], b[j])
m_inv = mod_inverse(m, bigN)
qc.append(create_ctrl_mult_mod_inv(n, bigN, m_inv),
[x[i]] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
m = (m * m) % bigN # update for next cycle
if draw:
display(qc.draw())
return qc.to_gate(label=name or 'mod_exp')
create_mod_exp(3, 5, 3, 3, 'mod_exp', True)
n = 3
bigN = 5
y = 3
nx = 3
x = QuantumRegister(nx, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
creg = ClassicalRegister(n, 'creg')
qc = QuantumCircuit(x, z, a, b, c, bN, t, creg)
qc.x(x[0]) # x = 3
qc.x(x[1])
qc.x(z[0]) # z = 1 init
qc.x(bN[0]) # bN = 5
qc.x(bN[2])
qc.append(create_mod_exp(n, bigN, y, nx), x[:] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
qc.measure(z, creg)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts) # 3^3 mod 5 = 2 or 010(2)
n = 5
bigN = 15
y = 7
nx = 8
x = QuantumRegister(nx, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
cregx = ClassicalRegister(nx, 'cregx')
qc = QuantumCircuit(x, z, a, b, c, bN, t, cregx)
qc.h(x)
qc.x(z[0]) # z = 1 init
qc.x(bN[0]) # bN = 15 = 1111(2)
qc.x(bN[1])
qc.x(bN[2])
qc.x(bN[3])
qc.append(create_mod_exp(n, bigN, y, nx), x[:] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
qc.append(create_qft(nx), x)
qc.measure(x, cregx)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
from fractions import Fraction
Fraction(192/2**8).limit_denominator(221)
import math
print(math.gcd(7**2+1, 15))
print(math.gcd(7**2-1, 15))
n = 6
bigN = 55
y = 7
nx = 12
x = QuantumRegister(nx, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
cregx = ClassicalRegister(nx, 'cregx')
qc = QuantumCircuit(x, z, a, b, c, bN, t, cregx)
qc.h(x)
qc.x(z[0]) # z = 1 init
qc.x(bN[0]) # bN = 55 = 110111(2)
qc.x(bN[1])
qc.x(bN[2])
qc.x(bN[4])
qc.x(bN[5])
qc.append(create_mod_exp(n, bigN, y, nx), x[:] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
qc.append(create_qft(nx), x)
qc.measure(x, cregx)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
import matplotlib.pyplot as plt
import math
from fractions import Fraction
def is_solution(k, nx, a, N, p, q):
r = Fraction(k/2**nx).limit_denominator(N).denominator
if r % 2 == 1:
return False
if math.gcd(a**(r//2)+1, N) == p and math.gcd(a**(r//2)-1, N) == q:
return True
if math.gcd(a**(r//2)+1, N) == q and math.gcd(a**(r//2)-1, N) == p:
return True
return False
def analyze_result(counts, nx, a, N, p, q):
xycorrect = {}
xywrong = {}
for k,v in counts.items():
if is_solution(int(k, 2), nx, a, N, p, q):
xycorrect[int(k, 2)] = v
else:
xywrong[int(k, 2)] = v
plt.title('Factor {}'.format(N))
plt.xlabel('measured values on {} qubits'.format(nx))
plt.ylabel('counts')
plt.scatter(xycorrect.keys(), xycorrect.values(), s=1, c='g')
plt.scatter(xywrong.keys(), xywrong.values(), s=1, c='r')
plt.legend(['correct', 'wrong'])
print('correct count {}, wrong count {}, total {}, correct rate {}'.format(
sum(xycorrect.values()),
sum(xywrong.values()),
sum(xycorrect.values()) + sum(xywrong.values()),
float(sum(xycorrect.values())) / float(sum(xycorrect.values()) + sum(xywrong.values()),)))
analyze_result(counts, 12, 7, 55, 5, 11)
from fractions import Fraction
Fraction(3891/2**12).limit_denominator(55)
import math
print(math.gcd(7**10+1, 55))
print(math.gcd(7**10-1, 55))
n = 8
bigN = 221
y = 7
nx = 16
x = QuantumRegister(nx, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
cregx = ClassicalRegister(nx, 'cregx')
qc = QuantumCircuit(x, z, a, b, c, bN, t, cregx)
qc.h(x)
qc.x(z[0]) # z = 1 init
qc.x(bN[0]) # bN = 221 = 11011101(2)
qc.x(bN[2])
qc.x(bN[3])
qc.x(bN[4])
qc.x(bN[6])
qc.x(bN[7])
qc.append(create_mod_exp(n, bigN, y, nx), x[:] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
qc.append(create_qft(nx), x)
qc.measure(x, cregx)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
analyze_result(counts, 16, 7, 221, 13, 17)
from fractions import Fraction
Fraction(1365/2**16).limit_denominator(221)
import math
print(math.gcd(3**24+1, 221))
print(math.gcd(3**24-1, 221))
17*13
n = 9
bigN = 437
y = 7
nx = 18
x = QuantumRegister(nx, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
cregx = ClassicalRegister(nx, 'cregx')
qc = QuantumCircuit(x, z, a, b, c, bN, t, cregx)
qc.h(x)
qc.x(z[0]) # z = 1 init
qc.x(bN[0]) # bN = 437 = 110110101(2)
qc.x(bN[2])
qc.x(bN[4])
qc.x(bN[5])
qc.x(bN[7])
qc.x(bN[8])
qc.append(create_mod_exp(n, bigN, y, nx), x[:] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
qc.append(create_qft(nx), x)
qc.measure(x, cregx)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
analyze_result(counts, 18, 7, 437, 19, 23)
from fractions import Fraction
Fraction(123128/2**18).limit_denominator(437)
import math
print(math.gcd(7**33+1, 437))
print(math.gcd(7**33-1, 437))
23*19
qc_t = transpile(qc, backend)
print('circuit depth {}, operator count {}'.format(qc_t.depth(), qc_t.count_ops()))
n = 10
bigN = 851
y = 7
nx = 20
x = QuantumRegister(nx, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
cregx = ClassicalRegister(nx, 'cregx')
qc = QuantumCircuit(x, z, a, b, c, bN, t, cregx)
qc.h(x)
qc.x(z[0]) # z = 1 init
qc.x(bN[0]) # bN = 851 = 1101010011(2)
qc.x(bN[1])
qc.x(bN[4])
qc.x(bN[6])
qc.x(bN[8])
qc.x(bN[9])
qc.append(create_mod_exp(n, bigN, y, nx), x[:] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
qc.append(create_qft(nx), x)
qc.measure(x, cregx)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
analyze_result(counts, 20, 7, 851, 23, 37)
from fractions import Fraction
Fraction(0/2**20).limit_denominator(851)
def gen_qc(n, bigN, y, nx):
x = QuantumRegister(nx, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
cregx = ClassicalRegister(nx, 'cregx')
qc = QuantumCircuit(x, z, a, b, c, bN, t, cregx)
qc.h(x)
qc.x(z[0]) # z = 1 init
tmp_bigN = bigN
i = 0
while tmp_bigN != 0:
if tmp_bigN % 2 == 1:
qc.x(bN[i])
tmp_bigN = tmp_bigN // 2
i = i + 1
qc.append(create_mod_exp(n, bigN, y, nx), x[:] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
qc.append(create_qft(nx), x)
qc.measure(x, cregx)
backend = Aer.get_backend('qasm_simulator')
qc_t = transpile(qc, backend)
return qc_t
qc_15 = gen_qc(4, 15, 7, 8)
qc_55 = gen_qc(6, 55, 7, 12)
qc_221 = gen_qc(8, 221, 7, 16)
qc_437 = gen_qc(9, 437, 7, 18)
qc_851 = gen_qc(10, 851, 7, 20)
print(qc_15.depth(), qc_15.count_ops())
print(qc_851.depth(), qc_851.count_ops())
n_array = [4, 6, 8, 9, 10]
qc_array = [qc_15, qc_55, qc_221, qc_437, qc_851]
depth_array = []
ops_array = []
for qc_i in qc_array:
depth_array.append(qc_i.depth())
ops_array.append(sum(qc_i.count_ops().values()))
print(depth_array)
print(ops_array)
import matplotlib.pyplot as plt
import numpy
opsfit = numpy.polyfit(n_array, ops_array, 3)
print(opsfit)
opsmodel = numpy.poly1d(opsfit)
opsline = numpy.linspace(1, 10, 10)
plt.xlabel('n qubits for N')
plt.ylabel('depth and count_ops')
plt.scatter(n_array, depth_array, marker='o', c='blue')
plt.scatter(n_array, ops_array, marker='x', c='orange')
plt.plot(opsline, opsmodel(opsline), c='orange')
plt.legend(['depth', 'count_ops', 'cout_ops poly deg 3 fit'])
plt.show()
opsline2 = numpy.linspace(1, 100, 100)
plt.xlabel('n qubits for N')
plt.ylabel('count_ops')
plt.scatter(n_array, ops_array, marker='x', c='orange')
plt.plot(opsline2, opsmodel(opsline2), c='orange')
plt.legend(['count_ops', 'cout_ops poly deg 3 fit'])
plt.show()
qc_7663 = gen_qc(13, 7663, 7, 26)
qc_35263 = gen_qc(16, 35263, 7, 32)
opsline3 = numpy.linspace(1, 20, 20)
plt.xlabel('n qubits for N')
plt.ylabel('count_ops')
plt.scatter(n_array, ops_array, marker='x', c='orange')
plt.scatter([13, 16], [sum(qc_7663.count_ops().values()), sum(qc_35263.count_ops().values())])
plt.plot(opsline3, opsmodel(opsline3), c='orange')
plt.legend(['count_ops', 'count_ops for 7663 and 35263', 'cout_ops poly deg 3 fit'])
plt.xticks(range(0, 22, 2))
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/thyung/qiskit_factorization
|
thyung
|
N = 37 * 31
a = 29
print(N)
import math
math.gcd(a, N)
import matplotlib.pyplot as plt
z = range(N)
y = [a**z0 % N for z0 in z]
plt.plot(z, y)
plt.xlabel('z')
plt.ylabel('{}^z mod {}'.format(a, N))
plt.show()
r = y[1:].index(1)+1
print(r)
if r%2 == 0:
x = (a**(r//2)) % N
print('x = {}'.format(x))
if ((x+1)%N) != 0:
print(math.gcd(int(x)+1, N), math.gcd(int(x)-1, N))
else:
print('x+1 % N = 0')
else:
print('r = {} is odd'.format(r))
|
https://github.com/thyung/qiskit_factorization
|
thyung
|
import numpy as np
from numpy import pi
# importing Qiskit
from qiskit import QuantumCircuit, transpile, assemble, Aer
from qiskit.visualization import plot_histogram, plot_bloch_multivector
qc = QuantumCircuit(3)
qc.h(2)
qc.cp(pi/2, 1, 2)
qc.cp(pi/4, 0, 2)
qc.h(1)
qc.cp(pi/2, 0, 1)
qc.h(0)
qc.swap(0, 2)
qc.draw()
def qft_rotations(circuit, n):
if n == 0:
return circuit
n -= 1
circuit.h(n)
for qubit in range(n):
circuit.cp(pi/2**(n-qubit), qubit, n)
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_rotations(circuit, n)
swap_registers(circuit, n)
return circuit
qc = QuantumCircuit(4)
qft(qc,4)
qc.draw()
# Create the circuit
qc = QuantumCircuit(3)
# Encode the state 5 (101 in binary)
qc.x(0)
qc.x(2)
qc.draw()
sim = Aer.get_backend("aer_simulator")
qc_init = qc.copy()
qc_init.save_statevector()
statevector = sim.run(qc_init).result().get_statevector()
plot_bloch_multivector(statevector)
qft(qc, 3)
qc.draw()
qc.save_statevector()
statevector = sim.run(qc).result().get_statevector()
plot_bloch_multivector(statevector)
|
https://github.com/thyung/qiskit_factorization
|
thyung
|
import numpy as np
from numpy import pi
from qiskit import QuantumCircuit, Aer, transpile
from qiskit.visualization import plot_histogram, plot_bloch_multivector
from qiskit.circuit import QuantumRegister, ClassicalRegister
sim = Aer.get_backend('statevector_simulator')
qc = QuantumCircuit(3)
init_state = '101'
qc.initialize(init_state)
qc.barrier()
qc.h(2)
qc.cp(pi/2, 1, 2)
qc.cp(pi/4, 0, 2)
qc.h(1)
qc.cp(pi/2, 0, 1)
qc.h(0)
qc.swap(0, 2)
display(qc.draw())
sv = sim.run(qc).result().get_statevector()
plot_bloch_multivector(sv)
from qiskit.circuit.library import QFT
qc2 = QuantumCircuit(3)
qc2.initialize(init_state)
qc2.append(QFT(num_qubits=3), [0, 1, 2])
display(qc2.draw())
sv2 = sim.run(transpile(qc2, sim)).result().get_statevector()
plot_bloch_multivector(sv2)
# implement general QFT
def myqft(n):
qc = QuantumCircuit(n)
for i in reversed(range(n)):
qc.h(i)
for e, j in enumerate(reversed(range(i))):
qc.cp(pi/2**(e+1), j, i)
for i in range(n//2):
qc.swap(i, n-i-1)
return qc.to_gate(label='myqft{}'.format(n))
qc3 = QuantumCircuit(3)
qc3.initialize(init_state)
qc3.append(myqft(3), [0, 1, 2])
display(qc3.draw())
sv3 = sim.run(transpile(qc3, sim)).result().get_statevector()
plot_bloch_multivector(sv3)
def create_carrier(name=None):
qc = QuantumCircuit(4)
qc.toffoli(1, 2, 3)
qc.cx(1, 2)
qc.toffoli(0, 2, 3)
return qc.to_gate(label=name or 'carrier')
def create_carrier_inv(name=None):
qc = QuantumCircuit(4)
qc.append(create_carrier().inverse(), range(4))
return qc.to_gate(label=name or 'carrier_inv')
def create_sum(name=None):
qc = QuantumCircuit(3)
qc.cx(1, 2)
qc.cx(0, 2)
return qc.to_gate(label=name or 'sum')
def create_sum_inv(name=None):
qc = QuantumCircuit(3)
qc.append(create_sum().inverse(), range(3))
return qc.to_gate(label=name or 'sum_inv')
a = QuantumRegister(3, 'a')
b = QuantumRegister(4, 'b')
c = QuantumRegister(3, 'c')
creg = ClassicalRegister(4, 'creg')
qc = QuantumCircuit(a, b, c, creg)
qc.x(a[0])
qc.x(a[1])
qc.x(b[1])
qc.x(b[2])
qc.append(create_carrier(), [c[0], a[0], b[0], c[1]])
qc.append(create_carrier(), [c[1], a[1], b[1], c[2]])
qc.append(create_carrier(), [c[2], a[2], b[2], b[3]])
qc.cx(a[2], b[2])
qc.append(create_sum(), [c[2], a[2], b[2]])
qc.append(create_carrier_inv(), [c[1], a[1], b[1], c[2]])
qc.append(create_sum(), [c[1], a[1], b[1]])
qc.append(create_carrier_inv(), [c[0], a[0], b[0], c[1]])
qc.append(create_sum(), [c[0], a[0], b[0]])
qc.barrier()
qc.measure(b, creg)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
def create_adder(n):
"""create adder with n bits a, n+1 bits b and n bits carrier"""
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
qc = QuantumCircuit(a, b, c)
for i in range(n-1):
qc.append(create_carrier(), [c[i], a[i], b[i], c[i+1]])
qc.append(create_carrier(), [c[n-1], a[n-1], b[n-1], b[n]])
qc.cx(a[n-1], b[n-1])
qc.append(create_sum(), [c[n-1], a[n-1], b[n-1]])
for i in reversed(range(n-1)):
qc.append(create_carrier_inv(), [c[i], a[i], b[i], c[i+1]])
qc.append(create_sum(), [c[i], a[i], b[i]])
return qc.to_gate(label='adder')
def create_adder_inv(n):
qc = QuantumCircuit(3*n+1)
qc.append(create_adder(n).inverse(), range(3*n+1))
return qc.to_gate(label='adder_inv')
qc = QuantumCircuit(10, 4)
qc.x(0)
qc.x(1)
qc.x(4)
qc.x(5)
qc.append(create_adder(3), range(10))
qc.measure([3, 4, 5, 6], range(4))
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
def create_adder_mod(n, bigN):
"""
:param n: number of bits for a, c and bigN; b has n+1 bits
:param bigN: mod number
:return: Gate of 4n+2 qubits
0-2 qubits for a
3-6 qubits for b
7-9 qubits for c (init to 0)
10-12 qubits for bigN (init to bigN when use)
13 qubit for temp (init to 0)
"""
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bigN')
t = QuantumRegister(1, 't')
qc = QuantumCircuit(a, b, c, bN, t)
# block 1
qc.append(create_adder(n), list(a)+list(b)+list(c))
for i in range(n):
qc.swap(a[i], bN[i])
qc.append(create_adder_inv(n), list(a)+list(b)+list(c))
qc.x(b[n])
qc.cx(b[n], t[0])
qc.x(b[n])
tempN = bigN
i = 0
while tempN != 0:
if tempN % 2 != 0:
qc.cx(t[0], a[i])
i = i + 1
tempN = tempN // 2
qc.append(create_adder(n), list(a)+list(b)+list(c))
tempN = bigN
i = 0
while tempN != 0:
if tempN % 2 != 0:
qc.cx(t[0], a[i])
i = i + 1
tempN = tempN // 2
for i in range(n):
qc.swap(a[i], bN[i])
# block 2
qc.append(create_adder_inv(n), list(a)+list(b)+list(c))
qc.cx(b[n], t[0])
qc.append(create_adder(n), list(a)+list(b)+list(c))
#display(qc.draw())
return qc.to_gate(label='adder_mod')
n = 3
bigN = 5
#qc = QuantumCircuit(4*n+2)
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bigN')
t = QuantumRegister(1, 't')
creg = ClassicalRegister(4, 'creg')
qc = QuantumCircuit(a, b, c, bN, t, creg)
# qc.x(a[0]) # a = 3
# qc.x(a[1])
qc.x(a[2]) # a = 4
qc.x(b[2]) # b = 4
qc.x(bN[0])
qc.x(bN[2]) # bN = 5
qc.append(create_adder_mod(n, bigN), list(a) + list(b) + list(c) + list(bN) + list(t))
qc.measure(b, creg)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
def create_ctrl_mult_mod(n, bigN, m):
"""
Calculate zm mod N and output to b
:param n: number of bits for a, c and bigN; b has n+1 bits
:param bigN: mod number
:param m: multiplier
:return: Gate of 4n+2 qubits
0 (1 qubit) for x
1 to n (n qubits) for z
n+1 to 2n (n qubits) for a
2n+1 to 3n+1 (n+1 qubits) for b
3n+2 to 4n+1 (n qubits) for c (init to 0)
4n+2 to 5n+1 (n qubits) for bigN (init to bigN when use)
5n+2 (1 qubit) for temp (init to 0)
"""
x = QuantumRegister(1, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
qc = QuantumCircuit(x, z, a, b, c, bN, t)
next_mod = m # m 2^0 mod N
for j in range(n):
temp_mod = next_mod
i = 0
while temp_mod != 0:
if temp_mod % 2 != 0:
qc.ccx(x[0], z[j], a[i])
i = i + 1
temp_mod = temp_mod // 2
qc.append(create_adder_mod(n, bigN), list(a) + list(b) + list(c) + list(bN) + list(t))
temp_mod = next_mod
i = 0
while temp_mod != 0:
if temp_mod % 2 != 0:
qc.ccx(x[0], z[j], a[i])
i = i + 1
temp_mod = temp_mod // 2
next_mod = (next_mod * 2) % bigN # update for m 2^i+1 mod N
qc.x(x[0])
for j in range(n):
qc.ccx(x[0], z[j], b[j])
qc.x(x[0])
# display(qc.draw())
return qc.to_gate(label='ctrl_mult_mod')
def create_ctrl_mult_mod_inv(n, bigN, m):
qc = QuantumCircuit(5*n+3)
qc.append(create_ctrl_mult_mod(n, bigN, m).inverse(), range(5*n+3))
return qc.to_gate(label='ctrl_mult_mod_inv')
n = 3
bigN = 5
m = 3
x = QuantumRegister(1, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
creg = ClassicalRegister(n, 'creg')
qc = QuantumCircuit(x, z, a, b, c, bN, t, creg)
qc.x(x[0]) # x = 1
qc.x(z[0]) # z = 3
qc.x(z[1])
qc.x(bN[0]) # bN = 5
qc.x(bN[2])
qc.append(create_ctrl_mult_mod(n, bigN, m), list(x) + z[:] + list(a) + list(b) + list(c) + list(bN) + list(t))
# for i in range(n):
# qc.measure(b[i], creg[i])
qc.measure(b[0:n], creg)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
from sympy import mod_inverse
def create_mod_exp(n, bigN, y, nx):
"""
Calculate y^x mod N and output to z
:param n: number of bits for z, a, c and bigN; b has n+1 bits
:param bigN: mod number
:param y: multiplier
:param nx: number of bits for x
:return: Gate of 4n+2 qubits
0 to nx-1 (n qubit) for x
nx to nx+n-1 (n qubits) for z (init to 1 when use)
nx+n to nx+2n-1 (n qubits) for a (init to 0)
nx+2n to nx+3n (n+1 qubits) for b (init to 0)
nx+3n+1 to nx+4n (n qubits) for c (init to 0)
nx+4n+1 to nx+5n (n qubits) for bigN (init to bigN when use)
nx+5n+1 (1 qubit) for temp (init to 0)
"""
x = QuantumRegister(nx, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
qc = QuantumCircuit(x, z, a, b, c, bN, t)
m = y
for i in range(nx):
qc.append(create_ctrl_mult_mod(n, bigN, m),
[x[i]] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
for j in range(n):
qc.cswap(x[i], z[j], b[j])
m_inv = mod_inverse(m, bigN)
qc.append(create_ctrl_mult_mod_inv(n, bigN, m_inv),
[x[i]] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
m = (m * m) % bigN # update for next cycle
# display(qc.draw())
return qc.to_gate(label='mod_exp')
n = 3
bigN = 5
y = 3
nx = 6
x = QuantumRegister(nx, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
creg = ClassicalRegister(n, 'creg')
qc = QuantumCircuit(x, z, a, b, c, bN, t, creg)
#qc.x(x[2]) # x = 4
# qc.x(x[0]) # x = 3
# qc.x(x[1])
qc.x(x[1]) # x = 42
qc.x(x[3])
qc.x(x[5])
qc.x(z[0]) # z = 1 init
qc.x(bN[0]) # bN = 5
qc.x(bN[2])
qc.append(create_mod_exp(n, bigN, y, nx), x[:] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
qc.measure(z, creg)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1)
counts = job.result().get_counts()
print(counts)
n = 5 # use 4 qubits may not work, do not know the reason
bigN = 15
y = 7
nx = 8
x = QuantumRegister(nx, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
# cregz = ClassicalRegister(n, 'cregz')
cregx = ClassicalRegister(nx, 'cregx')
# qc = QuantumCircuit(x, z, a, b, c, bN, t, cregz, cregx)
qc = QuantumCircuit(x, z, a, b, c, bN, t, cregx)
qc.h(x)
qc.x(z[0]) # z = 1 init
qc.x(bN[0]) # bN = 15 = 1111(2)
qc.x(bN[1])
qc.x(bN[2])
qc.x(bN[3])
qc.append(create_mod_exp(n, bigN, y, nx), x[:] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
qc.append(myqft(nx).inverse(), x)
# qc.measure(z, cregz)
qc.measure(x, cregx)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
from fractions import Fraction
Fraction(192/2**8).limit_denominator(15)
import math
print(math.gcd(7**2+1, 15))
print(math.gcd(7**2-1, 15))
n = 6
bigN = 55
y = 7
nx = 12
x = QuantumRegister(nx, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
# cregz = ClassicalRegister(n, 'cregz')
cregx = ClassicalRegister(nx, 'cregx')
# qc = QuantumCircuit(x, z, a, b, c, bN, t, cregz, cregx)
qc = QuantumCircuit(x, z, a, b, c, bN, t, cregx)
qc.h(x)
qc.x(z[0]) # z = 1 init
qc.x(bN[0]) # bN = 55 = 110111(2)
qc.x(bN[1])
qc.x(bN[2])
qc.x(bN[4])
qc.x(bN[5])
# qc.x(bN[7])
qc.append(create_mod_exp(n, bigN, y, nx), x[:] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
qc.append(myqft(nx).inverse(), x)
# qc.measure(z, cregz)
qc.measure(x, cregx)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
from fractions import Fraction
Fraction(205/2**12).limit_denominator(55)
import math
print(math.gcd(7**10+1, 55))
print(math.gcd(7**10-1, 55))
n = 8
bigN = 221
y = 7
nx = 16
x = QuantumRegister(nx, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
# cregz = ClassicalRegister(n, 'cregz')
cregx = ClassicalRegister(nx, 'cregx')
# qc = QuantumCircuit(x, z, a, b, c, bN, t, cregz, cregx)
qc = QuantumCircuit(x, z, a, b, c, bN, t, cregx)
qc.h(x)
qc.x(z[0]) # z = 1 init
qc.x(bN[0]) # bN = 221 = 11011101(2)
qc.x(bN[2])
qc.x(bN[3])
qc.x(bN[4])
qc.x(bN[6])
qc.x(bN[7])
qc.append(create_mod_exp(n, bigN, y, nx), x[:] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
qc.append(myqft(nx).inverse(), x)
# qc.measure(z, cregz)
qc.measure(x, cregx)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1)
counts = job.result().get_counts()
print(counts)
from fractions import Fraction
Fraction(53248/2**16).limit_denominator(221)
import math
print(math.gcd(7**8+1, 221))
print(math.gcd(7**8-1, 221))
17*13
n = 9
bigN = 437
y = 7
nx = 18
x = QuantumRegister(nx, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
# cregz = ClassicalRegister(n, 'cregz')
cregx = ClassicalRegister(nx, 'cregx')
# qc = QuantumCircuit(x, z, a, b, c, bN, t, cregz, cregx)
qc = QuantumCircuit(x, z, a, b, c, bN, t, cregx)
qc.h(x)
qc.x(z[0]) # z = 1 init
qc.x(bN[0]) # bN = 437 = 110110101(2)
qc.x(bN[2])
qc.x(bN[4])
qc.x(bN[5])
qc.x(bN[7])
qc.x(bN[8])
qc.append(create_mod_exp(n, bigN, y, nx), x[:] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
qc.append(myqft(nx).inverse(), x)
# qc.measure(z, cregz)
qc.measure(x, cregx)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
from fractions import Fraction
Fraction(170791/2**18).limit_denominator(437)
import math
print(math.gcd(7**33+1, 437))
print(math.gcd(7**33-1, 437))
|
https://github.com/shell-raiser/Introduction-to-Quantum-Computing-Quantum-Algorithms-and-Qiskit
|
shell-raiser
|
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 *
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
from qiskit import assemble
import numpy as np
import matplotlib.pyplot as plt
n=4
grover_ckt = QuantumCircuit(n+1, n)
marked = [1,0,1,1] # 1101 element is marked (lsb to msb)=>13
def apply_oracle(n,marked,ckt):
control0 = [i for i in range(n) if not marked[i]]
ckt.x(control0)
ckt.mct(list(range(n)),n)
ckt.x(control0)
ckt.draw()
def reflect_uniform(ckt,n):
ckt.h(list(range(n)))
ckt.x(list(range(n)))
ckt.mct(list(range(n)),n)
ckt.x(list(range(n)))
ckt.h(list(range(n)))
ckt.x(n)
pass
grover_ckt.x(n)
grover_ckt.barrier()
grover_ckt.h(list(range(n)))
grover_ckt.draw()
svsim = Aer.get_backend('statevector_simulator') # Tell Qiskit how to simulate our circuit
qobj = assemble(grover_ckt) # Create a Qobj from the circuit for the simulator to run
result = svsim.run(qobj).result() # Do the simulation and return the result
statevector = result.data()['statevector']
statevector = statevector[:2**n]
marked = [1,0,1,1] # Corresponds to integer 1101 in binary => 13
ket_a = np.zeros(2**n)
ket_a[13] =1
ket_e = (np.ones(2**n) - ket_a)/np.sqrt(2**n -1)
def get_projection(psi,e,a ):
proj = [np.real(np.vdot(e,psi)), np.real(np.vdot(a,psi))]
return proj
def plt_vector(proj, axes =[0.0,1.0,0.0,1.0]):
x_pos = 0
y_pos = 0
x_direct = proj[0]
y_direct = proj[1]
# Creating plot
fig, ax = plt.subplots()
ax.quiver(x_pos, y_pos, x_direct, y_direct,scale=1.0)
ax.axis(axes)
# show plot
plt.show()
proj = get_projection(statevector, ket_e, ket_a)
plt_vector(proj)
#grover_ckt.append(oracle, list(range(n+1)))
apply_oracle(4,marked,grover_ckt)
grover_ckt.barrier()
grover_ckt.draw()
reflect_uniform(grover_ckt,n)
grover_ckt.barrier()
grover_ckt.draw()
svsim = Aer.get_backend('statevector_simulator') # Tell Qiskit how to simulate our circuit
qobj = assemble(grover_ckt) # Create a Qobj from the circuit for the simulator to run
result = svsim.run(qobj).result() # Do the simulation and return the result
statevector = result.data()['statevector']
statevector = statevector[:2**n]
proj = get_projection(statevector, ket_e, ket_a)
plt_vector(proj)
apply_oracle(4,marked,grover_ckt)
grover_ckt.barrier()
reflect_uniform(grover_ckt,n)
grover_ckt.barrier()
grover_ckt.draw()
svsim = Aer.get_backend('statevector_simulator') # Tell Qiskit how to simulate our circuit
qobj = assemble(grover_ckt) # Create a Qobj from the circuit for the simulator to run
result = svsim.run(qobj).result() # Do the simulation and return the result
statevector = result.data()['statevector']
statevector = statevector[:2**n]
proj = get_projection(statevector, ket_e, ket_a)
plt_vector(proj)
apply_oracle(4,marked,grover_ckt)
grover_ckt.barrier()
reflect_uniform(grover_ckt,n)
grover_ckt.barrier()
grover_ckt.draw()
svsim = Aer.get_backend('statevector_simulator') # Tell Qiskit how to simulate our circuit
qobj = assemble(grover_ckt) # Create a Qobj from the circuit for the simulator to run
result = svsim.run(qobj).result() # Do the simulation and return the result
statevector = result.data()['statevector']
statevector = statevector[:2**n]
proj = get_projection(statevector, ket_e, ket_a)
plt_vector(proj, axes = [-1.0,1.0,-1.0,1.0])
from math import *
N = (math.sqrt(n**2))
theta0 = asin(1/N)
theta0
T = int((((3.14/2)/theta0)-1)/2)
T
n=4
grover_ckt = QuantumCircuit(n+1, n)
marked = [1,0,1,1] # 1101 element is marked (lsb to msb)=>13
grover_ckt.x(n)
grover_ckt.barrier()
grover_ckt.h(list(range(n+1)))
grover_ckt.barrier()
for _ in range(int(np.floor(T))):
apply_oracle(4,marked,grover_ckt)
grover_ckt.barrier()
reflect_uniform(grover_ckt,n)
grover_ckt.barrier()
for j in range(n):
grover_ckt.measure(j,j)
grover_ckt.draw()
sim = Aer.get_backend('qasm_simulator') # Tell Qiskit how to simulate our circuit
qobj = assemble(grover_ckt) # Create a Qobj from the circuit for the simulator to run
result = sim.run(qobj).result() # Do the simulation and return the result
result
counts = result.get_counts(grover_ckt)
plot_histogram(counts)
|
https://github.com/rowanshah/IBM-Qiskit-Models
|
rowanshah
|
import numpy as np
from qiskit import *
%matplotlib inline
# Create a Quantum Register with 3 qubits.
q = QuantumRegister(4, 'q')
# Create a Quantum Circuit acting on the q register
circ = QuantumCircuit(q)
# Add a H gate on qubit 0, putting this qubit in superposition.
circ.h(q[0])
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting
# the qubits in a Bell state.
circ.cx(q[0], q[1])
# Add a CX (CNOT) gate on control qubit 0 and target qubit 2, putting
# the qubits in a GHZ state.
circ.cx(q[0], q[2])
# Add a CX (CNOT) gate on control qubit 0 and target qubit 3, putting
# the qubits in a GHZ state.
circ.cx(q[0], q[3])
circ.draw()
# Import Aer
from qiskit import BasicAer
# Run the quantum circuit on a statevector simulator backend
backend = BasicAer.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 = BasicAer.get_backend('unitary_simulator')
job = execute(circ, backend)
result = job.result()
# Show the results
print(result.get_unitary(circ, decimals=3))
# Create a Classical Register with 3 bits.
c = ClassicalRegister(4, 'c')
# Create a Quantum Circuit
meas = QuantumCircuit(q, c)
meas.barrier(q)
# map the quantum measurement to the classical bits
meas.measure(q,c)
# 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 = 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_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
provider = IBMQ.load_account()
print("Available backends:")
provider.backends()
from qiskit.providers.ibmq import least_busy
large_enough_devices = provider.backends(filters=lambda x: x.configuration().n_qubits < 10 and
not x.configuration().simulator)
backend = least_busy(large_enough_devices)
print("The best backend is " + backend.name())
from qiskit.tools.monitor import job_monitor
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_exp = job_exp.result()
counts_exp = result_exp.get_counts(qc)
plot_histogram([counts_exp,counts])
simulator_backend = provider.get_backend('ibmq_qasm_simulator')
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_hpc = execute(qc, backend=simulator_backend, shots=shots, max_credits=max_credits)
result_hpc = job_hpc.result()
counts_hpc = result_hpc.get_counts(qc)
plot_histogram(counts_hpc)
job_id = job_exp.job_id()
print('JOB ID: {}'.format(job_id))
retrieved_job = backend.retrieve_job(job_id)
retrieved_job.result().get_counts(qc)
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
import numpy as np
import math
from qiskit import QuantumCircuit
from qiskit.circuit.library import GroverOperator, MCMT, ZGate
from qiskit.visualization import plot_distribution
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Session
from qiskit.providers.basic_provider import BasicProvider
from qiskit.visualization import plot_histogram
from qiskit import transpile
from qiskit.providers.fake_provider import GenericBackendV2
backend = GenericBackendV2(num_qubits=5)
def grover_oracle(marked_states, i, j, k):
if not isinstance(marked_states, list):
marked_states = [marked_states]
num_qubits = len(marked_states[0])
qc = QuantumCircuit(num_qubits)
for target in marked_states:
rev_target = target[::-1]
zero_inds = [ind for ind in range(num_qubits) if rev_target.startswith("0", ind)]
qc.x(zero_inds)
"""ZAJ 1"""
qc.rx(i,zero_inds)
qc.ry(j,zero_inds)
qc.rz(k,zero_inds)
qc.compose(MCMT(ZGate(), num_qubits - 1, 1), inplace=True)
qc.x(zero_inds)
return qc
def printToConsole():
# Format counts data
formatted_output = ""
#for state in ['000', '001', '010', '011', '100', '101', '110', '111']:
for state in ['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111',
'1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']:
formatted_output += f"{counts.get(state, 0)} "
# Write counts data to a text file
with open('counts_data.txt', 'a') as file:
file.write(formatted_output)
file.write(f"{x} {y} {z}\n")
if(printDebug):
import matplotlib.pyplot as plt
# Parse counts data
counts_data = {state: counts.get(state, 0) for state in ['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111',
'1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']}
#for state in ['000', '001', '010', '011', '100', '101', '110', '111']}
# Plot counts
plt.bar(counts_data.keys(), counts_data.values())
plt.xlabel('States')
plt.ylabel('Counts')
plt.title('Quantum Circuit Measurement Results')
plt.show()
print(counts_data)
marked_states = ["0010", "1000"]
printDebug = False
randomXYZ = False
#RX, RY, RZ trasformators causing error in the grover oracle by rotating state by v/100
fromRot = -100
toRot = 101
XYZ = 2 #1->RX, 2->RY, 3->RZ
num_simulations = 10 #averaging this many simulations, (good for graphing)
for i in range(fromRot, toRot,1):
# Initialize empty dictionary for averages
averages = {}
x=0
y=0
z=0
# Loop for multiple simulations
for _ in range(num_simulations):
zaj=i
if(randomXYZ):
k = random.randrange(-100,100)#-1 - +1 fok kozott random zaj
if XYZ == 1:
x=zaj/100
elif XYZ == 2:
y=zaj/100
elif XYZ == 3:
z=zaj/100
oracle = grover_oracle(marked_states, x, y, z)
grover_op = GroverOperator(oracle)
optimal_num_iterations = math.floor(math.pi / 4 * math.sqrt(2 ** grover_op.num_qubits / len(marked_states)))
qc = QuantumCircuit(grover_op.num_qubits)
qc.h(range(grover_op.num_qubits))
qc.compose(grover_op.power(optimal_num_iterations), inplace=True)
qc.measure_all()
backend = GenericBackendV2(num_qubits=4)
transpiled_circuit = transpile(qc, backend)
job = backend.run(transpiled_circuit)
counts = job.result().get_counts()
# Update averages for each state
#for state in ['000', '001', '010', '011', '100', '101', '110', '111']:
for state in ['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111',
'1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']:
averages[state] = averages.get(state, 0) + counts.get(state, 0)
# Calculate averages
for state in averages:
averages[state] /= num_simulations
# Write averages to a text file
with open('averages_data.txt', 'a') as file:
for state in averages:
file.write(f"{int(averages[state])} ")
file.write(f"{x} {y} {z}")
file.write("\n")
if(printDebug):
printToConsole()
print("All done")
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
from qiskit import QuantumCircuit
def prepare_bell_state(state_number,qc):
if state_number == 1: # |Φ+⟩
qc.h(0)
qc.cx(0, 1)
elif state_number == 2: # |Φ-⟩
qc.h(0)
qc.cx(0, 1)
qc.z(0)
elif state_number == 3: # |Ψ+⟩
qc.h(0)
qc.cx(0, 1)
qc.x(1)
elif state_number == 4: # |Ψ-⟩
qc.h(0)
qc.cx(0, 1)
qc.x(1)
qc.z(0)
else:
raise ValueError("State number must be 1, 2, 3, or 4.")
return qc
from qiskit import execute, Aer
from qiskit.visualization import plot_histogram
import numpy as np
def cxHI_simul(bell_state):
# Create a 2-qubit quantum circuit
qc = QuantumCircuit(2)
prepare_bell_state(bell_state,qc)
# Apply CNOT gate with the first qubit as control and the second as target
qc.cx(0, 1)
# Apply H gate on the first qubit
qc.h(0)
# Draw the circuit
qc.draw(output='mpl')
# (Optional) Simulate the circuit
simulator = Aer.get_backend('statevector_simulator')
result = execute(qc, simulator).result()
statevector = result.get_statevector()
statevector = np.asarray(result.get_statevector())
rounded_statevector = [round(x.real, 3) + round(x.imag, 3) * 1j for x in statevector]
print("Rounded Statevector:", rounded_statevector)
qc.measure_all()
# szimulálás
job = execute(qc, simulator, shots=1024)
result = job.result()
counts = result.get_counts(qc)
print(counts)
# bell állapotok előkészítése
for i in range(1,5):
cxHI_simul(i)
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
# Standard Qiskit könyvtárak importálása
from qiskit import QuantumCircuit, transpile
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Estimator, Session, Options
# IBM Quantum fiók betöltése
service = QiskitRuntimeService(channel="ibm_quantum")
from qiskit import QuantumCircuit, execute, Aer
# quantumáramkör létrehozása
circuit = QuantumCircuit(1)
# Get the simulator backend
simulator = Aer.get_backend('qasm_simulator')
def apply_hadamard_and_measure(circuit, simulator,hanyszor):
#Hadamard kapuk alkalmazása a qbitekre
for i in range(hanyszor):
circuit.h(0)
# qubit megmérése
circuit.measure_all()
# szimulálás
job = execute(circuit, simulator, shots=1024)
result = job.result()
counts = result.get_counts(circuit)
return counts
#Más eredményt kapunk ha két kapuk között mérünk. Szuperpozíciót megzavarja a mérés.
# Függvény hívása a Hadamard kapu alkalmazásához és méréshez, majd az eredmények kiírása
counts1 = apply_hadamard_and_measure(circuit, simulator, 2)
print("Eredmények a két H kapu után:")
print(counts1)
# Függvény újra hívása a Hadamard kapu alkalmazásához és méréshez, majd az eredmények kiírása
counts2 = apply_hadamard_and_measure(circuit, simulator, 1)
print("Eredmények az első H kapu után:")
print(counts2)
# Függvény újra hívása a Hadamard kapu alkalmazásához és méréshez, majd az eredmények kiírása
counts3 = apply_hadamard_and_measure(circuit, simulator, 1)
print("Eredmények a második H kapu után:")
print(counts3)
import numpy as np
from qiskit.visualization import plot_state_city
# Kvantumáramkör létrehozása 2 qubittel
circuit = QuantumCircuit(2)
# Pauli-X, Y, Z kapuk alkalmazása a qubitekre
circuit.x(0)
circuit.y(0)
circuit.z(1)
# Qubit mérése
circuit.measure_all()
stateVsim = Aer.get_backend('statevector_simulator')
# Áramkör futtatása a szimulátoron
feladat = execute(circuit, stateVsim, shots=1024)
eredmeny = feladat.result()
stateVector = eredmeny.get_statevector()
print(stateVector)
plot_state_city(stateVector)
from qiskit import QuantumCircuit, Aer, transpile
def set_quantum_state(qc, state):
# Validate input state
valid_states = [0, 1, 2, 3]
if state not in valid_states:
raise ValueError("Invalid state code. Choose from 0, 1, 2, or 3.")
# Quantum circuit creation
# Set the state according to the given state code
if state == 0:
qc.initialize([1, 0, 0, 0], [0, 1]) # |00>
elif state == 1:
qc.initialize([0, 1, 0, 0], [0, 1]) # |01>
elif state == 2:
qc.initialize([0, 0, 1, 0], [0, 1]) # |10>
elif state == 3:
qc.initialize([0, 0, 0, 1], [0, 1]) # |11>
# Transpile the circuit
transpiled_circuit = transpile(qc, Aer.get_backend('statevector_simulator'))
# Run the transpiled circuit
result = Aer.get_backend('statevector_simulator').run(transpiled_circuit).result()
statevector = result.get_statevector()
return statevector
# Example usage:
qc = QuantumCircuit(2)
state = 3 # Set to the |10> state, for example
result_statevector = set_quantum_state(qc, state)
print("Result state vector:", result_statevector)
from qiskit import Aer, transpile
def printStateVector(circuit):
simulator = Aer.get_backend('statevector_simulator')
# Transpile the circuit
transpiled_circuit = transpile(circuit, simulator)
# Run the transpiled circuit
result = simulator.run(transpiled_circuit).result()
statevector = result.get_statevector()
rounded_statevector = np.round(statevector, decimals=3)
print("Rounded State Vector:", rounded_statevector)
# Exercise 2.2 QCCEA
from qiskit import QuantumCircuit, Aer, execute
from qiskit import QuantumCircuit, Aer, transpile, assemble
for i in range (0,4):
print(f"\nKezdő állapot: {i}")
# Szimulátor definiálása
szimulator = Aer.get_backend('qasm_simulator')
# HXH=Z----------------------------------------------------------------------
circuit = QuantumCircuit(2)
set_quantum_state(circuit,i)
# Hadamard és Pauli-X kapu alkalmazása a qubitre
circuit.h(0)
circuit.x(0)
circuit.h(0)
# Qubit mérése
circuit.measure_all()
# Áramkör futtatása a szimulátoron
feladat = execute(circuit, szimulator, shots=1)
eredmény = feladat.result()
counts = eredmény.get_counts(circuit)
print(f"HXH:{counts}")
#eredmény kiiratása állapotvectorokkal
printStateVector(circuit)
print(circuit)
#--------------------------------------------
circuit = QuantumCircuit(2)
# Pauli-Z kapu alkalmazása a qubitre
set_quantum_state(circuit,i)
circuit.z(0)
# Qubit mérése
circuit.measure_all()
# Áramkör futtatása a szimulátoron
feladat = execute(circuit, szimulator, shots=1)
eredmény = feladat.result()
counts = eredmény.get_counts(circuit)
print(f"Z:{counts}")
#eredmény kiiratása állapotvectorokkal
printStateVector(circuit)
print(circuit)
# HYH=-Y---------------------------------------------------------------------
# Hadamard kapu alkalmazása a qubitre
circuit = QuantumCircuit(2)
set_quantum_state(circuit,i)
circuit.h(0)
circuit.y(0)
circuit.h(0)
# Qubit mérése
circuit.measure_all()
# Áramkör futtatása a szimulátoron
feladat = execute(circuit, szimulator, shots=1)
eredmény = feladat.result()
counts = eredmény.get_counts(circuit)
print(f"HYH:{counts}")
#eredmény kiiratása állapotvectorokkal
printStateVector(circuit)
print(circuit)
#--------------------------------------------
circuit = QuantumCircuit(2)
set_quantum_state(circuit,i)
# Kapuk alkalmazása
circuit.y(0)
# Qubit mérése
circuit.measure_all()
# Áramkör futtatása a szimulátoron
feladat = execute(circuit, szimulator, shots=1)
eredmény = feladat.result()
counts = eredmény.get_counts(circuit)
print(f"-Y:{counts}")
#eredmény kiiratása állapotvectorokkal
printStateVector(circuit)
print(circuit)
# HZH=X---------------------------------------------------------------------
# Kapuk alkalmazása
circuit = QuantumCircuit(2)
set_quantum_state(circuit,i)
circuit.h(0)
circuit.z(0)
circuit.h(0)
# Qubit mérése
circuit.measure_all()
# Áramkör futtatása a szimulátoron
feladat = execute(circuit, szimulator, shots=1)
eredmény = feladat.result()
counts = eredmény.get_counts(circuit)
print(f"HZH:{counts}")
#eredmény kiiratása állapotvectorokkal
printStateVector(circuit)
print(circuit)
#--------------------------------------------
circuit = QuantumCircuit(2)
set_quantum_state(circuit,i)
# HZH=X
circuit.x(0)
# Qubit mérése
circuit.measure_all()
# Áramkör futtatása a szimulátoron
feladat = execute(circuit, szimulator, shots=1)
eredmény = feladat.result()
counts = eredmény.get_counts(circuit)
print(f"X:{counts}")
#eredmény kiiratása állapotvectorokkal
printStateVector(circuit)
print(circuit)
# Exercise 2.1 QCCEA - HH=I
# Kvantumáramkör létrehozása egyetlen qubittel
circuit = QuantumCircuit(2)
set_quantum_state(circuit,2)
circuit.h(0)
circuit.h(0)
# Qubit mérése
circuit.measure_all()
# Áramkör futtatása a szimulátoron
feladat = execute(circuit, simulator, shots=1024)
eredmény = feladat.result()
counts = eredmény.get_counts(circuit)
print(counts)
circuit.i(0)
# Qubit mérése
circuit.measure_all()
feladat = execute(circuit, szimulátor, shots=1024)
eredmény = feladat.result()
counts = eredmény.get_counts(circuit)
print(counts)
# Exercise 2.1 QCCEA HH=I
# Kvantumáramkör létrehozása egyetlen qubittel
circuit = QuantumCircuit(2)
circuit.x(0)
# Qubit mérése
circuit.measure_all()
circuit.swap(1,0)
circuit.measure_all()
# Áramkör futtatása a szimulátoron
feladat = execute(circuit, simulator, shots=1024)
eredmény = feladat.result()
counts = eredmény.get_counts(circuit)
print(counts)
#3 CNOT = SWAP (in this configuration)
circuit.cx(0,1)
circuit.cx(1,0)
circuit.cx(0,1)
# Qubit mérése
circuit.measure_all()
feladat = execute(circuit, szimulátor, shots=1024)
eredmény = feladat.result()
counts = eredmény.get_counts(circuit)
print(counts)
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
# Standard Qiskit könyvtárak importálása
from qiskit import QuantumCircuit, transpile
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Estimator, Session, Options
# IBM Quantum fiókok betöltése
service = QiskitRuntimeService(channel="ibm_quantum")
from qiskit import QuantumCircuit, Aer, transpile, assemble
# Create a quantum register with 3 qubits
qr = QuantumCircuit(3)
# Example circuit using the quantum register
qr.h(0)
qr.cx(0, 1)
qr.cx(1, 2)
print(qr)
qr.i(0)# egy sorba legyenek a h kapuk
qr.h([0, 1, 2])
print(qr)
from qiskit import QuantumCircuit, Aer, execute
# Kvantumáramkör létrehozása megfelelő kvantum bitekkel és segéd bitekkel
n = 4 # A N számhoz szükséges kvantumbitek száma
circuit = QuantumCircuit(n + 1, n)
# Moduláris kitevőkivonatkozás megvalósítása
a = 7 # Válassz egy véletlenszerű 'a' értéket
x = 3 # Válassz egy 'x' értéket
N = 15 # Az faktorizálni kívánt egész szám
for i in range(n):
circuit.h(i) # Hadamard kapuk alkalmazása szuperpozíció létrehozásához
circuit.x(n) # Az segéd qubit beállítása |1>-re
for i in range(2 ** n):
# Valósítsd meg a moduláris kitevőkivonatkozási áramkört itt
binary_x = format(i, f"0{n}b")
for j, bit in enumerate(binary_x):
if bit == '1':
circuit.cx(j, n)
circuit.barrier()
for _ in range(x):
# Valósítsd meg az 'a' moduláris szorzatát
# Például, ha a = 7, ez sorozat lesz kontrollált-nem (CNOT) kapukból
# és kontrollált-fázis kapukból, 'a' értékétől függően
# Ezt a részt az 'a' értékének megfelelően kell megvalósítani
# Ebben az egyszerűsített példában feltételezzük, hogy a = 7, amihez CNOT kapuk sorozata szükséges.
circuit.cx(0, n) # Kontrollált-X kapu
circuit.barrier()
circuit.barrier()
# Visszafejtés 'a^x' része
for j, bit in enumerate(binary_x):
if bit == '1':
circuit.cx(j, n)
circuit.barrier()
# Mérjük meg a kvantumáramkört
circuit.measure(range(n), range(n))
# Szimuláljuk a kvantumáramkört a mérések eredményeinek eléréséhez
szimulátor = Aer.get_backend('qasm_simulator')
feladat = execute(circuit, szimulátor, shots=128)
eredmény = feladat.result()
számok = eredmény.get_counts(circuit)
print(számok)
from qiskit import QuantumCircuit, transpile, assemble, Aer, execute
from qiskit.visualization import plot_histogram
from math import pi
# Qubits számának meghatározása
num_qubits = 3
# Kvantum áramkör létrehozása 'num_qubits' qubittel
iqft_circuit = QuantumCircuit(num_qubits)
# Az inverz QFT alkalmazása a 'num_qubits' qubitekre
for qubit in range(num_qubits):
for j in range(qubit):
iqft_circuit.cp(-pi/float(2**(qubit-j)), j, qubit)
iqft_circuit.h(qubit)
# Mérések hozzáadása az áramkörhöz
iqft_circuit.measure_all()
# Most futtathatod az Inverz QFT áramkört egy szimulátoron vagy egy valós kvantum eszközön
simulator = Aer.get_backend('qasm_simulator')
munka = execute(iqft_circuit, simulator, shots=1024)
eredmeny = munka.result()
szamlalok = eredmeny.get_counts()
# Az eredmények megjelenítése
plot_histogram(szamlalok)
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
# 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")
IBMQ.load_account()
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute, IBMQ
from qiskit.tools.monitor import job_monitor
from qiskit.circuit.library import QFT
import numpy as np
pi = np.pi
# IBMQ.enable_account('ENTER API KEY HERE')
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator')
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circuit = QuantumCircuit(q, c)
circuit.x(q[2])
circuit.x(q[0])
qft_gate = QFT(num_qubits=3, approximation_degree=0, do_swaps=True, inverse=False, insert_barriers=False, name='qft')
circuit.append(qft_gate, q)
circuit.measure(q, c)
circuit.draw(output='mpl', filename='qft1.png')
print(circuit)
job = execute(circuit, backend, shots=1000)
job_monitor(job)
counts = job.result().get_counts()
print("\n QFT Output")
print("-------------")
print(counts)
#Idealis phase estimation
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.visualization import plot_histogram
# Define the number of qubits and the phase estimation precision
n = 3 # number of qubits
precision = 2**n
# Create quantum and classical registers
qreg_upper = QuantumRegister(1, 'q_upper') # Upper qubit
qreg_lower = QuantumRegister(n, 'q_lower') # Lower qubits
creg = ClassicalRegister(n, 'c') # Classical register for measurement outcomes
# Create quantum circuit
circuit = QuantumCircuit(qreg_upper, qreg_lower, creg)
# Initialize the lower qubits with the eigenvector |u
# Note: You need to provide the specific eigenvector |u as initial state
# For simplicity, let's assume |u = |0 for demonstration purposes
circuit.initialize([1] + [0] * (2**n - 1), qreg_lower)
# Apply Hadamard gate to the upper qubit
circuit.h(qreg_upper[0])
# Apply controlled unitary operations based on the phase estimation algorithm
for qubit in range(n):
circuit.cp(2 * 3.141592653589793 / (2**(n - qubit)), qreg_upper[0], qreg_lower[qubit])
# Apply the inverse quantum Fourier transform (IQFT)
circuit.h(qreg_upper[0])
for qubit in range(n):
circuit.cp(-2 * 3.141592653589793 / (2**(qubit + 1)), qreg_upper[0], qreg_lower[qubit])
# Measure the lower qubits
circuit.measure(qreg_lower, creg)
# Simulate the circuit
simulator = Aer.get_backend('qasm_simulator')
job = execute(circuit, simulator, shots=1000)
result = job.result()
print(circuit)
# Display the histogram of measurement outcomes
counts = result.get_counts()
print("\nMeasurement outcomes:")
print("---------------------")
print(counts)
# Plot the histogram
plot_histogram(counts)
#Idealis phase estimation
#CASE 1
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.visualization import plot_histogram
# Define the number of qubits and the phase estimation precision
n = 3 # number of qubits
precision = 2**n
PI = 3.141592653589793
# Create quantum and classical registers
qreg_upper = QuantumRegister(1, 'q_upper') # Upper qubit
qreg_lower = QuantumRegister(n, 'q_lower') # Lower qubits
creg = ClassicalRegister(n, 'c') # Classical register for measurement outcomes
# Create quantum circuit
circuit = QuantumCircuit(qreg_upper, qreg_lower, creg)
# Initialize the lower qubits with the eigenvector |u
# Note: You need to provide the specific eigenvector |u as initial state
# For simplicity, let's assume |u = |0 for demonstration purposes
circuit.initialize([1] + [0] * (2**n - 1), qreg_lower)
# Apply Hadamard gate to the upper qubit
circuit.h(qreg_upper[0])
"""circuit.h(qreg_lower[1])
circuit.h(qreg_lower[2])"""
# Apply controlled unitary operations based on the phase estimation algorithm
for qubit in range(n):
circuit.cp(2 * PI / (2**(n - qubit)), qreg_upper[0], qreg_lower[qubit])
# Apply the inverse quantum Fourier transform (IQFT)
circuit.h(qreg_upper[0])
for qubit in range(n):
circuit.cp(-2 * PI / (2**(qubit + 1)), qreg_upper[0], qreg_lower[qubit])
# Measure the lower qubits
circuit.measure(qreg_lower, creg)
# Simulate the circuit
simulator = Aer.get_backend('qasm_simulator')
job = execute(circuit, simulator, shots=1000)
result = job.result()
print(circuit)
# Display the histogram of measurement outcomes
counts = result.get_counts()
print("\nMeasurement outcomes:")
print("---------------------")
print(counts)
# Plot the histogram
plot_histogram(counts)
#CASE 2
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit.library import QFT
from qiskit.visualization import plot_histogram
import numpy as np
PI = np.pi
n = 4 # number of qubits
#---------INIT----------#
# Create quantum and classical registers
#qreg_upper = QuantumRegister(1, 'q_upper') # Upper qubit
qreg_lower = QuantumRegister(n, 'q_lower') # Lower qubits
creg = ClassicalRegister(n, 'c') # Classical register for measurement outcomes
# Create quantum circuit
#circuit = QuantumCircuit(qreg_upper, qreg_lower, creg)
circuit = QuantumCircuit(qreg_lower, creg)
# Initialize the lower qubits with the eigenvector |u
# Note: You need to provide the specific eigenvector |u as the initial state
# For simplicity, let's assume |u = |0 for demonstration purposes
circuit.initialize([1] + [0] * (2**n - 1), qreg_lower)
#-------------MAKING INPUT----------#
# Apply controlled unitary operations based on the phase estimation algorithm
for qubit in range(n-1):
#circuit.cy(qreg_lower[0], qreg_lower[qubit+1])
#circuit.ch(qreg_lower[0], qreg_lower[qubit+1]) #egyik init
circuit.cp(2 * PI / (2**(n - qubit)), qreg_lower[0], qreg_lower[qubit+1]) #masik init
circuit.h(qreg_lower[0])
"""circuit.h(qreg_lower[1])
circuit.h(qreg_lower[2])"""
#--------------IQFT----------------#
# preparing for IQFT
circuit.x(qreg_lower[2])
circuit.x(qreg_lower[0])
#circuit.x(qreg_lower[4])
# Apply Hadamard gate to the upper qubit
#circuit.h(qreg_lower[0])
# Apply inverse QFT
qft_gate = QFT(num_qubits=n, approximation_degree=0, do_swaps=True, inverse=True, insert_barriers=True, name='qft')
circuit.append(qft_gate, qreg_lower)
"""for qubit in range(n-1):
circuit.cp(-2 * PI / (2**(qubit + 1)), qreg_lower[0], qreg_lower[qubit+1])"""
#----------MEASUREMENT-----------#
circuit.measure(qreg_lower, creg)
# Display the circuit
#circuit.draw(output='mpl', filename='qft1.png')
print(circuit)
# Execute the circuit on the simulator
backend = Aer.get_backend('qasm_simulator')
job = execute(circuit, backend, shots=1000)
# Monitor the job
job_monitor(job)
# Get and display the measurement results
counts = job.result().get_counts()
print("\nIQFT Output")
print("-------------")
print(counts)
plot_histogram(counts)
#CASE 3
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit.library import QFT
from qiskit.visualization import plot_histogram
import numpy as np
PI = np.pi
n = 4 # number of qubits
#---------INIT----------#
# Create quantum and classical registers
#qreg_upper = QuantumRegister(1, 'q_upper') # Upper qubit
qreg_lower = QuantumRegister(n, 'q_lower') # Lower qubits
creg = ClassicalRegister(n, 'c') # Classical register for measurement outcomes
# Create quantum circuit
#circuit = QuantumCircuit(qreg_upper, qreg_lower, creg)
circuit = QuantumCircuit(qreg_lower, creg)
# Initialize the lower qubits with the eigenvector |u
# Note: You need to provide the specific eigenvector |u as the initial state
# For simplicity, let's assume |u = |0 for demonstration purposes
circuit.initialize([1] + [0] * (2**n - 1), qreg_lower)
#-------------MAKING INPUT----------#
# Apply controlled unitary operations based on the phase estimation algorithm
for qubit in range(n-1):
#circuit.cy(qreg_lower[0], qreg_lower[qubit+1])
#circuit.ch(qreg_lower[0], qreg_lower[qubit+1]) #egyik init
circuit.cp(2 * PI / (2**(n - qubit)), qreg_lower[0], qreg_lower[qubit+1]) #masik init
#circuit.h(qreg_lower[0])
"""circuit.h(qreg_lower[1])
circuit.h(qreg_lower[2])"""
#--------------IQFT----------------#
# preparing for IQFT
circuit.x(qreg_lower[2])
circuit.x(qreg_lower[0])
#circuit.x(qreg_lower[4])
# Apply Hadamard gate to the upper qubit
circuit.h(qreg_lower[0])
# Apply inverse QFT
qft_gate = QFT(num_qubits=n, approximation_degree=0, do_swaps=True, inverse=True, insert_barriers=True, name='qft')
circuit.append(qft_gate, qreg_lower)
"""for qubit in range(n-1):
circuit.cp(-2 * PI / (2**(qubit + 1)), qreg_lower[0], qreg_lower[qubit+1])"""
#----------MEASUREMENT-----------#
circuit.measure(qreg_lower, creg)
# Display the circuit
#circuit.draw(output='mpl', filename='qft1.png')
print(circuit)
# Execute the circuit on the simulator
backend = Aer.get_backend('qasm_simulator')
job = execute(circuit, backend, shots=1000)
# Monitor the job
job_monitor(job)
# Get and display the measurement results
counts = job.result().get_counts()
print("\nIQFT Output")
print("-------------")
print(counts)
plot_histogram(counts)
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit.library import QFT
from qiskit.visualization import plot_histogram
import numpy as np
PI = np.pi
n = 4 # number of qubits
from qiskit import IBMQ
#provider = IBMQ.load_account() # Load your IBM Quantum Experience account
# Choose an available backend
#backend = provider.get_backend('your_preferred_backend_name')
#---------INIT----------#
# Create quantum and classical registers
#qreg_upper = QuantumRegister(1, 'q_upper') # Upper qubit
qreg_lower = QuantumRegister(n, 'q_lower') # Lower qubits
creg = ClassicalRegister(n, 'c') # Classical register for measurement outcomes
# Create quantum circuit
#circuit = QuantumCircuit(qreg_upper, qreg_lower, creg)
circuit = QuantumCircuit(qreg_lower, creg)
# Initialize the lower qubits with the eigenvector |u
# Note: You need to provide the specific eigenvector |u as the initial state
# For simplicity, let's assume |u = |0 for demonstration purposes
circuit.initialize([0] * (2**n - 1)+[1], qreg_lower)
#-------------MAKING INPUT----------#
# Apply controlled unitary operations based on the phase estimation algorithm
for qubit in range(n-1):
#circuit.cy(qreg_lower[0], qreg_lower[qubit+1])
#circuit.ch(qreg_lower[0], qreg_lower[qubit+1]) #egyik init
circuit.cp(2 * PI / (2**(n - qubit)), qreg_lower[0], qreg_lower[qubit+1]) #masik init
for qubit in range(n-1):
circuit.h(qreg_lower[qubit+1])
"""circuit.h(qreg_lower[1])
circuit.h(qreg_lower[2])"""
#--------------IQFT----------------#
# preparing for IQFT
circuit.x(qreg_lower[2])
circuit.x(qreg_lower[0])
#circuit.x(qreg_lower[4])
# Apply Hadamard gate to the upper qubit
#circuit.h(qreg_lower[0])
# Apply inverse QFT
qft_gate = QFT(num_qubits=n, approximation_degree=0, do_swaps=True, inverse=True, insert_barriers=True, name='qft')
circuit.append(qft_gate, qreg_lower)
"""for qubit in range(n-1):
circuit.cp(-2 * PI / (2**(qubit + 1)), qreg_lower[0], qreg_lower[qubit+1])"""
#----------MEASUREMENT-----------#
"""for i in range(circuit.num_qubits-1):
circuit.measure(qreg_lower[i], creg[i])"""
circuit.measure(qreg_lower[0], creg[0])
# Display the circuit
#circuit.draw(output='mpl', filename='qft1.png')
print(circuit)
# Execute the circuit on the simulator
backend = Aer.get_backend('qasm_simulator')
job = execute(circuit, backend, shots=1000)
# Monitor the job
job_monitor(job)
# Get and display the measurement results
counts = job.result().get_counts()
print("\nIQFT Output")
print("-------------")
print(counts)
plot_histogram(counts)
# Phase estimator - in the initialized input 1 is in the first or the second half => output: 0 or 1
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit.library import QFT
from qiskit.visualization import plot_histogram
import numpy as np
from qiskit import IBMQ, Aer, transpile, assemble
from qiskit.tools.monitor import job_monitor
from qiskit.visualization import plot_histogram
from qiskit.providers.ibmq import least_busy
PI = np.pi
n = 4 # number of qubits
# Az IBMQ fiókaink betöltése és a legkevésbé leterhelt háttértároló eszköz megszerzése, amelynek (n+1) kubit vagy több van
#IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
"""backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and
not x.configuration().simulator and x.status().operational==True))
print("Legkevésbé leterhelt backend: ", backend)"""
#---------INIT----------#
# Create quantum and classical registers
qreg = QuantumRegister(n, 'q') #qubits
creg = ClassicalRegister(n, 'c') # Classical register for measurement outcomes
# Create quantum circuit
#circuit = QuantumCircuit(qreg_upper, qreg_lower, creg)
circuit = QuantumCircuit(qreg, creg)
# Initialize the lower qubits with the eigenvector |u
# Note: You need to provide the specific eigenvector |u as the initial state
# For simplicity, let's assume |u = |0 for demonstration purposes
#circuit.initialize([1 + [0] * (2**n - 1), qreg)
#circuit.initialize([0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0], qreg)
circuit.initialize([1,0], qreg[n-1])
for qubit in range(n-1):
circuit.h(qreg[qubit])
#-------------MAKING INPUT----------#
# Apply controlled unitary operations based on the phase estimation algorithm
for qubit in range(n-1):
circuit.cx(qreg[n-qubit-2],qreg[n-1])
#--------------IQFT----------------#
# Apply Hadamard gate to the upper qubit
#circuit.h(qreg[0])
# Apply inverse QFT
circuit.append(QFT(num_qubits=n, inverse=True), qreg)
#----------MEASUREMENT-----------#
#circuit.measure(qreg[0], creg[0])
for i in range(circuit.num_qubits-1):
circuit.measure(qreg[i], creg[i])
# Display the circuit
#circuit.draw(output='mpl', filename='qft1.png')
print(circuit)
# Execute the circuit on the simulator
backend = Aer.get_backend('qasm_simulator')
job = execute(circuit, backend, shots=1000)
"""
# futtatas kv.szamitogepen
transpiled_circuit = transpile(circuit, backend, optimization_level=3)
job = backend.run(transpiled_circuit)"""
# Monitor the job
job_monitor(job, interval=2)
# Get and display the measurement results
counts = job.result().get_counts()
print("\nIQFT Output")
print("-------------")
print(counts)
plot_histogram(counts)
# Phase estimator - in the initialized input 1 is in the first or the second half => output: 0 or 1
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit.library import QFT
from qiskit.visualization import plot_histogram
import numpy as np
from qiskit import IBMQ, Aer, transpile, assemble
from qiskit.tools.monitor import job_monitor
from qiskit.visualization import plot_histogram
from qiskit.providers.ibmq import least_busy
PI = np.pi
t=1
n=4
# Create quantum registers
upper_register = QuantumRegister(n, 'upper')
bottom_register = QuantumRegister(t, 'bottom')
classical_reg = ClassicalRegister(n, 'creg')
# Construct quantum circuit
qc = QuantumCircuit(upper_register, bottom_register, classical_reg)
#qc.initialize([1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], upper_register) #alapbol 0-ra van inicializalva
qc.initialize([1,0], bottom_register)
# Apply Hadamard gates on upper register
qc.h(upper_register)
for qubit in range(n-1):
qc.cx(upper_register[n-qubit-2],bottom_register)
#qc.cx(upper_register,bottom_register)
# Apply Inverse Quantum Fourier Transform (IQFT)
qc.append(QFT(n, inverse=True), upper_register)
# Measure upper register
qc.measure(upper_register, classical_reg)
print(qc)
# Execute the circuit on a simulator
simulator = Aer.get_backend('qasm_simulator')
job = execute(qc, simulator, shots=1024)
result = job.result()
# Get the counts
counts = result.get_counts(qc)
# Visualize the counts
plot_histogram(counts)
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, Aer, transpile
from qiskit.providers.ibmq import least_busy, IBMQ
from qiskit.tools.monitor import job_monitor
from qiskit.visualization import plot_histogram
# Load IBM Quantum Experience account
IBMQ.load_account()
# Define your quantum and classical registers
n = 4
t = 1
upper_register = QuantumRegister(n, 'upper')
bottom_register = QuantumRegister(t, 'bottom')
classical_reg = ClassicalRegister(n, 'creg')
# Construct quantum circuit
qc = QuantumCircuit(upper_register, bottom_register, classical_reg)
# Initialize the bottom register
qc.initialize([1, 0], bottom_register)
# Apply Hadamard gates on upper register
qc.h(upper_register)
# Apply controlled-NOT gates
for qubit in range(n - 1):
qc.cx(upper_register[n - qubit - 2], bottom_register)
# Apply Inverse Quantum Fourier Transform (IQFT)
qc.append(QFT(n, inverse=True), upper_register)
# Measure the upper register
qc.measure(upper_register, classical_reg)
# Choose an IBM Quantum device to run the circuit
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))
# Transpile the circuit for the selected backend
qc_transpiled = transpile(qc, backend)
# Execute the circuit on the selected backend
job = backend.run(qc_transpiled)
# Monitor the job
job_monitor(job)
# Get the results
result = job.result()
# Get the counts
counts = result.get_counts(qc)
# Visualize the counts
plot_histogram(counts)
#Deutsch–Jozsa circuit as a simple phase estimator
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit.library import QFT
from qiskit.visualization import plot_histogram
import numpy as np
from qiskit import IBMQ, Aer, transpile, assemble
from qiskit.tools.monitor import job_monitor
from qiskit.visualization import plot_histogram
from qiskit.providers.ibmq import least_busy
PI = np.pi
n = 2 # number of qubits
# Az IBMQ fiókaink betöltése és a legkevésbé leterhelt háttértároló eszköz megszerzése, amelynek (n+1) kubit vagy több van
#IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
"""backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and
not x.configuration().simulator and x.status().operational==True))
print("Legkevésbé leterhelt backend: ", backend)"""
#---------INIT----------#
# Create quantum and classical registers
qreg = QuantumRegister(n, 'q') #qubits
creg = ClassicalRegister(n, 'c') # Classical register for measurement outcomes
# Create quantum circuit
circuit = QuantumCircuit(qreg, creg)
initial_state = [0, 1, 0, 0] # Amplitudes for |00⟩, |01⟩, |10⟩, |11⟩
circuit.initialize(initial_state, qreg)
for qubit in range(n):
circuit.h(qreg[qubit])
circuit.cx(qreg[0],qreg[1])
circuit.h(qreg[0])
#----------MEASUREMENT-----------#
circuit.measure(qreg[0], creg[0])
# Display the circuit
print(circuit)
# Execute the circuit on the simulator
backend = Aer.get_backend('qasm_simulator')
job = execute(circuit, backend, shots=1000)
"""
# futtatas kv.szamitogepen
transpiled_circuit = transpile(circuit, backend, optimization_level=3)
job = backend.run(transpiled_circuit)"""
# Monitor the job
job_monitor(job, interval=2)
# Get and display the measurement results
counts = job.result().get_counts()
print("\nIQFT Output")
print("-------------")
print(counts)
plot_histogram(counts)
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
# 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")
IBMQ.load_account()
# Invoke a primitive. For more details see https://docs.quantum.ibm.com/run/primitives
# result = Sampler().run(circuits).result()
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute, IBMQ
from qiskit.tools.monitor import job_monitor
from qiskit.circuit.library import QFT
import numpy as np
pi = np.pi
# IBMQ.enable_account('ENTER API KEY HERE')
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator')
q = QuantumRegister(5, 'q')
c = ClassicalRegister(5, 'c')
circuit = QuantumCircuit(q, c)
circuit.x(q[4])
circuit.x(q[2])
circuit.x(q[0])
qft_gate = QFT(num_qubits=5, approximation_degree=0, do_swaps=True, inverse=False, insert_barriers=False, name='qft')
circuit.append(qft_gate, q)
circuit.measure(q, c)
circuit.draw(output='mpl', filename='qft1.png')
print(circuit)
job = execute(circuit, backend, shots=1000)
job_monitor(job)
counts = job.result().get_counts()
print("\n QFT Output")
print("-------------")
print(counts)
q = QuantumRegister(5,'q')
c = ClassicalRegister(5,'c')
circuit = QuantumCircuit(q,c)
circuit.x(q[4])
circuit.x(q[2])
circuit.x(q[0])
qft_gate2 = QFT(num_qubits=5, approximation_degree=0, do_swaps=True, inverse=False, insert_barriers=True, name='qft')
qft_gate3 = QFT(num_qubits=5, approximation_degree=0, do_swaps=True, inverse=True, insert_barriers=True, name='qft')
circuit.append(qft_gate2, q)
circuit.append(qft_gate3, q)
circuit.measure(q,c)
circuit.draw(output='mpl',filename='qft2.png')
print(circuit)
job = execute(circuit, backend, shots=1000)
job_monitor(job)
counts = job.result().get_counts()
print("\n QFT with inverse QFT Output")
print("------------------------------")
print(counts)
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
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/Harcipan/QAI_GroverSim
|
Harcipan
|
# initialization
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, transpile
# import basic plot tools
from qiskit.visualization import plot_histogram
# set the length of the n-bit input string.
n = 3
# set the length of the n-bit input string.
n = 3
const_oracle = QuantumCircuit(n+1)
output = np.random.randint(2)
if output == 1:
const_oracle.x(n)
const_oracle.draw()
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
balanced_oracle.draw()
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
balanced_oracle.draw()
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Show oracle
balanced_oracle.draw()
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
dj_circuit.draw()
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit = dj_circuit.compose(balanced_oracle)
dj_circuit.draw()
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit = dj_circuit.compose(balanced_oracle)
# Repeat H-gates
for qubit in range(n):
dj_circuit.h(qubit)
dj_circuit.barrier()
# Measure
for i in range(n):
dj_circuit.measure(i, i)
# Display circuit
dj_circuit.draw()
# use local simulator
aer_sim = Aer.get_backend('aer_simulator')
results = aer_sim.run(dj_circuit).result()
answer = results.get_counts()
plot_histogram(answer)
# ...we have a 0% chance of measuring 000.
assert answer.get('000', 0) == 0
def dj_oracle(case, n):
# We need to make a QuantumCircuit object to return
# This circuit has n+1 qubits: the size of the input,
# plus one output qubit
oracle_qc = QuantumCircuit(n+1)
# First, let's deal with the case in which oracle is balanced
if case == "balanced":
# First generate a random number that tells us which CNOTs to
# wrap in X-gates:
b = np.random.randint(1,2**n)
# Next, format 'b' as a binary string of length 'n', padded with zeros:
b_str = format(b, '0'+str(n)+'b')
# Next, we place the first X-gates. Each digit in our binary string
# corresponds to a qubit, if the digit is 0, we do nothing, if it's 1
# we apply an X-gate to that qubit:
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Do the controlled-NOT gates for each qubit, using the output qubit
# as the target:
for qubit in range(n):
oracle_qc.cx(qubit, n)
# Next, place the final X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Case in which oracle is constant
if case == "constant":
# First decide what the fixed output of the oracle will be
# (either always 0 or always 1)
output = np.random.randint(2)
if output == 1:
oracle_qc.x(n)
oracle_gate = oracle_qc.to_gate()
oracle_gate.name = "Oracle" # To show when we display the circuit
return oracle_gate
def dj_algorithm(oracle, n):
dj_circuit = QuantumCircuit(n+1, n)
# Set up the output qubit:
dj_circuit.x(n)
dj_circuit.h(n)
# And set up the input register:
for qubit in range(n):
dj_circuit.h(qubit)
# Let's append the oracle gate to our circuit:
dj_circuit.append(oracle, range(n+1))
# Finally, perform the H-gates again and measure:
for qubit in range(n):
dj_circuit.h(qubit)
for i in range(n):
dj_circuit.measure(i, i)
return dj_circuit
n = 4
oracle_gate = dj_oracle('balanced', n)
dj_circuit = dj_algorithm(oracle_gate, n)
dj_circuit.draw()
transpiled_dj_circuit = transpile(dj_circuit, aer_sim)
results = aer_sim.run(transpiled_dj_circuit).result()
answer = results.get_counts()
plot_histogram(answer)
# Load our saved IBMQ accounts and get the least busy backend device with greater than or equal to (n+1) qubits
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
transpiled_dj_circuit = transpile(dj_circuit, backend, optimization_level=3)
job = backend.run(transpiled_dj_circuit)
job_monitor(job, interval=2)
# Get the results of the computation
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
# ...the most likely result is 1111.
assert max(answer, key=answer.get) == '1111'
from qiskit_textbook.problems import dj_problem_oracle
oracle = dj_problem_oracle(1)
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ, execute
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector, plot_histogram
class DeutschJozsa:
'''
Class to generate a DeutschJozsa object containing:
- init functions
- oracle function
- dj function
'''
def __init__(self, case, input_str):
'''
Initialization of the object:
@case: (str) type of oracle balanced or constant
@input_str: (str) string input state values
'''
self.case = case
self.number_qubit = len(input_str)
self.str_input = input_str
def oracle(self):
'''
Will create the oracle needed for the Deutsch-Jozsa algorithm
No input, the function will be used in the dj function
@return the oracle in form of a gate
'''
# Create the QuantumCircuit with n+1 qubits
self.oracle_circuit = QuantumCircuit(self.number_qubit+1)
# Balanced case
if self.case == "balanced":
# apply an X-gate to a qubit when its value is 1
for qubit in range(len(self.str_input)):
if self.str_input[qubit] == '1':
self.oracle_circuit.x(qubit)
# Apply CNOT gates on each qubit
for qubit in range(self.number_qubit):
self.oracle_circuit.cx(qubit, self.number_qubit)
# apply another set of X gates when the input qubit == 1
for qubit in range(len(self.str_input)):
if self.str_input[qubit] == '1':
self.oracle_circuit.x(qubit)
# Constant case
if self.case == "constant":
# Output 0 for a constant oracle
self.output = np.random.randint(2)
if self.output == 1:
self.oracle_circuit.x(self.number_qubit)
# convert the quantum circuit into a gate
self.oracle_gate = self.oracle_circuit.to_gate()
# name of the oracle
self.oracle_gate.name = "Oracle"
return self.oracle_gate
def dj(self):
'''
Create the Deutsch-Jozsa algorithm in the general case with n qubit
No input
@return the quantum circuit of the DJ
'''
self.dj_circuit = QuantumCircuit(self.number_qubit+1, self.number_qubit)
# Set up the output qubit:
self.dj_circuit.x(self.number_qubit)
self.dj_circuit.h(self.number_qubit)
# Psi_0
for qubit in range(self.number_qubit):
self.dj_circuit.h(qubit)
# Psi_1 + oracle
self.dj_circuit.append(self.oracle(), range(self.number_qubit+1))
# Psi_2
for qubit in range(self.number_qubit):
self.dj_circuit.h(qubit)
# Psi_3
# Let's put some measurement
for i in range(self.number_qubit):
self.dj_circuit.measure(i, i)
return self.dj_circuit
test = DeutschJozsa('constant', '0110')
#circuit = test.oracle()
dj_circuit = test.dj()
dj_circuit.draw('mpl')
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_dj_circuit = transpile(dj_circuit, qasm_sim)
qobj = assemble(transpiled_dj_circuit)
results = qasm_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
from qiskit import IBMQ
#TOKEN = 'paste your token here'
#IBMQ.save_account(TOKEN)
IBMQ.load_account() # Load account from disk
IBMQ.providers()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
provider.backends(filters=lambda x: x.configuration().n_qubits >= 5
and not x.configuration().simulator
and x.status().operational==True)
backend = provider.get_backend('ibmq_manila')
backend
mapped_circuit = transpile(dj_circuit, backend=backend)
qobj = assemble(mapped_circuit, backend=backend, shots=1024)
job = backend.run(qobj)
job.status() # 9:17 pm
result = job.result()
counts = result.get_counts()
print(counts)
plot_histogram(counts)
plot_histogram(counts,figsize=(10,8), filename='DJ.jpeg')
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
# Alap Qiskit könyvtárak
from qiskit import QuantumCircuit, transpile
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Estimator, Session, Options
# IBM Quantum account betöltése
service = QiskitRuntimeService(channel="ibm_quantum")
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute
from qiskit.circuit import ControlledGate
# Tegyük fel, hogy n a qubitek száma
n = 3
# Hozzunk létre egy kvantum regisztert n qubittal a függvényhez és 1 qubittal a CNOT céljához
qr = QuantumRegister(n + 1)
# Hozzunk létre egy klasszikus regisztert a méréshez
cr = ClassicalRegister(n + 1)
circuit = QuantumCircuit(qr, cr)
# Az f függvény implementálása: Bitenkénti NOT művelet minden egyes első n qubit esetén (csak próbaként)
for qubit in range(n):
circuit.x(qr[qubit])
# Alkalmazzunk CNOT-t az n-edik qubit vezérlésével és az (n+1)-edik qubit célpontjával
circuit.cnot(qr[n-1], qr[n])
# Mérjük meg a qubiteket
circuit.measure(qr, cr)
print(circuit)
# szimuláció
simulator = Aer.get_backend('qasm_simulator')
job = execute(circuit, simulator, shots=1024)
result = job.result()
counts = result.get_counts(circuit)
print(counts)
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
# 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/Harcipan/QAI_GroverSim
|
Harcipan
|
# 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://docs.quantum-computing.ibm.com/run/primitives
# result = Sampler().run(circuits).result()
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, Aer, transpile, assemble
# considering our bit string to be ‘101’
b = '101'
n = len(b)
# creating two quantum registers of ’n’ qubits and 1 classical register of ’n’ qubits
q_reg1 = QuantumRegister(n, 'reg1')
q_reg2 = QuantumRegister(n, 'reg2')
c_reg = ClassicalRegister(n)
circuit = QuantumCircuit(q_reg1, q_reg2, c_reg)
# applying H-gate on qubits of the first register
circuit.h(q_reg1)
circuit.barrier()
# copying the data of the first register to the second register
circuit.cx(q_reg1, q_reg2)
circuit.barrier()
# applying bit-wise X-OR from register 1 to register 2 where qubits of the first register are 1
circuit.cx(q_reg1[0], q_reg2[0])
circuit.cx(q_reg1[0], q_reg2[2])
circuit.barrier()
# measuring qubits of the second register
circuit.measure(q_reg2, c_reg)
# applying H-gate to qubits of the first register
circuit.h(q_reg1)
circuit.barrier()
# measuring qubits of the first register
circuit.measure(q_reg1, c_reg)
circuit.draw()
# running the circuit using "qasm simulator"
qasm_sim = Aer.get_backend("qasm_simulator")
job = assemble(circuit,qasm_sim)
result = qasm_sim.run(job).result()
counts = result.get_counts()
plot_histogram(counts)
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import Kraus, SuperOp
from qiskit.visualization import plot_histogram
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit_aer import AerSimulator
# Import from Qiskit Aer noise module
from qiskit_aer.noise import (
NoiseModel,
QuantumError,
ReadoutError,
depolarizing_error,
pauli_error,
thermal_relaxation_error,
)
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
backend = service.backend("ibm_brisbane")
noise_model = NoiseModel.from_backend(backend)
# Construct a 1-qubit bit-flip and phase-flip errors
p_error = 0.05
bit_flip = pauli_error([('X', p_error), ('I', 1 - p_error)])
phase_flip = pauli_error([('Z', p_error), ('I', 1 - p_error)])
print(bit_flip)
print(phase_flip)
# Compose two bit-flip and phase-flip errors
bitphase_flip = bit_flip.compose(phase_flip)
print(bitphase_flip)
# Tensor product two bit-flip and phase-flip errors with
# bit-flip on qubit-0, phase-flip on qubit-1
error2 = phase_flip.tensor(bit_flip)
print(error2)
# Convert to Kraus operator
bit_flip_kraus = Kraus(bit_flip)
print(bit_flip_kraus)
# Convert to Superoperator
phase_flip_sop = SuperOp(phase_flip)
print(phase_flip_sop)
# Convert back to a quantum error
print(QuantumError(bit_flip_kraus))
# Check conversion is equivalent to original error
QuantumError(bit_flip_kraus) == bit_flip
# Measurement misassignment probabilities
p0given1 = 0.1
p1given0 = 0.05
ReadoutError([[1 - p1given0, p1given0], [p0given1, 1 - p0given1]])
# Create an empty noise model
noise_model = NoiseModel()
# Add depolarizing error to all single qubit u1, u2, u3 gates
error = depolarizing_error(0.05, 1)
noise_model.add_all_qubit_quantum_error(error, ['u1', 'u2', 'u3'])
# Print noise model info
print(noise_model)
# Create an empty noise model
noise_model = NoiseModel()
# Add depolarizing error to all single qubit u1, u2, u3 gates on qubit 0 only
error = depolarizing_error(0.05, 1)
noise_model.add_quantum_error(error, ['u1', 'u2', 'u3'], [0])
# Print noise model info
print(noise_model)
# System Specification
n_qubits = 4
circ = QuantumCircuit(n_qubits)
# Test Circuit
circ.h(0)
for qubit in range(n_qubits - 1):
circ.cx(qubit, qubit + 1)
circ.measure_all()
print(circ)
# Ideal simulator and execution
sim_ideal = AerSimulator()
result_ideal = sim_ideal.run(circ).result()
plot_histogram(result_ideal.get_counts(0))
# Example error probabilities
p_reset = 0.03
p_meas = 0.1
p_gate1 = 0.05
# QuantumError objects
error_reset = pauli_error([('X', p_reset), ('I', 1 - p_reset)])
error_meas = pauli_error([('X',p_meas), ('I', 1 - p_meas)])
error_gate1 = pauli_error([('X',p_gate1), ('I', 1 - p_gate1)])
error_gate2 = error_gate1.tensor(error_gate1)
# Add errors to noise model
noise_bit_flip = NoiseModel()
noise_bit_flip.add_all_qubit_quantum_error(error_reset, "reset")
noise_bit_flip.add_all_qubit_quantum_error(error_meas, "measure")
noise_bit_flip.add_all_qubit_quantum_error(error_gate1, ["u1", "u2", "u3"])
noise_bit_flip.add_all_qubit_quantum_error(error_gate2, ["cx"])
print(noise_bit_flip)
# Create noisy simulator backend
sim_noise = AerSimulator(noise_model=noise_bit_flip)
# Transpile circuit for noisy basis gates
passmanager = generate_preset_pass_manager(optimization_level=3, backend=sim_noise)
circ_tnoise = passmanager.run(circ)
# Run and get counts
result_bit_flip = sim_noise.run(circ_tnoise).result()
counts_bit_flip = result_bit_flip.get_counts(0)
# Plot noisy output
plot_histogram(counts_bit_flip)
# T1 and T2 values for qubits 0-3
T1s = np.random.normal(50e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec
T2s = np.random.normal(70e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec
# Truncate random T2s <= T1s
T2s = np.array([min(T2s[j], 2 * T1s[j]) for j in range(4)])
# Instruction times (in nanoseconds)
time_u1 = 0 # virtual gate
time_u2 = 50 # (single X90 pulse)
time_u3 = 100 # (two X90 pulses)
time_cx = 300
time_reset = 1000 # 1 microsecond
time_measure = 1000 # 1 microsecond
# QuantumError objects
errors_reset = [thermal_relaxation_error(t1, t2, time_reset)
for t1, t2 in zip(T1s, T2s)]
errors_measure = [thermal_relaxation_error(t1, t2, time_measure)
for t1, t2 in zip(T1s, T2s)]
errors_u1 = [thermal_relaxation_error(t1, t2, time_u1)
for t1, t2 in zip(T1s, T2s)]
errors_u2 = [thermal_relaxation_error(t1, t2, time_u2)
for t1, t2 in zip(T1s, T2s)]
errors_u3 = [thermal_relaxation_error(t1, t2, time_u3)
for t1, t2 in zip(T1s, T2s)]
errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand(
thermal_relaxation_error(t1b, t2b, time_cx))
for t1a, t2a in zip(T1s, T2s)]
for t1b, t2b in zip(T1s, T2s)]
# Add errors to noise model
noise_thermal = NoiseModel()
for j in range(4):
noise_thermal.add_quantum_error(errors_reset[j], "reset", [j])
noise_thermal.add_quantum_error(errors_measure[j], "measure", [j])
noise_thermal.add_quantum_error(errors_u1[j], "u1", [j])
noise_thermal.add_quantum_error(errors_u2[j], "u2", [j])
noise_thermal.add_quantum_error(errors_u3[j], "u3", [j])
for k in range(4):
noise_thermal.add_quantum_error(errors_cx[j][k], "cx", [j, k])
print(noise_thermal)
# Run the noisy simulation
sim_thermal = AerSimulator(noise_model=noise_thermal)
# Transpile circuit for noisy basis gates
passmanager = generate_preset_pass_manager(optimization_level=3, backend=sim_thermal)
circ_tthermal = passmanager.run(circ)
# Run and get counts
result_thermal = sim_thermal.run(circ_tthermal).result()
counts_thermal = result_thermal.get_counts(0)
# Plot noisy output
plot_histogram(counts_thermal)
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
from qiskit import transpile, QuantumCircuit
import qiskit.quantum_info as qi
from qiskit_aer import AerSimulator
from qiskit_aer.noise import NoiseModel, amplitude_damping_error
from qiskit.visualization import plot_histogram
# CNOT matrix operator with qubit-0 as control and qubit-1 as target
g_op = qi.Operator([[-1/2, 1/2, -1/2, 1/2],
[1/2, -1/2, -1/2, 1/2],
[1/2,1/2,1/2, 1/2],
[1/2, 1/2, -1/2, -1/2]])
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute, IBMQ
from qiskit.tools.monitor import job_monitor
from qiskit.circuit.library import QFT
import numpy as np
pi = np.pi
# IBMQ.enable_account('ENTER API KEY HERE')
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator')
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circuit = QuantumCircuit(q, c)
circuit.h(q[2])
circuit.h(q[1])
circuit.h(q[0])
qft_gate = QFT(num_qubits=3, approximation_degree=0, do_swaps=True, inverse=False, insert_barriers=False, name='qft')
circuit.append(qft_gate, q)
circuit.measure(q, c)
circuit.draw(output='mpl', filename='qft1.png')
print(circuit)
job = execute(circuit, backend, shots=1000)
job_monitor(job)
counts = job.result().get_counts()
print("\n QFT Output")
print("-------------")
print(counts)
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.visualization import plot_histogram
from math import pi
from qiskit.circuit.library import QFT
# Example usage
N = 15
t=4 # log_2(N) upper limit
n=t
# Create quantum registers
upper_register = QuantumRegister(n, 'upper')
bottom_register = QuantumRegister(t, 'bottom')
ancilla = QuantumRegister(1, 'ancilla')
classical_reg = ClassicalRegister(n, 'creg')
# Construct quantum circuit
qc = QuantumCircuit(upper_register, bottom_register, ancilla, classical_reg)
# Apply Hadamard gates on upper register
qc.h(upper_register)
qc.unitary(g_op, [0, 8], label='grover_op')
# Apply Inverse Quantum Fourier Transform (IQFT)
qc.append(QFT(n, inverse=True), upper_register)
# Measure upper register
qc.measure(upper_register, classical_reg)
print(qc)
sim_ideal = AerSimulator()
tbell_circ = transpile(qc, sim_ideal)
ideal_result = sim_ideal.run(tbell_circ).result()
ideal_counts = ideal_result.get_counts(0)
plot_histogram(ideal_counts,
title='Ideal output for gOp')
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile
from qiskit_ibm_provider import IBMProvider
import qiskit_ibm_provider.jupyter
#provider = IBMProvider('ibm-q')
#backend = provider.get_backend('ibmq_vigo')
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')
from qiskit.circuit import QuantumCircuit, Gate, Instruction
from qiskit.circuit.library.standard_gates import ZGate
def MCMT(gate, num_controls, num_targets):
"""Construct a multi-controlled multi-target gate.
Args:
gate (Gate): The gate to apply to the target qubits.
num_controls (int): The number of control qubits.
num_targets (int): The number of target qubits.
Returns:
Instruction: The multi-controlled multi-target gate as a Qiskit Instruction.
"""
mcmt_gate = QuantumCircuit(num_controls + num_targets)
mcmt_gate.append(gate.control(num_controls), list(range(num_controls + num_targets)))
return mcmt_gate.to_instruction()
def grover_oracle(marked_states):
"""Build a Grover oracle for multiple marked states
Here we assume all input marked states have the same number of bits
Parameters:
marked_states (str or list): Marked states of oracle
Returns:
QuantumCircuit: Quantum circuit representing Grover oracle
"""
if not isinstance(marked_states, list):
marked_states = [marked_states]
# Compute the number of qubits in circuit
num_qubits = len(marked_states[0])
qc = QuantumCircuit(num_qubits)
# Mark each target state in the input list
for target in marked_states:
# Flip target bit-string to match Qiskit bit-ordering
rev_target = target[::-1]
# Find the indices of all the '0' elements in bit-string
zero_inds = [ind for ind in range(num_qubits) if rev_target.startswith("0", ind)]
# Add a multi-controlled Z-gate with pre- and post-applied X-gates (open-controls)
# where the target bit-string has a '0' entry
qc.x(zero_inds)
qc.rx(0.1,zero_inds)
qc.compose(MCMT(ZGate(), num_qubits - 1, 1), inplace=True)
qc.x(zero_inds)
return qc
marked_states = ["011", "100"]
oracle = grover_oracle(marked_states)
oracle.draw("mpl")
grover_op = GroverOperator(oracle)
grover_op.decompose().draw("mpl")
optimal_num_iterations = math.floor(
math.pi / 4 * math.sqrt(2**grover_op.num_qubits / len(marked_states))
)
qc = QuantumCircuit(grover_op.num_qubits)
# Create even superposition of all basis states
qc.h(range(grover_op.num_qubits))
# Apply Grover operator the optimal number of times
qc.compose(grover_op.power(optimal_num_iterations), inplace=True)
# Measure all qubits
qc.measure_all()
qc.draw("mpl")
# Select the simulator with the fewest number of jobs in the queue
backend_simulator = service.least_busy(simulator=True, operational=True)
backend_simulator.name
# Initialize your session
sim_session = Session(backend=backend_simulator)
sim_sampler = Sampler(session=sim_session)
sim_dist = sim_sampler.run(qc, shots=int(1e4)).result().quasi_dists[0]
plot_distribution(sim_dist.binary_probabilities())
sim_session.close()
# Select the backend with the fewest number of jobs in the queue
backend = service.least_busy(simulator=False, operational=True)
backend.name
# Initialize your session
session = Session(backend=backend)
real_sampler = Sampler(session=session)
real_dist = real_sampler.run(qc, shots=int(1e4)).result().quasi_dists[0]
plot_distribution(real_dist.binary_probabilities())
# Close session
session.close()
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
# 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, Batch
# To run on hardware, select the backend with the fewest number of jobs in the queue
service = QiskitRuntimeService(channel="ibm_quantum")
backend = service.least_busy(operational=True, simulator=False)
backend.name
def grover_oracle(marked_states):
"""Build a Grover oracle for multiple marked states
Here we assume all input marked states have the same number of bits
Parameters:
marked_states (str or list): Marked states of oracle
Returns:
QuantumCircuit: Quantum circuit representing Grover oracle
"""
if not isinstance(marked_states, list):
marked_states = [marked_states]
# Compute the number of qubits in circuit
num_qubits = len(marked_states[0])
qc = QuantumCircuit(num_qubits)
# Mark each target state in the input list
for target in marked_states:
# Flip target bit-string to match Qiskit bit-ordering
rev_target = target[::-1]
# Find the indices of all the '0' elements in bit-string
zero_inds = [ind for ind in range(num_qubits) if rev_target.startswith("0", ind)]
# Add a multi-controlled Z-gate with pre- and post-applied X-gates (open-controls)
# where the target bit-string has a '0' entry
qc.x(zero_inds)
qc.compose(MCMT(ZGate(), num_qubits - 1, 1), inplace=True)
qc.x(zero_inds)
return qc
marked_states = ["011", "100"]
oracle = grover_oracle(marked_states)
oracle.draw(output="mpl", style="iqp")
grover_op = GroverOperator(oracle)
grover_op.decompose().draw(output="mpl", style="iqp")
optimal_num_iterations = math.floor(
math.pi / (4 * math.asin(math.sqrt(len(marked_states) / 2**grover_op.num_qubits)))
)
qc = QuantumCircuit(grover_op.num_qubits)
# Create even superposition of all basis states
qc.h(range(grover_op.num_qubits))
# Apply Grover operator the optimal number of times
qc.compose(grover_op.power(optimal_num_iterations), inplace=True)
# Measure all qubits
qc.measure_all()
qc.draw(output="mpl", style="iqp")
# To run on local simulator:
# 1. Use the Sampler from qiskit.primitives instead
# 2. Remove the Batch context manager below
with Batch(backend=backend) as batch:
sampler = Sampler()
dist = sampler.run(qc, shots=10000).result().quasi_dists[0]
plot_distribution(dist.binary_probabilities())
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
# 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, Batch
# To run on hardware, select the backend with the fewest number of jobs in the queue
service = QiskitRuntimeService(channel="ibm_quantum")
backend = service.least_busy(operational=True, simulator=False)
backend.name
def grover_oracle(marked_states):
"""Build a Grover oracle for multiple marked states
Here we assume all input marked states have the same number of bits
Parameters:
marked_states (str or list): Marked states of oracle
Returns:
QuantumCircuit: Quantum circuit representing Grover oracle
"""
if not isinstance(marked_states, list):
marked_states = [marked_states]
# Compute the number of qubits in circuit
num_qubits = len(marked_states[0])
qc = QuantumCircuit(num_qubits)
# Mark each target state in the input list
for target in marked_states:
# Flip target bit-string to match Qiskit bit-ordering
rev_target = target[::-1]
# Find the indices of all the '0' elements in bit-string
zero_inds = [ind for ind in range(num_qubits) if rev_target.startswith("0", ind)]
# Add a multi-controlled Z-gate with pre- and post-applied X-gates (open-controls)
# where the target bit-string has a '0' entry
qc.x(zero_inds)
qc.compose(MCMT(ZGate(), num_qubits - 1, 1), inplace=True)
qc.x(zero_inds)
return qc
marked_states = ["011", "100"]
oracle = grover_oracle(marked_states)
oracle.draw(output="mpl", style="iqp")
grover_op = GroverOperator(oracle)
grover_op.decompose().draw(output="mpl", style="iqp")
optimal_num_iterations = math.floor(
math.pi / (4 * math.asin(math.sqrt(len(marked_states) / 2**grover_op.num_qubits)))
)
qc = QuantumCircuit(grover_op.num_qubits)
# Create even superposition of all basis states
qc.h(range(grover_op.num_qubits))
# Apply Grover operator the optimal number of times
qc.compose(grover_op.power(optimal_num_iterations), inplace=True)
# Measure all qubits
qc.measure_all()
qc.draw(output="mpl", style="iqp")
# To run on local simulator:
# 1. Use the Sampler from qiskit.primitives instead
# 2. Remove the Batch context manager below
with Batch(backend=backend) as batch:
sampler = Sampler()
dist = sampler.run(qc, shots=10000).result().quasi_dists[0]
plot_distribution(dist.binary_probabilities())
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
import qiskit
qiskit.version.get_version_info()
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
from qiskit import transpile, QuantumCircuit
import qiskit.quantum_info as qi
from qiskit_aer import AerSimulator
from qiskit_aer.noise import NoiseModel, amplitude_damping_error
from qiskit.visualization import plot_histogram
# CNOT matrix operator with qubit-0 as control and qubit-1 as target
cx_op = qi.Operator([[1, 0, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 0],
[0, 1, 0, 0]])
# iSWAP matrix operator
iswap_op = qi.Operator([[1, 0, 0, 0],
[0, 0, 1j, 0],
[0, 1j, 0, 0],
[0, 0, 0, 1]])
# CNOT in terms of iSWAP and single-qubit gates
cx_circ = QuantumCircuit(2, name='cx<iSWAP>')
# Add gates
cx_circ.sdg(1)
cx_circ.h(1)
cx_circ.sdg(0)
cx_circ.unitary(iswap_op, [0, 1], label='iswap')
cx_circ.sdg(0)
cx_circ.h(0)
cx_circ.sdg(0)
cx_circ.unitary(iswap_op, [0, 1], label='iswap')
cx_circ.s(1)
print(cx_circ)
# Simulate the unitary for the circuit using Operator:
unitary = qi.Operator(cx_circ)
print(unitary)
'unitary' in AerSimulator().configuration().basis_gates
# Error parameters
param_q0 = 0.05 # damping parameter for qubit-0
param_q1 = 0.1 # damping parameter for qubit-1
# Construct the error
qerror_q0 = amplitude_damping_error(param_q0)
qerror_q1 = amplitude_damping_error(param_q1)
iswap_error = qerror_q1.tensor(qerror_q0)
# Build the noise model by adding the error to the "iswap" gate
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(iswap_error, 'iswap')
# Bell state circuit where iSWAPS should be inserted at barrier locations
bell_circ = QuantumCircuit(2, 2, name='bell')
bell_circ.h(0)
bell_circ.append(cx_circ, [0, 1])
bell_circ.measure([0,1], [0,1])
print(bell_circ)
noise_model.add_basis_gates(['unitary'])
print(noise_model.basis_gates)
# Create ideal simulator backend and transpile circuit
sim_ideal = AerSimulator()
tbell_circ = transpile(bell_circ, sim_ideal)
ideal_result = sim_ideal.run(tbell_circ).result()
ideal_counts = ideal_result.get_counts(0)
plot_histogram(ideal_counts,
title='Ideal output for iSWAP bell-state preparation')
# Create noisy simulator and transpile circuit
sim_noise = AerSimulator(noise_model=noise_model)
tbell_circ_noise = transpile(bell_circ, sim_noise)
# Run on the simulator without noise
noise_result = sim_noise.run(tbell_circ_noise).result()
noise_counts = noise_result.get_counts(bell_circ)
plot_histogram(noise_counts,
title='Noisy output for iSWAP bell-state preparation')
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
from qiskit import transpile, QuantumCircuit
import qiskit.quantum_info as qi
from qiskit_aer import AerSimulator
from qiskit_aer.noise import NoiseModel, amplitude_damping_error
from qiskit.visualization import plot_histogram
# CNOT matrix operator with qubit-0 as control and qubit-1 as target
cx_op = qi.Operator([[1, 0, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 0],
[0, 1, 0, 0]])
# iSWAP matrix operator
iswap_op = qi.Operator([[1, 0, 0, 0],
[0, 0, 1j, 0],
[0, 1j, 0, 0],
[0, 0, 0, 1]])
# CNOT in terms of iSWAP and single-qubit gates
cx_circ = QuantumCircuit(2, name='cx<iSWAP>')
# Add gates
cx_circ.sdg(1)
cx_circ.h(1)
cx_circ.sdg(0)
cx_circ.unitary(iswap_op, [0, 1], label='iswap')
cx_circ.sdg(0)
cx_circ.h(0)
cx_circ.sdg(0)
cx_circ.unitary(iswap_op, [0, 1], label='iswap')
cx_circ.s(1)
print(cx_circ)
# Simulate the unitary for the circuit using Operator:
unitary = qi.Operator(cx_circ)
print(unitary)
'unitary' in AerSimulator().configuration().basis_gates
# Error parameters
param_q0 = 0.05 # damping parameter for qubit-0
param_q1 = 0.1 # damping parameter for qubit-1
# Construct the error
qerror_q0 = amplitude_damping_error(param_q0)
qerror_q1 = amplitude_damping_error(param_q1)
iswap_error = qerror_q1.tensor(qerror_q0)
# Build the noise model by adding the error to the "iswap" gate
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(iswap_error, 'iswap')
# Bell state circuit where iSWAPS should be inserted at barrier locations
bell_circ = QuantumCircuit(2, 2, name='bell')
bell_circ.h(0)
bell_circ.append(cx_circ, [0, 1])
bell_circ.measure([0,1], [0,1])
print(bell_circ)
noise_model.add_basis_gates(['unitary'])
print(noise_model.basis_gates)
# Create ideal simulator backend and transpile circuit
sim_ideal = AerSimulator()
tbell_circ = transpile(bell_circ, sim_ideal)
ideal_result = sim_ideal.run(tbell_circ).result()
ideal_counts = ideal_result.get_counts(0)
plot_histogram(ideal_counts,
title='Ideal output for iSWAP bell-state preparation')
# Create noisy simulator and transpile circuit
sim_noise = AerSimulator(noise_model=noise_model)
tbell_circ_noise = transpile(bell_circ, sim_noise)
# Run on the simulator without noise
noise_result = sim_noise.run(tbell_circ_noise).result()
noise_counts = noise_result.get_counts(bell_circ)
plot_histogram(noise_counts,
title='Noisy output for iSWAP bell-state preparation')
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile
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://docs.quantum.ibm.com/run/primitives
# result = Sampler().run(circuits).result()
from qiskit import QuantumCircuit, ClassicalRegister, transpile
from qiskit.providers.fake_provider import GenericBackendV2
# Create a circuit with classical control
creg = ClassicalRegister(19)
qc = QuantumCircuit(25)
qc.add_register(creg)
qc.h(0)
for i in range(18):
qc.cx(0, i + 1)
for i in range(18):
qc.measure(i, creg[i])
with qc.if_test((creg, 0)):
qc.ecr(20, 21)
# Define backend with custom basis gates and
# control flow instructions
backend = GenericBackendV2(
num_qubits=25,
basis_gates=["ecr", "id", "rz", "sx", "x"],
control_flow=True,
)
#Transpile
transpiled_qc = transpile(qc, backend)
job = backend.run(transpiled_qc)
#job = execute(qc, simulator, shots=1024)
# Wait for the job to finish
job_result = job.result()
# Get counts from the result
counts = job.result()[0].data.meas.get_counts()
#counts = job_result.get_counts()
"""# Plot the histogram
plot_histogram(counts)"""
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile
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://docs.quantum.ibm.com/run/primitives
# result = Sampler().run(circuits).result()
import qiskit
print(qiskit.__version__)
from qiskit import QuantumCircuit
qc = QuantumCircuit(3)
qc.h(0)
qc.h(1)
qc.cx(1, 2)
qc.measure_all()
# Previous
from qiskit import BasicAer
backend = BasicAer.get_backend("statevector_simulator")
statevector = backend.run(qc).result().get_statevector()
# Current
qc.remove_final_measurements() # no measurements allowed
from qiskit.quantum_info import Statevector
statevector = Statevector(qc)
from qiskit import QuantumCircuit
qc = QuantumCircuit(3)
qc.h(0)
qc.h(1)
qc.cx(1, 2)
qc.measure_all()
"""# Previous
from qiskit import BasicAer
backend = BasicAer.get_backend("qasm_simulator")
result = backend.run(qc).result()"""
# One current option
from qiskit.providers.basic_provider import BasicProvider
backend = BasicProvider().get_backend("basic_simulator")
result = backend.run(qc).result()
# Get counts from the result
counts = result.get_counts()
from qiskit.visualization import plot_histogram
print(counts)
data = [counts]
plot_histogram(data)
print("h")
"""# Another current option is to specify it directly
from qiskit.providers.basic_provider import BasicSimulator
backend = BasicSimulator()
result = backend.run(qc).result()"""
from qiskit import QuantumCircuit
from qiskit.providers.basic_provider import BasicProvider
from qiskit.visualization import plot_histogram
# Create a quantum circuit
qc = QuantumCircuit(3)
qc.h(0)
qc.h(1)
qc.cx(1, 2)
qc.measure_all()
# Get the BasicSimulator backend from the BasicProvider
backend = BasicProvider().get_backend("basic_simulator")
# Simulate the quantum circuit
result = backend.run(qc).result()
# Get counts from the result
counts = result.get_counts()
# Plot the histogram
plot_histogram(counts)
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
from qiskit import QuantumCircuit, transpile, assemble
from qiskit_aer import AerSimulator
from qiskit.visualization import plot_histogram
# Define the function to create the oracle
def create_oracle(n, marked_states):
oracle = QuantumCircuit(n)
# Apply Z gate to the qubits corresponding to the marked states
for state in marked_states:
oracle.z(state)
# Apply controlled-Z gates for diffusion
if n > 2:
oracle.h(range(n))
oracle.x(range(n))
oracle.h(n-1)
oracle.mct(list(range(n-1)), n-1)
oracle.h(n-1)
oracle.x(range(n))
oracle.h(range(n))
return oracle
# Define the function to create the Grover's diffusion operator
def create_diffusion(n):
diffusion = QuantumCircuit(n)
diffusion.h(range(n))
diffusion.x(range(n))
diffusion.h(n-1)
diffusion.mct(list(range(n-1)), n-1)
diffusion.h(n-1)
diffusion.x(range(n))
diffusion.h(range(n))
return diffusion
# Define the function to apply Grover's algorithm
def grover_algorithm(oracle, diffusion, n, marked_states, num_iterations):
grover_circuit = QuantumCircuit(n)
# Apply Hadamard gates to all qubits
grover_circuit.h(range(n))
# Apply the Grover iterations
for _ in range(num_iterations):
grover_circuit.append(oracle, range(n))
grover_circuit.append(diffusion, range(n))
# Measure all qubits
grover_circuit.measure_all()
return grover_circuit
# Define the marked states and the number of qubits
n = 3
marked_states = [4, 7] # Corresponding to |100⟩ and |111⟩
num_iterations = 1
# Create the oracle and the diffusion operator
oracle = create_oracle(n, marked_states)
diffusion = create_diffusion(n)
# Apply Grover's algorithm
grover_circuit = grover_algorithm(oracle, diffusion, n, marked_states, num_iterations)
# Draw the circuit
print(grover_circuit.draw())
# Simulate the circuit
simulator = AerSimulator()
grover_transpiled = transpile(grover_circuit, simulator)
qobj = assemble(grover_transpiled)
result = simulator.run(qobj).result()
# Plot the histogram of the result
counts = result.get_counts()
print(counts)
plot_histogram(counts)
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import Kraus, SuperOp
from qiskit.visualization import plot_histogram
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit_aer import AerSimulator
# Import from Qiskit Aer noise module
from qiskit_aer.noise import (
NoiseModel,
QuantumError,
ReadoutError,
depolarizing_error,
pauli_error,
thermal_relaxation_error,
)
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
backend = service.backend("ibm_brisbane")
noise_model = NoiseModel.from_backend(backend)
# Construct a 1-qubit bit-flip and phase-flip errors
p_error = 0.05
bit_flip = pauli_error([('X', p_error), ('I', 1 - p_error)])
phase_flip = pauli_error([('Z', p_error), ('I', 1 - p_error)])
print(bit_flip)
print(phase_flip)
# Compose two bit-flip and phase-flip errors
bitphase_flip = bit_flip.compose(phase_flip)
print(bitphase_flip)
# Tensor product two bit-flip and phase-flip errors with
# bit-flip on qubit-0, phase-flip on qubit-1
error2 = phase_flip.tensor(bit_flip)
print(error2)
# Convert to Kraus operator
bit_flip_kraus = Kraus(bit_flip)
print(bit_flip_kraus)
# Convert to Superoperator
phase_flip_sop = SuperOp(phase_flip)
print(phase_flip_sop)
# Convert back to a quantum error
print(QuantumError(bit_flip_kraus))
# Check conversion is equivalent to original error
QuantumError(bit_flip_kraus) == bit_flip
# Measurement misassignment probabilities
p0given1 = 0.1
p1given0 = 0.05
ReadoutError([[1 - p1given0, p1given0], [p0given1, 1 - p0given1]])
# Create an empty noise model
noise_model = NoiseModel()
# Add depolarizing error to all single qubit u1, u2, u3 gates
error = depolarizing_error(0.05, 1)
noise_model.add_all_qubit_quantum_error(error, ['u1', 'u2', 'u3'])
# Print noise model info
print(noise_model)
# Create an empty noise model
noise_model = NoiseModel()
# Add depolarizing error to all single qubit u1, u2, u3 gates on qubit 0 only
error = depolarizing_error(0.05, 1)
noise_model.add_quantum_error(error, ['u1', 'u2', 'u3'], [0])
# Print noise model info
print(noise_model)
# System Specification
n_qubits = 4
circ = QuantumCircuit(n_qubits)
# Test Circuit
circ.h(0)
for qubit in range(n_qubits - 1):
circ.cx(qubit, qubit + 1)
circ.measure_all()
print(circ)
# Ideal simulator and execution
sim_ideal = AerSimulator()
result_ideal = sim_ideal.run(circ).result()
plot_histogram(result_ideal.get_counts(0))
# Example error probabilities
p_reset = 0.03
p_meas = 0.1
p_gate1 = 0.05
# QuantumError objects
error_reset = pauli_error([('X', p_reset), ('I', 1 - p_reset)])
error_meas = pauli_error([('X',p_meas), ('I', 1 - p_meas)])
error_gate1 = pauli_error([('X',p_gate1), ('I', 1 - p_gate1)])
error_gate2 = error_gate1.tensor(error_gate1)
# Add errors to noise model
noise_bit_flip = NoiseModel()
noise_bit_flip.add_all_qubit_quantum_error(error_reset, "reset")
noise_bit_flip.add_all_qubit_quantum_error(error_meas, "measure")
noise_bit_flip.add_all_qubit_quantum_error(error_gate1, ["u1", "u2", "u3"])
noise_bit_flip.add_all_qubit_quantum_error(error_gate2, ["cx"])
print(noise_bit_flip)
# Create noisy simulator backend
sim_noise = AerSimulator(noise_model=noise_bit_flip)
# Transpile circuit for noisy basis gates
passmanager = generate_preset_pass_manager(optimization_level=3, backend=sim_noise)
circ_tnoise = passmanager.run(circ)
# Run and get counts
result_bit_flip = sim_noise.run(circ_tnoise).result()
counts_bit_flip = result_bit_flip.get_counts(0)
# Plot noisy output
plot_histogram(counts_bit_flip)
# T1 and T2 values for qubits 0-3
T1s = np.random.normal(50e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec
T2s = np.random.normal(70e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec
# Truncate random T2s <= T1s
T2s = np.array([min(T2s[j], 2 * T1s[j]) for j in range(4)])
# Instruction times (in nanoseconds)
time_u1 = 0 # virtual gate
time_u2 = 50 # (single X90 pulse)
time_u3 = 100 # (two X90 pulses)
time_cx = 300
time_reset = 1000 # 1 microsecond
time_measure = 1000 # 1 microsecond
# QuantumError objects
errors_reset = [thermal_relaxation_error(t1, t2, time_reset)
for t1, t2 in zip(T1s, T2s)]
errors_measure = [thermal_relaxation_error(t1, t2, time_measure)
for t1, t2 in zip(T1s, T2s)]
errors_u1 = [thermal_relaxation_error(t1, t2, time_u1)
for t1, t2 in zip(T1s, T2s)]
errors_u2 = [thermal_relaxation_error(t1, t2, time_u2)
for t1, t2 in zip(T1s, T2s)]
errors_u3 = [thermal_relaxation_error(t1, t2, time_u3)
for t1, t2 in zip(T1s, T2s)]
errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand(
thermal_relaxation_error(t1b, t2b, time_cx))
for t1a, t2a in zip(T1s, T2s)]
for t1b, t2b in zip(T1s, T2s)]
# Add errors to noise model
noise_thermal = NoiseModel()
for j in range(4):
noise_thermal.add_quantum_error(errors_reset[j], "reset", [j])
noise_thermal.add_quantum_error(errors_measure[j], "measure", [j])
noise_thermal.add_quantum_error(errors_u1[j], "u1", [j])
noise_thermal.add_quantum_error(errors_u2[j], "u2", [j])
noise_thermal.add_quantum_error(errors_u3[j], "u3", [j])
for k in range(4):
noise_thermal.add_quantum_error(errors_cx[j][k], "cx", [j, k])
print(noise_thermal)
# Run the noisy simulation
sim_thermal = AerSimulator(noise_model=noise_thermal)
# Transpile circuit for noisy basis gates
passmanager = generate_preset_pass_manager(optimization_level=3, backend=sim_thermal)
circ_tthermal = passmanager.run(circ)
# Run and get counts
result_thermal = sim_thermal.run(circ_tthermal).result()
counts_thermal = result_thermal.get_counts(0)
# Plot noisy output
plot_histogram(counts_thermal)
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile
from qiskit_ibm_provider import IBMProvider
import qiskit_ibm_provider.jupyter
#provider = IBMProvider('ibm-q')
#backend = provider.get_backend('ibmq_vigo')
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
from qiskit.circuit import QuantumCircuit, Gate, Instruction
from qiskit.circuit.library.standard_gates import ZGate
def MCMT(gate, num_controls, num_targets):
"""Construct a multi-controlled multi-target gate.
Args:
gate (Gate): The gate to apply to the target qubits.
num_controls (int): The number of control qubits.
num_targets (int): The number of target qubits.
Returns:
Instruction: The multi-controlled multi-target gate as a Qiskit Instruction.
"""
mcmt_gate = QuantumCircuit(num_controls + num_targets)
mcmt_gate.append(gate.control(num_controls), list(range(num_controls + num_targets)))
return mcmt_gate.to_instruction()
def grover_oracle(marked_states):
"""Build a Grover oracle for multiple marked states
Here we assume all input marked states have the same number of bits
Parameters:
marked_states (str or list): Marked states of oracle
Returns:
QuantumCircuit: Quantum circuit representing Grover oracle
"""
if not isinstance(marked_states, list):
marked_states = [marked_states]
# Compute the number of qubits in circuit
num_qubits = len(marked_states[0])
qc = QuantumCircuit(num_qubits)
# Mark each target state in the input list
for target in marked_states:
# Flip target bit-string to match Qiskit bit-ordering
rev_target = target[::-1]
# Find the indices of all the '0' elements in bit-string
zero_inds = [ind for ind in range(num_qubits) if rev_target.startswith("0", ind)]
# Add a multi-controlled Z-gate with pre- and post-applied X-gates (open-controls)
# where the target bit-string has a '0' entry
qc.x(zero_inds)
#qc.ry(0.1,zero_inds)
qc.compose(MCMT(ZGate(), num_qubits - 1, 1), inplace=True)
qc.x(zero_inds)
return qc
marked_states = ["011", "100"]
oracle = grover_oracle(marked_states)
oracle.draw("mpl")
grover_op = GroverOperator(oracle)
grover_op.decompose().draw("mpl")
optimal_num_iterations = math.floor(
math.pi / 4 * math.sqrt(2**grover_op.num_qubits / len(marked_states))
)
qc = QuantumCircuit(grover_op.num_qubits)
# Create even superposition of all basis states
qc.h(range(grover_op.num_qubits))
# Apply Grover operator the optimal number of times
qc.compose(grover_op.power(optimal_num_iterations), inplace=True)
# Measure all qubits
qc.measure_all()
qc.draw("mpl")
from qiskit import QuantumCircuit
from qiskit.providers.basic_provider import BasicProvider
from qiskit.visualization import plot_histogram
from qiskit import transpile
from qiskit.providers.fake_provider import GenericBackendV2
#from qiskit.visualization import plot_histogram
# Generate a 5-qubit simulated backend
backend = GenericBackendV2(num_qubits=5)
"""
# Alternative
from qiskit_ibm_runtime.fake_provider import FakeProvider
backend1 = FakeProvider().get_backend("fake_ourense")
from qiskit_ibm_runtime.fake_provider import FakeSherbrooke
backend2 = FakeSherbrooke()"""
# Transpile the ideal circuit to a circuit that can be directly executed by the backend
transpiled_circuit = transpile(qc, backend)#transpiled_circuit = transpile(qc, backend=backend_simulator)
transpiled_circuit.draw('mpl')
# Run the transpiled circuit using the simulated backend
job = backend.run(transpiled_circuit)
counts = job.result().get_counts()
print(counts)
plot_histogram(counts)
from qiskit import QuantumCircuit
from qiskit.providers.basic_provider import BasicProvider
from qiskit.visualization import plot_histogram
from qiskit import transpile
from qiskit.providers.fake_provider import GenericBackendV2
#from qiskit.visualization import plot_histogram
# Generate a 5-qubit simulated backend
backend = GenericBackendV2(num_qubits=5)
"""
# Alternative
from qiskit_ibm_runtime.fake_provider import FakeProvider
backend1 = FakeProvider().get_backend("fake_ourense")
from qiskit_ibm_runtime.fake_provider import FakeSherbrooke
backend2 = FakeSherbrooke()"""
# Transpile the ideal circuit to a circuit that can be directly executed by the backend
transpiled_circuit = transpile(qc, backend)#transpiled_circuit = transpile(qc, backend=backend_simulator)
transpiled_circuit.draw('mpl')
# Run the transpiled circuit using the simulated backend
job = backend.run(transpiled_circuit)
counts = job.result().get_counts()
print(counts)
plot_histogram(counts)
from qiskit import QuantumCircuit
from qiskit.providers.basic_provider import BasicProvider
from qiskit.visualization import plot_histogram
#qc.measure_all()
from qiskit.providers.basic_provider import BasicProvider
backend = BasicProvider().get_backend("basic_simulator")
result = backend.run(qc).result()
"""
# Get the BasicSimulator backend from the BasicProvider
backend = BasicProvider().get_backend("basic_simulator")
# Simulate the quantum circuit
result = backend.run(qc).result()"""
# Alternative
from qiskit_ibm_runtime.fake_provider import FakeProvider
backend1 = FakeProvider().get_backend("fake_ourense")
from qiskit_ibm_runtime.fake_provider import FakeSherbrooke
backend2 = FakeSherbrooke()
# Get counts from the result
counts = result.get_counts()
# Plot the histogram
plot_histogram(counts)
backend_simulator = service.least_busy(operational=True, simulator=False)
backend_simulator.name
# Initialize your session
sim_session = Session(backend=backend_simulator)
sim_sampler = Sampler(session=sim_session)
from qiskit import transpile
from qiskit.visualization import plot_histogram
# Assuming qc is your quantum circuit
# Transpile the circuit to match the target backend
transpiled_circuit = transpile(qc, backend=backend_simulator)
from qiskit.providers.basic_provider import BasicProvider
backend = BasicProvider().get_backend("ibmq_qasm_simulator")
job = backend.run(transpiled_circuit)
job = execute(qc, simulator, shots=1024)
# Wait for the job to finish
job_result = job.result()
# Get counts from the result
counts = job_result.get_counts()
# Plot the histogram
plot_histogram(counts)
from qiskit import transpile
from qiskit.visualization import plot_histogram
# Assuming qc is your quantum circuit
# Transpile the circuit to match the target backend
transpiled_circuit = transpile(qc, backend=backend_simulator)
# Run the transpiled circuit on the backend
job = backend_simulator.run(transpiled_circuit)
# Wait for the job to finish
job_result = job.result()
# Get counts from the result
counts = job_result.get_counts()
# Plot the histogram
plot_histogram(counts)
sim_dist = sim_sampler.run(qc, shots=int(1e4)).result().quasi_dists[0]
plot_distribution(sim_dist.binary_probabilities())
sim_session.close()
# Select the backend with the fewest number of jobs in the queue
backend = service.least_busy(simulator=False, operational=True)
backend.name
# Initialize your session
session = Session(backend=backend)
real_sampler = Sampler(session=session)
real_dist = real_sampler.run(qc, shots=int(1e4)).result().quasi_dists[0]
plot_distribution(real_dist.binary_probabilities())
# Close session
session.close()
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile
from qiskit_ibm_provider import IBMProvider
import qiskit_ibm_provider.jupyter
#provider = IBMProvider('ibm-q')
#backend = provider.get_backend('ibmq_vigo')
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
from qiskit.providers.basic_provider import BasicProvider
from qiskit.visualization import plot_histogram
from qiskit import transpile
from qiskit.providers.fake_provider import GenericBackendV2
def grover_oracle(marked_states, i, j, k):
if not isinstance(marked_states, list):
marked_states = [marked_states]
num_qubits = len(marked_states[0])
qc = QuantumCircuit(num_qubits)
for target in marked_states:
rev_target = target[::-1]
zero_inds = [ind for ind in range(num_qubits) if rev_target.startswith("0", ind)]
qc.x(zero_inds)
"""ZAJ 1"""
qc.rx(0.1*i,zero_inds)
qc.ry(0.1*j,zero_inds)
qc.rz(0.1*k,zero_inds)
qc.compose(MCMT(ZGate(), num_qubits - 1, 1), inplace=True)
qc.x(zero_inds)
return qc
marked_states = ["011", "100"]
printToConsole = False
for i in range(0,10):
for j in range(0,10):
for k in range(0,10):
oracle = grover_oracle(marked_states, i, j, k)
grover_op = GroverOperator(oracle)
optimal_num_iterations = math.floor(
math.pi / 4 * math.sqrt(2**grover_op.num_qubits / len(marked_states))
)
qc = QuantumCircuit(grover_op.num_qubits)
# Create even superposition of all basis states
qc.h(range(grover_op.num_qubits))
# Apply Grover operator the optimal number of times
qc.compose(grover_op.power(optimal_num_iterations), inplace=True)
"""ZAJ 2"""
#qc.x(range(grover_op.num_qubits))
# Measure all qubits
qc.measure_all()
#qc.draw('mpl')
grover_op.decompose().draw("mpl")
backend = GenericBackendV2(num_qubits=5)
transpiled_circuit = transpile(qc, backend)
job = backend.run(transpiled_circuit)
counts = job.result().get_counts()
# Format counts data
formatted_output = ""
for state in ['000', '001', '010', '011', '100', '101', '110', '111']:
formatted_output += f"{counts.get(state, 0)} "
# Write counts data to a text file
with open('counts_data.txt', 'a') as file:
file.write(formatted_output + "\n")
"""# Write counts data to a text file
with open('counts_data.txt', 'a') as file:
file.write(f"i={i}j={j}k={k}")
file.write("State,Count\n")
for state, count in counts.items():
file.write(f"{state},{count}\n")
if(printToConsole):
# Print counts data
print(counts)
print("State,Count\n")
for state, count in counts.items():
print(f"{state},{count}\n")
#plot_histogram(counts)"""
print("All done")
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile
from qiskit_ibm_provider import IBMProvider
import qiskit_ibm_provider.jupyter
#provider = IBMProvider('ibm-q')
#backend = provider.get_backend('ibmq_vigo')
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
from qiskit.providers.basic_provider import BasicProvider
from qiskit.visualization import plot_histogram
from qiskit import transpile
from qiskit.providers.fake_provider import GenericBackendV2
def grover_oracle(marked_states):
if not isinstance(marked_states, list):
marked_states = [marked_states]
# Compute the number of qubits in circuit
num_qubits = len(marked_states[0])
qc = QuantumCircuit(num_qubits)
# Mark each target state in the input list
for target in marked_states:
# Flip target bit-string to match Qiskit bit-ordering
rev_target = target[::-1]
# Find the indices of all the '0' elements in bit-string
zero_inds = [ind for ind in range(num_qubits) if rev_target.startswith("0", ind)]
# Add a multi-controlled Z-gate with pre- and post-applied X-gates (open-controls)
# where the target bit-string has a '0' entry
qc.x(zero_inds)
"""ZAJ 1"""
qc.ry(0.5,zero_inds)
qc.compose(MCMT(ZGate(), num_qubits - 1, 1), inplace=True)
qc.x(zero_inds)
return qc
marked_states = ["011", "100"]
oracle = grover_oracle(marked_states)
grover_op = GroverOperator(oracle)
optimal_num_iterations = math.floor(
math.pi / 4 * math.sqrt(2**grover_op.num_qubits / len(marked_states))
)
qc = QuantumCircuit(grover_op.num_qubits)
# Create even superposition of all basis states
qc.h(range(grover_op.num_qubits))
# Apply Grover operator the optimal number of times
qc.compose(grover_op.power(optimal_num_iterations), inplace=True)
"""ZAJ 2"""
#qc.x(range(grover_op.num_qubits))
# Measure all qubits
qc.measure_all()
#qc.draw('mpl')
grover_op.decompose().draw("mpl")
qc.draw("mpl")
backend = GenericBackendV2(num_qubits=5)
transpiled_circuit = transpile(qc, backend)
job = backend.run(transpiled_circuit)
counts = job.result().get_counts()
# Write counts data to a text file
with open('counts_data.txt', 'w') as file:
file.write("State,Count\n")
for state, count in counts.items():
file.write(f"{state},{count}\n")
# Print counts data
print(counts)
print("State,Count\n")
for state, count in counts.items():
print(f"{state},{count}\n")
#plot_histogram(counts)
|
https://github.com/purvi1508/Quantum_Computing_Fundamentals
|
purvi1508
|
!pip install qiskit
!pip install pylatexenc
import qiskit
import pylatexenc
from qiskit import *
from pylatexenc import *
qr= QuantumRegister(2)
#quantum register is a system comprising multiple qubits
cr= ClassicalRegister(2)
circuit = QuantumCircuit(qr,cr)
%matplotlib inline
import matplotlib.pyplot as plt
circuit.draw(initial_state = True)
circuit.h(qr[0])
#applying handmard gate
circuit.draw(output='mpl',initial_state = True)
#logical if
circuit.cx(qr[0],qr[1])
circuit.draw(output='mpl')
circuit.measure(qr,cr)
#measure quantum bits and take those measurements and store in classical bits
circuit.draw(output='mpl',initial_state = True)
simulator = Aer.get_backend('qasm_simulator')
result= execute(circuit,backend=simulator).result()
from qiskit.tools.visualization import plot_histogram
print(result.get_counts(circuit))
#These outcomes correspond to the basis states |00⟩, |01⟩, |10⟩, and |11⟩, respectively.
counts = result.get_counts(circuit)
total_shots = sum(counts.values())
# Calculate the probabilities
probabilities = {state: count / total_shots for state, count in counts.items()}
plot_histogram(probabilities)
|
https://github.com/purvi1508/Quantum_Computing_Fundamentals
|
purvi1508
|
!pip install qiskit
import qiskit.quantum_info as qi
from qiskit.circuit.library import FourierChecking
from qiskit.visualization import plot_histogram
f=[1,-1,-1,-1]
g=[1,1,-1,-1]
#The Discrete Fourier Transform (DFT) is a mathematical algorithm used to compute the discrete Fourier transform of a sequence.
#It takes a sequence of N complex numbers as input and produces another sequence of N complex numbers as output.
#fourier checking would tell how correlated the fourier transforrmation of G is to F
#P(f,g)>0.05-> then our function is correlated
circ=FourierChecking(f=f,g=g)
circ.draw(initial_state = True)
zero=qi.Statevector.from_label('00')
sv=zero.evolve(circ)
probs= sv.probabilities_dict()
plot_histogram(probs)
|
https://github.com/purvi1508/Quantum_Computing_Fundamentals
|
purvi1508
|
!pip install qiskit
#superpositon, entanglement and interference
my_list=[1,3,5,2,4,9,5,8,0,7,6]
#eracle is the black box at the disposal->we can call it and ask whether this number is a whinner or not
def the_oracle(my_input):
winner=7
if my_input is winner:
response=True
else:
response=False
return response
for index, trial_number in enumerate(my_list):
if the_oracle(trial_number)==True:
print('winner found at index %i'%index)
print('%i calls at the oracle used'%(index+1))
#oracle works here by flipping the sign of the input of the winner
#controlled Z gate -> |11> -> [CZ] -> -|11>
#amplitute amplification ->reflection operator
#Grovvers diffusion operator-> oracle+ Reflection
from qiskit import *
import matplotlib.pyplot as py
import numpy as np
#define oracle circuit
oracle = QuantumCircuit(2,name='oracle')
oracle.cz(0,1)
oracle.to_gate()#make oracle into its own gate
oracle.draw(initial_state = True)
#preparing a supepositon state of all the gates by applying the handmard gate on each one of them
#in this way each uery xould be simuntaneousky reached oracle
backend=Aer.get_backend('statevector_simulator')
# statevector_simulator backend is selected, which allows for simulation of the quantum state vector of the circuit.
grover_circ=QuantumCircuit(2,2)
#The first argument 2 specifies the number of qubits in the quantum registers, and the second argument 2 specifies the number of classical bits in the classical registers.
grover_circ.h([0,1])
#This line applies the Hadamard gate (H gate) to qubits 0 and 1 in the grover_circ circuit.
grover_circ.append(oracle,[0,1])
grover_circ.draw(initial_state = True)
job= execute(grover_circ,backend)
result=job.result()
sv=result.get_statevector()
np.around(sv,2)
#square the state vectors to get back the probabilities
reflection = QuantumCircuit(2,name="reflection")
reflection.h([0,1])
reflection.z([0,1])
reflection.cz(0,1)
reflection.h([0,1])
reflection.to_gate()
reflection.draw(initial_state = True)
backend=Aer.get_backend('statevector_simulator')
# statevector_simulator backend is selected, which allows for simulation of the quantum state vector of the circuit.
grover_circ=QuantumCircuit(2,2)
#The first argument 2 specifies the number of qubits in the quantum registers, and the second argument 2 specifies the number of classical bits in the classical registers.
grover_circ.h([0,1])
#This line applies the Hadamard gate (H gate) to qubits 0 and 1 in the grover_circ circuit.
grover_circ.append(oracle,[0,1])
grover_circ.append(reflection,[0,1])
grover_circ.measure([0,1],[0,1])
grover_circ.draw(initial_state = True)
job= execute(grover_circ,backend,shots=1)
result=job.result()
result.get_counts()
|
https://github.com/purvi1508/Quantum_Computing_Fundamentals
|
purvi1508
|
!pip install qiskit
!pip install pylatexenc
import qiskit
import pylatexenc
from qiskit import *
from pylatexenc import *
# Create a quantum circuit with three qubits
qc = QuantumCircuit(3, 3)
%matplotlib inline
qc.draw(initial_state = True)
# Create a Bell pair between qubits 1 and 2
qc.h(1)
qc.cx(1, 2)
# The Hadamard gate qc.h(1) is applied to qubit 1 to create a superposition, and the CNOT gate qc.cx(1, 2) is applied between qubits 1 and 2 to entangle them and create a Bell pair
qc.draw(initial_state = True)
# Entangle qubit 0 with qubit 1
qc.cx(0, 1)
qc.h(0)
qc.draw(initial_state = True)
# Apply a measurement to qubits 0 and 1
qc.barrier()
qc.measure([0,1], [0,1])
qc.draw(initial_state = True)
# Apply a controlled-X gate to qubits 1 and 2
qc.cx(1, 2)
qc.draw(initial_state = True)
# Apply a controlled-Z gate to qubits 0 and 2
qc.cz(0, 2)
qc.draw(initial_state = True)
# Apply a measurement to qubit 2
qc.measure(2, 2)
qc.draw(initial_state = True)
# Run the circuit on a simulator
backend = Aer.get_backend('qasm_simulator')
result = execute(qc, backend).result()
# Print the result
print(result.get_counts(qc))
|
https://github.com/bernardomendonca/qiskit-fourier-check
|
bernardomendonca
|
import qiskit.quantum_info as qi
from qiskit.circuit.library import FourierChecking
from qiskit.visualization import plot_histogram
f=[1,-1,-1,-1]
g=[1,1,-1,-1]
circ = FourierChecking(f=f,g=g)
circ.draw()
zero = qi.Statevector.from_label('00')
sv = zero.evolve(circ)
probs = sv.probabilities_dict()
plot_histogram(probs)
|
https://github.com/INFINIT27/Grover-s-Algorithm
|
INFINIT27
|
from qiskit import QuantumCircuit
from qiskit_aer import *
from qiskit.visualization import plot_histogram
import math
import random
# val - number to be converted
# length - the number of bits for the binary value
def toBinary(val, length):
binary = '' # declare an empty string
loop = val
if val == 0:
binary = '0'
else:
while loop > 0:
temp = loop % 2 # calculate the bit value
loop = loop // 2
binary += str(temp) # add the bit value to the bit string
# If the binary value is shorter than the number of bits
# passed, append 0's in front of the binary number equal
# to the difference between the binary length and the total length .
while len(binary) < length:
binary += '0'
binary = binary[::-1] # reverse the string
return binary
# Only converts the value to binary, doesn't add extra 0's in front
# to match the number of required qubits.
def toBinary_only(val):
binary = '' # declare an empty string
loop = val
while loop > 0:
temp = loop % 2 # calculate the bit value
loop = loop // 2
binary += str(temp) # add the bit value to the bit string
binary = binary[::-1] # reverse the string
return binary
choice_list = []
# Define the length of the array, can be any length
array_length = 16
for i in range(array_length):
choice_list.append(random.randint(0, 50))
print("Array/Database =",choice_list)
binary_length = toBinary_only(array_length)
qubits_needed = len(binary_length)
# Define a search index (less then array_length) of the list/array/database
search_index = 15
search_val = choice_list[search_index]
print("Search Value =",search_val)
print("Search Index =",search_index)
def oracle(circuit, n, val):
binary_val = toBinary(val, n)
binary_val = binary_val[::-1]
# If the input value contains a qubit 0, apply an x gate to it
# to switch it to a 1 to affect the axillary bit. 1100
for i in range(len(binary_val)):
if binary_val[i] == '0':
circuit.x(i)
############ Implement the multi-control conditional gate ################
circuit.ccx(0, 1, n) # Apply the toffoli gate to the first helper qubit.
for i in range(2, n):
circuit.ccx(i, i+(n-2), i+(n-1)) # Apply a toffoli gate from the second to the last (auxillary) gate.
for i in range(n-2, 1, -1):
circuit.ccx(i, i+(n-2), i+(n-1)) # Apply the reverse gates from the second helper qubit to the last helper qubit.
circuit.ccx(0, 1, n) # Apply the toffoli gate to the first helper qubit.
##########################################################################
# Repeat the same step to revert the qubit change from '1' to '0'.
for i in range(len(binary_val)):
if binary_val[i] == '0':
circuit.x(i)
return circuit
# The diffuser takes in a circuit that applies the appropriate gates.
def diffuser(circuit, n):
# Apply the hadamard gate to the "n" address bits.
for qubit in range(n):
circuit.h(qubit)
# Apply the flip gate to the "n" address bits.
for qubit in range(n):
circuit.x(qubit)
# Apply the multi-control conditional gate to the circuit to change the auxillary bit.
########################################
circuit.ccx(0, 1, n)
for i in range(2, n):
circuit.ccx(i, i+(n-2), i+(n-1))
for i in range(n-2, 1, -1):
circuit.ccx(i, i+(n-2), i+(n-1))
circuit.ccx(0, 1, n)
########################################
# Reverse the flip gate applied earlier.
for qubit in range(n):
circuit.x(qubit)
# Reverse the hadamard gate applied earlier.
for qubit in range(n):
circuit.h(qubit)
return circuit
def ispower2(number):
log_val = math.log(number, 2);
pow_val = math.pow(2, round(log_val));
return pow_val == number
# First "n" qubits will be allocated to the address qubits.
if ispower2(array_length):
address_bit = qubits_needed - 1
else:
address_bit = qubits_needed
helper_bits = address_bit - 2 # next "n-2" qubits will be used as helper qubits for the multi-control conditional gate.
auxillary_bit = 1 # Last qubit will be reserved to the auxillary qubit.
qubits = address_bit + helper_bits + auxillary_bit # Find the total number of qubits needed to implement the circuit.
# Define the test value for the cirucit
test_value = search_index
qc = QuantumCircuit(qubits, address_bit)
# Initialise the address qubits and place them into a superposition.
for i in range(address_bit):
qc.h(i)
# Place the auxillary qubit into the |-> state.
qc.x(qubits-1)
qc.h(qubits-1)
# Define the number of needed iterations for the search to occurr.
# The optimal value is equal to the square root of the number of values in the array/database.
iterations = int(address_bit**(1/2))+1 # The int() value rounds down the number of iterations, thus we add 1 to the number of iterations.
# Apply the number of Oracle-Diffusor pair equal to the number of iterations.
for i in range(iterations):
qc.barrier()
oracle(qc, address_bit, test_value)
qc.barrier()
diffuser(qc, address_bit)
qc.barrier()
# Measure the address qubits.
for i in range(address_bit):
qc.measure(i, i)
qc.draw('mpl')
# Construct an ideal simulator
simulator = AerSimulator()
results = simulator.run(qc).result()
counts = results.get_counts()
print(counts)
display(plot_histogram(counts))
largest_val = 0
value = ''
for entry in counts:
if counts[entry] > largest_val:
largest_val = counts[entry]
value = entry
print(value)
def toInteger(val: str):
num = 0
val = val[::-1] # take the reverse of the string of integers 100 - 001
for i in range(len(val)):
if val[i] == '0':
continue
else:
num += 2**i
return num
print("The estimated index from the simulator is:",toInteger(value))
|
https://github.com/diegour1/QiskitHackaton2021
|
diegour1
|
!pip install qiskit
!pip install pylatexenc
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
#from qiskit import *
import numpy as np
backend = Aer.get_backend('qasm_simulator')
# Given the density matrix find the angle of the corresponding rotation
def measure_theta(P):
w0, v0 = np.linalg.eig(P)
v0 = v0*np.sign(v0[0, 0])
theta = np.sign(v0[0, 0])*np.sign(v0[1, 0])*2*np.arccos(abs(v0[0, 0]))
return theta
# measure_theta(P_1)
# Given an rotation angle in the y axis, print its unitary matrix
def unitary_matrix(theta):
qc = QuantumCircuit(1, 1)
qc.ry(theta, 0)
unitary_backend = Aer.get_backend('unitary_simulator')
unitary = execute(qc, unitary_backend).result().get_unitary().round(10)
return unitary
#unitary_matrix(-1.0013820370897397)
unitary_matrix(1.047184849024927)
import copy
def round_lambda(lambda_param_2):
lambda_param = copy.copy(lambda_param_2)
for i in range(4):
if lambda_param[i] < 0.00000001:
lambda_param[i] = 0.00000001
lambda_param[3] = 1 - lambda_param[0] - lambda_param[1] - lambda_param[2]
return lambda_param
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
def ArbRot(p0, p1, p2, p3):
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
ang0 = 2*np.arccos(np.sqrt(p0+p1))
qc.rx(ang0, qr[1])
ang1 = 2*np.arccos(np.sqrt(p0/(p0+p1)))
qc.rx(ang1, qr[0])
ang2 = 2*np.arccos(np.sqrt(p2/(p2+p3))) - ang1
qc.crx(ang2, qr[1], qr[0])
#qc.swap(qr[0], qr[1])
gate = qc.to_gate()
gate.label = "ArbInit"
return gate
def ArbRotControlled(p0, p1, p2, p3):
qr = QuantumRegister(3)
qc = QuantumCircuit(qr)
ang0 = 2*np.arccos(np.sqrt(p0+p1))
qc.crx(ang0, qr[0], qr[2])
ang1 = 2*np.arccos(np.sqrt(p0/(p0+p1)))
qc.crx(ang1, qr[0], qr[1])
ang2 = 2*np.arccos(np.sqrt(p2/(p2+p3))) - ang1
qc.mcrx(ang2, [qr[0], qr[2]], qr[1])
#qc.swap(qr[0], qr[1])
gate = qc.to_gate()
gate.label = "ArbInit"
return gate
def ArbRotControlledTranspose(p0, p1, p2, p3):
qr = QuantumRegister(3)
qc = QuantumCircuit(qr)
ang0 = 2*np.arccos(np.sqrt(p0+p1))
qc.crx(-ang0, qr[0], qr[2])
ang1 = 2*np.arccos(np.sqrt(p0/(p0+p1)))
qc.crx(-ang1, qr[0], qr[1])
ang2 = 2*np.arccos(np.sqrt(p2/(p2+p3))) - ang1
qc.mcrx(-ang2, [qr[0], qr[2]], qr[1])
#qc.swap(qr[0], qr[1])
gate = qc.to_gate()
gate.label = "ArbInit"
return gate
def ArbRotToffTranspose(p0, p1, p2, p3):
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
ang0 = 2*np.arccos(np.sqrt(p0+p1))
qc.mcrx(-ang0, [qr[0], qr[1]], qr[3])
ang1 = 2*np.arccos(np.sqrt(p0/(p0+p1)))
qc.mcrx(-ang1, [qr[0], qr[1]], qr[2])
ang2 = 2*np.arccos(np.sqrt(p2/(p2+p3))) - ang1
qc.mcrx(-ang2, [qr[0], qr[1], qr[3]], qr[2])
#qc.swap(qr[0], qr[1])
gate = qc.to_gate()
gate.label = "ArbInitCT"
return gate
def ArbRotToffM2Transpose(p0, p1, p2, p3):
qr = QuantumRegister(5)
qc = QuantumCircuit(qr)
ang0 = 2*np.arccos(np.sqrt(p0+p1))
qc.mcrx(-ang0, [qr[0], qr[1], qr[2]], qr[4])
ang1 = 2*np.arccos(np.sqrt(p0/(p0+p1)))
qc.mcrx(-ang1, [qr[0], qr[1], qr[2]], qr[3])
ang2 = 2*np.arccos(np.sqrt(p2/(p2+p3))) - ang1
qc.mcrx(-ang2, [qr[0], qr[1], qr[2], qr[4]], qr[3])
#qc.swap(qr[0], qr[1])
gate = qc.to_gate()
gate.label = "ArbInitCT"
return gate
a0 = np.array([0.30507657, 0.9523278250881023])
b0 = np.array([0.75399555, 0.6568795251643924])
c0 = np.array([0.50986323, 0.8602554775727772])
P0 = 0.35*np.outer(a0, a0) + 0.65*np.outer(b0, b0)
exp_c = c0.T @ P0 @ c0
P0, exp_c
# Find eigenvectors and eigenvalues
lambda_P, U = np.linalg.eigh(P0)
lambda_P, U
vector_0, vector_1 = U[:, 0], U[:, 1]
vector_0, vector_1, 0.5*np.dot(vector_0, a0)**2, 0.5*np.dot(vector_1, b0)**2
0.5 * (np.dot(vector_0, c0)**2/(np.dot(vector_0, c0)**2+np.dot(vector_1, c0)**2))
theta_0, theta_1 = measure_theta(U), measure_theta(U.T)
theta_0 = theta_0+np.pi
theta_1 = theta_0-np.pi/2
theta_0, theta_1
qc = QuantumCircuit(1, 1)
qc.ry(2*theta_0, 0)
qc.measure(0, 0)
counts = execute(qc, backend, shots=15000).result().get_counts()
plot_histogram(counts)
# 2 x 2 Example
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.x(0)
qc.initialize(c0, 1)
qc.cry(-(2*theta_0), 0, 1)
qc.x(0)
qc.cry(-(2*theta_1), 0, 1)
qc.measure(0, 0)
qc.measure(1, 1)
counts = execute(qc, backend, shots=15000).result().get_counts()
plot_histogram(counts)
## Works
qc.draw('mpl')
# 2 x 2 Example with eigenvalues
backend = Aer.get_backend('qasm_simulator')
qc = QuantumCircuit(3, 2)
qc.h(0)
qc.initialize(c0, 1)
qc.initialize(np.sqrt(lambda_P), 2)
qc.barrier()
qc.x(0)
qc.cry(-(2*theta_0), 0, 1)
qc.x(0)
qc.cry(-(2*theta_1), 0, 1)
qc.cx(0, 2)
qc.barrier()
qc.measure(1, 0)
qc.measure(2, 1)
counts = execute(qc, backend, shots=150000).result().get_counts()
plot_histogram(counts)
qc.draw('mpl')
# expected_value = (np.dot(vector_0, c0))**2 * lambda_P[0] + (np.dot(vector_1, c0))**2 * lambda_P[1]
expected_value = c0.T @ P0 @ c0
expected_value, (counts["00"]/150000)*2
## Examples 4x4 , we build the density matrix with b, c, and predict the data a
a0 = np.array([0.30507657, 0.9523278250881023])
a1 = np.array([0.69810362, 0.715996742829809])
b0 = np.array([0.75399555, 0.6568795251643924])
b1 = np.array([0.53842219, 0.8426752312223279])
c0 = np.array([0.50986323, 0.8602554775727772])
c1 = np.array([0.58868076, 0.8083656120876385])
a = np.kron(a0, a1)
b = np.kron(b0, b1)
c = np.kron(c0, c1)
a, b, c
# Density Matrix and expected value
P4 = 0.56*np.outer(b, b) + 0.44*np.outer(c, c)
exp_a = a.T @ P4 @ a
P4, exp_a
# Find eigenvectors and eigenvalues
lambda_P4, U4 = np.linalg.eigh(P4)
lambda_P4 = round_lambda(lambda_P4)
lambda_P4, U4
# 4 x 4 Example with eigenvalues
backend = Aer.get_backend('qasm_simulator')
qc = QuantumCircuit(6, 4)
qc.h(0)
qc.h(1)
qc.append(ArbRot(*(a**2)), [2, 3])
qc.append(ArbRot(*lambda_P4), [4, 5])
qc.barrier()
qc.x(0)
qc.x(1)
qc.append(ArbRotToffTranspose(*(U4[:, 0]**2)), [0, 1, 2, 3])
qc.x(1)
qc.append(ArbRotToffTranspose(*(U4[:, 1]**2)), [0, 1, 2, 3])
qc.x(0)
qc.x(1)
qc.append(ArbRotToffTranspose(*(U4[:, 2]**2)), [0, 1, 2, 3])
qc.x(1)
qc.append(ArbRotToffTranspose(*(U4[:, 3]**2)), [0, 1, 2, 3])
qc.cx(1, 5)
qc.cx(0, 4)
qc.measure(2, 0)
qc.measure(3, 1)
qc.measure(4, 2)
qc.measure(5, 3)
counts = execute(qc, backend, shots=150000).result().get_counts()
plot_histogram(counts)
qc.draw('mpl')
exp_a_calculated = (counts["0000"]/150000)*4
exp_a_theorical = a.T @ P4 @ a
exp_a_calculated, exp_a_theorical
## Examples 4x4 , we build the density matrix of class 0 with b, c
## the density matrix of class 1 with d, and predict the data a
a0 = np.array([0.30507657, 0.9523278250881023])
a1 = np.array([0.69810362, 0.715996742829809])
b0 = np.array([0.75399555, 0.6568795251643924])
b1 = np.array([0.53842219, 0.8426752312223279])
c0 = np.array([0.50986323, 0.8602554775727772])
c1 = np.array([0.58868076, 0.8083656120876385])
d0 = np.array([0.10894686, 0.9940475751673762])
d1 = np.array([0.38544095, 0.9227325040677268])
a = np.kron(a0, a1)
b = np.kron(b0, b1)
c = np.kron(c0, c1)
d = np.kron(d0, d1)
a, b, c, d
# Density Matrix and expected value
P0 = 0.66*np.outer(b, b) + 0.34*np.outer(c, c)
P1 = np.outer(d, d)
exp_a_P0 = a.T @ P0 @ a
exp_a_P1 = a.T @ P1 @ a
exp_a_P0, exp_a_P1
# Find eigenvectors and eigenvalues
lambda_P0_temp, U0 = np.linalg.eigh(P0)
lambda_P0 = round_lambda(lambda_P0_temp)
lambda_P1_temp, U1 = np.linalg.eigh(P1)
lambda_P1 = round_lambda(lambda_P1_temp)
(lambda_P0, U0), (lambda_P1, U1)
# 4 x 4 Example with eigenvalues
backend = Aer.get_backend('qasm_simulator')
qc = QuantumCircuit(7, 5)
qc.h(0)
qc.h(1)
qc.h(2)
qc.append(ArbRot(*(a**2)), [3, 4])
qc.barrier()
qc.x(2)
qc.x(0)
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U0[:, 0]**2)), [0, 1, 2, 3, 4])
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U0[:, 1]**2)), [0, 1, 2, 3, 4])
qc.x(0)
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U0[:, 2]**2)), [0, 1, 2, 3, 4])
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U0[:, 3]**2)), [0, 1, 2, 3, 4])
qc.append(ArbRotControlled(*lambda_P0), [2, 5, 6])
qc.barrier()
qc.x(2)
qc.x(0)
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U1[:, 0]**2)), [0, 1, 2, 3, 4])
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U1[:, 1]**2)), [0, 1, 2, 3, 4])
qc.x(0)
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U1[:, 2]**2)), [0, 1, 2, 3, 4])
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U1[:, 3]**2)), [0, 1, 2, 3, 4])
qc.append(ArbRotControlled(*lambda_P1), [2, 5, 6])
qc.cx(1, 6)
qc.cx(0, 5)
qc.barrier()
qc.measure(2, 0)
qc.measure(3, 1)
qc.measure(4, 2)
qc.measure(5, 3)
qc.measure(6, 4)
counts = execute(qc, backend, shots=150000).result().get_counts()
plot_histogram(counts)
qc.draw('mpl')
# Expected and calculated for class 0
exp_a_calculated_P0 = (counts["00000"]/150000)*8
exp_a_theorical_P0 = a.T @ P0 @ a
# Expected and calculated for class 1
exp_a_calculated_P1 = (counts["00001"]/150000)*8
exp_a_theorical_P1 = a.T @ P1 @ a
exp_a_calculated_P0, exp_a_theorical_P0, exp_a_calculated_P1, exp_a_theorical_P1
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets
from sklearn.decomposition import PCA
digits, labels = datasets.load_digits(n_class=2, return_X_y=True)
print(digits.shape)
_, axes = plt.subplots(nrows=1, ncols=4, figsize=(10, 3))
for ax, image, label in zip(axes, digits, labels):
ax.set_axis_off()
ax.imshow(image.reshape(8,8), cmap=plt.cm.gray_r, interpolation='nearest')
sklearn_pca = PCA(n_components=64)
sklearn_transf = sklearn_pca.fit_transform(digits)
varianza_expl = sklearn_pca.explained_variance_ratio_
plt.figure(figsize = (9, 6))
plt.xlabel('Número de componentes principales')
plt.ylabel('Varianza acumulada')
cum_var_exp = np.cumsum(varianza_expl)
nc = np.arange(1, varianza_expl.shape[0] + 1)
plt.plot(nc, cum_var_exp, 'g^')
plt.show()
print(np.sum(varianza_expl[0:4]), np.sum(varianza_expl[0:8]),
np.sum(varianza_expl[0:16]), np.sum(varianza_expl[0:32]))
n_comps = 4
pca = PCA(n_components = n_comps)
Xpca = pca.fit_transform(digits)
plt.figure(figsize=(10,2.5))
for i in range(4):
plt.subplot(1,4,i+1)
plt.imshow(pca.components_[i].reshape(8,8), cmap=plt.cm.gray)
plt.xticks([]); plt.yticks([])
Xpca.shape
V0 = []
V1 = []
for i in range(Xpca.shape[0]):
if (labels[i] == 0):
V0.append(Xpca[i] / np.linalg.norm(Xpca[i]))
elif (labels[i] == 1):
V1.append(Xpca[i] / np.linalg.norm(Xpca[i]))
print(V0[0:9])
print(V1[0:9])
print(len(V0))
print(len(V1))
print((V1[3]**2).round(4))
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
def ArbRot(p0, p1, p2, p3):
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
ang0 = 2*np.arccos(np.sqrt(p0+p1))
qc.rx(ang0, qr[1])
ang1 = 2*np.arccos(np.sqrt(p0/(p0+p1)))
qc.rx(ang1, qr[0])
ang2 = 2*np.arccos(np.sqrt(p2/(p2+p3))) - ang1
qc.crx(ang2, qr[1], qr[0])
#qc.swap(qr[0], qr[1])
gate = qc.to_gate()
gate.label = "ArbRot"
return gate
def ArbRotControlled(p0, p1, p2, p3):
qr = QuantumRegister(3)
qc = QuantumCircuit(qr)
ang0 = 2*np.arccos(np.sqrt(p0+p1))
qc.crx(ang0, qr[0], qr[2])
ang1 = 2*np.arccos(np.sqrt(p0/(p0+p1)))
qc.crx(ang1, qr[0], qr[1])
ang2 = 2*np.arccos(np.sqrt(p2/(p2+p3))) - ang1
qc.mcrx(ang2, [qr[0], qr[2]], qr[1])
#qc.swap(qr[0], qr[1])
gate = qc.to_gate()
gate.label = "ArbRot-C"
return gate
def ArbRotControlledTranspose(p0, p1, p2, p3):
qr = QuantumRegister(3)
qc = QuantumCircuit(qr)
ang0 = 2*np.arccos(np.sqrt(p0+p1))
qc.crx(-ang0, qr[0], qr[2])
ang1 = 2*np.arccos(np.sqrt(p0/(p0+p1)))
qc.crx(-ang1, qr[0], qr[1])
ang2 = 2*np.arccos(np.sqrt(p2/(p2+p3))) - ang1
qc.mcrx(-ang2, [qr[0], qr[2]], qr[1])
#qc.swap(qr[0], qr[1])
gate = qc.to_gate()
gate.label = "ArbRot-C-dg"
return gate
def ArbRotToffTranspose(p0, p1, p2, p3):
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
ang0 = 2*np.arccos(np.sqrt(p0+p1))
qc.mcrx(-ang0, [qr[0], qr[1]], qr[3])
ang1 = 2*np.arccos(np.sqrt(p0/(p0+p1)))
qc.mcrx(-ang1, [qr[0], qr[1]], qr[2])
ang2 = 2*np.arccos(np.sqrt(p2/(p2+p3))) - ang1
qc.mcrx(-ang2, [qr[0], qr[1], qr[3]], qr[2])
#qc.swap(qr[0], qr[1])
gate = qc.to_gate()
gate.label = "ArbRot-2C-dg"
return gate
def ArbRotToffM2Transpose(p0, p1, p2, p3):
qr = QuantumRegister(5)
qc = QuantumCircuit(qr)
ang0 = 2*np.arccos(np.sqrt(p0+p1))
qc.mcrx(-ang0, [qr[0], qr[1], qr[2]], qr[4])
ang1 = 2*np.arccos(np.sqrt(p0/(p0+p1)))
qc.mcrx(-ang1, [qr[0], qr[1], qr[2]], qr[3])
ang2 = 2*np.arccos(np.sqrt(p2/(p2+p3))) - ang1
qc.mcrx(-ang2, [qr[0], qr[1], qr[2], qr[4]], qr[3])
#qc.swap(qr[0], qr[1])
gate = qc.to_gate()
gate.label = "ArbRot-3C-dg"
return gate
import numpy as np
a0 = np.array(V0[1])
a1 = np.array(V1[1])
b = np.array(V0[2])
c = np.array(V1[2])
0.5*np.dot(a0, b)**2, 0.5*(np.dot(a0, c)**2)
0.5*np.dot(a1, b)**2, 0.5*(np.dot(a1, c)**2)
# Zero sample
qc = QuantumCircuit(3, 3)
qc.h(0)
qc.append(ArbRot(*(a0**2)), [2,1])
qc.barrier()
qc.x(0)
qc.append(ArbRotControlledTranspose(*(b**2)), [0,2,1])
qc.barrier()
qc.x(0)
qc.append(ArbRotControlledTranspose(*(c**2)), [0,2,1])
qc.barrier()
qc.measure(0, 0)
qc.measure(1, 1)
qc.measure(2, 2)
shots = 10000
job = execute(qc, Aer.get_backend('qasm_simulator'),shots=shots)
counts = job.result().get_counts()
plot_histogram(counts)
print((int)(counts['000'] < counts['001']))
# One sample
qc = QuantumCircuit(3, 3)
qc.h(0)
qc.append(ArbRot(*(a1**2)), [2,1])
qc.barrier()
qc.x(0)
qc.append(ArbRotControlledTranspose(*(b**2)), [0,2,1])
qc.barrier()
qc.x(0)
qc.append(ArbRotControlledTranspose(*(c**2)), [0,2,1])
qc.barrier()
qc.measure(0, 0)
qc.measure(1, 1)
qc.measure(2, 2)
shots = 10000
job = execute(qc, Aer.get_backend('qasm_simulator'),shots=shots)
counts = job.result().get_counts()
plot_histogram(counts)
print((int)(counts['000'] < counts['001']))
qc.draw('mpl')
qc.decompose().draw('mpl')
#Pure state for class 0
S_zero = np.sum(np.abs(V0[0:121]), axis=0)
#S_zero = np.sum(V0[0:121], axis=0)
S_zero = S_zero / np.linalg.norm(S_zero)
print(S_zero)
#Pure state for class 1
S_one = np.sum(np.abs(V1[0:121]), axis=0)
#S_one = np.sum(V1[0:121], axis=0)
S_one = S_one / np.linalg.norm(S_one)
print(S_one)
# Pure state case
test_zeros = []
for i in range(121, 178):
qc = QuantumCircuit(3, 3)
qc.h(0)
qc.append(ArbRot(*(np.array(V0[i])**2)), [2,1])
qc.barrier()
qc.x(0)
qc.append(ArbRotControlledTranspose(*(S_zero**2)), [0,2,1])
qc.barrier()
qc.x(0)
qc.append(ArbRotControlledTranspose(*(S_one**2)), [0,2,1])
qc.barrier()
qc.measure(0, 0)
qc.measure(1, 1)
qc.measure(2, 2)
shots = 12000
job = execute(qc, Aer.get_backend('qasm_simulator'),shots=shots)
counts = job.result().get_counts()
test_zeros.append((int)(counts['000'] < counts['001']))
print(test_zeros)
# Pure state case
test_ones = []
for i in range(121, 182):
qc = QuantumCircuit(3, 3)
qc.h(0)
qc.append(ArbRot(*(np.array(V1[i])**2)), [2,1])
qc.barrier()
qc.x(0)
qc.append(ArbRotControlledTranspose(*(S_zero**2)), [0,2,1])
qc.barrier()
qc.x(0)
qc.append(ArbRotControlledTranspose(*(S_one**2)), [0,2,1])
qc.barrier()
qc.measure(0, 0)
qc.measure(1, 1)
qc.measure(2, 2)
shots = 12000
job = execute(qc, Aer.get_backend('qasm_simulator'),shots=shots)
counts = job.result().get_counts()
test_ones.append((int)(counts['000'] < counts['001']))
print(test_ones)
ytest = np.concatenate([np.zeros(len(test_zeros)), np.ones(len(test_ones))])
preds = np.concatenate([test_zeros, test_ones])
import sklearn.metrics as metrics
cm = metrics.confusion_matrix(ytest, preds)
cm_display = metrics.ConfusionMatrixDisplay(cm, display_labels=[0,1]).plot()
accuracy = metrics.accuracy_score(ytest,preds)
print("Accuracy: ", accuracy)
precision, recall, f_score, _ = metrics.precision_recall_fscore_support(ytest, preds, average='binary')
print("Precision: ", precision)
print("Recall: ", recall)
print("F1: ", f_score)
Z_zero = np.outer(np.abs(V0[0]), np.abs(V0[0]))
for i in range(1, 121):
Z_zero += np.outer(np.abs(V0[i]), np.abs(V0[i]))
Z_zero *= 1/120
print(Z_zero)
lambda_P0_temp, U_zero = np.linalg.eigh(Z_zero)
lambda_zero = round_lambda(lambda_P0_temp)
print(lambda_zero)
print(U_zero)
Z_one = np.outer(np.abs(V1[0]), np.abs(V1[0]))
for i in range(1, 121):
Z_one += np.outer(np.abs(V1[i]), np.abs(V1[i]))
Z_one *= 1/120
print(Z_one)
lambda_P1_temp, U_one = np.linalg.eigh(Z_one)
lambda_one = round_lambda(lambda_P1_temp)
print(lambda_one)
print(U_one)
backend2 = Aer.get_backend('qasm_simulator')
# Mixed state case
test2_zeros = []
for i in range(121, 178):
qc = QuantumCircuit(7, 5)
qc.h(0)
qc.h(1)
qc.h(2)
qc.append(ArbRot(*(V0[i]**2)), [3, 4])
qc.barrier()
qc.x(2)
qc.x(0)
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_zero[:, 0]**2)), [0, 1, 2, 3, 4])
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_zero[:, 1]**2)), [0, 1, 2, 3, 4])
qc.x(0)
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_zero[:, 2]**2)), [0, 1, 2, 3, 4])
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_zero[:, 3]**2)), [0, 1, 2, 3, 4])
qc.append(ArbRotControlled(*lambda_zero), [2, 5, 6])
qc.barrier()
qc.x(2)
qc.x(0)
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_one[:, 0]**2)), [0, 1, 2, 3, 4])
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_one[:, 1]**2)), [0, 1, 2, 3, 4])
qc.x(0)
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_one[:, 2]**2)), [0, 1, 2, 3, 4])
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_one[:, 3]**2)), [0, 1, 2, 3, 4])
qc.append(ArbRotControlled(*lambda_one), [2, 5, 6])
qc.cx(1, 6)
qc.cx(0, 5)
qc.barrier()
qc.measure(2, 0)
qc.measure(3, 1)
qc.measure(4, 2)
qc.measure(5, 3)
qc.measure(6, 4)
counts = execute(qc, backend2, shots=50000).result().get_counts()
test2_zeros.append((int)(counts['00000'] < counts['00001']))
print(test2_zeros)
# Mixed state case
test2_ones = []
for i in range(121, 182):
qc = QuantumCircuit(7, 5)
qc.h(0)
qc.h(1)
qc.h(2)
qc.append(ArbRot(*(V1[i]**2)), [3, 4])
qc.barrier()
qc.x(2)
qc.x(0)
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_zero[:, 0]**2)), [0, 1, 2, 3, 4])
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_zero[:, 1]**2)), [0, 1, 2, 3, 4])
qc.x(0)
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_zero[:, 2]**2)), [0, 1, 2, 3, 4])
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_zero[:, 3]**2)), [0, 1, 2, 3, 4])
qc.append(ArbRotControlled(*lambda_zero), [2, 5, 6])
qc.barrier()
qc.x(2)
qc.x(0)
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_one[:, 0]**2)), [0, 1, 2, 3, 4])
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_one[:, 1]**2)), [0, 1, 2, 3, 4])
qc.x(0)
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_one[:, 2]**2)), [0, 1, 2, 3, 4])
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_one[:, 3]**2)), [0, 1, 2, 3, 4])
qc.append(ArbRotControlled(*lambda_one), [2, 5, 6])
qc.cx(1, 6)
qc.cx(0, 5)
qc.barrier()
qc.measure(2, 0)
qc.measure(3, 1)
qc.measure(4, 2)
qc.measure(5, 3)
qc.measure(6, 4)
counts = execute(qc, backend2, shots=50000).result().get_counts()
test2_ones.append((int)(counts['00000'] < counts['00001']))
print(test2_ones)
ytest = np.concatenate([np.zeros(len(test2_zeros)), np.ones(len(test2_ones))])
preds2 = np.concatenate([test2_zeros, test2_ones])
import sklearn.metrics as metrics
cm2 = metrics.confusion_matrix(ytest, preds2)
cm2_display = metrics.ConfusionMatrixDisplay(cm2, display_labels=[0,1]).plot()
accuracy = metrics.accuracy_score(ytest,preds2)
print("Accuracy: ", accuracy)
precision, recall, f_score, _ = metrics.precision_recall_fscore_support(ytest, preds2, average='binary')
print("Precision: ", precision)
print("Recall: ", recall)
print("F1: ", f_score)
from qiskit import IBMQ, transpile
from qiskit import QuantumCircuit
from qiskit.providers.aer import AerSimulator
from qiskit.tools.visualization import plot_histogram
from qiskit.test.mock import FakeCasablanca
from qiskit.providers.aer import AerSimulator
device_backend = FakeCasablanca()
casablanca = AerSimulator.from_backend(device_backend)
# Pure state case
test_zeros = []
for i in range(121, 178):
qc = QuantumCircuit(3, 3)
qc.h(0)
qc.append(ArbRot(*(np.array(V0[i])**2)), [2,1])
qc.barrier()
qc.x(0)
qc.append(ArbRotControlledTranspose(*(S_zero**2)), [0,2,1])
qc.barrier()
qc.x(0)
qc.append(ArbRotControlledTranspose(*(S_one**2)), [0,2,1])
qc.barrier()
qc.measure(0, 0)
qc.measure(1, 1)
qc.measure(2, 2)
shots = 12000
job = execute(qc, backend=casablanca, shots=shots)
counts = job.result().get_counts()
test_zeros.append((int)(counts['000'] < counts['001']))
print(test_zeros)
# Pure state case
test_ones = []
for i in range(121, 182):
qc = QuantumCircuit(3, 3)
qc.h(0)
qc.append(ArbRot(*(np.array(V1[i])**2)), [2,1])
qc.barrier()
qc.x(0)
qc.append(ArbRotControlledTranspose(*(S_zero**2)), [0,2,1])
qc.barrier()
qc.x(0)
qc.append(ArbRotControlledTranspose(*(S_one**2)), [0,2,1])
qc.barrier()
qc.measure(0, 0)
qc.measure(1, 1)
qc.measure(2, 2)
shots = 12000
job = execute(qc, backend=casablanca, shots=shots)
counts = job.result().get_counts()
test_ones.append((int)(counts['000'] < counts['001']))
print(test_ones)
ytest = np.concatenate([np.zeros(len(test_zeros)), np.ones(len(test_ones))])
preds = np.concatenate([test_zeros, test_ones])
import sklearn.metrics as metrics
cm = metrics.confusion_matrix(ytest, preds)
cm_display = metrics.ConfusionMatrixDisplay(cm, display_labels=[0,1]).plot()
accuracy = metrics.accuracy_score(ytest,preds)
print("Accuracy: ", accuracy)
precision, recall, f_score, _ = metrics.precision_recall_fscore_support(ytest, preds, average='binary')
print("Precision: ", precision)
print("Recall: ", recall)
print("F1: ", f_score)
# Mixed state case
test2_zeros = []
for i in range(121, 178):
qc = QuantumCircuit(7, 5)
qc.h(0)
qc.h(1)
qc.h(2)
qc.append(ArbRot(*(V0[i]**2)), [3, 4])
qc.barrier()
qc.x(2)
qc.x(0)
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_zero[:, 0]**2)), [0, 1, 2, 3, 4])
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_zero[:, 1]**2)), [0, 1, 2, 3, 4])
qc.x(0)
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_zero[:, 2]**2)), [0, 1, 2, 3, 4])
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_zero[:, 3]**2)), [0, 1, 2, 3, 4])
qc.append(ArbRotControlled(*lambda_zero), [2, 5, 6])
qc.barrier()
qc.x(2)
qc.x(0)
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_one[:, 0]**2)), [0, 1, 2, 3, 4])
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_one[:, 1]**2)), [0, 1, 2, 3, 4])
qc.x(0)
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_one[:, 2]**2)), [0, 1, 2, 3, 4])
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_one[:, 3]**2)), [0, 1, 2, 3, 4])
qc.append(ArbRotControlled(*lambda_one), [2, 5, 6])
qc.cx(1, 6)
qc.cx(0, 5)
qc.barrier()
qc.measure(2, 0)
qc.measure(3, 1)
qc.measure(4, 2)
qc.measure(5, 3)
qc.measure(6, 4)
counts = execute(qc, backend=casablanca, shots=50000).result().get_counts()
test2_zeros.append((int)(counts['00000'] < counts['00001']))
print(test2_zeros)
# Mixed state case
test2_ones = []
for i in range(121, 182):
qc = QuantumCircuit(7, 5)
qc.h(0)
qc.h(1)
qc.h(2)
qc.append(ArbRot(*(V1[i]**2)), [3, 4])
qc.barrier()
qc.x(2)
qc.x(0)
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_zero[:, 0]**2)), [0, 1, 2, 3, 4])
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_zero[:, 1]**2)), [0, 1, 2, 3, 4])
qc.x(0)
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_zero[:, 2]**2)), [0, 1, 2, 3, 4])
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_zero[:, 3]**2)), [0, 1, 2, 3, 4])
qc.append(ArbRotControlled(*lambda_zero), [2, 5, 6])
qc.barrier()
qc.x(2)
qc.x(0)
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_one[:, 0]**2)), [0, 1, 2, 3, 4])
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_one[:, 1]**2)), [0, 1, 2, 3, 4])
qc.x(0)
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_one[:, 2]**2)), [0, 1, 2, 3, 4])
qc.x(1)
qc.append(ArbRotToffM2Transpose(*(U_one[:, 3]**2)), [0, 1, 2, 3, 4])
qc.append(ArbRotControlled(*lambda_one), [2, 5, 6])
qc.cx(1, 6)
qc.cx(0, 5)
qc.barrier()
qc.measure(2, 0)
qc.measure(3, 1)
qc.measure(4, 2)
qc.measure(5, 3)
qc.measure(6, 4)
counts = execute(qc, backend=casablanca, shots=50000).result().get_counts()
test2_ones.append((int)(counts['00000'] < counts['00001']))
print(test2_ones)
ytest = np.concatenate([np.zeros(len(test2_zeros)), np.ones(len(test2_ones))])
preds2 = np.concatenate([test2_zeros, test2_ones])
import sklearn.metrics as metrics
cm2 = metrics.confusion_matrix(ytest, preds2)
cm2_display = metrics.ConfusionMatrixDisplay(cm2, display_labels=[0,1]).plot()
accuracy = metrics.accuracy_score(ytest,preds2)
print("Accuracy: ", accuracy)
precision, recall, f_score, _ = metrics.precision_recall_fscore_support(ytest, preds2, average='binary')
print("Precision: ", precision)
print("Recall: ", recall)
print("F1: ", f_score)
|
https://github.com/SamScherf/shors-algorithm
|
SamScherf
|
import sys
import numpy as np
from matplotlib import pyplot as plt
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, visualization
from random import randint
def to_binary(N,n_bit):
Nbin = np.zeros(n_bit, dtype=bool)
for i in range(1,n_bit+1):
bit_state = (N % (2**i) != 0)
if bit_state:
N -= 2**(i-1)
Nbin[n_bit-i] = bit_state
return Nbin
def modular_multiplication(qc,a,N):
"""
applies the unitary operator that implements
modular multiplication function x -> a*x(modN)
Only works for the particular case x -> 7*x(mod15)!
"""
for i in range(0,3):
qc.x(i)
qc.cx(2,1)
qc.cx(1,2)
qc.cx(2,1)
qc.cx(1,0)
qc.cx(0,1)
qc.cx(1,0)
qc.cx(3,0)
qc.cx(0,1)
qc.cx(1,0)
def quantum_period(a, N, n_bit):
# Quantum part
print(" Searching the period for N =", N, "and a =", a)
qr = QuantumRegister(n_bit)
cr = ClassicalRegister(n_bit)
qc = QuantumCircuit(qr,cr)
simulator = Aer.get_backend('qasm_simulator')
s0 = randint(1, N-1) # Chooses random int
sbin = to_binary(s0,n_bit) # Turns to binary
print("\n Starting at \n s =", s0, "=", "{0:b}".format(s0), "(bin)")
# Quantum register is initialized with s (in binary)
for i in range(0,n_bit):
if sbin[n_bit-i-1]:
qc.x(i)
s = s0
r=-1 # makes while loop run at least 2 times
# Applies modular multiplication transformation until we come back to initial number s
while s != s0 or r <= 0:
r+=1
# sets up circuit structure
qc.measure(qr, cr)
modular_multiplication(qc,a,N)
qc.draw('mpl')
# runs circuit and processes data
job = execute(qc,simulator, shots=10)
result_counts = job.result().get_counts(qc)
result_histogram_key = list(result_counts)[0] # https://qiskit.org/documentation/stubs/qiskit.result.Result.get_counts.html#qiskit.result.Result.get_counts
s = int(result_histogram_key, 2)
print(" ", result_counts)
plt.show()
print("\n Found period r =", r)
return r
if __name__ == '__main__':
a = 7
N = 15
n_bit=5
r = quantum_period(a, N, n_bit)
|
https://github.com/yellowskydragon/VQAA
|
yellowskydragon
|
import matplotlib.pyplot
import math
import random
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from pathlib import Path
from qiskit import Aer, transpile, assemble, BasicAer, transpiler
from qiskit.providers.aer import Aer
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit.circuit.library import QFT, PhaseGate
from random import uniform
from qiskit.providers.aer.library import save_statevector
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.providers.aer.noise.errors import thermal_relaxation_error, pauli_error
from qiskit.providers.aer.noise import NoiseModel
# GRAPH = nx.random_graphs.random_regular_graph(DEGREE, AES_KEY_LENGTH)
error_list = {
"1qb" : -1,
"2qb" : -1,
"spam": -1,
"thermal" : [5000,6000]
}
pauli_Z = np.array([[1, 0], [0, -1]])
def is_noisy(error_type):
random_noise = uniform(0.0, 1.0)
if error_type == "1qb" or error_type == "2qb":
if random_noise <= error_list[error_type]:
different_gate_noise = uniform(0.0, 1.0)
if 0.0 <= different_gate_noise < 1/3:
return "X"
elif 1/3 <= random_noise < 2/3:
return "Y"
else:
return "Z"
else:
return False
else:
if random_noise <= error_list[error_type]:
return True
else:
return False
def generate_circuit_with_state_vector(ansatz_type, if_back_control, plain_text, theta_list):
n = len(plain_text)
key_space = QuantumRegister(n)
data_space = QuantumRegister(n)
qc = QuantumCircuit(key_space, data_space)
## Begin ansatz
qc.h(key_space)
### 1-qubit gate noise
for i in range(n):
if_noisy = is_noisy("1qb")
if if_noisy == False:
continue
else:
if if_noisy == "X":
qc.x(key_space[i])
elif if_noisy == "Y":
qc.y(key_space[i])
else:
qc.z(key_space[i])
for i in range(n):
qc.ry(theta_list[i], key_space[i])
# 1-qubit gate noise
if_noisy = is_noisy("1qb")
if if_noisy == False:
continue
else:
if if_noisy == "X":
qc.x(key_space[i])
elif if_noisy == "Y":
qc.y(key_space[i])
else:
qc.z(key_space[i])
qc.barrier()
if ansatz_type == "rx":
for i in range(n - 1):
qc.cx(key_space[i], key_space[i+1])
elif ansatz_type == "ry":
for i in range(n - 1):
qc.cy(key_space[i], key_space[i+1])
elif ansatz_type == "rz":
for i in range(n - 1):
qc.cz(key_space[i], key_space[i+1])
# 2-qubit gate noise
for i in range(n - 1):
if_noisy = is_noisy("2qb")
if if_noisy == False:
continue
else:
if if_noisy == "X":
qc.x(key_space[i + 1])
elif if_noisy == "Y":
qc.y(key_space[i + 1])
else:
qc.z(key_space[i + 1])
if if_back_control:
if ansatz_type == "rx":
qc.cx(key_space[n - 1], key_space[0])
elif ansatz_type == "ry":
qc.cy(key_space[n - 1], key_space[0])
elif ansatz_type == "rz":
qc.cz(key_space[n - 1], key_space[0])
# 2-qubit gate noise
if_noisy = is_noisy("2qb")
if if_noisy != False:
if if_noisy == "X":
qc.x(key_space[0])
elif if_noisy == "Y":
qc.y(key_space[0])
else:
qc.z(key_space[0])
qc.barrier()
## End ansatz
## Prepare plaintext
for i in range(n):
if plain_text[i] == '1':
qc.x(data_space[i])
# 1-qubit gate noise
if_noisy = is_noisy("1qb")
if if_noisy != False:
if if_noisy == "X":
qc.x(data_space[i])
elif if_noisy == "Y":
qc.y(data_space[i])
else:
qc.z(data_space[i])
qc.barrier()
## Begin AES encryption
for i in range(n // 2):
qc.swap(data_space[i], data_space[n - 1 - i])
qc.barrier()
for i in range(n):
qc.cx(key_space[i], data_space[i])
#2-qubit gate noise
if_noisy = is_noisy("2qb")
if if_noisy == False:
continue
else:
if if_noisy == "X":
qc.x(data_space[i])
elif if_noisy == "Y":
qc.y(data_space[i])
else:
qc.z(data_space[i])
qc.barrier()
## End AES encryption
## spam error
for i in range(n):
if_noisy = is_noisy("spam")
if if_noisy == False:
continue
else:
qc.x(data_space[i])
qc.save_statevector(label="final")
# qc.measure(data_space, classic_reg)
return qc
def get_thermal_error(num_qubits):
t1 = error_list["thermal"][0]
t2 = error_list["thermal"][1]
# nanosecond
time_u1 = 50
time_x = 10
time_h = 10
time_cx = 10
time_cu1 = 10
time_measure = 1000 # 1 microsecond
errors_measure = thermal_relaxation_error(t1, t2, time_measure)
errors_u1 = thermal_relaxation_error(t1, t2, time_u1)
errors_x = thermal_relaxation_error(t1, t2, time_x)
errors_h = thermal_relaxation_error(t1, t2, time_h)
errors_cx = thermal_relaxation_error(t1, t2, time_cx).expand(
thermal_relaxation_error(t1, t2, time_cx))
errors_cu1 = thermal_relaxation_error(t1, t2, time_cu1).expand(
thermal_relaxation_error(t1, t2, time_cu1))
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(errors_u1, "u1")
noise_model.add_all_qubit_quantum_error(errors_x, "x")
noise_model.add_all_qubit_quantum_error(errors_h, "h")
# noise_model.add_all_qubit_quantum_error(errors_cx, "cx")
# noise_model.add_all_qubit_quantum_error(errors_cu1, "cu1")
noise_model.add_all_qubit_quantum_error(errors_measure, "measure")
for i in range(num_qubits - 1):
for j in range(i + 1, num_qubits):
noise_model.add_quantum_error(errors_cx, "cx", [i, j])
noise_model.add_quantum_error(errors_cu1, "cu1", [i, j])
return noise_model
def run_one_sim(qc, if_gpu, error_type):
backend = Aer.get_backend("statevector_simulator")
if if_gpu:
backend.set_options(device="GPU")
if error_type == "thermal":
noise_thermal = get_thermal_error(qc.num_qubits)
job = execute(qc, backend=backend, noise_model=noise_thermal, optimization_level=0)
else:
tqc = transpile(qc, backend)
job = backend.run(tqc)
result = job.result()
state_vector = result.data()["final"]
return state_vector
def VQAA(ansatz, if_back, optimization, max_iter, plain, key, cipher, if_GPU, error_type, threshold, end_prob):
prev_cost = 114514
learning_rate = 0.72
xerr = -9
gd_time = -1
graph = create_graph(degree=3, aes_key_length=len(plain))
cur_iter = 0
theta_list = [math.pi / 4 for _ in range(len(cipher))]
while cur_iter < max_iter:
# 进入一轮优化循环
qc = generate_circuit_with_state_vector(ansatz_type=ansatz, if_back_control=if_back,
plain_text=plain, theta_list=theta_list)
## 获取这一次的测量结果
from time import perf_counter
qc_start_time = perf_counter()
state_vector = run_one_sim(qc=qc, if_gpu=if_GPU, error_type=error_type)
qc_end_time = perf_counter()
qc_run_time = round(qc_end_time - qc_start_time)
## 计算这次的哈密顿量
prob = prob_of_measure_correct_cipher(state_vector, cipher)
expectation = cal_expect_of_ham(g=graph, state_vector=state_vector, cipher=cipher)
print("---"*60)
print(f"Current iter is {cur_iter} . This prob is {prob} . Expectation of Ham is {expectation} . Theta : {theta_list}")
if prob > end_prob:
if_end = 1
else:
if_end = 0
## 通过哈密顿量和theta的值更新下一轮线路的theta
if optimization == "gd":
gd_begin_time = perf_counter()
cost, theta_list = gd(graph, ansatz, if_back, plain, cipher,
if_GPU, error_type, expectation, theta_list, threshold, learning_rate, xerr)
# if (prev_cost - cost) <= threshold:
# if_end = 1
# else:
# prev_cost = cost
gd_end_time = perf_counter()
gd_time = gd_end_time - gd_begin_time
with open(Path(f"./iter_{cur_iter}.txt"), "w") as f:
f.write(f"key : {key}\n")
f.write(f"plaintext : {plain}\n")
f.write(f"cipher : {cipher}\n")
f.write(f"error type : {error_type}\n")
f.write(f"error level : {error_list[error_type]}\n")
f.write(f"ansatz type : {ansatz}\n")
f.write(f"optimization method : {optimization}\n")
f.write(f"if back : {if_back}\n")
f.write(f"max iteration : {max_iter}\n")
f.write(f"if gpu : {if_GPU}\n")
f.write(f"end prob threshold : {end_prob}")
f.write(f"--------------------------------------------------------------------------------------------\n")
f.write(f"current iteration : {cur_iter}\n")
f.write(f"qc run time : {qc_run_time}\n")
f.write(f"gd run time : {gd_time}\n")
f.write(f"correct cipher prob : {prob}\n")
f.write(f"expectation : {expectation}\n")
f.write(f"learning rate : {learning_rate}\n")
f.write(f"xerr : {xerr}\n")
f.write(f"cost : {cost}\n")
f.write(f"optimized theta_list : {theta_list}\n")
f.write(f"if end : {if_end}\n")
if if_end:
return
cur_iter += 1
return
def create_graph(degree, aes_key_length=8):
# G = nx.random_graphs.random_regular_graph(degree, aes_key_length)
G = nx.Graph()
G.add_node(range(0,aes_key_length))
G.add_edge(0, 1)
G.add_edge(0, 6)
G.add_edge(0, 7)
G.add_edge(1, 7)
G.add_edge(1, 3)
G.add_edge(2, 4)
G.add_edge(2, 5)
G.add_edge(2, 7)
G.add_edge(3, 4)
G.add_edge(3, 6)
G.add_edge(4, 5)
G.add_edge(5, 6)
return G
pos = nx.circular_layout(G)
options = {
"with_labels": True,
"font_size": 20,
"font_weight": "bold",
"font_color": "white",
"node_size": 2000,
"width": 2
}
nx.draw_networkx(G, pos, **options)
ax = plt.gca()
ax.margins(0.20)
plt.axis("off")
plt.savefig("g.png", format="png")
return G
def get_corresponding_beta_vector(state_vector, n, single_i, omega_i=-1, omega_j=-1):
# print(state_vector)
normalized_v = state_vector / np.linalg.norm(state_vector)
# print(normalized_v)
if single_i == -1:
prob = np.array([0, 0, 0, 0],dtype=float).reshape((-1, 1))
for i in range(2 ** (2 * n)):
bin_index = bin(i)[2:].rjust(2 * n, '0')
if bin_index[omega_i] == "0" and bin_index[omega_j] == "0":
prob[0] = prob[0] + abs(normalized_v[i]) ** 2
elif bin_index[omega_i] == "0" and bin_index[omega_j] == "1":
prob[1] = prob[1] + abs(normalized_v[i]) ** 2
elif bin_index[omega_i] == "1" and bin_index[omega_j] == "0":
prob[2] = prob[2] + abs(normalized_v[i]) ** 2
elif bin_index[omega_i] == "1" and bin_index[omega_j] == "1":
prob[3] = prob[3] + abs(normalized_v[i]) ** 2
else:
prob = np.array([0, 0], dtype=float).reshape((-1, 1))
for i in range(2 ** (2 * n)):
bin_index = bin(i)[2:].rjust(2 * n, '0')
if bin_index[single_i] == "0":
prob[0] = prob[0] + abs(normalized_v[i]) ** 2
elif bin_index[single_i] == "1":
prob[1] = prob[1] + abs(normalized_v[i]) ** 2
return prob
def cal_expect_of_ham(g: nx.Graph, state_vector, cipher):
"""
:param g: 使用的3-正则图
:param theta_list: 应该是测量的结果向量,如[0,0,1,0,1,0,1,0]
:return:
"""
n = len(cipher)
expectation = 0
edge_list = g.edges
# print(g.edges)
for one_edge in edge_list:
V_i, V_j = one_edge[0], one_edge[1]
if cipher[V_i] == cipher[V_j]:
omega_ij = -1
else:
omega_ij = 1
correspond_theta_vector = get_corresponding_beta_vector(state_vector=state_vector, n=n, single_i=-1, omega_i=V_i, omega_j=V_j)
# print(f"omega i,j de vector is {correspond_theta_vector}")
# print(f"corresponding matrix is {np.kron(pauli_Z, pauli_Z)}")
expectation = expectation + omega_ij * (correspond_theta_vector.T.conjugate() @ (np.kron(pauli_Z, pauli_Z)) @ correspond_theta_vector)
#
for i in range(len(cipher)):
if cipher[i] == "0":
t_i = -0.5
else:
t_i = 0.5
correspond_theta_vector = get_corresponding_beta_vector(state_vector=state_vector, n=n, single_i=i)
# print(f"omega i,j de vector is {correspond_theta_vector}")
# print(f"corresponding matrix is {pauli_Z}")
expectation = expectation + t_i * (correspond_theta_vector.T.conjugate() @ pauli_Z @ correspond_theta_vector)
return expectation[0][0]
def arr2str(vec: np.array):
return ','.join(str(i) for i in vec)
def prob_of_measure_correct_cipher(state_vector, cipher):
n = len(cipher)
prob = 0
normalized_v = state_vector / np.linalg.norm(state_vector)
for i in range(2 ** (2 * n)):
if_add = 1
bin_index = bin(i)[2:].rjust(2 * n, '0')
for j in range(n):
if bin_index[j] != cipher[j]:
if_add = 0
break
if if_add:
prob += (normalized_v[i]) ** 2
return prob
def gd(graph, ansatz, if_back, plain, cipher, if_GPU, error_type, expectation, thetas, threshold, lr=0.72, xerr=-9):
times = 0
x0 = thetas
length = len(x0)
cost = expectation
print("***"*20)
print(f"current theta list is {x0}")
times += 1
Gd = [0] * length
for i in range(length):
x = [t for t in x0]
x[i] += 0.5
qc = generate_circuit_with_state_vector(ansatz_type=ansatz, if_back_control=if_back,
plain_text=plain, theta_list=x)
state_vector = run_one_sim(qc=qc, if_gpu=if_GPU, error_type=error_type)
cost_ = cal_expect_of_ham(g=graph, state_vector=state_vector, cipher=cipher)
print(f"changing the {i}th of parameter of theta list and new cost is {cost_}")
times += 1
Gd[i] = (cost_ - cost) / 0.5
r0 = random.uniform(0, 1)
print(f"current gradient is : {Gd}")
for j in range(length):
x0[j] = x0[j] - (lr / abs(cost) + math.log10(times) / times * r0) * Gd[j]
def abs_sum(some_list):
return sum([abs(tmp) for tmp in some_list])
t_sum = abs_sum(Gd)
if t_sum < 0.8:
x0 = [random.uniform(0, math.pi / 2) for _ in range(length)]
print(f"After one iter of gd, |Gd| is {t_sum}")
for i in range(len(x0)):
x0[i] = x0[i] % (2 * math.pi)
return cost, x0
if __name__ == '__main__':
qc = generate_circuit_with_state_vector("rx", 1, "11110001", "00000010", "11100101",[0,0,0,0,0,0,0])
qc.draw(output='mpl')
matplotlib.pyplot.savefig("m.png")
|
https://github.com/sakthianand7/Bernstein_Vazirani_Algorithm
|
sakthianand7
|
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/calm-cookie/deutsch-jozsa-algorithm
|
calm-cookie
|
import qiskit as q
import numpy as np
import matplotlib as mpl
# the oracle function takes n-bit input
n = 5
# define an unbalanced oracle
def oracle_balanced(n):
size = np.random.randint(n)
random_qubits = set(np.random.randint(n, size=(size)))
qc = q.QuantumCircuit(n + 1)
for qubit in random_qubits:
qc.x(qubit)
for qubit in range(n):
qc.cx(qubit, n)
for qubit in random_qubits:
qc.x(qubit)
return qc
# define a constant oracle that always returns 0
def oracle_zero(n):
qc = q.QuantumCircuit(n + 1)
return qc
# define a constant oracle that always returns 1
def oracle_one(n):
qc = q.QuantumCircuit(n + 1)
qc.x(n)
return qc
# define an oracle function that decides whether to use a 'balanced' or a constant' oracle
def oracle(choice, n):
if choice == 'balanced':
oracle_qc = oracle_balanced(n)
elif choice == 'constant':
random = np.random.randint(2)
if random:
oracle_qc = oracle_one(n)
else:
oracle_qc = oracle_zero(n)
oracle_gate = oracle_qc.to_gate()
oracle_gate.name = "Oracle"
return oracle_gate
# Suppose the function take n-bit strings as input.
# define a query quantum register with n qubits and an answer quantum register with 1 qubit
query = q.QuantumRegister(n, 'query')
answer = q.QuantumRegister(1, 'answer')
classical = q.ClassicalRegister(n)
qc = q.QuantumCircuit(query, answer, classical)
# apply hadamard gates on all query qubits to create a superposition
qc.h(query)
# prepare the answer qubit in state |->
qc.x(answer)
qc.h(answer)
qc.barrier()
# apply the oracle
oracle_gate = oracle('constant', n)
qc.append(oracle_gate, range(n+1))
qc.barrier()
# apply hadamard gates on all query qubits to reverse the superposition
qc.h(query)
# measure the query qubits to calculate the result
qc.measure(query, classical)
qc.draw(output='mpl')
# execute the circuit on a qasm simulator
backend = q.Aer.get_backend('qasm_simulator')
job = q.execute(qc, backend, shots=1000)
result = job.result()
counts = result.get_counts()
graph = q.visualization.plot_histogram(counts)
display(graph)
# If the probability of all zeroes = 1, then the function is constant, otherwise it is balanced
# Hence, a single calculation solved the problem, which classically takes (2^N - 1) steps
|
https://github.com/icarosadero/maxima_function_qiskit
|
icarosadero
|
%matplotlib inline
from qiskit import QuantumCircuit, execute, Aer, IBMQ, QuantumRegister
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
provider = IBMQ.load_account()
circ = QuantumCircuit(4,4)
#Preparation
circ.h(0)
circ.h(1)
#Oracle function
def oracle(circuit, mapping):
if mapping=="a":
"""
100x
010
101x
011
"""
circuit.cx(1,2)
circuit.x(2)
elif mapping=="b":
"""
100x
001
110x
011
"""
circuit.cx(0,2)
circuit.x(2)
elif mapping=="constant":
circuit.x(2)
oracle(circ,"b")
circ.barrier(range(4))
circ.x(2)
circ.ch(2,3)
circ.x(2)
circ.barrier(range(4))
circ.measure(range(4),range(4))
circ.draw("mpl")
nruns = 2048
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(circ, backend_sim, shots=nruns)
result_sim = job_sim.result()
counts = result_sim.get_counts(circ)
plot_histogram(counts)
dict(filter(lambda x: x[1]/nruns >= 0.2,counts.items()))
|
https://github.com/icarosadero/maxima_function_qiskit
|
icarosadero
|
%matplotlib inline
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
provider = IBMQ.load_account()
circ = QuantumCircuit(9,9)
#Hadamard
for i in [6,7,8]:
circ.h(i)
circ.barrier(range(9))
#Function
circ.cx(6,5)
circ.ccx(6,7,4)
circ.cx(8,4)
circ.barrier(range(9))
for i,j in zip([3,4,5],[0,1,2]):
circ.x(i)
circ.ch(i,j)
circ.x(i)
circ.barrier(range(9))
circ.measure(range(9),range(9))
circ.draw("mpl")
nruns = 2048
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(circ, backend_sim, shots=nruns)
result_sim = job_sim.result()
counts = result_sim.get_counts(circ)
plot_histogram(counts)
result_raw = sorted(counts.items(), key=lambda x: x[1], reverse=True)
result = list(map(lambda x: [x[0][:3],x[0][3:6],x[0][6:],x[1]/nruns],result_raw))
result
|
https://github.com/RakhshandaMujib/Deutsch-Joza-Algorithm
|
RakhshandaMujib
|
# initialization
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, transpile
# import basic plot tools
from qiskit.visualization import plot_histogram
# set the length of the n-bit input string.
n = 3
# set the length of the n-bit input string.
n = 3
const_oracle = QuantumCircuit(n+1)
output = np.random.randint(2)
if output == 1:
const_oracle.x(n)
const_oracle.draw()
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
balanced_oracle.draw()
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
balanced_oracle.draw()
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Show oracle
balanced_oracle.draw()
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
dj_circuit.draw()
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit = dj_circuit.compose(balanced_oracle)
dj_circuit.draw()
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit = dj_circuit.compose(balanced_oracle)
# Repeat H-gates
for qubit in range(n):
dj_circuit.h(qubit)
dj_circuit.barrier()
# Measure
for i in range(n):
dj_circuit.measure(i, i)
# Display circuit
dj_circuit.draw()
# use local simulator
aer_sim = Aer.get_backend('aer_simulator')
results = aer_sim.run(dj_circuit).result()
answer = results.get_counts()
plot_histogram(answer)
# ...we have a 0% chance of measuring 000.
assert answer.get('000', 0) == 0
def dj_oracle(case, n):
# We need to make a QuantumCircuit object to return
# This circuit has n+1 qubits: the size of the input,
# plus one output qubit
oracle_qc = QuantumCircuit(n+1)
# First, let's deal with the case in which oracle is balanced
if case == "balanced":
# First generate a random number that tells us which CNOTs to
# wrap in X-gates:
b = np.random.randint(1,2**n)
# Next, format 'b' as a binary string of length 'n', padded with zeros:
b_str = format(b, '0'+str(n)+'b')
# Next, we place the first X-gates. Each digit in our binary string
# corresponds to a qubit, if the digit is 0, we do nothing, if it's 1
# we apply an X-gate to that qubit:
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Do the controlled-NOT gates for each qubit, using the output qubit
# as the target:
for qubit in range(n):
oracle_qc.cx(qubit, n)
# Next, place the final X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Case in which oracle is constant
if case == "constant":
# First decide what the fixed output of the oracle will be
# (either always 0 or always 1)
output = np.random.randint(2)
if output == 1:
oracle_qc.x(n)
oracle_gate = oracle_qc.to_gate()
oracle_gate.name = "Oracle" # To show when we display the circuit
return oracle_gate
def dj_algorithm(oracle, n):
dj_circuit = QuantumCircuit(n+1, n)
# Set up the output qubit:
dj_circuit.x(n)
dj_circuit.h(n)
# And set up the input register:
for qubit in range(n):
dj_circuit.h(qubit)
# Let's append the oracle gate to our circuit:
dj_circuit.append(oracle, range(n+1))
# Finally, perform the H-gates again and measure:
for qubit in range(n):
dj_circuit.h(qubit)
for i in range(n):
dj_circuit.measure(i, i)
return dj_circuit
n = 4
oracle_gate = dj_oracle('balanced', n)
dj_circuit = dj_algorithm(oracle_gate, n)
dj_circuit.draw()
transpiled_dj_circuit = transpile(dj_circuit, aer_sim)
results = aer_sim.run(transpiled_dj_circuit).result()
answer = results.get_counts()
plot_histogram(answer)
# Load our saved IBMQ accounts and get the least busy backend device with greater than or equal to (n+1) qubits
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
transpiled_dj_circuit = transpile(dj_circuit, backend, optimization_level=3)
job = backend.run(transpiled_dj_circuit)
job_monitor(job, interval=2)
# Get the results of the computation
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
# ...the most likely result is 1111.
assert max(answer, key=answer.get) == '1111'
from qiskit_textbook.problems import dj_problem_oracle
oracle = dj_problem_oracle(1)
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/MarvOdo/Quantum-Counting
|
MarvOdo
|
#Implementation of Quantum Counting Algorithm in Qiskit
#By Marvin Odobashi
import numpy as np
from qiskit import *
from qiskit.circuit.library.standard_gates import ZGate
#qubits that determine precision of algorithm
p = 7
#qubits to represent possible inputs to Boolean Function
n = 4
upper = QuantumRegister(p, 'upper')
#1 ancilla qubit to phase shift "correct" states with oracle
lower = QuantumRegister(n+1, 'lower')
measurements = ClassicalRegister(p, 'measurements')
qc = QuantumCircuit(upper, lower, measurements)
#There exists some unknown n-bit input Boolean Function F: {0, 1}^n -> {0, 1}
#Assume we have this oracle that will phase shift solution states
#In this speific case I have picked n=4, but the "solution state selectors" have been defined for a general n
def oracle(qc):
w = qc.width()
#controlled z gate (phase shift state if it is a solution)
ctrlz = ZGate().control(w-1)
#ctrlz for |1111..>
qc.append(ctrlz, range(w))
#ctrlz for |0000..>
qc.x(range(w-1))
qc.append(ctrlz, range(w))
qc.x(range(w-1))
#ctrlz for |10..01>
qc.x(range(1, w-2))
qc.append(ctrlz, range(w))
qc.x(range(1, w-2))
#ctrlz for |01..10>
qc.x([0, w-2])
qc.append(ctrlz, range(w))
qc.x([0, w-2])
#ctrlz for |0111..>
#qc.x([0])
#qc.append(ctrlz, range(w))
#qc.x([0])
#ctrlz for |1011..>
#qc.x([1])
#qc.append(ctrlz, range(w))
#qc.x([1])
return qc
#Grover operator to be repeated
def grover(qc):
w = qc.width()
#oracle
qc = oracle(qc)
#Hadamard-All
qc.h(range(w-1))
#Check if all are 0
ctrlz = ZGate().control(w-1)
qc.x(range(w-1))
qc.append(ctrlz, range(w))
qc.x(range(w-1))
#Hadamard-All
qc.h(range(w-1))
return qc
from qiskit.circuit.library import QFT
#quantum counting
def quantumCount(qc):
#create controlled gate version of grover operation
ctrlGrover = grover(QuantumCircuit(lower)).to_gate(label='CG').control(1)
#initialize circuit, flip last (ancilla) qubit so it can be used for phase shifting by oracle
qc.h(upper)
qc.h(lower[0:-1])
qc.x(lower[-1])
#repeat controlled grover 2^i times for i in {0, p-1}
for i in range(p):
for j in range(2**i):
#controlled grover, ith upper qubit as control, lower register is operated on
qc.append(ctrlGrover, [qc.qubits[i]] + qc.qubits[p:])
#apply inverse QFT on upper register
#using built-in QFT for convenience
iqft = QFT(num_qubits=p, inverse=True).to_gate(label='iQFT')
qc.append(iqft, qc.qubits[:p])
#measure upper register
qc.measure(range(p), range(p))
return qc
#full circuit
final = quantumCount(qc)
#final.draw('mpl')
from qiskit import transpile
from qiskit.providers.aer import AerSimulator
backend = AerSimulator()
qc_compiled = transpile(final, backend)
job_sim = backend.run(qc_compiled, shots=1024)
result_sim = job_sim.result()
counts = result_sim.get_counts(qc_compiled)
#from qiskit.visualization import plot_histogram
#plot_histogram(counts)
#take highest counted state
measured_n = int(max(counts, key=counts.get), 2)
#get theta
theta = 2*np.pi*measured_n/(2**p)
#compute number of solutions
num_sol = (2**n)*np.cos(theta/2)**2
#compute error (formula from https://qiskit.org/textbook/ch-algorithms/quantum-counting.html#finding_m)
N = 2**n
M = N * np.sin(theta / 2)**2
error = (np.sqrt(2*M*N) + N/(2**(p)))*(2**(-p+1))
print(f"""Actual Number of Solutions = 4\n
Quantum Counting Number of Solutions = {num_sol:.1f}\n
Quantum Counting Error < {error:.2f}""")
|
https://github.com/intrinsicvardhan/QuantumComputingAlgos
|
intrinsicvardhan
|
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile
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://docs.quantum.ibm.com/run/primitives
# result = Sampler().run(circuits).result()
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
qc.cx(1,0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set(msg).issubset({"0","1"}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1,0)
qc.h(1)
return qc
# Charlie creates the entangled pair between Alice and Bob
qc = create_bell_pair()
# We'll add a barrier for visual separation
qc.barrier()
message = '11'
qc = encode_message(qc, 1, message)
qc.barrier()
# Alice then sends her qubit to Bob.
# After receiving qubit 0, Bob applies the recovery protocol:
qc = decode_message(qc)
# Finally, Bob measures his qubits to read Alice's message
qc.measure_all()
# Draw our output
qc.draw()
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from numpy import pi
qreg_q = QuantumRegister(3, 'q')
creg_c0 = ClassicalRegister(1, 'c0')
creg_c1 = ClassicalRegister(1, 'c1')
creg_c2 = ClassicalRegister(1, 'c2')
circuit = QuantumCircuit(qreg_q, creg_c0, creg_c1, creg_c2)
#quantum teleportation example
circuit.u(0.3, 0.2, 0.1, qreg_q[0])
#creating the first qubit change the values of theta, phi and lambda to create a different qubit
circuit.h(qreg_q[1])
circuit.cx(qreg_q[1], qreg_q[2])
circuit.barrier(qreg_q)
circuit.cx(qreg_q[0], qreg_q[1])
circuit.h(qreg_q[0])
circuit.measure(qreg_q[0], creg_c0[0])
circuit.measure(qreg_q[1], creg_c1[0])
circuit.z(qreg_q[2]).c_if(creg_c0, 1)
circuit.x(qreg_q[2]).c_if(creg_c1, 1)
circuit.measure(qreg_q[2], creg_c2[0])
circuit.draw()
from qiskit_aer import Aer, AerSimulator
from qiskit.compiler import assemble
qc = QuantumCircuit(2)
qc.h(0)
qc.h(1)
qc.cx(0,1)
qc.h(0)
qc.h(1)
display(qc.draw())
qc.save_unitary()
usim = Aer.get_backend('aer_simulator')
qobj = assemble(qc)
unitary = usim.run(qobj).result().get_unitary()
array_to_latex(unitary, prefix="\\text{Circuit = }\n")
qc = QuantumCircuit(2)
qc.cx(1,0)
display(qc.draw())
qc.save_unitary()
qobj = assemble(qc)
unitary = usim.run(qobj).result().get_unitary()
array_to_latex(unitary, prefix="\\text{Circuit = }\n")
qc = QuantumCircuit(2)
qc.cp(pi/4, 0, 1)
display(qc.draw())
# See Results:
qc.save_unitary()
qobj = assemble(qc)
unitary = usim.run(qobj).result().get_unitary()
array_to_latex(unitary, prefix="\\text{Controlled-T} = \n")
|
https://github.com/intrinsicvardhan/QuantumComputingAlgos
|
intrinsicvardhan
|
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_histogram, plot_bloch_multivector
from numpy.random import randint
import numpy as np
from qiskit_aer import AerSimulator
qc = QuantumCircuit(1,1)
# Alice prepares qubit in state |+>
qc.h(0)
qc.barrier()
# Alice now sends the qubit to Bob
# who measures it in the X-basis
qc.h(0)
qc.measure(0,0)
# Draw and simulate circuit
display(qc.draw())
aer_sim = AerSimulator()
job = aer_sim.run(qc)
plot_histogram(job.result().get_counts())
qc = QuantumCircuit(1,1)
# Alice prepares qubit in state |+>
qc.h(0)
# Alice now sends the qubit to Bob
# but Eve intercepts and tries to read it
qc.measure(0, 0)
qc.barrier()
# Eve then passes this on to Bob
# who measures it in the X-basis
qc.h(0)
qc.measure(0,0)
# Draw and simulate circuit
display(qc.draw())
aer_sim = AerSimulator()
job = aer_sim.run(qc)
plot_histogram(job.result().get_counts())
np.random.seed(seed=0)
n = 100
np.random.seed(seed=0)
n = 100
## Step 1
# Alice generates bits
alice_bits = randint(2, size=n)
print(alice_bits)
np.random.seed(seed=0)
n = 100
## Step 1
#Alice generates bits
alice_bits = randint(2, size=n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = randint(2, size=n)
print(alice_bases)
def encode_message(bits, bases):
message = []
for i in range(n):
qc = QuantumCircuit(1,1)
if bases[i] == 0: # Prepare qubit in Z-basis
if bits[i] == 0:
pass
else:
qc.x(0)
else: # Prepare qubit in X-basis
if bits[i] == 0:
qc.h(0)
else:
qc.x(0)
qc.h(0)
qc.barrier()
message.append(qc)
return message
np.random.seed(seed=0)
n = 100
## Step 1
# Alice generates bits
alice_bits = randint(2, size=n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
print('bit = %i' % alice_bits[0])
print('basis = %i' % alice_bases[0])
message[0].draw()
print('bit = %i' % alice_bits[4])
print('basis = %i' % alice_bases[4])
message[4].draw()
np.random.seed(seed=0)
n = 100
## Step 1
# Alice generates bits
alice_bits = randint(2, size=n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Step 3
# Decide which basis to measure in:
bob_bases = randint(2, size=n)
print(bob_bases)
def measure_message(message, bases):
backend = AerSimulator()
measurements = []
for q in range(n):
if bases[q] == 0: # measuring in Z-basis
message[q].measure(0,0)
if bases[q] == 1: # measuring in X-basis
message[q].h(0)
message[q].measure(0,0)
aer_sim = AerSimulator()
result = aer_sim.run(message[q], shots=1, memory=True).result()
measured_bit = int(result.get_memory()[0])
measurements.append(measured_bit)
return measurements
np.random.seed(seed=0)
n = 100
## Step 1
# Alice generates bits
alice_bits = randint(2, size=n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Step 3
# Decide which basis to measure in:
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
message[0].draw()
message[6].draw()
print(bob_results)
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
np.random.seed(seed=0)
n = 100
## Step 1
# Alice generates bits
alice_bits = randint(2, size=n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Step 3
# Decide which basis to measure in:
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
## Step 4
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
print(alice_key)
np.random.seed(seed=0)
n = 100
## Step 1
# Alice generates bits
alice_bits = randint(2, size=n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Step 3
# Decide which basis to measure in:
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
## Step 4
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
print(bob_key)
def sample_bits(bits, selection):
sample = []
for i in selection:
# use np.mod to make sure the
# bit we sample is always in
# the list range
i = np.mod(i, len(bits))
# pop(i) removes the element of the
# list at index 'i'
sample.append(bits.pop(i))
return sample
np.random.seed(seed=0)
n = 100
## Step 1
# Alice generates bits
alice_bits = randint(2, size=n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Step 3
# Decide which basis to measure in:
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
## Step 4
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
## Step 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))
bob_sample == alice_sample
print(bob_key)
print(alice_key)
print("key length = %i" % len(alice_key))
np.random.seed(seed=3)
np.random.seed(seed=3)
## Step 1
alice_bits = randint(2, size=n)
print(alice_bits)
np.random.seed(seed=3)
## Step 1
alice_bits = randint(2, size=n)
## Step 2
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
print(alice_bases)
message[0].draw()
np.random.seed(seed=3)
## Step 1
alice_bits = randint(2, size=n)
## Step 2
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Interception!!
eve_bases = randint(2, size=n)
intercepted_message = measure_message(message, eve_bases)
print(intercepted_message)
message[0].draw()
np.random.seed(seed=3)
## Step 1
alice_bits = randint(2, size=n)
## Step 2
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Interception!!
eve_bases = randint(2, size=n)
intercepted_message = measure_message(message, eve_bases)
## Step 3
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
message[0].draw()
np.random.seed(seed=3)
## Step 1
alice_bits = randint(2, size=n)
## Step 2
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Interception!!
eve_bases = randint(2, size=n)
intercepted_message = measure_message(message, eve_bases)
## Step 3
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
## Step 4
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
np.random.seed(seed=3)
## Step 1
alice_bits = randint(2, size=n)
## Step 2
alice_bases = randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Interception!!
eve_bases = randint(2, size=n)
intercepted_message = measure_message(message, eve_bases)
## Step 3
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
## Step 4
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
## Step 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))
bob_sample == alice_sample
n = 100
# Step 1
alice_bits = randint(2, size=n)
alice_bases = randint(2, size=n)
# Step 2
message = encode_message(alice_bits, alice_bases)
# Interception!
eve_bases = randint(2, size=n)
intercepted_message = measure_message(message, eve_bases)
# Step 3
bob_bases = randint(2, size=n)
bob_results = measure_message(message, bob_bases)
# Step 4
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
# Step 5
sample_size = 15 # Change this to something lower and see if
# Eve can intercept the message without Alice
# and Bob finding out
bit_selection = randint(n, size=sample_size)
bob_sample = sample_bits(bob_key, bit_selection)
alice_sample = sample_bits(alice_key, bit_selection)
if bob_sample != alice_sample:
print("Eve's interference was detected.")
else:
print("Eve went undetected!")
# import qiskit.tools.jupyter
# %qiskit_version_table
|
https://github.com/intrinsicvardhan/QuantumComputingAlgos
|
intrinsicvardhan
|
# initialization
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, transpile
# import basic plot tools
from qiskit.visualization import plot_histogram
# set the length of the n-bit input string.
n = 3
# set the length of the n-bit input string.
n = 3
const_oracle = QuantumCircuit(n+1)
output = np.random.randint(2)
if output == 1:
const_oracle.x(n)
const_oracle.draw()
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
balanced_oracle.draw()
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
balanced_oracle.draw()
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Show oracle
balanced_oracle.draw()
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
dj_circuit.draw()
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit = dj_circuit.compose(balanced_oracle)
dj_circuit.draw()
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit = dj_circuit.compose(balanced_oracle)
# Repeat H-gates
for qubit in range(n):
dj_circuit.h(qubit)
dj_circuit.barrier()
# Measure
for i in range(n):
dj_circuit.measure(i, i)
# Display circuit
dj_circuit.draw()
# use local simulator
aer_sim = Aer.get_backend('aer_simulator')
results = aer_sim.run(dj_circuit).result()
answer = results.get_counts()
plot_histogram(answer)
# ...we have a 0% chance of measuring 000.
assert answer.get('000', 0) == 0
def dj_oracle(case, n):
# We need to make a QuantumCircuit object to return
# This circuit has n+1 qubits: the size of the input,
# plus one output qubit
oracle_qc = QuantumCircuit(n+1)
# First, let's deal with the case in which oracle is balanced
if case == "balanced":
# First generate a random number that tells us which CNOTs to
# wrap in X-gates:
b = np.random.randint(1,2**n)
# Next, format 'b' as a binary string of length 'n', padded with zeros:
b_str = format(b, '0'+str(n)+'b')
# Next, we place the first X-gates. Each digit in our binary string
# corresponds to a qubit, if the digit is 0, we do nothing, if it's 1
# we apply an X-gate to that qubit:
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Do the controlled-NOT gates for each qubit, using the output qubit
# as the target:
for qubit in range(n):
oracle_qc.cx(qubit, n)
# Next, place the final X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Case in which oracle is constant
if case == "constant":
# First decide what the fixed output of the oracle will be
# (either always 0 or always 1)
output = np.random.randint(2)
if output == 1:
oracle_qc.x(n)
oracle_gate = oracle_qc.to_gate()
oracle_gate.name = "Oracle" # To show when we display the circuit
return oracle_gate
def dj_algorithm(oracle, n):
dj_circuit = QuantumCircuit(n+1, n)
# Set up the output qubit:
dj_circuit.x(n)
dj_circuit.h(n)
# And set up the input register:
for qubit in range(n):
dj_circuit.h(qubit)
# Let's append the oracle gate to our circuit:
dj_circuit.append(oracle, range(n+1))
# Finally, perform the H-gates again and measure:
for qubit in range(n):
dj_circuit.h(qubit)
for i in range(n):
dj_circuit.measure(i, i)
return dj_circuit
n = 4
oracle_gate = dj_oracle('balanced', n)
dj_circuit = dj_algorithm(oracle_gate, n)
dj_circuit.draw()
transpiled_dj_circuit = transpile(dj_circuit, aer_sim)
results = aer_sim.run(transpiled_dj_circuit).result()
answer = results.get_counts()
plot_histogram(answer)
# Load our saved IBMQ accounts and get the least busy backend device with greater than or equal to (n+1) qubits
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
transpiled_dj_circuit = transpile(dj_circuit, backend, optimization_level=3)
job = backend.run(transpiled_dj_circuit)
job_monitor(job, interval=2)
# Get the results of the computation
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
# ...the most likely result is 1111.
assert max(answer, key=answer.get) == '1111'
from qiskit_textbook.problems import dj_problem_oracle
oracle = dj_problem_oracle(1)
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/intrinsicvardhan/QuantumComputingAlgos
|
intrinsicvardhan
|
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/intrinsicvardhan/QuantumComputingAlgos
|
intrinsicvardhan
|
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile
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://docs.quantum.ibm.com/run/primitives
# result = Sampler().run(circuits).result()
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
qc.cx(1,0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set(msg).issubset({"0","1"}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1,0)
qc.h(1)
return qc
# Charlie creates the entangled pair between Alice and Bob
qc = create_bell_pair()
# We'll add a barrier for visual separation
qc.barrier()
message = '11'
qc = encode_message(qc, 1, message)
qc.barrier()
# Alice then sends her qubit to Bob.
# After receiving qubit 0, Bob applies the recovery protocol:
qc = decode_message(qc)
# Finally, Bob measures his qubits to read Alice's message
qc.measure_all()
# Draw our output
qc.draw()
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from numpy import pi
qreg_q = QuantumRegister(3, 'q')
creg_c0 = ClassicalRegister(1, 'c0')
creg_c1 = ClassicalRegister(1, 'c1')
creg_c2 = ClassicalRegister(1, 'c2')
circuit = QuantumCircuit(qreg_q, creg_c0, creg_c1, creg_c2)
#quantum teleportation example
circuit.u(0.3, 0.2, 0.1, qreg_q[0])
#creating the first qubit change the values of theta, phi and lambda to create a different qubit
circuit.h(qreg_q[1])
circuit.cx(qreg_q[1], qreg_q[2])
circuit.barrier(qreg_q)
circuit.cx(qreg_q[0], qreg_q[1])
circuit.h(qreg_q[0])
circuit.measure(qreg_q[0], creg_c0[0])
circuit.measure(qreg_q[1], creg_c1[0])
circuit.z(qreg_q[2]).c_if(creg_c0, 1)
circuit.x(qreg_q[2]).c_if(creg_c1, 1)
circuit.measure(qreg_q[2], creg_c2[0])
circuit.draw()
from qiskit_aer import Aer, AerSimulator
from qiskit.compiler import assemble
qc = QuantumCircuit(2)
qc.h(0)
qc.h(1)
qc.cx(0,1)
qc.h(0)
qc.h(1)
display(qc.draw())
qc.save_unitary()
usim = Aer.get_backend('aer_simulator')
qobj = assemble(qc)
unitary = usim.run(qobj).result().get_unitary()
array_to_latex(unitary, prefix="\\text{Circuit = }\n")
qc = QuantumCircuit(2)
qc.cx(1,0)
display(qc.draw())
qc.save_unitary()
qobj = assemble(qc)
unitary = usim.run(qobj).result().get_unitary()
array_to_latex(unitary, prefix="\\text{Circuit = }\n")
qc = QuantumCircuit(2)
qc.cp(pi/4, 0, 1)
display(qc.draw())
# See Results:
qc.save_unitary()
qobj = assemble(qc)
unitary = usim.run(qobj).result().get_unitary()
array_to_latex(unitary, prefix="\\text{Controlled-T} = \n")
|
https://github.com/intrinsicvardhan/QuantumComputingAlgos
|
intrinsicvardhan
|
print('hello world')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.