-
Notifications
You must be signed in to change notification settings - Fork 23
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #124 from chensgit169/stable/0.3
Stable/0.3: some small fixs, add visualization of Bloch Sphere
- Loading branch information
Showing
6 changed files
with
233 additions
and
19 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,119 @@ | ||
from abc import ABCMeta | ||
from quafu.elements import QuantumGate, Instruction | ||
from typing import Dict, Iterable, List | ||
import copy | ||
|
||
|
||
class OracleGateMeta(ABCMeta): | ||
""" | ||
Metaclass to create OracleGate CLASS which is its instance. | ||
""" | ||
|
||
def __init__(cls, name, bases, attrs): | ||
for attr_name in ['cls_name', 'gate_structure', 'qubit_num']: | ||
assert attr_name in attrs, f"OracleGateMeta: {attr_name} not found in {attrs}." | ||
|
||
# TODO: check if instructions inside gate_structure are valid | ||
|
||
super().__init__(name, bases, attrs) | ||
cls.name = attrs.__getitem__('cls_name') | ||
cls.gate_structure = attrs.__getitem__('gate_structure') | ||
cls.qubit_num = attrs.__getitem__('qubit_num') | ||
|
||
|
||
class OracleGate(QuantumGate): # TODO: Can it be related to OracleGateMeta explicitly? | ||
""" | ||
OracleGate is a gate that can be customized by users. | ||
""" | ||
name = None | ||
gate_structure = [] | ||
qubit_num = 0 | ||
|
||
_named_pos = {} | ||
insides = [] | ||
|
||
def __init__(self, pos: List, paras=None, label: str = None): | ||
""" | ||
Args: | ||
pos: position of the gate | ||
paras: parameters of the gate # TODO: how to set paras? | ||
label: label when draw or plot | ||
""" | ||
if not self.qubit_num == len(pos): | ||
raise ValueError(f"OracleGate: qubit number {self.qubit_num} does not match pos length {len(pos)}.") | ||
super().__init__(pos=pos, paras=paras) | ||
|
||
self.__instantiate_gates__() | ||
self.label = label if label is not None else self.name | ||
|
||
@property | ||
def matrix(self): | ||
# TODO: this should be finished according to usage in simulation | ||
# to avoid store very large matrix | ||
raise NotImplemented | ||
|
||
@property | ||
def named_pos(self) -> Dict: | ||
return {'pos': self.pos} | ||
|
||
@property | ||
def named_paras(self) -> Dict: | ||
# TODO: how to manage paras and the names? | ||
return self._named_pos | ||
|
||
def to_qasm(self): | ||
# TODO: this is similar to QuantumCircuit.to_qasm | ||
raise NotImplemented | ||
|
||
def __instantiate_gates__(self) -> None: | ||
""" | ||
Instantiate the gate structure through coping ins and bit mapping. | ||
""" | ||
bit_mapping = {i: p for i, p in enumerate(self.pos)} | ||
|
||
def map_pos(pos): | ||
if isinstance(pos, int): | ||
return bit_mapping[pos] | ||
elif isinstance(pos, Iterable): | ||
return [bit_mapping[p] for p in pos] | ||
else: | ||
raise ValueError | ||
|
||
for gate in self.gate_structure: | ||
gate_ = copy.deepcopy(gate) | ||
for key, val in gate.named_pos.items(): | ||
setattr(gate_, key, map_pos(val)) | ||
setattr(gate_, 'pos', map_pos(gate.pos)) | ||
self.insides.append(gate_) | ||
|
||
|
||
def customize_gate(cls_name: str, | ||
gate_structure: List[Instruction], | ||
qubit_num: int, | ||
): | ||
""" | ||
Helper function to create customized gate class | ||
Args: | ||
cls_name: name of the gate class | ||
gate_structure: a list of instruction INSTANCES | ||
qubit_num: number of qubits of the gate (TODO: extract from gate_structure?) | ||
Returns: | ||
customized gate class | ||
Raises: | ||
ValueError: if gate class already exists | ||
""" | ||
if cls_name in QuantumGate.gate_classes: | ||
raise ValueError(f"Gate class {cls_name} already exists.") | ||
|
||
attrs = {'cls_name': cls_name, | ||
'gate_structure': gate_structure, # TODO: translate | ||
'qubit_num': qubit_num, | ||
} | ||
|
||
customized_cls = OracleGateMeta(cls_name, (OracleGate,), attrs) | ||
assert issubclass(customized_cls, OracleGate) | ||
QuantumGate.register_gate(customized_cls, cls_name) | ||
return customized_cls |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |