mindquantum.io
Input/Output module for MindQuantum.
- class mindquantum.io.BlochScene(config=None)[source]
Display a one qubit quantum state in bloch sphere.
- Parameters
config (Union[dict, str]) – The bloch sphere style configuration. If None, a built-in style configuration will be used. Beside built-in style, we also support a dark style. Default: None.
Examples
>>> import matplotlib.pyplot as plt >>> import numpy as np >>> from mindquantum.core.gates import RX, RZ >>> from mindquantum.io.display import BlochScene >>> state = np.array([1, 1 + 1j])/np.sqrt(3) >>> scene = BlochScene() >>> fig, ax = scene.create_scene() >>> scene.add_state(ax, state) >>> plt.show() >>> n_step = 100 >>> amps = np.zeros((n_step, 2), dtype=np.complex128) >>> for i, angle in enumerate(np.linspace(0, np.pi * 2, n_step)): ... state = RZ(angle).matrix() @ RX(np.pi / 4).matrix() @ np.array([[1], [0]]) ... state = state.T[0] ... amps[i] = state >>> scene = BlochScene('dark') >>> fig, ax = scene.create_scene() >>> scene.add_state(ax, np.array([1, 1 - 1j])/np.sqrt(3), with_proj=False) >>> objs = scene.add_state(ax, amps[0], linecolor='r') >>> anim = scene.animation(fig, ax, objs, amps,history_len=10) >>> plt.show()
- add_3d_arrow(ax, data, *args, **kwargs)[source]
Add a three dimension arrow in given axes.
- Parameters
ax (mpl_toolkits.mplot3d.axes3d.Axes3D) – The three dimension axes you want set 3d arrow.
data (list) – A 6 elements list that include start point coordinate (first three) and the displacement of this arrow.
args (tuple) – The other args for FancyArrowPatch.
kwargs (dict) – The other key word args for FancyArrowPatch.
- add_ket_label(ax, *args, fontsize=None, **kwargs)[source]
Set ket label in given axes.
- Parameters
ax (mpl_toolkits.mplot3d.axes3d.Axes3D) – The three dimension axes you want add ket label.
args (tuple) – The args for ket label of text object in matplotlib.
kwargs (dict) – The key word args for ket label of text object in matplotlib.
fontsize (int) – The fontsize of label. If None, the fontsize will be found in config of BlochScene with key ket_label_fs. Default: None.
- add_state(ax, amp, linecolor=None, linewidth=None, pointcolor=None, pointsize=None, marker=None, projcolor=None, mode=None, with_proj=None, stick_args=None, stick_kwargs=None, point_args=None, point_kwargs=None, proj_args=None, proj_kwargs=None)[source]
Add one quantum state on bloch sphere.
- Parameters
ax (mpl_toolkits.mplot3d.axes3d.Axes3D) – The three dimension axes you want add quantum state.
amp (numpy.ndarray) – The quantum state.
linecolor (str) – The color for stick. If None, it will be found in config in BlochScene with key stick_c. Default: None.
linewidth (numbers.Number) – The line width for stick. If None, it will be found in config in BlochScene with stick_w. Default: None.
pointcolor (str) – The color for point. If None, it will be found in config in BlochScene with key point_c. Default: None.
pointsize (numbers.Number) – The size of point. If None it will be found in config in BlochScene with key point_s. Default: None.
marker (str) – Point marker. If None, it will be found in config in BlochScene with key point_m. Default: None.
projcolor (str) – Project line color. If None it will be found in config in BlochScene with key proj_c. Default: None.
mode (str) – How to display the quantum state. Can be one of ‘stick’, ‘point’, ‘both’. If None, if will be found in config of BlochScene with key state_mode. Default: None.
with_proj (bool) – Whether to display the projection line alone x, y and z axis. If None, it will be found in config in BlochScene with key with_proj. Default: None.
stick_args (tuple) – The other args for stick. These args will be send to Axes3D.plot. Default: None.
stick_kwargs (dict) – The other key word args for stick. These args will be send to Axes3D.plot. Default: None.
point_args (tuple) – The other args for point. These args will be send to Axes3D.scatter. Default: None.
point_kwargs (dict) – The other key word args for point. These args will be send to Axes3D.scatter. Default: None.
proj_args (tuple) – The other args for projection line. These args will be send to Axes3D.plot. Default: None.
proj_kwargs (dict) – The other key word args for projection line. These args will be send to Axes3D.plot. Default: None.
- Returns
dict, a dict of object of stick, point, and projection line.
- animation(fig, ax, objs, new_amps: np.ndarray, interval=15, with_trace=True, history_len=None, **kwargs)[source]
Animate a quantum state on bolch sphere.
- Parameters
fig (matplotlib.figure.Figure) – The bloch sphere scene figure.
ax (mpl_toolkits.mplot3d.axes3d.Axes3D) – The axes of bloch sphere scene.
objs (dict) – The objects generated by BlochScene.add_state.
new_amps (numpy.ndarray) – All quantum state you want to animate.
interval (int) – Delay between frames in milliseconds. Default: 15.
with_trace (bool) – Whether to display the trace of quantum state. Default: True.
history_len (int) – The trace length. If None, it will be the length of given quantum states. Defaults: None.
kwargs (dict) – The other key word args for animation.FuncAnimation.
- Returns
animation.FuncAnimation, the animation object in matplotlib.
- circle_xy(ax, *args, angle=np.pi / 2, **kwargs)[source]
Plot circle in xy plane.
- Parameters
ax (mpl_toolkits.mplot3d.axes3d.Axes3D) – The three dimension axes you want add circle parallel with xy plane.
args (tuple) – The args of Axes3D.plot.
angle (numbers.Number) – Elevation angle of circle along z axis. Default: π / 2.
kwargs (dict) – The key word args for Axes3D.plot.
- circle_yz(ax, *args, angle=0, **kwargs)[source]
Plot circle in yz plane.
- Parameters
ax (mpl_toolkits.mplot3d.axes3d.Axes3D) – The three dimension axes you want add ket label.
args (tuple) – The args of Axes3D.plot.
angle (numbers.Number) – Rotate angle of circle around z axis. Default: 0.
kwargs (dict) – The key word args for Axes3D.plot.
- gen_fig_ax(boxes=None)[source]
Add three dimension scene.
- Parameters
boxes (list) – A float list with 4 elements that are left, bottom, width, height of this scene. If None, then left and bottom will be 0 and width and height will be 1. Default: None.
- plot_slice(ax, x, y, z, frame_color, frame_alpha, surface_color, surface_alpha, frame_args=None, frame_kwargs=None, surface_args=None, surface_kwargs=None)[source]
Plot reference surface in xy, yz and zx plane.
- Parameters
ax (mpl_toolkits.mplot3d.axes3d.Axes3D) – The three dimension axes you want to add reference surface.
x (numpy.ndarray) – The x coordinate of reference plane.
y (numpy.ndarray) – The y coordinate of reference plane.
z (numpy.ndarray) – The z coordinate of reference plane.
frame_color (str) – The wire frame color.
frame_alpha (numbers.Number) – The frame transparency.
surface_color (str) – The surface color.
surface_alpha (numbers.Number) – The surface transparency.
frame_args (tuple) – The other args for Axes3D.plot_wireframe.
frame_kwargs (dict) – The other key word args for Axes3D.plot_wireframe.
surface_args (tuple) – The other args for Axes3D.plot_surface.
surface_kwargs (dict) – The other key word args for Axes3D.plot_surface.
- set_view(ax, elev=0, azim=0)[source]
Fit the view to bloch sphere.
- Parameters
ax (mpl_toolkits.mplot3d.axes3d.Axes3D) – The three dimension axes you want to set view.
elev (numbers.Number) – stores the elevation angle in the z plane (in degrees). Default: 0.
azim (numbers.Number) – stores the azimuth angle in the (x, y) plane (in degrees). Default: 0.
- static state_to_cor(amp: np.ndarray)[source]
Convert one qubit state to three dimension coordinate.
- Parameters
amp (numpy.ndarray) – One qubit quantum state.
- Returns
numpy.ndarray, three dimension coordinate.
- update(objs: dict, new_amp: np.ndarray)[source]
Update quantum state in bloch sphere.
Update the quantum state in bloch sphere for a given objs generated by
mindquantum.io.BlochScene.add_state
and a given quantum state.- Parameters
objs (dict) – The objects generated by
mindquantum.io.BlochScene.add_state
.new_amp (numpy.ndarray) – The new quantum state.
- class mindquantum.io.HiQASM[source]
Convert a circuit to HiQASM format.
Examples
>>> import numpy as np >>> from mindquantum.io.qasm import HiQASM >>> from mindquantum.core import Circuit >>> circuit = Circuit().rx(0.3, 0).z(0, 1).zz(np.pi, [0, 1]) >>> HiQASM = HiQASM() >>> circuit_str = HiQASM.to_string(circuit) >>> print(circuit_str[68: 80]) CZ q[1],q[0] >>> circuit_2 = HiQASM.from_string(circuit_str) >>> circuit_2 q0: ──RX(3/10)────Z────ZZ(π)── │ │ q1: ──────────────●────ZZ(π)──
- from_file(file_name)[source]
Read a HiQASM file.
- Parameters
file_name (str) – The path of file that stored quantum circuit in HiQASM format.
- Returns
Circuit, the quantum circuit translated from HiQASM file.
- from_string(string)[source]
Read a HiQASM string.
- Parameters
string (str) – The HiQASM string of a Circuit.
- Returns
Circuit, The quantum circuit translated from HiQASM string.
- to_file(file_name, circuit, version='0.1')[source]
Convert a quantum circuit to HiQASM format and save in file.
- Parameters
- Raises
- to_string(circuit, version='0.1')[source]
Convert circuit to HiQASM.
- Parameters
- Returns
str, The HiQASM format of input circuit.
- Raises
TypeError – if circuit is not a Circuit.
TypeError – if version is not a str.
NotImplementedError – if HiQASM version not implement.
ValueError – if gate not implement in this version.
- class mindquantum.io.OpenQASM[source]
Convert a circuit to openqasm format.
Examples
>>> import numpy as np >>> from mindquantum.core import Circuit >>> from mindquantum.io import OpenQASM >>> circuit = Circuit().rx(0.3, 0).z(0, 1).zz(np.pi, [0, 1]) >>> openqasm = OpenQASM() >>> circuit_str = openqasm.to_string(circuit) >>> circuit_str[47:60] 'rx(0.3) q[0];'
- from_file(file_name)[source]
Read a openqasm file.
- Parameters
file_name (str) – The path of file that stored quantum circuit in openqasm format.
- Returns
Circuit, the quantum circuit translated from openqasm file.
- to_file(file_name, circuit, version='2.0')[source]
Convert a quantum circuit to openqasm format and save in file.
- Parameters
- Raises
- to_string(circuit, version='2.0')[source]
Convert circuit to openqasm.
- Parameters
- Returns
str, The openqasm format of input circuit.
- Raises
TypeError – if circuit is not a Circuit.
TypeError – if version is not a str.
NotImplementedError – if openqasm version not implement.
ValueError – if gate not implement in this version.
- mindquantum.io.bprint(strings: list, align=':', title='', v_around='=', h_around='|', fill_char=' ')[source]
Print the information in block shape.
- Parameters
align (str) – The align char alone vertal direction. Default: “:”.
title (str) – The title of this information block. Default: “”.
v_around (str) – Vertical boundary char. Default: “=”.
h_around (str) – horizontal boundary char. Default: “|”.
fill_char (str) – Empty space fill with this char. Default: ” “.
- Returns
list, a list of formatted string.
Examples
>>> from mindquantum.io import bprint >>> title='Info of Bob' >>> o = bprint(['Name:Bob', 'Age:17', 'Nationality:China'], ... title=title) >>> for i in o: ... print(i) ====Info of Bob==== |Name :Bob | |Age :17 | |Nationality:China| ===================
- mindquantum.io.random_hiqasm(n_qubits, gate_num, version='0.1', seed=42)[source]
Generate random HiQASM supported circuit.
- Parameters
- Returns
str, quantum circuit in HIQASM format.
Examples
>>> from mindquantum.io import random_hiqasm >>> from mindquantum.io import HiQASM >>> HiQASM_str = random_hiqasm(2, 5) >>> HiQASM = HiQASM() >>> circuit = HiQASM.from_string(HiQASM_str) >>> circuit q0: ──RZ(-2.513)────RZ(-3.012)────RX(0.738)────M(k0)─────────── │ q1: ──────S───────────────────────────●──────────Z──────M(k1)──