Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance gate register mechanism, add visualization of Bloch Sphere #125

Merged
merged 5 commits into from
Dec 17, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 7 additions & 9 deletions quafu/elements/element_gates/c11.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from ..quantum_gate import ControlledGate, FixedGate
from ..quantum_gate import ControlledGate, FixedGate, QuantumGate
from abc import ABC
from quafu.elements.matrices import XMatrix, YMatrix, ZMatrix, SMatrix, TMatrix, pmatrix
from typing import Dict
Expand All @@ -13,6 +13,7 @@ class _C11Gate(ControlledGate, ABC):
ct_dims = (1, 1, 2)


@QuantumGate.register_gate('cx')
class CXGate(_C11Gate, FixedGate):
name = "CX"

Expand All @@ -21,20 +22,23 @@ def __init__(self, ctrl: int, targ: int):
self.symbol = "+"


@QuantumGate.register_gate('cy')
class CYGate(_C11Gate, FixedGate):
name = "CY"

def __init__(self, ctrl: int, targ: int):
_C11Gate.__init__(self, "Y", [ctrl], [targ], None, tar_matrix=YMatrix)


@QuantumGate.register_gate('cz')
class CZGate(_C11Gate, FixedGate):
name = "CZ"

def __init__(self, ctrl: int, targ: int):
_C11Gate.__init__(self, "Z", [ctrl], [targ], None, tar_matrix=ZMatrix)


@QuantumGate.register_gate('cs')
class CSGate(_C11Gate, FixedGate):
name = "CS"

Expand All @@ -45,6 +49,7 @@ def to_qasm(self):
return "cp(pi/2) " + "q[%d],q[%d]" % (self.pos[0], self.pos[1])


@QuantumGate.register_gate('ct')
class CTGate(_C11Gate, FixedGate):
name = "CT"

Expand All @@ -55,6 +60,7 @@ def to_qasm(self):
return "cp(pi/4) " + "q[%d],q[%d]" % (self.pos[0], self.pos[1])


@QuantumGate.register_gate('cp')
class CPGate(_C11Gate):
name = "CP"

Expand All @@ -64,11 +70,3 @@ def __init__(self, ctrl: int, targ: int, paras):
@property
def named_paras(self) -> Dict:
return {'theta': self.paras}


ControlledGate.register_gate(CXGate)
ControlledGate.register_gate(CYGate)
ControlledGate.register_gate(CZGate)
ControlledGate.register_gate(CSGate)
ControlledGate.register_gate(CTGate)
ControlledGate.register_gate(CPGate)
31 changes: 5 additions & 26 deletions quafu/elements/element_gates/cm1.py
Original file line number Diff line number Diff line change
@@ -1,57 +1,36 @@
from ..quantum_gate import ControlledGate, FixedGate
from ..quantum_gate import ControlledGate, FixedGate, QuantumGate
from quafu.elements.matrices import XMatrix, YMatrix, ZMatrix

__all__ = ['MCXGate', 'MCYGate', 'MCZGate', 'ToffoliGate']


@QuantumGate.register_gate('mcx')
class MCXGate(ControlledGate, FixedGate):
name = "MCX"

def __init__(self, ctrls, targ: int):
ControlledGate.__init__(self, "X", ctrls, [targ], None, tar_matrix=XMatrix)


@QuantumGate.register_gate('mcy')
class MCYGate(ControlledGate, FixedGate):
name = "MCY"

def __init__(self, ctrls, targ: int):
ControlledGate.__init__(self, "Y", ctrls, [targ], None, tar_matrix=YMatrix)


@QuantumGate.register_gate('mcz')
class MCZGate(ControlledGate, FixedGate):
name = "MCZ"

def __init__(self, ctrls, targ: int):
ControlledGate.__init__(self, "Z", ctrls, [targ], None, tar_matrix=ZMatrix)



@QuantumGate.register_gate('ccx')
class ToffoliGate(ControlledGate, FixedGate):
name = "CCX"

def __init__(self, ctrl1: int, ctrl2: int, targ: int):
ControlledGate.__init__(self, "X", [ctrl1, ctrl2], [targ], None, tar_matrix=XMatrix)


ControlledGate.register_gate(MCXGate)
ControlledGate.register_gate(MCYGate)
ControlledGate.register_gate(MCZGate)
ControlledGate.register_gate(ToffoliGate)

# deprecated

# class ControlledU(ControlledGate):
# """ Controlled gate class, where the matrix act non-trivially on target qubits"""
# name = 'CU'
#
# def __init__(self, ctrls: List[int], u: Union[SingleQubitGate, MultiQubitGate]):
# self.targ_gate = u
# targs = u.pos
# if isinstance(targs, int):
# targs = [targs]
#
# ControlledGate.__init__(self, u.name, ctrls, targs, u.paras, tar_matrix=self.targ_gate.get_targ_matrix())
#
# def get_targ_matrix(self, reverse_order=False):
# return self.targ_gate.get_targ_matrix(reverse_order)
# ControlledGate.register_gate(ControlledU)
2 changes: 1 addition & 1 deletion quafu/elements/oracle.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ def customize_gate(cls_name: str,
raise ValueError(f"Gate class {cls_name} already exists.")

attrs = {'cls_name': cls_name,
'gate_structure': gate_structure, # TODO: translate
'gate_structure': gate_structure,
'qubit_num': qubit_num,
}

Expand Down
95 changes: 95 additions & 0 deletions quafu/visualisation/bloch_sphere.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import matplotlib.pyplot as plt
import numpy as np

"""
Plotting state of single qubit on the Bloch sphere.

TODO:
1. Plot by density matrix, say, from single-qubit sub-system.
2. Plot geometrical representation of quantum operations.
3. Plot a chain of qubits.
"""


def angles_to_xyz(thetas, phis):
"""Transform angles to cartesian coordinates."""
xs = np.sin(thetas) * np.cos(phis)
ys = np.sin(thetas) * np.sin(phis)
zs = np.cos(thetas)
return xs, ys, zs


def xyz_to_angles(xs, ys, zs):
"""Transform cartesian coordinates to angles."""
phis = np.arctan2(ys, xs)
thetas = np.arccos(zs)
return thetas, phis


def hex_to_rgb(hex_color):
"""Transform a hex color code to RGB (normalized float)."""
hex_color = hex_color.lstrip('#')
if len(hex_color) != 6:
raise ValueError("Invalid hex color code")

r = int(hex_color[0:2], 16) / 255
g = int(hex_color[2:4], 16) / 255
b = int(hex_color[4:6], 16) / 255
return r, g, b


def plot_bloch_vector(v_x, v_y, v_z, title=""):
"""
Plot the Bloch vector on the Bloch sphere.

Args:
v_x (float): x coordinate of the Bloch vector.
v_y (float): y coordinate of the Bloch vector.
v_z (float): z coordinate of the Bloch vector.
title (str): title of the plot.

Returns:
ax: matplotlib axes of the Bloch sphere plot.
"""
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# surface of Bloch sphere
theta = np.linspace(0, np.pi, 21)
phi = np.linspace(0, 2 * np.pi, 21)
theta, phi = np.meshgrid(theta, phi)
x, y, z = angles_to_xyz(theta, phi)

surf = ax.plot_surface(x, y, z, color='white', alpha=0.2)
edge_color = hex_to_rgb('#000000') # #ff7f0e
edge_alpha = 0.05
surf.set_edgecolor((edge_color[0], edge_color[1], edge_color[2], edge_alpha))

# coordinate axes inside the sphere span
span = np.linspace(-1.0, 1.0, 2)
ax.plot(span, 0 * span, zs=0, zdir="z", label="X", lw=1, color="black", alpha=0.5)
ax.plot(0 * span, span, zs=0, zdir="z", label="Y", lw=1, color="black", alpha=0.5)
ax.plot(0 * span, span, zs=0, zdir="y", label="Z", lw=1, color="black", alpha=0.5)

# coordinate values
ax.text(1.4, 0, 0, 'x', color='black')
ax.text(0, 1.2, 0, 'y', color='black')
ax.text(0, 0, 1.2, 'z', color='black')

# Bloch vector
ax.quiver(0, 0, 0, v_x, v_y, v_z, color='r')
v_theta, v_phi = xyz_to_angles(v_x, v_y, v_z)

# coordinates value text
ax.text(0, 0, 1.6, 'Bloch vector: ($\\theta=${:.2f}, $\\varphi$={:.2f})'.format(v_theta, v_phi), fontsize=8, color='red')
# ax.text(0, 0, 1.6, 'Bloch vector: ({:.2f}, {:.2f}, {:.2f})'.format(v_x, v_y, v_z), fontsize=8, color='red')

# Set the range of the axes
ax.set_box_aspect([1, 1, 1])
ax.set_xlim(-1, 1)
ax.set_ylim(-1, 1)
ax.set_zlim(-1, 1)
ax.view_init(32, 32)
ax.set_axis_off()
ax.set_title(title)
return ax
Loading