• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

使用python编写量子线路打印的简单项目,并使用Sphinx自动化生成API文档

python 陆言君 2464次浏览 0个评论

技术背景

该文章一方面从量子线路的打印着手,介绍了一个简单的python量子线路工程。同时基于这个简单的小工程,我们顺带的介绍了python的API文档自动化生成工具Sphinx的基本使用方法。

量子线路背景知识

在前面几篇博客中,有介绍过使用开源量子计算编程框架ProjectQ进行量子线路的绘制,会给我们输出一个tex格式的线路图,在文章中可以直接使用。关于量子线路与量子逻辑门操作,在这篇博客中有比较初步的介绍。而本文章中所创建的工程,是直接在cmd窗口里面打印输出字符串形式的量子线路,同样的,在量子计算资源估计和量子线路工程中,可以产生一定的作用。

自动化文档生成的方案

对于一个比较优雅的python开源项目来说,一份简介的文档是必不可少的。一般一个python项目的文档有两部分组成:一部分是用markdown撰写的使用说明文档,其宗旨在于概述的介绍整个项目的重点内容,以及可能包含少部分的使用示例。这部分的文档可以先用markdown写,然后通过一些开源工具,如mkdocs等转换成read_the_docs格式的文档。read_the_docs格式的文档大概如下图所示,也可以直接参考其官方文档。而文档的第二个部分则是具体到每个函数、每个类的接口文档。在开发阶段,我们先按照格式要求写好注释文档,然后通过开源工具Sphinx就可以自动化的生成API接口文档。
使用python编写量子线路打印的简单项目,并使用Sphinx自动化生成API文档

安装sphinx

这里我们直接使用python的包管理工具pip来安装Sphinx以及一个read_the_docs格式的python库。如果不需要使用read_the_docs格式也可以不安装后者,只是后者在python的开源项目中还是最常用的一种文档格式,并且可以配合read_the_docs网站进行API文档的托管,因此推荐使用。

[dechin@dechin-manjaro circuit]$ python3 -m pip install sphinx
Requirement already satisfied: sphinx in /home/dechin/anaconda3/lib/python3.8/site-packages (3.4.3)
Requirement already satisfied: sphinxcontrib-htmlhelp in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx) (1.0.3)
Requirement already satisfied: docutils>=0.12 in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx) (0.16)
Requirement already satisfied: sphinxcontrib-devhelp in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx) (1.0.2)
Requirement already satisfied: sphinxcontrib-serializinghtml in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx) (1.1.4)
Requirement already satisfied: sphinxcontrib-jsmath in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx) (1.0.1)
Requirement already satisfied: alabaster<0.8,>=0.7 in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx) (0.7.12)
Requirement already satisfied: Pygments>=2.0 in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx) (2.7.2)
Requirement already satisfied: requests>=2.5.0 in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx) (2.24.0)
Requirement already satisfied: babel>=1.3 in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx) (2.8.1)
Requirement already satisfied: sphinxcontrib-applehelp in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx) (1.0.2)
Requirement already satisfied: Jinja2>=2.3 in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx) (2.11.2)
Requirement already satisfied: snowballstemmer>=1.1 in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx) (2.0.0)
Requirement already satisfied: setuptools in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx) (50.3.1.post20201107)
Requirement already satisfied: sphinxcontrib-qthelp in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx) (1.0.3)
Requirement already satisfied: packaging in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx) (20.4)
Requirement already satisfied: imagesize in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx) (1.2.0)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /home/dechin/anaconda3/lib/python3.8/site-packages (from requests>=2.5.0->sphinx) (1.25.11)
Requirement already satisfied: certifi>=2017.4.17 in /home/dechin/anaconda3/lib/python3.8/site-packages (from requests>=2.5.0->sphinx) (2020.6.20)
Requirement already satisfied: chardet<4,>=3.0.2 in /home/dechin/anaconda3/lib/python3.8/site-packages (from requests>=2.5.0->sphinx) (3.0.4)
Requirement already satisfied: idna<3,>=2.5 in /home/dechin/anaconda3/lib/python3.8/site-packages (from requests>=2.5.0->sphinx) (2.10)
Requirement already satisfied: pytz>=2015.7 in /home/dechin/anaconda3/lib/python3.8/site-packages (from babel>=1.3->sphinx) (2020.1)
Requirement already satisfied: MarkupSafe>=0.23 in /home/dechin/anaconda3/lib/python3.8/site-packages (from Jinja2>=2.3->sphinx) (1.1.1)
Requirement already satisfied: six in /home/dechin/anaconda3/lib/python3.8/site-packages (from packaging->sphinx) (1.15.0)
Requirement already satisfied: pyparsing>=2.0.2 in /home/dechin/anaconda3/lib/python3.8/site-packages (from packaging->sphinx) (2.4.7)
[dechin@dechin-manjaro circuit]$ python3 -m pip install sphinx-rtd-theme
Collecting sphinx-rtd-theme
  Downloading sphinx_rtd_theme-0.5.1-py2.py3-none-any.whl (2.8 MB)
     |████████████████████████████████| 2.8 MB 74 kB/s 
Requirement already satisfied: sphinx in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx-rtd-theme) (3.5.1)
Requirement already satisfied: sphinxcontrib-jsmath in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx->sphinx-rtd-theme) (1.0.1)
Requirement already satisfied: snowballstemmer>=1.1 in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx->sphinx-rtd-theme) (2.0.0)
Requirement already satisfied: sphinxcontrib-serializinghtml in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx->sphinx-rtd-theme) (1.1.4)
Requirement already satisfied: imagesize in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx->sphinx-rtd-theme) (1.2.0)
Requirement already satisfied: alabaster<0.8,>=0.7 in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx->sphinx-rtd-theme) (0.7.12)
Requirement already satisfied: requests>=2.5.0 in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx->sphinx-rtd-theme) (2.24.0)
Requirement already satisfied: docutils>=0.12 in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx->sphinx-rtd-theme) (0.16)
Requirement already satisfied: setuptools in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx->sphinx-rtd-theme) (50.3.1.post20201107)
Requirement already satisfied: Pygments>=2.0 in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx->sphinx-rtd-theme) (2.7.2)
Requirement already satisfied: packaging in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx->sphinx-rtd-theme) (20.4)
Requirement already satisfied: sphinxcontrib-devhelp in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx->sphinx-rtd-theme) (1.0.2)
Requirement already satisfied: sphinxcontrib-applehelp in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx->sphinx-rtd-theme) (1.0.2)
Requirement already satisfied: sphinxcontrib-qthelp in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx->sphinx-rtd-theme) (1.0.3)
Requirement already satisfied: sphinxcontrib-htmlhelp in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx->sphinx-rtd-theme) (1.0.3)
Requirement already satisfied: babel>=1.3 in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx->sphinx-rtd-theme) (2.8.1)
Requirement already satisfied: Jinja2>=2.3 in /home/dechin/anaconda3/lib/python3.8/site-packages (from sphinx->sphinx-rtd-theme) (2.11.2)
Requirement already satisfied: idna<3,>=2.5 in /home/dechin/anaconda3/lib/python3.8/site-packages (from requests>=2.5.0->sphinx->sphinx-rtd-theme) (2.10)
Requirement already satisfied: chardet<4,>=3.0.2 in /home/dechin/anaconda3/lib/python3.8/site-packages (from requests>=2.5.0->sphinx->sphinx-rtd-theme) (3.0.4)
Requirement already satisfied: certifi>=2017.4.17 in /home/dechin/anaconda3/lib/python3.8/site-packages (from requests>=2.5.0->sphinx->sphinx-rtd-theme) (2020.6.20)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /home/dechin/anaconda3/lib/python3.8/site-packages (from requests>=2.5.0->sphinx->sphinx-rtd-theme) (1.25.11)
Requirement already satisfied: pyparsing>=2.0.2 in /home/dechin/anaconda3/lib/python3.8/site-packages (from packaging->sphinx->sphinx-rtd-theme) (2.4.7)
Requirement already satisfied: six in /home/dechin/anaconda3/lib/python3.8/site-packages (from packaging->sphinx->sphinx-rtd-theme) (1.15.0)
Requirement already satisfied: pytz>=2015.7 in /home/dechin/anaconda3/lib/python3.8/site-packages (from babel>=1.3->sphinx->sphinx-rtd-theme) (2020.1)
Requirement already satisfied: MarkupSafe>=0.23 in /home/dechin/anaconda3/lib/python3.8/site-packages (from Jinja2>=2.3->sphinx->sphinx-rtd-theme) (1.1.1)
Installing collected packages: sphinx-rtd-theme
Successfully installed sphinx-rtd-theme-0.5.1

基于python的量子线路打印小项目

我们先看一下使用的方法以及效果,再回过头来分析代码实现的原理:

if __name__ == '__main__':
    qc = QuantumCircuit(3)
    qc.apply(0, 0)
    qc.apply(1, (1,0))
    qc.apply(1, (2,1))
    qc.apply(1, (2,0))
    qc.apply(2)
    print (qc)

输出结果如下所示(注意使用等宽字体):

 |0>     |0>     |0>     
  |       |       | 
  |       |       h 
  |       |       | 
  |       x ----- c 
  |       |       | 
  x ----- c       | 
  |       |       | 
  x ----- | ----- c 
  |       |       | 
  m       m       m 

这里我们就可以了解到,这个项目的核心功能就是通过构造一个量子线路的对象,并且对这个对象逐一的施加量子门操作,就可以输出成对应的量子线路字符串。接下来我们再看看源码实现:

# qcprinter.py
"""
The module used for print a quantum circuit in string format.
"""

class QuantumCircuit:
    """The class of quantum circuit from input quantum logical gates.
    
    Parameters
        ----------
        qubits : int
            Totcal number of qubits used in this quantum circuit.
    
    Returns
        -------
        str
            The string format of quantum circuit.
            
    How to use?
        -------

        >>> qc = QuantumCircuit(3)
        >>> qc.apply(0, 0)
        >>> qc.apply(1, (1,0))
        >>> qc.apply(1, (2,1))
        >>> qc.apply(1, (2,0))
        >>> qc.apply(2)
        >>> print (qc)
    Example output
        -------
    
        >>>  |0>     |0>     |0>     
        >>>   |       |       | 
        >>>   |       |       h 
        >>>   |       |       | 
        >>>   |       x ----- c 
        >>>   |       |       | 
        >>>   x ----- c       | 
        >>>   |       |       | 
        >>>   x ----- | ----- c 
        >>>   |       |       | 
        >>>   m       m       m 
    """
    def __init__(self, qubits=0):
        self.qubits = qubits
        self.str_circuit = ' |0>\t' * self.qubits + ' \n'
    
    def __str__(self):
        return self.str_circuit
    
    def apply(self, gate_type, qubit_index=0):
        """The function used to apply quantum logical gates on quantum state.
        
        Parameters
            ----------
            gate_type : int
                An index number represents for different type of quantum logical gates. 0 for h gate, 
                1 for cx gate and 2 for measure gate.
            qubit_index: int, tuple, none
                The qubit index quantum logical gates allpied on. If the gate_type is h, the qubit_index
                would be int format. If the gate_type is cx, the qubit_index should be a tuple. If the 
                gate_type is m, that means do measurement to all qubits, thus you do not need to set
                the value of qubit_index.
    
        Returns
            -------
            str
                The string format of quantum circuit.
        """
        if gate_type == 0:
            self.str_circuit += '  | \t' * self.qubits + '\n'
            self.str_circuit += '  | \t' * (self.qubits - qubit_index - 1) + '  h \t' + '  | \t' * (qubit_index) + '\n'
        elif gate_type == 1:
            self.str_circuit += '  | \t' * self.qubits + '\n'
            self.str_circuit += '  | \t' * (self.qubits - qubit_index[0] - 1) + '  x'
            for i in range(qubit_index[0] - qubit_index[1] - 1):
                self.str_circuit += ' ' + '-' * 5 + ' |'
            self.str_circuit +=  ' ' + '-' * 5 + ' c \t'
            self.str_circuit += '  | \t' * (qubit_index[1]) + '\n'
        elif gate_type == 2:
            self.str_circuit += '  | \t' * self.qubits + '\n'
            self.str_circuit += '  m \t' * self.qubits + '\n'
        else:
            pass

在这个简单的代码实现中,我们主要是为量子线路的类设置了一个魔法函数__str__,将我们所需要的量子线路的字符串作为整个对象的字符串返回值(关于python的魔法函数的使用方法可以参考前面这篇博客介绍)。这个字符串的类的核心功能是通过字符串拼接来实现的,我们不过多的赘述。这里为了方便操作,我们将量子逻辑门操作使用整型数字来替代:0代表\(H\)门,1代表\(CNOT\)门,2代表全局的量子测量操作。同时,为了展示API文档的制作过程,这里我们在类与函数内都写了一部分的示例注释代码,在下一个章节介绍一下文档的效果。

sphinx文档生成与效果一览

首先使用sphinx-quickstart来生成一些配置文件:

[dechin@dechin-manjaro circuit]$ sphinx-quickstart
欢迎使用 Sphinx 3.5.1 快速配置工具。

Please enter values for the following settings (just press Enter to
accept a default value, if one is given in brackets).

Selected root path: .

You have two options for placing the build directory for Sphinx output.
Either, you use a directory "_build" within the root path, or you separate
"source" and "build" directories within the root path.
> 独立的源文件和构建目录(y/n) [n]: y

The project name will occur in several places in the built documentation.
> 项目名称: qcprinter
> 作者名称: DechinPhy
> 项目发行版本 []: 1.0

If the documents are to be written in a language other than English,
you can select a language here by its language code. Sphinx will then
translate text that it generates into that language.

For a list of supported codes, see
https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-language.
> 项目语种 [en]: en

创建文件 /home/dechin/projects/2021-quantum/circuit/source/conf.py。
创建文件 /home/dechin/projects/2021-quantum/circuit/source/index.rst。
创建文件 /home/dechin/projects/2021-quantum/circuit/Makefile。
创建文件 /home/dechin/projects/2021-quantum/circuit/make.bat。

完成:已创建初始目录结构。

You should now populate your master file /home/dechin/projects/2021-quantum/circuit/source/index.rst and create other documentation
source files. Use the Makefile to build the docs, like so:
   make builder
where "builder" is one of the supported builders, e.g. html, latex or linkcheck.

在这一系列的配置之后,会在当前目录下生成几个新的文件(由于我们选择了build和source分离的模式,因此这里会有2个目录):

[dechin@dechin-manjaro circuit]$ ll
总用量 52
drwxr-xr-x 2 dechin dechin  4096  2月 23 00:04 build
-rw-r--r-- 1 dechin dechin   799  2月 23 00:04 make.bat
-rw-r--r-- 1 dechin dechin   638  2月 23 00:04 Makefile
-rw-r--r-- 1 dechin dechin  3055  2月 22 23:26 qcprinter.py
drwxr-xr-x 4 dechin dechin  4096  2月 23 00:04 source

在source目录下会产生一些配置文件,这里我们需要修改其中的conf.py文件:

[dechin@dechin-manjaro circuit]$ cd source/
[dechin@dechin-manjaro source]$ ll
总用量 16
-rw-r--r-- 1 dechin dechin 1884  2月 23 00:04 conf.py
-rw-r--r-- 1 dechin dechin  443  2月 23 00:04 index.rst
drwxr-xr-x 2 dechin dechin 4096  2月 23 00:04 _static
drwxr-xr-x 2 dechin dechin 4096  2月 23 00:04 _templates

可以参考楼主的配置方案,这里我们主要是将主题配置成了rtd的格式,同时打开了autodoc的选项以及通过sys配置了索引目录(索引目录不配置的话,有可能导致找不到模块,从而无法正常的生成API接口文档):

[dechin@dechin-manjaro circuit]$ cat source/conf.py 
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

# -- Path setup --------------------------------------------------------------

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath('..'))


# -- Project information -----------------------------------------------------

project = 'qcprinter'
copyright = '2021, DechinPhy'
author = 'DechinPhy'

# The full version, including alpha/beta/rc tags
release = '1.0'


# -- General configuration ---------------------------------------------------
import sphinx_rtd_theme
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ["sphinx_rtd_theme", "sphinx.ext.autodoc", "sphinx.ext.autosummary"
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = []


# -- Options for HTML output -------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

执行sphinx-build指令将source中的rst文档编译成html文档,并输出到build目录下:

[dechin@dechin-manjaro circuit]$ sphinx-build source/ build/
正在运行 Sphinx v3.5.1
加载 pickled环境... 完成
构建 [mo]: 0 个 po 文件的目标文件已过期
构建 [html]: 0 个源文件的目标文件已过期
更新环境: 已添加 0,1 已更改,0 已移除
阅读源... [100%] qcprinter                                                                                                                                                                                                                     
/home/dechin/projects/2021-quantum/circuit/qcprinter.py:docstring of qcprinter.QuantumCircuit:4: WARNING: Unexpected section title or transition.

----------
/home/dechin/projects/2021-quantum/circuit/qcprinter.py:docstring of qcprinter.QuantumCircuit:9: WARNING: Unexpected section title or transition.

-------
/home/dechin/projects/2021-quantum/circuit/qcprinter.py:docstring of qcprinter.QuantumCircuit:14: WARNING: Unexpected section title or transition.

-------
/home/dechin/projects/2021-quantum/circuit/qcprinter.py:docstring of qcprinter.QuantumCircuit:24: WARNING: Unexpected section title or transition.

-------
/home/dechin/projects/2021-quantum/circuit/qcprinter.py:docstring of qcprinter.QuantumCircuit.apply:4: WARNING: Unexpected section title or transition.

----------
/home/dechin/projects/2021-quantum/circuit/qcprinter.py:docstring of qcprinter.QuantumCircuit.apply:15: WARNING: Unexpected section title or transition.

-------
查找当前已过期的文件... 没有找到
pickling环境... 完成
检查一致性... /home/dechin/projects/2021-quantum/circuit/source/modules.rst: WARNING: 文档没有加入到任何目录树中
完成
准备文件... 完成
写入输出... [ 33%] index                                                                                                                                                                                                                    写入输出... [ 66%] modules                                                                                                                                                                                                                  写入输出... [100%] qcprinter                                                                                                                                                                                                                    
generating indices... genindex py-modindex 完成
writing additional pages... search 完成
copying static files... 完成
copying extra files... 完成
dumping search index in English (code: en)... 完成
dumping object inventory... 完成
build 成功, 7 warnings.

HTML 页面保存在 build 目录。

在这个执行的过程中,有一部分的告警是跟注释规范相关的,其实不用处理也没有关系。接下来就可以打开build目录,查看已经生成成功的html文档,首先我们可以打开index.html,是常用的网页主页索引,大概内容如下图所示:
使用python编写量子线路打印的简单项目,并使用Sphinx自动化生成API文档
我们先点击这里的index和module看看内容,分别为下列的两个图所示:
使用python编写量子线路打印的简单项目,并使用Sphinx自动化生成API文档
使用python编写量子线路打印的简单项目,并使用Sphinx自动化生成API文档
最后在这个索引列表中我们点击进入qcprinter这个类中,去查看详细的类的文档说明:
使用python编写量子线路打印的简单项目,并使用Sphinx自动化生成API文档
相应的函数注释内容也会在接口文档中体现:
使用python编写量子线路打印的简单项目,并使用Sphinx自动化生成API文档
需要注意的是,如果相关的类或者函数是受保护的类型,那么在sphinx生成的文档中是不会显示的(构造过程中自动忽略)。

总结概要

在这篇文章中,我们主要通过一个量子线路打印的python项目介绍,也顺带通过sphinx将python项目的注释文档自动化的生成API接口文档,完成了一个项目开发及文档输出流程的简要分析,在实战中掌握更多的工具使用方法。

版权声明

本文首发链接为:https://www.cnblogs.com/dechinphy/p/qcprinter.html
作者ID:DechinPhy
更多原著文章请参考:https://www.cnblogs.com/dechinphy/


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明使用python编写量子线路打印的简单项目,并使用Sphinx自动化生成API文档
喜欢 (0)

您必须 登录 才能发表评论!

加载中……