百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程字典 > 正文

使用Python编写量子线路打印项目,并使用Sphinx生成API文档

toyiye 2024-09-07 20:34 3 浏览 0 评论

目录

  • 技术背景
    • 量子线路背景知识
    • 自动化文档生成的方案
  • 安装sphinx
  • 基于python的量子线路打印小项目
  • sphinx文档生成与效果一览
  • 补充说明(2021.03.27)
  • 总结概要
  • 版权声明

技术背景

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

量子线路背景知识

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

自动化文档生成的方案

对于一个比较优雅的python开源项目来说,一份简介的文档是必不可少的。一般一个python项目的文档有两部分组成:一部分是用markdown撰写的使用说明文档,其宗旨在于概述的介绍整个项目的重点内容,以及可能包含少部分的使用示例。这部分的文档可以先用markdown写,然后通过一些开源工具,如mkdocs等转换成read_the_docs格式的文档。read_the_docs格式的文档大概如下图所示,也可以直接参考其官方文档。而文档的第二个部分则是具体到每个函数、每个类的接口文档。在开发阶段,我们先按照格式要求写好注释文档,然后通过开源工具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: 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代表HH门,1代表CNOTCNOT门,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,是常用的网页主页索引,大概内容如下图所示:


我们先点击这里的index和module看看内容,分别为下列的两个图所示:



最后在这个索引列表中我们点击进入qcprinter这个类中,去查看详细的类的文档说明:


相应的函数注释内容也会在接口文档中体现:


需要注意的是,如果相关的类或者函数是受保护的类型,那么在sphinx生成的文档中是不会显示的(构造过程中自动忽略)。

补充说明(2021.03.27)

如果在使用sphinx的过程中,发现代码中的注释文件并未被成功生成。如果成功执行的话,诸如module1.rstmodule2.rst等会被自动的生成在source目录下。这些rst文件没有被自动生成的情况下,可能需要使用sphinx-apidoc去手动地添加:

[dechin@dechin-manjaro hiqfermion]$ sphinx-apidoc -f src/hiqfermion -o docs/source/
创建文件 docs/source/hiqfermion.rst。
创建文件 docs/source/hiqfermion.ansatzes.rst。
创建文件 docs/source/hiqfermion.drivers.rst。
创建文件 docs/source/hiqfermion.ops.rst。
创建文件 docs/source/hiqfermion.optimizers.rst。
创建文件 docs/source/hiqfermion.third_party.rst。
创建文件 docs/source/hiqfermion.transforms.rst。
创建文件 docs/source/hiqfermion.utils.rst。
创建文件 docs/source/modules.rst。

在上述示例中,src/hiqfermion是源代码的存放地址,而docs/source是生成的rst文件存放的位置。一般我们需要先生成这些rst文件,再使用sphinx-build执行文档构建。

还有一点需要注意的是,如果我们直接使用sphinx-apidoc -f src/hiqfermion -o docs/source/这样的指令去生成的话,最终文档中的结构都是hiqfermion.module1hiqfermion.module2,这样显得不太简洁,因为正常情况下我们需要的是module1module2这样比较直接的形式。此时我们可以更改其中的module.rst文件。当然,首先我们需要逐一的去执行sphinx-apidoc来生成一些模块化的rst文件:sphinx-apidoc -f src/hiqfermion/module1 -o docs/source/以及sphinx-apidoc -f src/hiqfermion/module2 -o docs/source/分开执行。这样我们可以把module.rst修改成这样的形式:

module1
=======

.. toctree::
   :maxdepth: 4

   module1

module2
=======

.. toctree::
   :maxdepth: 4

   module2

这里rst文档会自动搜寻同目录下的module1.rstmodule2.rst文件,并自动化的生成文档。

总结概要

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

版权声明

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

相关推荐

# Python 3 # Python 3字典Dictionary(1)

Python3字典字典是另一种可变容器模型,且可存储任意类型对象。字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中,格式如...

Python第八课:数据类型中的字典及其函数与方法

Python3字典字典是另一种可变容器模型,且可存储任意类型对象。字典的每个键值...

Python中字典详解(python 中字典)

字典是Python中使用键进行索引的重要数据结构。它们是无序的项序列(键值对),这意味着顺序不被保留。键是不可变的。与列表一样,字典的值可以保存异构数据,即整数、浮点、字符串、NaN、布尔值、列表、数...

Python3.9又更新了:dict内置新功能,正式版十月见面

机器之心报道参与:一鸣、JaminPython3.8的热乎劲还没过去,Python就又双叒叕要更新了。近日,3.9版本的第四个alpha版已经开源。从文档中,我们可以看到官方透露的对dic...

Python3 基本数据类型详解(python三种基本数据类型)

文章来源:加米谷大数据Python中的变量不需要声明。每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建。在Python中,变量就是变量,它没有类型,我们所说的"类型"是变...

一文掌握Python的字典(python字典用法大全)

字典是Python中最强大、最灵活的内置数据结构之一。它们允许存储键值对,从而实现高效的数据检索、操作和组织。本文深入探讨了字典,涵盖了它们的创建、操作和高级用法,以帮助中级Python开发...

超级完整|Python字典详解(python字典的方法或操作)

一、字典概述01字典的格式Python字典是一种可变容器模型,且可存储任意类型对象,如字符串、数字、元组等其他容器模型。字典的每个键值key=>value对用冒号:分割,每个对之间用逗号,...

Python3.9版本新特性:字典合并操作的详细解读

处于测试阶段的Python3.9版本中有一个新特性:我们在使用Python字典时,将能够编写出更可读、更紧凑的代码啦!Python版本你现在使用哪种版本的Python?3.7分?3.5分?还是2.7...

python 自学,字典3(一些例子)(python字典有哪些基本操作)

例子11;如何批量复制字典里的内容2;如何批量修改字典的内容3;如何批量修改字典里某些指定的内容...

Python3.9中的字典合并和更新,几乎影响了所有Python程序员

全文共2837字,预计学习时长9分钟Python3.9正在积极开发,并计划于今年10月发布。2月26日,开发团队发布了alpha4版本。该版本引入了新的合并(|)和更新(|=)运算符,这个新特性几乎...

Python3大字典:《Python3自学速查手册.pdf》限时下载中

最近有人会想了,2022了,想学Python晚不晚,学习python有前途吗?IT行业行业薪资高,发展前景好,是很多求职群里严重的香饽饽,而要进入这个高薪行业,也不是那么轻而易举的,拿信工专业的大学生...

python学习——字典(python字典基本操作)

字典Python的字典数据类型是基于hash散列算法实现的,采用键值对(key:value)的形式,根据key的值计算value的地址,具有非常快的查取和插入速度。但它是无序的,包含的元素个数不限,值...

324页清华教授撰写【Python 3 菜鸟查询手册】火了,小白入门字典

如何入门学习python...

Python3.9中的字典合并和更新,了解一下

全文共2837字,预计学习时长9分钟Python3.9正在积极开发,并计划于今年10月发布。2月26日,开发团队发布了alpha4版本。该版本引入了新的合并(|)和更新(|=)运算符,这个新特性几乎...

python3基础之字典(python中字典的基本操作)

字典和列表一样,也是python内置的一种数据结构。字典的结构如下图:列表用中括号[]把元素包起来,而字典是用大括号{}把元素包起来,只不过字典的每一个元素都包含键和值两部分。键和值是一一对应的...

取消回复欢迎 发表评论:

请填写验证码