diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 0000000..d70b1d1 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,2 @@ +# Overhaul project structure, developer workflow, and documentation +4e3707d369d7d77a0d3c99974057abdd62877347 diff --git a/.readthedocs.yaml b/.readthedocs.yaml new file mode 100644 index 0000000..6606de1 --- /dev/null +++ b/.readthedocs.yaml @@ -0,0 +1,16 @@ +version: 2 + +build: + os: ubuntu-24.04 + tools: + python: "3.14" + +sphinx: + configuration: docs/source/conf.py + +python: + install: + - method: pip + path: . + extra_requirements: + - docs diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 09f1680..1278c32 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,8 +1,3 @@ -This is a comprehensive, professional `CONTRIBUTING.md` tailored for your project. -It covers the specific tools you've configured and adds industry-standard best practices for a seamless open-source contribution experience. - ---- - # Contributing to DeepQuantum First off, thank you for considering contributing to DeepQuantum! diff --git a/README.md b/README.md index f972ef9..7a14ec4 100644 --- a/README.md +++ b/README.md @@ -290,7 +290,7 @@ To maintain high code quality and consistent style, we use a modern development [![Jupytext](https://img.shields.io/badge/jupytext-enabled-blue)](https://github.com/mwouts/jupytext) [![pre-commit](https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit)](https://github.com/pre-commit/pre-commit) -Please refer to our **[CONTRIBUTING.md](CONTRIBUTING.md)** for detailed instructions on: +Please refer to our **[CONTRIBUTING.md](./CONTRIBUTING.md)** for detailed instructions on: - **Linting & Formatting**: Our coding standards using Ruff. - **Notebook Management**: How we sync `.ipynb` and `.py` files using Jupytext. - **Pull Request Process**: How to link issues and submit your changes. diff --git a/docs/source/conf.py b/docs/source/conf.py index a516b2c..f2c4b3c 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -31,6 +31,9 @@ ] add_module_names = False +autodoc_inherit_docstrings = False +autodoc_typehints = 'both' +autodoc_typehints_description_target = 'documented' autosummary_generate = True napoleon_google_docstring = True diff --git a/docs/source/index.md b/docs/source/index.md index 51eaec3..bd97ef0 100644 --- a/docs/source/index.md +++ b/docs/source/index.md @@ -1,6 +1,5 @@ ```{include} ../../README.md :relative-images: -:relative-docs: ``` ```{toctree} :maxdepth: 1 diff --git a/docs/source/quick_start/basic_examples.md b/docs/source/quick_start/basic_examples.md index b7cb51f..ba4f9ed 100644 --- a/docs/source/quick_start/basic_examples.md +++ b/docs/source/quick_start/basic_examples.md @@ -84,10 +84,10 @@ print(cir3.expectation()) For quantum simulators, operational efficiency is a crucial performance metric. In tasks like VQE and quantum machine learning, aside from the forward evolution of quantum circuits, gradient calculation is a pivotal factor affecting efficiency. Comparisons between DeepQuantum, Qiskit and VQNet are illustrated as follows. ```python +import deepquantum as dq import time import torch from torch.autograd.functional import hessian -import deepquantum as dq def benchmark(f, *args, trials=10): time0 = time.time() diff --git a/docs/source/quick_start/basic_examples_cn.md b/docs/source/quick_start/basic_examples_cn.md index a8eba95..765093c 100644 --- a/docs/source/quick_start/basic_examples_cn.md +++ b/docs/source/quick_start/basic_examples_cn.md @@ -81,13 +81,15 @@ print(cir3.expectation()) ## 梯度计算的benchmark -对于量子模拟器来说,运行效率是最重要的评价指标之一。对于VQE和量子机器学习等任务,除了量子线路的前向演化,梯度的计算是影响运行效率的最重要的因素。下面展示了DeepQuantum和Qiskit、VQNet的对比。 +对于量子模拟器来说,运行效率是最重要的评价指标之一。 +对于VQE和量子机器学习等任务,除了量子线路的前向演化,梯度的计算是影响运行效率的最重要的因素。 +下面展示了DeepQuantum和Qiskit、VQNet的对比。 ```python +import deepquantum as dq import time import torch from torch.autograd.functional import hessian -import deepquantum as dq def benchmark(f, *args, trials=10): time0 = time.time() @@ -152,8 +154,9 @@ def hessian_dq(n, l, trials=10): ## 大规模模拟 -用经典计算机对量子线路进行模拟,所需的计算资源会随着量子比特数的增加而呈指数级增长。DeepQuantum底层实现了张量网络算法,得以支持大规模的模拟。 -用户只需要设置QubitCircuit的mps=True即可,并且可以用chi来调节基于张量网络近似量子态的精度,chi越大模拟精度越高,运行速度越慢。 +用经典计算机对量子线路进行模拟,所需的计算资源会随着量子比特数的增加而呈指数级增长。 +DeepQuantum底层实现了张量网络算法,得以支持大规模的模拟。 +用户只需要设置`QubitCircuit`的`mps=True`即可,并且可以用`chi`来调节基于张量网络近似量子态的精度,`chi`越大模拟精度越高,运行速度越慢。 ```python batch = 2 @@ -172,7 +175,8 @@ print(cir.expectation()) ## 量子傅里叶变换 量子傅里叶变换是离散傅里叶变换的量子对应。 -DeepQuantum基于Ansatz类实现了量子傅里叶变换(Ansatz类只是在QubitCircuit的基础上对新增的输入参数进行了有效性的判断)。用户同样可以基于Ansatz类来方便地复现和开发各种量子算法。 +DeepQuantum基于`Ansatz`类实现了量子傅里叶变换(`Ansatz`类只是在`QubitCircuit`的基础上对新增的输入参数进行了有效性的判断)。 +用户同样可以基于`Ansatz`类来方便地复现和开发各种量子算法。 下面是具体的实现。 ```python @@ -207,7 +211,8 @@ class QuantumFourierTransform(dq.Ansatz): ## 量子相位估计 -量子相位估计算法是很多量子算法的关键。假设一个幺正算符U作用在其本征态 |u⟩ 上会出现一个相位 $e^{2{\pi}i{\psi}}$ ,相位估计算法的作用就是对这个相位 $\psi$ 进行估计。 +量子相位估计算法是很多量子算法的关键。 +假设一个幺正算符U作用在其本征态 |u⟩ 上会出现一个相位 $e^{2{\pi}i{\psi}}$ ,相位估计算法的作用就是对这个相位 $\psi$ 进行估计。 下面演示的是DeepQuantum中已经实现的量子相位估计的例子,即针对单量子比特的相移门,得到它的相位。 ```python diff --git a/docs/source/quick_start/basic_usage_cn.md b/docs/source/quick_start/basic_usage_cn.md index 68cc02a..a25da5c 100644 --- a/docs/source/quick_start/basic_usage_cn.md +++ b/docs/source/quick_start/basic_usage_cn.md @@ -11,17 +11,17 @@ import torch.nn as nn ## 量子线路对象 -DeepQuantum的基本对象是QubitCircuit和QumodeCircuit。 -QubitCircuit用量子比特数(n)来初始化量子线路,即cir=dq.QubitCircuit(n)。 -QumodeCircuit用模式数(n)来初始化光量子线路,即cir=dq.QumodeCircuit(n)。 +DeepQuantum的基本对象是`QubitCircuit`和`QumodeCircuit`。 +`QubitCircuit`用量子比特数(n)来初始化量子线路,即`cir=dq.QubitCircuit(n)`。 +`QumodeCircuit`用模式数(n)来初始化光量子线路,即`cir=dq.QumodeCircuit(n)`。 DeepQuantum可以帮助用户很方便地实现参数化量子线路,从而进行量子机器学习。 ## QubitCircuit基础使用说明 ### 量子态 -QubitState是表示量子态的类。 -比如,我们可以利用QubitState准备一个单比特量子态,其数据是torch的tensor,存在属性state中。 +`QubitState`是表示量子态的类。 +比如,我们可以利用`QubitState`准备一个单比特量子态,其数据是`torch`的`Tensor`,存在属性`state`中。 便捷地将经典数据编码为一个量子态 ```python @@ -53,23 +53,23 @@ print(qstate.state) ### 基本的量子门 -我们可以将各种量子门作用在QubitCircuit上。 -例如,我们可以将Hadamard门作用于1号量子比特:cir.h(1);将Rx门作用于2号量子比特:cir.rx(2, inputs=0.2);多量子比特门也一样:cir.cnot(0, 1)。 -同时,我们还可以一次性在量子线路上放置一层量子门,如cir.rxlayer()。 +我们可以将各种量子门作用在`QubitCircuit上`。 +例如,我们可以将Hadamard门作用于1号量子比特:`cir.h(1)`;将Rx门作用于2号量子比特:`cir.rx(2, inputs=0.2)`;多量子比特门也一样:`cir.cnot(0, 1)`。 +同时,我们还可以一次性在量子线路上放置一层量子门,如`cir.rxlayer()`。 如果量子门没有指定输入参数,则会自动初始化变分参数。 ```python cir = dq.QubitCircuit(4) ``` -第一个参数wires指定放置的线路,自动初始化内部的变分参数 +第一个参数`wires`指定放置的线路,自动初始化内部的变分参数 ```python cir.rxlayer(wires=[0,2]) ``` 我们也可以手动初始化参数,具体如下所示。 -利用inputs手动初始化固定参数 +利用`inputs`手动初始化固定参数 ```python cir.rxlayer(wires=[0, 1, 2, ...], inputs=[theta_0, theta_1, ...]) @@ -158,7 +158,7 @@ print(cir.expectation()) #### 条件测量 -使用condition参数可以实现条件测量,此时条件测量的位置由控制位controls决定。 +使用`condition`参数可以实现条件测量,此时条件测量的位置由控制位`controls`决定。 ```python cir = dq.QubitCircuit(3) @@ -174,13 +174,13 @@ print(cir.post_select(measure_rst)) cir.draw() ``` -注意,defer_measure和post_select并不改变QubitCircuit所保存的末态state,因此measure和expectation目前并不兼容条件测量。 +注意,`defer_measure`和`post_select`并不改变`QubitCircuit`所保存的末态`state`,因此`measure`和`expectation`目前并不兼容条件测量。 ## QumodeCircuit基础使用说明 ### Fock后端的使用 -使用Fock后端可以构建基于离散变量的光量子线路,basis=True对应着量子态用Fock基矢态表示,basis=False对应着量子态用Fock态张量表示。 +使用Fock后端可以构建基于离散变量的光量子线路,`basis=True`对应着量子态用Fock基矢态表示,`basis=False`对应着量子态用Fock态张量表示。 #### 量子态 @@ -194,8 +194,8 @@ print(qstate1, qstate2) #### 基本量子门 -我们可以将各种量子门作用在QumodeCircuit上。 -例如,我们可以将移相器作用于第1个mode:cir.ps(0);将分束器作用于第1、2个mode:cir.bs([0,1])。 +我们可以将各种量子门作用在`QumodeCircuit`上。 +例如,我们可以将移相器作用于第1个mode:`cir.ps(0)`;将分束器作用于第1、2个mode:`cir.bs([0,1])`。 如果量子门没有指定输入参数,则会自动初始化变分参数。 ```python @@ -217,7 +217,7 @@ print(state, sample) #### 线路可视化 -通过cir.draw()可以将搭建的光量子线路可视化并保存 +通过`cir.draw()`可以将搭建的光量子线路可视化并保存 ```python cir.draw(filename='circuit.svg') @@ -252,7 +252,7 @@ clements.draw() #### 量子态 -高斯态通过协方差矩阵cov和平均值矢量mean来表示,'vac'对应真空态,也可以设置cov和mean。 +高斯态通过协方差矩阵`cov`和平均值矢量`mean`来表示,`'vac'`对应真空态,也可以设置`cov`和`mean`。 ```python qstate1 = dq.GaussianState(nmode=2, state='vac') @@ -264,7 +264,7 @@ print(qstate1, qstate2) #### 基本量子门 -高斯操作对应的量子门有单模压缩门s、位移门d、旋转门r和分束器bs等。 +高斯操作对应的量子门有单模压缩门`s`、位移门`d`、旋转门`r`和分束器`bs`等。 ```python cir = dq.QumodeCircuit(nmode=2, init_state='vac', cutoff=3, backend='gaussian') @@ -277,13 +277,13 @@ cir.bs([0,1], [torch.pi/4, torch.pi/4]) cir.draw() ``` -上面的压缩门和位移门具有r和theta两个参数。 -当用户只指定r时,theta默认为0。 -当用户只指定theta时,r默认随机初始化。 +上面的压缩门和位移门具有`r`和`theta`两个参数。 +当用户只指定`r`时,`theta`默认为0。 +当用户只指定`theta`时,`r`默认随机初始化。 #### 线路演化和测量 -这里measure_homodyne测量对应的物理量是正交算符 $\hat{x}$ 和 $\hat{p}$ 的值,photon_number_mean_var对应的是每个mode的光子数的平均值和方差。 +这里`measure_homodyne`测量对应的物理量是正交算符 $\hat{x}$ 和 $\hat{p}$ 的值,`photon_number_mean_var`对应的是每个mode的光子数的平均值和方差。 ```python state = cir() @@ -304,13 +304,13 @@ adj_mat = torch.tensor([[0., 1., 1., 0., 0., 0.], [0., 1., 0., 0., 1., 1.], [0., 0., 0., 1., 0., 0.], [0., 1., 0., 1., 0., 0.]]) -gbs = dqp.GBS_Graph(adj_mat=adj_mat, cutoff=2) +gbs = dqp.GraphGBS(adj_mat=adj_mat, cutoff=2) state = gbs() sample = gbs.measure() # 高斯玻色采样 print(sample) ``` -通过gbs.draw()可以可视化高斯玻色采样线路。 +通过`gbs.draw()`可以可视化高斯玻色采样线路。 ```python gbs.draw() diff --git a/docs/source/quick_start/introduction.md b/docs/source/quick_start/introduction.md index 166ffaa..2292046 100644 --- a/docs/source/quick_start/introduction.md +++ b/docs/source/quick_start/introduction.md @@ -1,7 +1,15 @@ # Introduction and Overview -Quantum computing is a rapidly growing field, poised to address the enormous computational power demands of the future. The integration of machine learning (deep learning) into quantum machine learning (quantum deep learning) also holds the potential for significant value. In the current Noisy Intermediate-Scale Quantum (NISQ) era, due to the prohibitive cost and limited accessibility of real quantum computing resources, research in QML largely depends on classical computers to simulate quantum circuits. Therefore, with the boundless potential of this field, both domestic and international companies have already laid the groundwork in programming frameworks and software services, capitalizing on early-mover advantages to attract and cultivate potential users, even before the advent of fault-tolerant universal quantum computers. +Quantum computing is a rapidly growing field, poised to address the enormous computational power demands of the future. +The integration of machine learning (deep learning) into quantum machine learning (quantum deep learning) also holds the potential for significant value. +In the current Noisy Intermediate-Scale Quantum (NISQ) era, due to the prohibitive cost and limited accessibility of real quantum computing resources, research in QML largely depends on classical computers to simulate quantum circuits. +Therefore, with the boundless potential of this field, both domestic and international companies have already laid the groundwork in programming frameworks and software services, capitalizing on early-mover advantages to attract and cultivate potential users, even before the advent of fault-tolerant universal quantum computers. -In the era of deep learning, important considerations for a quantum computing framework include its simulation scale, the ability to leverage GPU power for efficiency, the degree of integration with machine learning/deep learning libraries, and its user-friendliness and convenience. Influential quantum computing frameworks often aim to provide real quantum computing resources to users through cloud platforms. +In the era of deep learning, important considerations for a quantum computing framework include its simulation scale, the ability to leverage GPU power for efficiency, the degree of integration with machine learning/deep learning libraries, and its user-friendliness and convenience. +Influential quantum computing frameworks often aim to provide real quantum computing resources to users through cloud platforms. -DeepQuantum is a lightweight quantum programming framework based on PyTorch, designed for programming and simulating quantum computing, quantum neural networks, and hybrid quantum-classical algorithms. It naturally integrates with PyTorch, offering a programming style closely aligned with PyTorch's own. This makes it more accessible to developers with a computer science background and those familiar with or exposed to PyTorch, lowering the learning curve and easing the transition from machine learning (deep learning) to quantum machine learning (quantum deep learning). DeepQuantum is meticulously designed for convenient initialization of quantum neural networks and flexible data encoding. It also implements tensor network algorithms, supporting large-scale quantum circuit simulations based on matrix product states. +DeepQuantum is a lightweight quantum programming framework based on PyTorch, designed for programming and simulating quantum computing, quantum neural networks, and hybrid quantum-classical algorithms. +It naturally integrates with PyTorch, offering a programming style closely aligned with PyTorch's own. +This makes it more accessible to developers with a computer science background and those familiar with or exposed to PyTorch, lowering the learning curve and easing the transition from machine learning (deep learning) to quantum machine learning (quantum deep learning). +DeepQuantum is meticulously designed for convenient initialization of quantum neural networks and flexible data encoding. +It also implements tensor network algorithms, supporting large-scale quantum circuit simulations based on matrix product states. diff --git a/docs/source/quick_start/introduction_cn.md b/docs/source/quick_start/introduction_cn.md index 0414245..96d28af 100644 --- a/docs/source/quick_start/introduction_cn.md +++ b/docs/source/quick_start/introduction_cn.md @@ -1,7 +1,14 @@ # 引言和概述 -量子计算是一个蓬勃发展的领域,有望为未来巨大的算力需求提供解决方案,而结合了机器学习(深度学习)的量子机器学习(量子深度学习)也有望产生巨大的价值。 在目前的NISQ时代,由于真实的量子计算资源过于昂贵而无法获得或难以获得,对于量子机器学习的研究在很大程度上需要借助经典计算机对量子线路进行模拟。 因此,基于这个领域在未来的无限可能,在真正的容错通用量子计算机落地前,国内外各家相关公司早已在编程框架、软件服务方面进行了布局,以利用先发优势吸引和培养潜在用户。 +量子计算是一个蓬勃发展的领域,有望为未来巨大的算力需求提供解决方案,而结合了机器学习(深度学习)的量子机器学习(量子深度学习)也有望产生巨大的价值。 +在目前的NISQ时代,由于真实的量子计算资源过于昂贵而无法获得或难以获得,对于量子机器学习的研究在很大程度上需要借助经典计算机对量子线路进行模拟。 +因此,基于这个领域在未来的无限可能,在真正的容错通用量子计算机落地前,国内外各家相关公司早已在编程框架、软件服务方面进行了布局,以利用先发优势吸引和培养潜在用户。 -在深度学习时代,一个量子计算框架所能支持的模拟规模、是否能够利用GPU的算力来提升效率、与机器学习/深度学习库结合的紧密程度以及其易用性、便捷性都是重要的考量。 同时,具有影响力的量子计算框架往往也肩负着通过云平台为用户提供真实量子计算资源的使命。 +在深度学习时代,一个量子计算框架所能支持的模拟规模、是否能够利用GPU的算力来提升效率、与机器学习/深度学习库结合的紧密程度以及其易用性、便捷性都是重要的考量。 +同时,具有影响力的量子计算框架往往也肩负着通过云平台为用户提供真实量子计算资源的使命。 -DeepQuantum是一款基于PyTorch的轻量级的量子编程框架,用于量子计算、量子神经网络和混合量子-经典算法的编程和模拟。因此可以很自然地与PyTorch做到无缝衔接,编程风格也十分接近PyTorch本身的用法。 对于计算机背景出身、熟悉或接触过PyTorch的开发者来说更加友好,学习门槛低,很容易上手,更加适合相关开发者从机器学习(深度学习)进入到量子机器学习(量子深度学习)。 经过精心的设计,DeepQuantum在初始化量子神经网络时更加便捷,进行数据编码时更加灵活。 同时,DeepQuantum中也实现了张量网络算法,支持基于矩阵乘积态的大规模量子线路模拟。 +DeepQuantum是一款基于PyTorch的轻量级的量子编程框架,用于量子计算、量子神经网络和混合量子-经典算法的编程和模拟。 +因此可以很自然地与PyTorch做到无缝衔接,编程风格也十分接近PyTorch本身的用法。 +对于计算机背景出身、熟悉或接触过PyTorch的开发者来说更加友好,学习门槛低,很容易上手,更加适合相关开发者从机器学习(深度学习)进入到量子机器学习(量子深度学习)。 +经过精心的设计,DeepQuantum在初始化量子神经网络时更加便捷,进行数据编码时更加灵活。 +同时,DeepQuantum中也实现了张量网络算法,支持基于矩阵乘积态的大规模量子线路模拟。 diff --git a/pyproject.toml b/pyproject.toml index 41ada39..f405472 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,5 +1,5 @@ [build-system] -requires = ['setuptools >= 80.0', 'wheel'] +requires = ['setuptools', 'wheel'] build-backend = 'setuptools.build_meta' [project] @@ -57,9 +57,15 @@ dev = [ 'pytest', 'qutip', 'ruff', + 'setuptools<82.0.0', 'strawberryfields', 'thewalrus', ] +docs = [ + 'myst-nb', + 'sphinx', + 'sphinx_book_theme', +] [project.urls] Homepage = 'https://deepquantum.turingq.com/' diff --git a/requirements-dev.txt b/requirements-dev.txt index a44dfa8..c0ad0b6 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -7,5 +7,6 @@ pre-commit-uv pytest qutip ruff +setuptools<82.0.0 strawberryfields @ git+https://github.com/XanaduAI/strawberryfields.git@master thewalrus @ git+https://github.com/XanaduAI/thewalrus.git@master diff --git a/requirements-docs.txt b/requirements-docs.txt new file mode 100644 index 0000000..30f473f --- /dev/null +++ b/requirements-docs.txt @@ -0,0 +1,3 @@ +myst-nb +sphinx +sphinx_book_theme diff --git a/src/deepquantum/__init__.py b/src/deepquantum/__init__.py index 3b968ef..c6cf21e 100644 --- a/src/deepquantum/__init__.py +++ b/src/deepquantum/__init__.py @@ -1,6 +1,6 @@ """This is the top level module from which all basic functions and classes of DeepQuantum can be directly imported.""" -__version__ = '4.4.0' +__version__ = '4.5.0' from . import ( diff --git a/src/deepquantum/adjoint.py b/src/deepquantum/adjoint.py index 6705492..a8b5ead 100644 --- a/src/deepquantum/adjoint.py +++ b/src/deepquantum/adjoint.py @@ -22,10 +22,10 @@ class AdjointExpectation(Function): See https://arxiv.org/pdf/2009.02823 Args: - state (DistributedQubitState): The final quantum state. - operators (nn.Sequential): The quantum operations. - observable (Observable): The observable. - *parameters (torch.Tensor): The parameters of the quantum circuit. + state: The final quantum state. + operators: The quantum operations. + observable: The observable. + *parameters: The parameters of the quantum circuit. """ @staticmethod diff --git a/src/deepquantum/ansatz.py b/src/deepquantum/ansatz.py index 48a1fc5..1a90bfa 100644 --- a/src/deepquantum/ansatz.py +++ b/src/deepquantum/ansatz.py @@ -15,20 +15,18 @@ class Ansatz(QubitCircuit): """A base class for Ansatz. Args: - nqubit (int): The number of qubits in the circuit. - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - minmax (List[int] or None, optional): The minimum and maximum indices of the qubits that the quantum - operation acts on. Only valid when ``wires`` is ``None``. Default: ``None`` - ancilla (int, List[int] or None, optional): The indices of the ancilla qubits. Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - init_state (Any, optional): The initial state of the circuit. Default: ``'zeros'`` - name (str or None, optional): The name of the circuit. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - reupload (bool, optional): Whether to use data re-uploading. Default: ``False`` - mps (bool, optional): Whether to use matrix product state representation. Default: ``False`` - chi (int or None, optional): The bond dimension for matrix product state representation. - Default: ``None`` + nqubit: The number of qubits in the circuit. + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + minmax: The minimum and maximum indices of the qubits that the quantum operation acts on. + Only valid when ``wires`` is ``None``. Default: ``None`` + ancilla: The indices of the ancilla qubits. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + init_state: The initial state of the circuit. Default: ``'zeros'`` + name: The name of the circuit. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + reupload: Whether to use data re-uploading. Default: ``False`` + mps: Whether to use matrix product state representation. Default: ``False`` + chi: The bond dimension for matrix product state representation. Default: ``None`` """ def __init__( @@ -74,19 +72,17 @@ class ControlledMultiplier(Ansatz): See https://arxiv.org/pdf/quant-ph/0205095.pdf Fig.6 Args: - nqubit (int): The number of qubits in the circuit. - a (int): Number ``a`` in :math:`b+a*x \mod N`. - mod (int): The modulus in :math:`b+a*x \mod N`. - minmax (List[int] or None, optional): The minimum and maximum indices of the qubits that the quantum - operation acts on. Default: ``None`` - ancilla (int, List[int] or None, optional): The indices of the ancilla qubits. Default: ``None`` - nqubitx (int or None, optional): The number of qubits in the register x. - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - mps (bool, optional): Whether to use matrix product state representation. Default: ``False`` - chi (int or None, optional): The bond dimension for matrix product state representation. - Default: ``None`` - debug (bool, optional): Whether to print the debug information. Default: ``False`` + nqubit: The number of qubits in the circuit. + a: Number ``a`` in :math:`b+a*x \mod N`. + mod: The modulus in :math:`b+a*x \mod N`. + minmax: The minimum and maximum indices of the qubits that the quantum operation acts on. Default: ``None`` + ancilla: The indices of the ancilla qubits. Default: ``None`` + nqubitx: The number of qubits in the register x. + controls: The indices of the control qubits. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + mps: Whether to use matrix product state representation. Default: ``False`` + chi: The bond dimension for matrix product state representation. Default: ``None`` + debug: Whether to print the debug information. Default: ``False`` """ def __init__( @@ -158,18 +154,16 @@ class ControlledUa(Ansatz): See https://arxiv.org/pdf/quant-ph/0205095.pdf Fig.7 Args: - nqubit (int): The number of qubits in the circuit. - a (int): Number ``a`` in :math:`a*x \mod N`. - mod (int): The modulus in :math:`a*x \mod N`. - minmax (List[int] or None, optional): The minimum and maximum indices of the qubits that the quantum - operation acts on. Default: ``None`` - ancilla (int, List[int] or None, optional): The indices of the ancilla qubits. Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - mps (bool, optional): Whether to use matrix product state representation. Default: ``False`` - chi (int or None, optional): The bond dimension for matrix product state representation. - Default: ``None`` - debug (bool, optional): Whether to print the debug information. Default: ``False`` + nqubit: The number of qubits in the circuit. + a: Number ``a`` in :math:`a*x \mod N`. + mod: The modulus in :math:`a*x \mod N`. + minmax: The minimum and maximum indices of the qubits that the quantum operation acts on. Default: ``None`` + ancilla: The indices of the ancilla qubits. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + mps: Whether to use matrix product state representation. Default: ``False`` + chi: The bond dimension for matrix product state representation. Default: ``None`` + debug: Whether to print the debug information. Default: ``False`` """ def __init__( @@ -243,15 +237,13 @@ class HHL(Ansatz): r"""A quantum circuit for the HHL algorithm. Args: - ncount (int): The number of counting qubits. - mat (Any): The Hermitian matrix `A`. - t0 (float, optional): The time parameter for the matrix exponential in units of :math:`2\pi`. - Default: 1 - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - mps (bool, optional): Whether to use matrix product state representation. Default: ``False`` - chi (int or None, optional): The bond dimension for matrix product state representation. - Default: ``None`` - show_barrier (bool, optional): Whether to show the barriers in the circuit. Default: ``False`` + ncount: The number of counting qubits. + mat: The Hermitian matrix `A`. + t0: The time parameter for the matrix exponential in units of :math:`2\pi`. Default: 1 + den_mat: Whether to use density matrix representation. Default: ``False`` + mps: Whether to use matrix product state representation. Default: ``False`` + chi: The bond dimension for matrix product state representation. Default: ``None`` + show_barrier: Whether to show the barriers in the circuit. Default: ``False`` """ def __init__( @@ -320,14 +312,12 @@ class NumberEncoder(Ansatz): """Convert number to corresponding encoding circuit. Args: - nqubit (int): The number of qubits in the circuit. - number (int): The integer for converting to bit string. - minmax (List[int] or None, optional): The minimum and maximum indices of the qubits that the quantum - operation acts on. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - mps (bool, optional): Whether to use matrix product state representation. Default: ``False`` - chi (int or None, optional): The bond dimension for matrix product state representation. - Default: ``None`` + nqubit: The number of qubits in the circuit. + number: The integer for converting to bit string. + minmax: The minimum and maximum indices of the qubits that the quantum operation acts on. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + mps: Whether to use matrix product state representation. Default: ``False`` + chi: The bond dimension for matrix product state representation. Default: ``None`` """ def __init__( @@ -363,16 +353,14 @@ class PhiAdder(Ansatz): See https://arxiv.org/pdf/quant-ph/0205095.pdf Fig.2 and Fig.3 Args: - nqubit (int): The number of qubits in the circuit. - number (int): Number ``a`` in :math:`\Phi(a+b)`. - minmax (List[int] or None, optional): The minimum and maximum indices of the qubits that the quantum - operation acts on. Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - mps (bool, optional): Whether to use matrix product state representation. Default: ``False`` - chi (int or None, optional): The bond dimension for matrix product state representation. - Default: ``None`` - debug (bool, optional): Whether to print the debug information. Default: ``False`` + nqubit: The number of qubits in the circuit. + number: Number ``a`` in :math:`\Phi(a+b)`. + minmax: The minimum and maximum indices of the qubits that the quantum operation acts on. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + mps: Whether to use matrix product state representation. Default: ``False`` + chi: The bond dimension for matrix product state representation. Default: ``None`` + debug: Whether to print the debug information. Default: ``False`` """ def __init__( @@ -414,18 +402,16 @@ class PhiModularAdder(Ansatz): See https://arxiv.org/pdf/quant-ph/0205095.pdf Fig.5 Args: - nqubit (int): The number of qubits in the circuit. - number (int): Number ``a`` in :math:`\Phi(a+b \mod N)`. - mod (int): The modulus in :math:`\Phi(a+b \mod N)`. - minmax (List[int] or None, optional): The minimum and maximum indices of the qubits that the quantum - operation acts on. Default: ``None`` - ancilla (int, List[int] or None, optional): The indices of the ancilla qubits. Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - mps (bool, optional): Whether to use matrix product state representation. Default: ``False`` - chi (int or None, optional): The bond dimension for matrix product state representation. - Default: ``None`` - debug (bool, optional): Whether to print the debug information. Default: ``False`` + nqubit: The number of qubits in the circuit. + number: Number ``a`` in :math:`\Phi(a+b \mod N)`. + mod: The modulus in :math:`\Phi(a+b \mod N)`. + minmax: The minimum and maximum indices of the qubits that the quantum operation acts on. Default: ``None`` + ancilla: The indices of the ancilla qubits. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + mps: Whether to use matrix product state representation. Default: ``False`` + chi: The bond dimension for matrix product state representation. Default: ``None`` + debug: Whether to print the debug information. Default: ``False`` """ def __init__( @@ -509,17 +495,15 @@ class QuantumConvolutionalNeuralNetwork(Ansatz): or https://pennylane.ai/qml/demos/tutorial_learning_few_data Args: - nqubit (int): The number of qubits in the circuit. - nlayer (int): The number of layers. - minmax (List[int] or None, optional): The minimum and maximum indices of the qubits that the quantum - operation acts on. Default: ``None`` - init_state (Any, optional): The initial state of the circuit. Default: ``'zeros'`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - requires_grad (bool, optional): Whether the parameters are ``nn.Parameter`` or ``buffer``. + nqubit: The number of qubits in the circuit. + nlayer: The number of layers. + minmax: The minimum and maximum indices of the qubits that the quantum operation acts on. Default: ``None`` + init_state: The initial state of the circuit. Default: ``'zeros'`` + den_mat: Whether to use density matrix representation. Default: ``False`` + requires_grad: Whether the parameters are ``nn.Parameter`` or ``buffer``. Default: ``True`` (which means ``nn.Parameter``) - mps (bool, optional): Whether to use matrix product state representation. Default: ``False`` - chi (int or None, optional): The bond dimension for matrix product state representation. - Default: ``None`` + mps: Whether to use matrix product state representation. Default: ``False`` + chi: The bond dimension for matrix product state representation. Default: ``None`` """ def __init__( @@ -582,18 +566,16 @@ class QuantumFourierTransform(Ansatz): """Quantum Fourier transform. Args: - nqubit (int): The number of qubits in the circuit. - minmax (List[int] or None, optional): The minimum and maximum indices of the qubits that the quantum - operation acts on. Default: ``None`` - reverse (bool, optional): Whether to reverse the output order. Default: ``False`` (which means - the default output order of phase is :math:`x/2, ..., x/2^n`. If ``reverse=True``, the output order - of phase is :math:`x/2^n, ..., x/2`) - init_state (Any, optional): The initial state of the circuit. Default: ``'zeros'`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - mps (bool, optional): Whether to use matrix product state representation. Default: ``False`` - chi (int or None, optional): The bond dimension for matrix product state representation. - Default: ``None`` - show_barrier (bool, optional): Whether to show the barriers in the circuit. Default: ``False`` + nqubit: The number of qubits in the circuit. + minmax: The minimum and maximum indices of the qubits that the quantum operation acts on. Default: ``None`` + reverse: Whether to reverse the output order. Default: ``False`` + (which means the default output order of phase is :math:`x/2, ..., x/2^n`. + If ``reverse=True``, the output order of phase is :math:`x/2^n, ..., x/2`) + init_state: The initial state of the circuit. Default: ``'zeros'`` + den_mat: Whether to use density matrix representation. Default: ``False`` + mps: Whether to use matrix product state representation. Default: ``False`` + chi: The bond dimension for matrix product state representation. Default: ``None`` + show_barrier: Whether to show the barriers in the circuit. Default: ``False`` """ def __init__( @@ -640,16 +622,14 @@ class QuantumPhaseEstimation(Ansatz): """Quantum phase estimation for arbitrary unitary operator. Args: - nqubit (int): The number of qubits in the circuit. - ncount (int): The number of counting qubits. - unitary (Any): The unitary operator. - minmax (List[int] or None, optional): The minimum and maximum indices of the qubits that the quantum - operation acts on. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - mps (bool, optional): Whether to use matrix product state representation. Default: ``False`` - chi (int or None, optional): The bond dimension for matrix product state representation. - Default: ``None`` - show_barrier (bool, optional): Whether to show the barriers in the circuit. Default: ``False`` + nqubit: The number of qubits in the circuit. + ncount: The number of counting qubits. + unitary: The unitary operator. + minmax: The minimum and maximum indices of the qubits that the quantum operation acts on. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + mps: Whether to use matrix product state representation. Default: ``False`` + chi: The bond dimension for matrix product state representation. Default: ``None`` + show_barrier: Whether to show the barriers in the circuit. Default: ``False`` """ def __init__( @@ -708,12 +688,11 @@ class QuantumPhaseEstimationSingleQubit(Ansatz): """Quantum phase estimation for single-qubit gate. Args: - t (int): The number of counting qubits. - phase (Any): The phase to be estimated. - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - mps (bool, optional): Whether to use matrix product state representation. Default: ``False`` - chi (int or None, optional): The bond dimension for matrix product state representation. - Default: ``None`` + t: The number of counting qubits. + phase: The phase to be estimated. + den_mat: Whether to use density matrix representation. Default: ``False`` + mps: Whether to use matrix product state representation. Default: ``False`` + chi: The bond dimension for matrix product state representation. Default: ``None`` """ def __init__(self, t: int, phase: Any, den_mat: bool = False, mps: bool = False, chi: int | None = None) -> None: @@ -745,17 +724,15 @@ class RandomCircuitG3(Ansatz): """Random circuit of G3 family. Args: - nqubit (int): The number of qubits in the circuit. - ngate (int): The number of random gates in the circuit. - wires (List[int] or None, optional): The indices of the qubits that the random gates act on. - Default: ``None`` - minmax (List[int] or None, optional): The minimum and maximum indices of the qubits that the quantum - operation acts on. Only valid when ``wires`` is ``None``. Default: ``None`` - init_state (Any, optional): The initial state of the circuit. Default: ``'zeros'`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - mps (bool, optional): Whether to use matrix product state representation. Default: ``False`` - chi (int or None, optional): The bond dimension for matrix product state representation. - Default: ``None`` + nqubit: The number of qubits in the circuit. + ngate: The number of random gates in the circuit. + wires: The indices of the qubits that the random gates act on. Default: ``None`` + minmax: The minimum and maximum indices of the qubits that the quantum operation acts on. + Only valid when ``wires`` is ``None``. Default: ``None`` + init_state: The initial state of the circuit. Default: ``'zeros'`` + den_mat: Whether to use density matrix representation. Default: ``False`` + mps: Whether to use matrix product state representation. Default: ``False`` + chi: The bond dimension for matrix product state representation. Default: ``None`` """ def __init__( @@ -798,14 +775,13 @@ class ShorCircuit(Ansatz): r"""Circuit for Shor's algorithm. Args: - mod (int): The odd integer to be factored. - ncount (int): The number of counting qubits. - a (int): Any integer that satisfies :math:`1 < a < N` and :math:`\gcd(a, N) = 1`. - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - mps (bool, optional): Whether to use matrix product state representation. Default: ``False`` - chi (int or None, optional): The bond dimension for matrix product state representation. - Default: ``None`` - debug (bool, optional): Whether to print the debug information. Default: ``False`` + mod: The odd integer to be factored. + ncount: The number of counting qubits. + a: Any integer that satisfies :math:`1 < a < N` and :math:`\gcd(a, N) = 1`. + den_mat: Whether to use density matrix representation. Default: ``False`` + mps: Whether to use matrix product state representation. Default: ``False`` + chi: The bond dimension for matrix product state representation. Default: ``None`` + debug: Whether to print the debug information. Default: ``False`` """ def __init__( @@ -867,12 +843,11 @@ class ShorCircuitFor15(Ansatz): See https://learn.qiskit.org/course/ch-algorithms/shors-algorithm Args: - ncount (int): The number of counting qubits. - a (int): Any integer that satisfies :math:`1 < a < N` and :math:`\gcd(a, N) = 1`. - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - mps (bool, optional): Whether to use matrix product state representation. Default: ``False`` - chi (int or None, optional): The bond dimension for matrix product state representation. - Default: ``None`` + ncount: The number of counting qubits. + a: Any integer that satisfies :math:`1 < a < N` and :math:`\gcd(a, N) = 1`. + den_mat: Whether to use density matrix representation. Default: ``False`` + mps: Whether to use matrix product state representation. Default: ``False`` + chi: The bond dimension for matrix product state representation. Default: ``None`` """ def __init__(self, ncount: int, a: int, den_mat: bool = False, mps: bool = False, chi: int | None = None) -> None: diff --git a/src/deepquantum/channel.py b/src/deepquantum/channel.py index 9edada2..41f0a1b 100644 --- a/src/deepquantum/channel.py +++ b/src/deepquantum/channel.py @@ -22,13 +22,12 @@ class BitFlip(Channel): \rho \Rightarrow (1-p) \rho + p X \rho X^{\dagger} Args: - inputs (Any, optional): The parameter of the channel. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` - requires_grad (bool, optional): Whether the parameter is ``nn.Parameter`` or ``buffer``. + inputs: The parameter of the channel. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + requires_grad: Whether the parameter is ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) """ @@ -65,13 +64,12 @@ class PhaseFlip(Channel): \rho \Rightarrow (1-p) \rho + p Z \rho Z^{\dagger} Args: - inputs (Any, optional): The parameter of the channel. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` - requires_grad (bool, optional): Whether the parameter is ``nn.Parameter`` or ``buffer``. + inputs: The parameter of the channel. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + requires_grad: Whether the parameter is ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) """ @@ -111,13 +109,12 @@ class Depolarizing(Channel): + p/3 Z \rho Z^{\dagger} Args: - inputs (Any, optional): The parameter of the channel. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` - requires_grad (bool, optional): Whether the parameter is ``nn.Parameter`` or ``buffer``. + inputs: The parameter of the channel. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + requires_grad: Whether the parameter is ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) """ @@ -164,13 +161,12 @@ class Pauli(Channel): + pz Z \rho Z^{\dagger} Args: - inputs (Any, optional): The parameters of the channel. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` - requires_grad (bool, optional): Whether the parameter is ``nn.Parameter`` or ``buffer``. + inputs: The parameters of the channel. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + requires_grad: Whether the parameter is ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) """ @@ -227,13 +223,12 @@ class AmplitudeDamping(Channel): K_1 = \begin{pmatrix} 0 & \sqrt{p} \\ 0 & 0 \end{pmatrix} Args: - inputs (Any, optional): The parameter of the channel. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` - requires_grad (bool, optional): Whether the parameter is ``nn.Parameter`` or ``buffer``. + inputs: The parameter of the channel. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + requires_grad: Whether the parameter is ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) """ @@ -279,13 +274,12 @@ class PhaseDamping(Channel): K_1 = \begin{pmatrix} 0 & 0 \\ 0 & \sqrt{p} \end{pmatrix} Args: - inputs (Any, optional): The parameter of the channel. The Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` - requires_grad (bool, optional): Whether the parameter is ``nn.Parameter`` or ``buffer``. + inputs: The parameter of the channel. The Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + requires_grad: Whether the parameter is ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) """ @@ -334,14 +328,13 @@ class GeneralizedAmplitudeDamping(Channel): K_3 = \sqrt{1 - p} \begin{pmatrix} 0 & 0 \\ \sqrt{\gamma} & 0 \end{pmatrix} Args: - inputs (Any, optional): The parameters of the channel. The first parameter is the probability - of amplitude damping error, and the second parameter is the damping rate. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` - requires_grad (bool, optional): Whether the parameter is ``nn.Parameter`` or ``buffer``. + inputs: The parameters of the channel. The first parameter is the probability of amplitude damping error, + and the second parameter is the damping rate. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + requires_grad: Whether the parameter is ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) """ diff --git a/src/deepquantum/circuit.py b/src/deepquantum/circuit.py index 24759cc..677aefc 100644 --- a/src/deepquantum/circuit.py +++ b/src/deepquantum/circuit.py @@ -84,15 +84,14 @@ class QubitCircuit(Operation): and measuring quantum states. Args: - nqubit (int): The number of qubits in the circuit. - init_state (Any, optional): The initial state of the circuit. Default: ``'zeros'`` - name (str or None, optional): The name of the circuit. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - reupload (bool, optional): Whether to use data re-uploading. Default: ``False`` - mps (bool, optional): Whether to use matrix product state representation. Default: ``False`` - chi (int or None, optional): The bond dimension for matrix product state representation. - Default: ``None`` - shots (int, optional): The number of shots for the measurement. Default: 1024 + nqubit: The number of qubits in the circuit. + init_state: The initial state of the circuit. Default: ``'zeros'`` + name: The name of the circuit. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + reupload: Whether to use data re-uploading. Default: ``False`` + mps: Whether to use matrix product state representation. Default: ``False`` + chi: The bond dimension for matrix product state representation. Default: ``None`` + shots: The number of shots for the measurement. Default: 1024 Raises: AssertionError: If the type or dimension of ``init_state`` does not match ``nqubit`` or ``den_mat``. @@ -203,13 +202,11 @@ def forward( representation of them. The ``data`` must be a 1D or 2D tensor. Args: - data (torch.Tensor or None, optional): The input data for the ``encoders``. Default: ``None`` - state (torch.Tensor, QubitState, List[torch.Tensor], MatrixProductState or None, optional): - The initial state for the quantum circuit. Default: ``None`` + data: The input data for the ``encoders``. Default: ``None`` + state: The initial state for the quantum circuit. Default: ``None`` Returns: - Union[torch.Tensor, List[torch.Tensor]]: The final state of the quantum circuit after - applying the ``operators``. + The final state of the quantum circuit after applying the ``operators``. """ if state is None: state = self.init_state @@ -273,7 +270,7 @@ def encode(self, data: torch.Tensor | None) -> None: the parameters. Args: - data (torch.Tensor or None): The input data for the ``encoders``, must be a 1D tensor. + data: The input data for the ``encoders``, must be a 1D tensor. Raises: AssertionError: If ``reupload`` is ``False`` and the input data is shorter than the number of @@ -326,9 +323,8 @@ def observable(self, wires: int | list[int] | None = None, basis: str = 'z') -> """Add an ``Observable``. Args: - wires (int, List[int] or None, optional): The wires to measure. Default: ``None`` (which means - all wires are measured) - basis (str, optional): The measurement basis for each wire. It can be ``'x'``, ``'y'``, or ``'z'``. + wires: The wires to measure. Default: ``None`` (which means all wires are measured) + basis: The measurement basis for each wire. It can be ``'x'``, ``'y'``, or ``'z'``. If only one character is given, it is repeated for all wires. Default: ``'z'`` """ observable = Observable(nqubit=self.nqubit, wires=wires, basis=basis, den_mat=self.den_mat, tsr_mode=False) @@ -348,11 +344,10 @@ def measure( """Measure the final state. Args: - shots (int or None, optional): The number of shots for the measurement. Default: ``None`` (which means - ``self.shots``) - with_prob (bool, optional): Whether to show the true probability of the measurement. Default: ``False`` - wires (int, List[int] or None, optional): The wires to measure. Default: ``None`` (which means all wires) - block_size (int, optional): The block size for sampling. Default: 2 ** 24 + shots: The number of shots for the measurement. Default: ``None`` (which means ``self.shots``) + with_prob: Whether to show the true probability of the measurement. Default: ``False`` + wires: The wires to measure. Default: ``None`` (which means all wires) + block_size: The block size for sampling. Default: 2**24 """ if shots is None: shots = self.shots @@ -386,8 +381,8 @@ def expectation(self, shots: int | None = None) -> torch.Tensor: """Get the expectation value according to the final state and ``observables``. Args: - shots (int or None, optional): The number of shots for the expectation value. - Default: ``None`` (which means the exact and differentiable expectation value). + shots: The number of shots for the expectation value. Default: ``None`` + (which means the exact and differentiable expectation value) """ assert len(self.observables) > 0, 'There is no observable' if isinstance(self.state, list): @@ -484,7 +479,7 @@ def get_amplitude(self, bits: str) -> torch.Tensor: """Get the amplitude for the given bit string. Args: - bits (str): A bit string. + bits: A bit string. """ assert not self.den_mat assert len(bits) == self.nqubit @@ -502,9 +497,9 @@ def get_prob(self, bits: str, wires: int | list[int] | None = None) -> torch.Ten """Get the probability for the given bit string. Args: - bits (str): A bit string. - wires (int, List[int] or None, optional): The wires to measure. It can be an integer or a list of - integers specifying the indices of the wires. + bits: A bit string. + wires: The wires to measure. It can be an integer or a list of integers specifying + the indices of the wires. """ if wires is not None: wires = self._convert_indices(wires) @@ -527,7 +522,7 @@ def _get_prob(self, bits: str) -> torch.Tensor: """During MCMC measurement, Get the probability for the given bit string. Args: - bits (str): A bit string. + bits: A bit string. """ return self.get_prob(bits, self.wires_measure) @@ -834,15 +829,14 @@ def add( attributes of the quantum circuit. If ``wires`` is specified, the parameters of gates are shared. Args: - op (Operation): The operation to add. It is an instance of ``Operation`` class or its subclasses, - such as ``Gate``, ``Layer``, ``Channel``, or ``QubitCircuit``. - encode (bool, optional): Whether the gate or layer is to encode data. Default: ``False`` - wires (int, List[int] or None, optional): The wires to apply the gate on. It can be an integer - or a list of integers specifying the indices of the wires. Default: ``None`` (which means - the gate has its own wires) - controls (int, List[int] or None, optional): The control wires for the gate. It can be an integer - or a list of integers specifying the indices of the control wires. Only valid when ``wires`` - is not ``None``. Default: ``None`` (which means the gate has its own control wires) + op: The operation to add. It is an instance of ``Operation`` class or its subclasses, such as + ``Gate``, ``Layer``, ``Channel``, or ``QubitCircuit``. + encode: Whether the gate or layer is to encode data. Default: ``False`` + wires: The wires to apply the gate on. It can be an integer or a list of integers specifying + the indices of the wires. Default: ``None`` (which means the gate has its own wires) + controls: The control wires for the gate. It can be an integer or a list of integers specifying + the indices of the control wires. Only valid when ``wires`` is not ``None``. + Default: ``None`` (which means the gate has its own control wires) Raises: AssertionError: If the input arguments are invalid or incompatible with the quantum circuit. @@ -1631,13 +1625,13 @@ class DistributedQubitCircuit(QubitCircuit): """Quantum circuit for a distributed state vector. Args: - nqubit (int): The number of qubits in the circuit. - name (str or None, optional): The name of the circuit. Default: ``None`` - reupload (bool, optional): Whether to use data re-uploading. Default: ``False`` - shots (int, optional): The number of shots for the measurement. Default: 1024 + nqubit: The number of qubits in the circuit. + name: The name of the circuit. Default: ``None`` + reupload: Whether to use data re-uploading. Default: ``False`` + shots: The number of shots for the measurement. Default: 1024 """ - def __init__(self, nqubit, name=None, reupload=False, shots=1024) -> None: + def __init__(self, nqubit: int, name: str | None = None, reupload: bool = False, shots: int = 1024) -> None: super().__init__( nqubit=nqubit, init_state='zeros', @@ -1667,9 +1661,8 @@ def forward( The ``data`` must be a 1D tensor. Args: - data (torch.Tensor or None, optional): The input data for the ``encoders``. Default: ``None`` - state (DistributedQubitState or None, optional): The initial state for the quantum circuit. - Default: ``None`` + data: The input data for the ``encoders``. Default: ``None`` + state: The initial state for the quantum circuit. Default: ``None`` """ if state is None: self.init_state.reset() @@ -1690,11 +1683,10 @@ def measure( """Measure the final state. Args: - shots (int or None, optional): The number of shots for the measurement. Default: ``None`` (which means - ``self.shots``) - with_prob (bool, optional): Whether to show the true probability of the measurement. Default: ``False`` - wires (int, List[int] or None, optional): The wires to measure. Default: ``None`` (which means all wires) - block_size (int, optional): The block size for sampling. Default: 2 ** 24 + shots: The number of shots for the measurement. Default: ``None`` (which means ``self.shots``) + with_prob: Whether to show the true probability of the measurement. Default: ``False`` + wires: The wires to measure. Default: ``None`` (which means all wires) + block_size: The block size for sampling. Default: 2**24 """ if shots is None: shots = self.shots @@ -1714,8 +1706,8 @@ def expectation(self, shots: int | None = None) -> torch.Tensor: """Get the expectation value according to the final state and ``observables``. Args: - shots (int or None, optional): The number of shots for the expectation value. - Default: ``None`` (which means the exact and differentiable expectation value). + shots: The number of shots for the expectation value. Default: ``None`` + (which means the exact and differentiable expectation value) """ assert len(self.observables) > 0, 'There is no observable' assert isinstance(self.state, DistributedQubitState), 'There is no final state' diff --git a/src/deepquantum/communication.py b/src/deepquantum/communication.py index 7f7c261..3ddfc3f 100644 --- a/src/deepquantum/communication.py +++ b/src/deepquantum/communication.py @@ -62,13 +62,11 @@ def comm_exchange_arrays(send_data: torch.Tensor, recv_data: torch.Tensor, pair_ to participate in the collective call without active data transfer by setting ``pair_rank`` to ``None``. Args: - send_data (torch.Tensor): Data to be sent to the ``pair_rank``. + send_data: Data to be sent to the ``pair_rank``. If ``pair_rank`` is ``None``, this can be an empty tensor with correct dtype and device. - recv_data (torch.Tensor): Pre-allocated buffer to store received data. Must match - ``send_data`` in shape and dtype if ``pair_rank`` is active. - If ``pair_rank`` is ``None``, this can be an empty tensor. - pair_rank (int or None): The target rank for exchange, or ``None`` to remain - quiescent during the collective call. + recv_data: Pre-allocated buffer to store received data. Must match ``send_data`` in shape and dtype + if ``pair_rank`` is active. If ``pair_rank`` is ``None``, this can be an empty tensor. + pair_rank: The target rank for exchange, or ``None`` to remain quiescent during the collective call. """ world_size = comm_get_world_size() rank = comm_get_rank() diff --git a/src/deepquantum/gate.py b/src/deepquantum/gate.py index c4f8dfd..5f377ee 100644 --- a/src/deepquantum/gate.py +++ b/src/deepquantum/gate.py @@ -20,17 +20,15 @@ class SingleGate(Gate): r"""A base class for single-qubit gates. Args: - name (str or None, optional): The name of the gate. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - condition (bool, optional): Whether to use ``controls`` as conditional measurement. Default: ``False`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + name: The name of the gate. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + condition: Whether to use ``controls`` as conditional measurement. Default: ``False`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -90,17 +88,15 @@ class DoubleGate(Gate): r"""A base class for two-qubit gates. Args: - name (str or None, optional): The name of the gate. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 2 - wires (List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - condition (bool, optional): Whether to use ``controls`` as conditional measurement. Default: ``False`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + name: The name of the gate. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 2 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + condition: Whether to use ``controls`` as conditional measurement. Default: ``False`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -192,15 +188,13 @@ class DoubleControlGate(DoubleGate): r"""A base class for two-qubit controlled gates. Args: - name (str or None, optional): The name of the gate. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 2 - wires (List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + name: The name of the gate. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 2 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -235,17 +229,15 @@ class TripleGate(Gate): r"""A base class for three-qubit gates. Args: - name (str or None, optional): The name of the gate. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 3 - wires (List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - condition (bool, optional): Whether to use ``controls`` as conditional measurement. Default: ``False`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + name: The name of the gate. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 3 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + condition: Whether to use ``controls`` as conditional measurement. Default: ``False`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -276,18 +268,16 @@ class ArbitraryGate(Gate): r"""A base class for customized gates. Args: - name (str or None, optional): The name of the gate. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - minmax (List[int] or None, optional): The minimum and maximum indices of the qubits that the quantum - operation acts on. Only valid when ``wires`` is ``None``. Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. - Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + name: The name of the gate. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + minmax: The minimum and maximum indices of the qubits that the quantum operation acts on. + Only valid when ``wires`` is ``None``. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. + Default: ``False`` (which means state vectors) + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -351,19 +341,17 @@ class ParametricSingleGate(SingleGate): r"""A base class for single-qubit gates with parameters. Args: - name (str or None, optional): The name of the gate. Default: ``None`` - inputs (Any, optional): The parameters of the gate. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - condition (bool, optional): Whether to use ``controls`` as conditional measurement. Default: ``False`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + name: The name of the gate. Default: ``None`` + inputs: The parameters of the gate. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + condition: Whether to use ``controls`` as conditional measurement. Default: ``False`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` - requires_grad (bool, optional): Whether the parameters are ``nn.Parameter`` or ``buffer``. + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + requires_grad: Whether the parameters are ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) """ @@ -444,19 +432,17 @@ class ParametricDoubleGate(DoubleGate): r"""A base class for two-qubit gates with parameters. Args: - name (str or None, optional): The name of the gate. Default: ``None`` - inputs (Any, optional): The parameters of the gate. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 2 - wires (List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - condition (bool, optional): Whether to use ``controls`` as conditional measurement. Default: ``False`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + name: The name of the gate. Default: ``None`` + inputs: The parameters of the gate. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 2 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + condition: Whether to use ``controls`` as conditional measurement. Default: ``False`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` - requires_grad (bool, optional): Whether the parameters are ``nn.Parameter`` or ``buffer``. + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + requires_grad: Whether the parameters are ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) """ @@ -549,19 +535,16 @@ class U3Gate(ParametricSingleGate): \end{pmatrix} Args: - inputs (Any, optional): The parameters of the gate (:math:`\theta`, :math:`\phi` and :math:`\lambda`). - Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - condition (bool, optional): Whether to use ``controls`` as conditional measurement. Default: ``False`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + inputs: The parameters of the gate (:math:`\theta`, :math:`\phi` and :math:`\lambda`). Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + condition: Whether to use ``controls`` as conditional measurement. Default: ``False`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` - requires_grad (bool, optional): Whether the parameters are ``nn.Parameter`` or ``buffer``. + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + requires_grad: Whether the parameters are ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) """ @@ -704,18 +687,16 @@ class PhaseShift(ParametricSingleGate): \end{pmatrix} Args: - inputs (Any, optional): The parameter of the gate. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - condition (bool, optional): Whether to use ``controls`` as conditional measurement. Default: ``False`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + inputs: The parameter of the gate. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + condition: Whether to use ``controls`` as conditional measurement. Default: ``False`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` - requires_grad (bool, optional): Whether the parameter is ``nn.Parameter`` or ``buffer``. + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + requires_grad: Whether the parameter is ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) """ @@ -784,14 +765,12 @@ class Identity(Gate): \end{pmatrix} Args: - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -830,16 +809,14 @@ class PauliX(SingleGate): \end{pmatrix} Args: - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - condition (bool, optional): Whether to use ``controls`` as conditional measurement. Default: ``False`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + condition: Whether to use ``controls`` as conditional measurement. Default: ``False`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -907,16 +884,14 @@ class PauliY(SingleGate): \end{pmatrix} Args: - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - condition (bool, optional): Whether to use ``controls`` as conditional measurement. Default: ``False`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + condition: Whether to use ``controls`` as conditional measurement. Default: ``False`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -988,16 +963,14 @@ class PauliZ(SingleGate): \end{pmatrix} Args: - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - condition (bool, optional): Whether to use ``controls`` as conditional measurement. Default: ``False`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + condition: Whether to use ``controls`` as conditional measurement. Default: ``False`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -1064,16 +1037,14 @@ class Hadamard(SingleGate): \end{pmatrix} Args: - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - condition (bool, optional): Whether to use ``controls`` as conditional measurement. Default: ``False`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + condition: Whether to use ``controls`` as conditional measurement. Default: ``False`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -1140,16 +1111,14 @@ class SGate(SingleGate): \end{pmatrix} Args: - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - condition (bool, optional): Whether to use ``controls`` as conditional measurement. Default: ``False`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + condition: Whether to use ``controls`` as conditional measurement. Default: ``False`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -1232,16 +1201,14 @@ class SDaggerGate(SingleGate): \end{pmatrix} Args: - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - condition (bool, optional): Whether to use ``controls`` as conditional measurement. Default: ``False`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + condition: Whether to use ``controls`` as conditional measurement. Default: ``False`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -1304,16 +1271,14 @@ class TGate(SingleGate): \end{pmatrix} Args: - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - condition (bool, optional): Whether to use ``controls`` as conditional measurement. Default: ``False`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + condition: Whether to use ``controls`` as conditional measurement. Default: ``False`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -1370,16 +1335,14 @@ class TDaggerGate(SingleGate): \end{pmatrix} Args: - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - condition (bool, optional): Whether to use ``controls`` as conditional measurement. Default: ``False`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + condition: Whether to use ``controls`` as conditional measurement. Default: ``False`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -1438,18 +1401,16 @@ class Rx(ParametricSingleGate): \end{pmatrix} Args: - inputs (Any, optional): The parameter of the gate. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - condition (bool, optional): Whether to use ``controls`` as conditional measurement. Default: ``False`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + inputs: The parameter of the gate. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + condition: Whether to use ``controls`` as conditional measurement. Default: ``False`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` - requires_grad (bool, optional): Whether the parameter is ``nn.Parameter`` or ``buffer``. + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + requires_grad: Whether the parameter is ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) """ @@ -1534,18 +1495,16 @@ class Ry(ParametricSingleGate): \end{pmatrix} Args: - inputs (Any, optional): The parameter of the gate. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - condition (bool, optional): Whether to use ``controls`` as conditional measurement. Default: ``False`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + inputs: The parameter of the gate. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + condition: Whether to use ``controls`` as conditional measurement. Default: ``False`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` - requires_grad (bool, optional): Whether the parameter is ``nn.Parameter`` or ``buffer``. + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + requires_grad: Whether the parameter is ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) """ @@ -1633,18 +1592,16 @@ class Rz(ParametricSingleGate): \end{pmatrix} Args: - inputs (Any, optional): The parameter of the gate. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - condition (bool, optional): Whether to use ``controls`` as conditional measurement. Default: ``False`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + inputs: The parameter of the gate. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + condition: Whether to use ``controls`` as conditional measurement. Default: ``False`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` - requires_grad (bool, optional): Whether the parameter is ``nn.Parameter`` or ``buffer``. + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + requires_grad: Whether the parameter is ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) """ @@ -1751,19 +1708,17 @@ class ProjectionJ(ParametricSingleGate): \end{pmatrix} Args: - inputs (Any, optional): The parameter of the gate. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - plane (str, optional): The measurement plane (``'xy'``, ``'yz'``, or ``'zx'``). Default: ``'xy'`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - condition (bool, optional): Whether to use ``controls`` as conditional measurement. Default: ``False`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + inputs: The parameter of the gate. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + plane: The measurement plane (``'xy'``, ``'yz'``, or ``'zx'``). Default: ``'xy'`` + controls: The indices of the control qubits. Default: ``None`` + condition: Whether to use ``controls`` as conditional measurement. Default: ``False`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` - requires_grad (bool, optional): Whether the parameter is ``nn.Parameter`` or ``buffer``. + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + requires_grad: Whether the parameter is ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) """ @@ -1835,18 +1790,16 @@ class CombinedSingleGate(SingleGate): r"""Combined single-qubit gate. Args: - gates (List[SingleGate]): The list of single-qubit gates. - name (str or None, optional): The name of the gate. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - condition (bool, optional): Whether to use ``controls`` as conditional measurement. Default: ``False`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + gates: The list of single-qubit gates. + name: The name of the gate. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + condition: Whether to use ``controls`` as conditional measurement. Default: ``False`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -1965,14 +1918,12 @@ class CNOT(DoubleControlGate): \end{pmatrix} Args: - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 2 - wires (List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + nqubit: The number of qubits that the quantum operation acts on. Default: 2 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -2023,16 +1974,14 @@ class Swap(DoubleGate): \end{pmatrix} Args: - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 2 - wires (List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - condition (bool, optional): Whether to use ``controls`` as conditional measurement. Default: ``False`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + nqubit: The number of qubits that the quantum operation acts on. Default: 2 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + condition: Whether to use ``controls`` as conditional measurement. Default: ``False`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -2088,16 +2037,14 @@ class ImaginarySwap(DoubleGate): \end{pmatrix} Args: - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 2 - wires (List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - condition (bool, optional): Whether to use ``controls`` as conditional measurement. Default: ``False`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + nqubit: The number of qubits that the quantum operation acts on. Default: 2 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + condition: Whether to use ``controls`` as conditional measurement. Default: ``False`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -2152,18 +2099,16 @@ class Rxx(ParametricDoubleGate): \end{pmatrix} Args: - inputs (Any, optional): The parameter of the gate. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 2 - wires (List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - condition (bool, optional): Whether to use ``controls`` as conditional measurement. Default: ``False`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + inputs: The parameter of the gate. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 2 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + condition: Whether to use ``controls`` as conditional measurement. Default: ``False`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` - requires_grad (bool, optional): Whether the parameter is ``nn.Parameter`` or ``buffer``. + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + requires_grad: Whether the parameter is ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) """ @@ -2227,18 +2172,16 @@ class Ryy(ParametricDoubleGate): \end{pmatrix} Args: - inputs (Any, optional): The parameter of the gate. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 2 - wires (List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - condition (bool, optional): Whether to use ``controls`` as conditional measurement. Default: ``False`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + inputs: The parameter of the gate. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 2 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + condition: Whether to use ``controls`` as conditional measurement. Default: ``False`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` - requires_grad (bool, optional): Whether the parameter is ``nn.Parameter`` or ``buffer``. + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + requires_grad: Whether the parameter is ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) """ @@ -2312,18 +2255,16 @@ class Rzz(ParametricDoubleGate): \end{pmatrix} Args: - inputs (Any, optional): The parameter of the gate. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 2 - wires (List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - condition (bool, optional): Whether to use ``controls`` as conditional measurement. Default: ``False`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + inputs: The parameter of the gate. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 2 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + condition: Whether to use ``controls`` as conditional measurement. Default: ``False`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` - requires_grad (bool, optional): Whether the parameter is ``nn.Parameter`` or ``buffer``. + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + requires_grad: Whether the parameter is ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) """ @@ -2385,18 +2326,16 @@ class Rxy(ParametricDoubleGate): \end{pmatrix} Args: - inputs (Any, optional): The parameter of the gate. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 2 - wires (List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - condition (bool, optional): Whether to use ``controls`` as conditional measurement. Default: ``False`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + inputs: The parameter of the gate. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 2 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + condition: Whether to use ``controls`` as conditional measurement. Default: ``False`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` - requires_grad (bool, optional): Whether the parameter is ``nn.Parameter`` or ``buffer``. + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + requires_grad: Whether the parameter is ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) """ @@ -2466,18 +2405,16 @@ class ReconfigurableBeamSplitter(ParametricDoubleGate): \end{pmatrix} Args: - inputs (Any, optional): The parameter of the gate. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 2 - wires (List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - condition (bool, optional): Whether to use ``controls`` as conditional measurement. Default: ``False`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + inputs: The parameter of the gate. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 2 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + condition: Whether to use ``controls`` as conditional measurement. Default: ``False`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` - requires_grad (bool, optional): Whether the parameter is ``nn.Parameter`` or ``buffer``. + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + requires_grad: Whether the parameter is ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) """ @@ -2560,14 +2497,12 @@ class Toffoli(TripleGate): \end{pmatrix} Args: - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 3 - wires (List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + nqubit: The number of qubits that the quantum operation acts on. Default: 3 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -2732,14 +2667,12 @@ class Fredkin(TripleGate): \end{pmatrix} Args: - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 3 - wires (List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + nqubit: The number of qubits that the quantum operation acts on. Default: 3 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -2812,19 +2745,17 @@ class UAnyGate(ArbitraryGate): r"""Arbitrary unitary gate. Args: - unitary (Any): Any given unitary matrix. - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - minmax (List[int] or None, optional): The minimum and maximum indices of the qubits that the quantum - operation acts on. Only valid when ``wires`` is ``None``. Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - name (str, optional): The name of the gate. Default: ``'UAnyGate'`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + unitary: Any given unitary matrix. + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + minmax: The minimum and maximum indices of the qubits that the quantum operation acts on. + Only valid when ``wires`` is ``None``. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + name: The name of the gate. Default: ``'UAnyGate'`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -2860,20 +2791,18 @@ class LatentGate(ArbitraryGate): r"""Latent gate. Args: - inputs (Any, optional): Any given real matrix. - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - minmax (List[int] or None, optional): The minimum and maximum indices of the qubits that the quantum - operation acts on. Only valid when ``wires`` is ``None``. Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - name (str, optional): The name of the gate. Default: ``'LatentGate'`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + inputs: Any given real matrix. + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + minmax: The minimum and maximum indices of the qubits that the quantum operation acts on. + Only valid when ``wires`` is ``None``. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + name: The name of the gate. Default: ``'LatentGate'`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` - requires_grad (bool, optional): Whether the parameters are ``nn.Parameter`` or ``buffer``. + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + requires_grad: Whether the parameters are ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) """ @@ -2938,24 +2867,22 @@ class HamiltonianGate(ArbitraryGate): r"""Hamiltonian gate. Args: - hamiltonian (Any): The Hamiltonian. It can be a list, e.g., ``[[0.5, 'x0y1'], [-1, 'z3y1']]`` for + hamiltonian: The Hamiltonian. It can be a list, e.g., ``[[0.5, 'x0y1'], [-1, 'z3y1']]`` for :math:`0.5 * \sigma^x_0 \otimes \sigma^y_1 - \sigma^y_1 \otimes \sigma^z_3`. It can also be a torch.Tensor when ``wires`` or ``minmax`` is specified. - t (Any, optional): The evolution time. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. + t: The evolution time. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Only valid when ``hamiltonian`` is not a list. Default: ``None`` - minmax (List[int] or None, optional): The minimum and maximum indices of the qubits that the quantum - operation acts on. Only valid when ``hamiltonian`` is not a list and ``wires`` is ``None``. - Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - name (str, optional): The name of the gate. Default: ``'HamiltonianGate'`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + minmax: The minimum and maximum indices of the qubits that the quantum operation acts on. + Only valid when ``hamiltonian`` is not a list and ``wires`` is ``None``. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + name: The name of the gate. Default: ``'HamiltonianGate'`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` - requires_grad (bool, optional): Whether the parameter is ``nn.Parameter`` or ``buffer``. + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + requires_grad: Whether the parameter is ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) """ @@ -3108,14 +3035,12 @@ class Reset(Gate): r"""Reset. Args: - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - postselect (int or None, optional): The postselected value. Default: 0 (``None`` means no postselection, - which is not compatible with vmap) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + postselect: The postselected value. Default: 0 + (``None`` means no postselection, which is not compatible with vmap) + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -3184,10 +3109,9 @@ class Barrier(Gate): """Barrier. Args: - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - name (str, optional): The name of the gate. Default: ``'Barrier'`` + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + name: The name of the gate. Default: ``'Barrier'`` """ def __init__(self, nqubit: int = 1, wires: int | list[int] | None = None, name: str = 'Barrier') -> None: @@ -3221,8 +3145,8 @@ class WireCut(Barrier): """Wire Cut. Args: - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int or List[int], optional): The indices of the qubits that the quantum operation acts on. Default: 0 + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: 0 """ def __init__(self, nqubit: int = 1, wires: int | list[int] = 0) -> None: @@ -3233,14 +3157,12 @@ class Move(DoubleGate): r"""Move, a two-qubit operation representing a reset of the second qubit followed by a swap. Args: - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - postselect (int or None, optional): The postselected value. Default: 0 (``None`` means no postselection, - which is not compatible with vmap) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + postselect: The postselected value. Default: 0 + (``None`` means no postselection, which is not compatible with vmap) + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( diff --git a/src/deepquantum/layer.py b/src/deepquantum/layer.py index ad469d7..3045071 100644 --- a/src/deepquantum/layer.py +++ b/src/deepquantum/layer.py @@ -15,15 +15,13 @@ class SingleLayer(Layer): r"""A base class for layers of single-qubit gates. Args: - name (str, optional): The name of the layer. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int], List[List[int]] or None, optional): The indices of the qubits that - the quantum operation acts on. Default: ``None`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + name: The name of the layer. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -54,16 +52,14 @@ class ParametricSingleLayer(SingleLayer): r"""A base class for layers of single-qubit gates with parameters. Args: - name (str or None, optional): The name of the layer. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int], List[List[int]] or None, optional): The indices of the qubits that - the quantum operation acts on. Default: ``None`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + name: The name of the layer. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` - requires_grad (bool, optional): Whether the parameters are ``nn.Parameter`` or ``buffer``. + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + requires_grad: Whether the parameters are ``nn.Parameter`` or ``buffer``. Default: ``True`` (which means ``nn.Parameter``) """ @@ -104,15 +100,13 @@ class DoubleLayer(Layer): r"""A base class for layers of two-qubit gates. Args: - name (str, optional): The name of the layer. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 2 - wires (List[List[int]] or None, optional): The indices of the qubits that the quantum operation - acts on. Default: ``None`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + name: The name of the layer. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 2 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -134,16 +128,14 @@ class Observable(SingleLayer): r"""A ``Layer`` that represents an observable which can be expressed by Pauli string. Args: - nqubit (int, optional): The number of qubits in the circuit. Default: 1 - wires (int, List[int], List[List[int]] or None, optional): The wires to measure. Default: ``None`` - (which means all wires are measured) - basis (str, optional): The measurement basis for each wire. It can be ``'x'``, ``'y'``, or ``'z'``. + nqubit: The number of qubits in the circuit. Default: 1 + wires: The wires to measure. Default: ``None`` (which means all wires are measured) + basis: The measurement basis for each wire. It can be ``'x'``, ``'y'``, or ``'z'``. If only one character is given, it is repeated for all wires. Default: ``'z'`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -177,16 +169,14 @@ class U3Layer(ParametricSingleLayer): r"""A layer of U3 gates. Args: - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int], List[List[int]] or None, optional): The indices of the qubits that - the quantum operation acts on. Default: ``None`` - inputs (Any, optional): The parameters of the layer. Default: ``None`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + inputs: The parameters of the layer. Default: ``None`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` - requires_grad (bool, optional): Whether the parameters are ``nn.Parameter`` or ``buffer``. + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + requires_grad: Whether the parameters are ``nn.Parameter`` or ``buffer``. Default: ``True`` (which means ``nn.Parameter``) """ @@ -215,14 +205,12 @@ class XLayer(SingleLayer): r"""A layer of Pauli-X gates. Args: - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int], List[List[int]] or None, optional): The indices of the qubits that - the quantum operation acts on. Default: ``None`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -242,14 +230,12 @@ class YLayer(SingleLayer): r"""A layer of Pauli-Y gates. Args: - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int], List[List[int]] or None, optional): The indices of the qubits that - the quantum operation acts on. Default: ``None`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -269,14 +255,12 @@ class ZLayer(SingleLayer): r"""A layer of Pauli-Z gates. Args: - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int], List[List[int]] or None, optional): The indices of the qubits that - the quantum operation acts on. Default: ``None`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -296,14 +280,12 @@ class HLayer(SingleLayer): r"""A layer of Hadamard gates. Args: - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int], List[List[int]] or None, optional): The indices of the qubits that - the quantum operation acts on. Default: ``None`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -323,16 +305,14 @@ class RxLayer(ParametricSingleLayer): r"""A layer of Rx gates. Args: - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int], List[List[int]] or None, optional): The indices of the qubits that - the quantum operation acts on. Default: ``None`` - inputs (Any, optional): The parameters of the layer. Default: ``None`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + inputs: The parameters of the layer. Default: ``None`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` - requires_grad (bool, optional): Whether the parameters are ``nn.Parameter`` or ``buffer``. + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + requires_grad: Whether the parameters are ``nn.Parameter`` or ``buffer``. Default: ``True`` (which means ``nn.Parameter``) """ @@ -361,16 +341,14 @@ class RyLayer(ParametricSingleLayer): r"""A layer of Ry gates. Args: - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int], List[List[int]] or None, optional): The indices of the qubits that - the quantum operation acts on. Default: ``None`` - inputs (Any, optional): The parameters of the layer. Default: ``None`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + inputs: The parameters of the layer. Default: ``None`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` - requires_grad (bool, optional): Whether the parameters are ``nn.Parameter`` or ``buffer``. + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + requires_grad: Whether the parameters are ``nn.Parameter`` or ``buffer``. Default: ``True`` (which means ``nn.Parameter``) """ @@ -399,16 +377,14 @@ class RzLayer(ParametricSingleLayer): r"""A layer of Rz gates. Args: - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int], List[List[int]] or None, optional): The indices of the qubits that - the quantum operation acts on. Default: ``None`` - inputs (Any, optional): The parameters of the layer. Default: ``None`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + inputs: The parameters of the layer. Default: ``None`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` - requires_grad (bool, optional): Whether the parameters are ``nn.Parameter`` or ``buffer``. + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + requires_grad: Whether the parameters are ``nn.Parameter`` or ``buffer``. Default: ``True`` (which means ``nn.Parameter``) """ @@ -437,15 +413,13 @@ class CnotLayer(DoubleLayer): r"""A layer of CNOT gates. Args: - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 2 - wires (List[List[int]] or None, optional): The indices of the qubits that the quantum operation - acts on. Default: ``None`` - name (str, optional): The name of the layer. Default: ``'CnotLayer'`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. - Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. - Default: ``False`` + nqubit: The number of qubits that the quantum operation acts on. Default: 2 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + name: The name of the layer. Default: ``'CnotLayer'`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. + Default: ``False`` (which means state vectors) + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -473,18 +447,15 @@ class CnotRing(CnotLayer): r"""A layer of CNOT gates in a cyclic way. Args: - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 2 - minmax (List[int] or None, optional): The minimum and maximum indices of qubits that the quantum - operation acts on. Default: ``None`` - step (int, optional): The distance between the control and target qubits of each CNOT gate. - Default: 1 - reverse (bool, optional): Whether the CNOT gates are applied from the maximum to the minimum index - or vice versa. Default: ``False`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. - Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. + nqubit: The number of qubits that the quantum operation acts on. Default: 2 + minmax: The minimum and maximum indices of qubits that the quantum operation acts on. Default: ``None`` + step: The distance between the control and target qubits of each CNOT gate. Default: 1 + reverse: Whether the CNOT gates are applied from the maximum to the minimum index or vice versa. Default: ``False`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. + Default: ``False`` (which means state vectors) + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( diff --git a/src/deepquantum/mbqc/command.py b/src/deepquantum/mbqc/command.py index 800dffb..7df198d 100644 --- a/src/deepquantum/mbqc/command.py +++ b/src/deepquantum/mbqc/command.py @@ -15,7 +15,7 @@ class Node(Command): """Node (qubit) preparation command. Args: - nodes (int or List[int]): The indices of the nodes to prepare. + nodes: The indices of the nodes to prepare. """ def __init__(self, nodes: int | list[int]) -> None: @@ -35,8 +35,8 @@ class Entanglement(Command): """Entanglement command. Args: - node1 (int): The first node index. - node2 (int): The second node index. + node1: The first node index. + node2: The second node index. """ def __init__(self, node1: int, node2: int) -> None: @@ -70,14 +70,12 @@ class Measurement(Command): """Measurement command. Args: - nodes (int or List[int]): The indices of the nodes to measure. - angle (Any, optional): The measurement angle in radians. Default: 0. - plane (str, optional): The measurement plane (``'xy'``, ``'yz'`` or ``'zx'``). Default: ``'xy'`` - s_domain (int, Iterable[int] or None, optional): The indices of the nodes that contribute to signal domain s. - Default: ``None`` - t_domain (int, Iterable[int] or None, optional): The indices of the nodes that contribute to signal domain t. - Default: ``None`` - requires_grad (bool, optional): Whether the parameter is ``nn.Parameter`` or ``buffer``. + nodes: The indices of the nodes to measure. + angle: The measurement angle in radians. Default: 0. + plane: The measurement plane (``'xy'``, ``'yz'`` or ``'zx'``). Default: ``'xy'`` + s_domain: The indices of the nodes that contribute to signal domain s. Default: ``None`` + t_domain: The indices of the nodes that contribute to signal domain t. Default: ``None`` + requires_grad: Whether the parameter is ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) """ @@ -193,10 +191,9 @@ class Correction(Command): """Correction command. Args: - nodes (int or List[int]): The indices of the nodes to correct. - basis (str, optional): The type of correction (``'x'`` or ``'z'``). Default: ``'x'`` - domain (Union[int, Iterable[int], None], optional): The indices of the nodes that contribute to signal domain s. - Default: ``None`` + nodes: The indices of the nodes to correct. + basis: The type of correction (``'x'`` or ``'z'``). Default: ``'x'`` + domain: The indices of the nodes that contribute to signal domain s. Default: ``None`` """ def __init__(self, nodes: int | list[int], basis: str = 'x', domain: int | Iterable[int] | None = None) -> None: diff --git a/src/deepquantum/mbqc/operation.py b/src/deepquantum/mbqc/operation.py index 3a47eab..8271b5d 100644 --- a/src/deepquantum/mbqc/operation.py +++ b/src/deepquantum/mbqc/operation.py @@ -9,9 +9,8 @@ class Operation(nn.Module): """A base class for quantum operations. Args: - name (str or None, optional): The name of the quantum operation. Default: ``None`` - nodes (int, List[int] or None, optional): The indices of the nodes that the quantum operation acts on. - Default: ``None`` + name: The name of the quantum operation. Default: ``None`` + nodes: The indices of the nodes that the quantum operation acts on. Default: ``None`` """ def __init__(self, name: str | None = None, nodes: int | list[int] | None = None) -> None: @@ -34,8 +33,8 @@ class Command(Operation): """A base class for MBQC commands. Args: - name (str): The name of the command. - nodes (int or List[int]): The indices of the nodes that the command acts on. + name: The name of the command. + nodes: The indices of the nodes that the command acts on. """ def __init__(self, name: str, nodes: int | list[int]) -> None: diff --git a/src/deepquantum/mbqc/pattern.py b/src/deepquantum/mbqc/pattern.py index 78ac497..535f9bc 100644 --- a/src/deepquantum/mbqc/pattern.py +++ b/src/deepquantum/mbqc/pattern.py @@ -23,16 +23,14 @@ class Pattern(Operation): in a graph structure. Args: - nodes_state (int, List[int] or None, optional): The nodes of the input state in the initial graph state. + nodes_state: The nodes of the input state in the initial graph state. It can be an integer representing the number of nodes or a list of node indices. Default: ``None`` - state (Any, optional): The input state of the initial graph state. The string representation of state - could be ``'plus'``, ``'minus'``, ``'zero'``, and ``'one'``. Default: ``'plus'`` - edges (List or None, optional): Additional edges connecting the nodes in the initial graph state. - Default: ``None`` - nodes (int, List[int] or None, optional): Additional nodes to include in the initial graph state. - Default: ``None`` - name (str or None, optional): The name of the pattern. Default: ``None`` - reupload (bool, optional): Whether to use data re-uploading. Default: ``False`` + state: The input state of the initial graph state. The string representation of state could be + ``'plus'``, ``'minus'``, ``'zero'``, and ``'one'``. Default: ``'plus'`` + edges: Additional edges connecting the nodes in the initial graph state. Default: ``None`` + nodes: Additional nodes to include in the initial graph state. Default: ``None`` + name: The name of the pattern. Default: ``None`` + reupload: Whether to use data re-uploading. Default: ``False`` Ref: V. Danos, E. Kashefi and P. Panangaden. J. ACM 54.2 8 (2007) """ @@ -67,11 +65,11 @@ def forward(self, data: torch.Tensor | None = None, state: GraphState | None = N """Perform a forward pass of the MBQC pattern and return the final graph state. Args: - data (torch.Tensor or None, optional): The input data for the ``encoders``. Default: ``None`` - state (GraphState or None, optional): The initial graph state for the pattern. Default: ``None`` + data: The input data for the ``encoders``. Default: ``None`` + state: The initial graph state for the pattern. Default: ``None`` Returns: - GraphState: The final graph state of the pattern after applying the ``commands``. + The final graph state of the pattern after applying the ``commands``. """ if state is None: self.state = deepcopy(self.init_state) @@ -94,7 +92,7 @@ def encode(self, data: torch.Tensor | None) -> None: the parameters. Args: - data (torch.Tensor or None): The input data for the ``encoders``, could be a 1D or 2D tensor. + data: The input data for the ``encoders``, could be a 1D or 2D tensor. Raises: AssertionError: If input data is shorter than the number of parameters in the ``encoders``. @@ -126,15 +124,13 @@ def add_graph( """Add a subgraph state to the graph state. Args: - nodes_state (int, List[int] or None, optional): The nodes of the input state in the subgraph state. + nodes_state: The nodes of the input state in the subgraph state. It can be an integer representing the number of nodes or a list of node indices. Default: ``None`` - state (Any, optional): The input state of the subgraph state. The string representation of state - could be ``'plus'``, ``'minus'``, ``'zero'``, and ``'one'``. Default: ``'plus'`` - edges (List or None, optional): Additional edges connecting the nodes in the subgraph state. - Default: ``None`` - nodes (int, List[int] or None, optional): Additional nodes to include in the subgraph state. - Default: ``None`` - index (int or None, optional): The index where to insert the subgraph state. Default: ``None`` + state: The input state of the subgraph state. The string representation of state could be + ``'plus'``, ``'minus'``, ``'zero'``, and ``'one'``. Default: ``'plus'`` + edges: Additional edges connecting the nodes in the subgraph state. Default: ``None`` + nodes: Additional nodes to include in the subgraph state. Default: ``None`` + index: The index where to insert the subgraph state. Default: ``None`` """ self.init_state.add_subgraph(nodes_state=nodes_state, state=state, edges=edges, nodes=nodes, index=index) @@ -154,9 +150,9 @@ def add(self, op: Operation, encode: bool = False) -> None: """A method that adds an operation to the MBQC pattern. Args: - op (Operation): The operation to add. It is an instance of ``Operation`` class or its subclasses, + op: The operation to add. It is an instance of ``Operation`` class or its subclasses, such as ``Node``, ``Entanglement``, ``Measurement``, or ``Correction``. - encode (bool): Whether the command is to encode data. Default: ``False`` + encode: Whether the command is to encode data. Default: ``False`` """ assert isinstance(op, Operation) self.commands.append(op) @@ -256,7 +252,7 @@ def is_standard(self) -> bool: """Determine whether the command sequence is standard. Returns: - bool: ``True`` if the pattern follows NEMC standardization, ``False`` otherwise + ``True`` if the pattern follows NEMC standardization, ``False`` otherwise """ it = iter(self.commands) try: @@ -275,13 +271,14 @@ def is_standard(self) -> bool: return True # If we run out of operations, pattern is standard # ----------------------------------------------------------------------------- - # Based on code from Graphix - # Copyright (c) 2022 Team Graphix + # Adapted from Graphix + # Original Copyright (c) 2022 Team Graphix + # Modified work Copyright (c) 2025-2026 TuringQ # Licensed under the Apache License, Version 2.0 # Source: https://github.com/TeamGraphix/graphix/blob/0ca40c196c55da6bbb0488a8ea1045f2572fd0b6/graphix/pattern.py#L287 # # Modifications: - # - Refactoring to fit internal data structures + # - Refactored to fit internal data structures. # ----------------------------------------------------------------------------- def standardize(self) -> None: """Standardize the command sequence into NEMC form. @@ -347,13 +344,14 @@ def add_correction_domain(domain_dict: dict, node, domain) -> None: ) # ----------------------------------------------------------------------------- - # Based on code from Graphix - # Copyright (c) 2022 Team Graphix + # Adapted from Graphix + # Original Copyright (c) 2022 Team Graphix + # Modified work Copyright (c) 2025-2026 TuringQ # Licensed under the Apache License, Version 2.0 # Source: https://github.com/TeamGraphix/graphix/blob/0ca40c196c55da6bbb0488a8ea1045f2572fd0b6/graphix/pattern.py#L426 # # Modifications: - # - Refactoring to fit internal data structures and conventions + # - Refactored to fit internal data structures and conventions. # ----------------------------------------------------------------------------- def shift_signals(self) -> dict: """Perform signal shifting procedure. @@ -365,10 +363,10 @@ def shift_signals(self) -> dict: 1. Extracting signals via t_domain (in XY plane cases) of measurements. 2. Moving signals to the left, through modifying other measurements and corrections. - Returns: - Dict: A signal dictionary including all the signal shifting commands. - See https://arxiv.org/pdf/0704.1263 Ch.(5.5) + + Returns: + A signal dictionary including all the signal shifting commands. """ signal_dict = {} diff --git a/src/deepquantum/mbqc/state.py b/src/deepquantum/mbqc/state.py index a486a53..2ee3b28 100644 --- a/src/deepquantum/mbqc/state.py +++ b/src/deepquantum/mbqc/state.py @@ -17,12 +17,12 @@ class SubGraphState(nn.Module): """A subgraph state of a quantum state. Args: - nodes_state (int, List[int] or None, optional): The nodes of the input state in the subgraph state. + nodes_state: The nodes of the input state in the subgraph state. It can be an integer representing the number of nodes or a list of node indices. Default: ``None`` - state (Any, optional): The input state of the subgraph state. The string representation of state - could be ``'plus'``, ``'minus'``, ``'zero'``, and ``'one'``. Default: ``'plus'`` - edges (List or None, optional): Additional edges connecting the nodes in the subgraph state. Default: ``None`` - nodes (int, List[int] or None, optional): Additional nodes to include in the subgraph state. Default: ``None`` + state: The input state of the subgraph state. The string representation of state could be + ``'plus'``, ``'minus'``, ``'zero'``, and ``'one'``. Default: ``'plus'`` + edges: Additional edges connecting the nodes in the subgraph state. Default: ``None`` + nodes: Additional nodes to include in the subgraph state. Default: ``None`` """ def __init__( @@ -157,11 +157,11 @@ def compose(self, other: 'SubGraphState', relabel: bool = True) -> 'SubGraphStat """Compose this subgraph state with another subgraph state. Args: - other (SubGraphState): The other subgraph state to compose with. - relabel (bool, optional): Whether to relabel nodes to avoid conflicts. Default: ``True`` + other: The other subgraph state to compose with. + relabel: Whether to relabel nodes to avoid conflicts. Default: ``True`` Returns: - SubGraphState: A new subgraph state that is the composition of the two. + A new subgraph state that is the composition of the two. """ if relabel and (set(self.nodes) & set(other.nodes)): shift = max(self.nodes) - min(other.nodes) + 1 @@ -187,7 +187,7 @@ def update_node2wire_dict(self) -> dict: """Update the mapping from nodes to wire indices. Returns: - Dict: A dictionary mapping nodes to their corresponding wire indices. + A dictionary mapping nodes to their corresponding wire indices. """ if self.nodes_out_seq is None: wires = inverse_permutation(np.argsort(self.nodes).tolist()) @@ -208,14 +208,12 @@ class GraphState(nn.Module): """A graph state composed by several SubGraphStates. Args: - nodes_state (int, List[int] or None, optional): The nodes of the input state in the initial graph state. + nodes_state: The nodes of the input state in the initial graph state. It can be an integer representing the number of nodes or a list of node indices. Default: ``None`` - state (Any, optional): The input state of the initial graph state. The string representation of state - could be ``'plus'``, ``'minus'``, ``'zero'``, and ``'one'``. Default: ``'plus'`` - edges (List or None, optional): Additional edges connecting the nodes in the initial graph state. - Default: ``None`` - nodes (int, List[int] or None, optional): Additional nodes to include in the initial graph state. - Default: ``None`` + state: The input state of the initial graph state. The string representation of state could be + ``'plus'``, ``'minus'``, ``'zero'``, and ``'one'``. Default: ``'plus'`` + edges: Additional edges connecting the nodes in the initial graph state. Default: ``None`` + nodes: Additional nodes to include in the initial graph state. Default: ``None`` """ def __init__( @@ -248,16 +246,14 @@ def add_subgraph( """Add a subgraph state to the graph state. Args: - nodes_state (int, List[int] or None, optional): The nodes of the input state in the subgraph state. + nodes_state: The nodes of the input state in the subgraph state. It can be an integer representing the number of nodes or a list of node indices. Default: ``None`` - state (Any, optional): The input state of the subgraph state. The string representation of state - could be ``'plus'``, ``'minus'``, ``'zero'``, and ``'one'``. Default: ``'plus'`` - edges (List or None, optional): Additional edges connecting the nodes in the subgraph state. - Default: ``None`` - nodes (int, List[int] or None, optional): Additional nodes to include in the subgraph state. - Default: ``None`` - measure_dict (Dict or None, optional): A dictionary containing all measurement results. Default: ``None`` - index (int or None, optional): The index where to insert the subgraph state. Default: ``None`` + state: The input state of the subgraph state. The string representation of state could be + ``'plus'``, ``'minus'``, ``'zero'``, and ``'one'``. Default: ``'plus'`` + edges: Additional edges connecting the nodes in the subgraph state. Default: ``None`` + nodes: Additional nodes to include in the subgraph state. Default: ``None`` + measure_dict: A dictionary containing all measurement results. Default: ``None`` + index: The index where to insert the subgraph state. Default: ``None`` """ sgs = SubGraphState(nodes_state, state, edges, nodes) if index is None: diff --git a/src/deepquantum/operation.py b/src/deepquantum/operation.py index 3d216af..98e17ad 100644 --- a/src/deepquantum/operation.py +++ b/src/deepquantum/operation.py @@ -16,14 +16,13 @@ class Operation(nn.Module): r"""A base class for quantum operations. Args: - name (str or None, optional): The name of the quantum operation. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + name: The name of the quantum operation. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -111,16 +110,15 @@ class Gate(Operation): r"""A base class for quantum gates. Args: - name (str or None, optional): The name of the gate. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - controls (int, List[int] or None, optional): The indices of the control qubits. Default: ``None`` - condition (bool, optional): Whether to use ``controls`` as conditional measurement. Default: ``False`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + name: The name of the gate. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + controls: The indices of the control qubits. Default: ``None`` + condition: Whether to use ``controls`` as conditional measurement. Default: ``False`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ # include default names in QASM @@ -415,14 +413,13 @@ class Layer(Operation): r"""A base class for quantum layers. Args: - name (str, optional): The name of the layer. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int | list[int] | list[list[int]] | None, optional): The indices of the qubits that - the quantum operation acts on. Default: ``None`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + name: The name of the layer. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -535,14 +532,13 @@ class Channel(Operation): r"""A base class for quantum channels. Args: - inputs (Any, optional): The parameter of the channel. Default: ``None`` - name (str or None, optional): The name of the channel. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` - requires_grad (bool, optional): Whether the parameter is ``nn.Parameter`` or ``buffer``. + inputs: The parameter of the channel. Default: ``None`` + name: The name of the channel. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + requires_grad: Whether the parameter is ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) """ @@ -647,18 +643,17 @@ class GateQPD(Gate): r"""A base class for quasiprobability-decomposition gates. Args: - bases (List[Tuple[nn.Sequential, ...]]): A list of tuples describing the operations probabilistically used to + bases: A list of tuples describing the operations probabilistically used to simulate an ideal quantum operation. - coeffs (List[float]): The coefficients for quasiprobability representation. - label (int or None, optional): The label of the gate. Default: ``None`` - name (str or None, optional): The name of the quantum operation. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + coeffs: The coefficients for quasiprobability representation. + label: The label of the gate. Default: ``None`` + name: The name of the quantum operation. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -710,8 +705,8 @@ def forward(self, x: torch.Tensor, idx: int | None = None) -> torch.Tensor: """Perform a forward pass. Args: - x (torch.Tensor): The input tensor. - idx (int, optional): The index of the operation to be applied. Default: 0 + x: The input tensor. + idx: The index of the operation to be applied. Default: ``None`` """ if idx is not None: self.idx = idx @@ -728,9 +723,8 @@ class MeasureQPD(Operation): """A operation for denoting a QPD measurement location. Args: - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` """ def __init__(self, nqubit: int = 1, wires: int | list[int] | None = None) -> None: diff --git a/src/deepquantum/optimizer.py b/src/deepquantum/optimizer.py index 5c12bbf..87b2aac 100644 --- a/src/deepquantum/optimizer.py +++ b/src/deepquantum/optimizer.py @@ -12,11 +12,11 @@ class Optimizer: """A base class for optimizers. Args: - target_func (function): The target function to optimize, more specifically, to minimize. + target_func: The target function to optimize, more specifically, to minimize. It is supposed to accept ``kwargs`` in the format of ``param_init`` as inputs. - param_init (Dict, List, np.ndarray or torch.Tensor): The initial parameters for - the target function. The keys of it should be consistent with inputs of ``target_func``. - random_state (int): The random seed for this optimization process. + param_init: The initial parameters for the target function. + The keys of it should be consistent with inputs of ``target_func``. + random_state: The random seed for this optimization process. """ def __init__(self, target_func, param_init, random_state=0): @@ -44,11 +44,11 @@ class OptimizerBayesian(Optimizer): See https://github.com/bayesian-optimization/BayesianOptimization. Args: - target_func (function): The target function to optimize, more specifically, to minimize. + target_func: The target function to optimize, more specifically, to minimize. It is supposed to accept ``kwargs`` in the format of ``param_init`` as inputs. - param_init (Dict, List, np.ndarray or torch.Tensor): The initial parameters for - the target function. The keys of it should be consistent with inputs of ``target_func``. - random_state (int): The random seed for this optimization process. + param_init: The initial parameters for the target function. + The keys of it should be consistent with inputs of ``target_func``. + random_state: The random seed for this optimization process. Note: In the scenerio of on-chip optimization, the periods of phase shifters are all from 0 to :math:`2\pi`, @@ -116,11 +116,11 @@ class OptimizerSPSA(Optimizer): See https://www.jhuapl.edu/spsa/Pages/MATLAB.htm. Args: - target_func (function): The target function to optimize, more specifically, to minimize. + target_func: The target function to optimize, more specifically, to minimize. It is supposed to accept ``kwargs`` in the format of ``param_init`` as inputs. - param_init (Dict, List, np.ndarray or torch.Tensor): The initial parameters for - the target function. The keys of it should be consistent with inputs of ``target_func``. - random_state (int): The random seed for this optimization process. + param_init: The initial parameters for the target function. + The keys of it should be consistent with inputs of ``target_func``. + random_state: The random seed for this optimization process. """ def __init__(self, target_func, param_init, random_state=0): @@ -194,14 +194,13 @@ class OptimizerFourier(Optimizer): Obtain the gradient approximation from the target function approximation. Args: - target_func (function): The target function to optimize, more specifically, to minimize. + target_func: The target function to optimize, more specifically, to minimize. It is supposed to accept ``kwargs`` in the format of ``param_init`` as inputs. - param_init (Dict, List, np.ndarray or torch.Tensor): The initial parameters for - the target function. The keys of it should be consistent with inputs of ``target_func``. - order (int): The order of Fourier series to approximate. - lr (float): The step length (or equivalently, learning rate) of the learning process - (namely, gradient descent process). - random_state (int): The random seed for this optimization process. + param_init: The initial parameters for the target function. + The keys of it should be consistent with inputs of ``target_func``. + order: The order of Fourier series to approximate. + lr: The learning rate of the learning process (namely, gradient descent process). + random_state: The random seed for this optimization process. """ def __init__(self, target_func, param_init, order=5, lr=0.1, random_state=0): diff --git a/src/deepquantum/photonic/channel.py b/src/deepquantum/photonic/channel.py index d697681..5187b54 100644 --- a/src/deepquantum/photonic/channel.py +++ b/src/deepquantum/photonic/channel.py @@ -21,12 +21,11 @@ class PhotonLoss(Channel): \hat{a}_{\text{out}} = \sqrt{T}\hat{a}_{\text{in}} + \sqrt{1-T}\hat{b}_{\text{vac}} Args: - inputs (Any, optional): The parameter of the channel. Default: ``None`` - nmode (int, optional): The number of modes that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - requires_grad (bool, optional): Whether the parameter is ``nn.Parameter`` or ``buffer``. + inputs: The parameter of the channel. Default: ``None`` + nmode: The number of modes that the quantum operation acts on. Default: 1 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` + requires_grad: Whether the parameter is ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) """ diff --git a/src/deepquantum/photonic/circuit.py b/src/deepquantum/photonic/circuit.py index 9064094..4fa9376 100644 --- a/src/deepquantum/photonic/circuit.py +++ b/src/deepquantum/photonic/circuit.py @@ -78,30 +78,27 @@ class QumodeCircuit(Operation): r"""Photonic quantum circuit. Args: - nmode (int): The number of modes in the circuit. - init_state (Any): The initial state of the circuit. It can be a vacuum state with ``'vac'`` or ``'zeros'``. + nmode: The number of modes in the circuit. + init_state: The initial state of the circuit. It can be a vacuum state with ``'vac'`` or ``'zeros'``. For Fock backend, it can be a Fock basis state, e.g., ``[1,0,0]``, or a Fock state tensor, e.g., ``[(1/2**0.5, [1,0]), (1/2**0.5, [0,1])]``. Alternatively, it can be a tensor representation. For Gaussian backend, it can be arbitrary Gaussian states with ``[cov, mean]``. For Bosonic backend, it can be arbitrary linear combinations of Gaussian states with ``[cov, mean, weight]``, or a list of local Bosonic states. Use ``xxpp`` convention and :math:`\hbar=2` by default. - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - backend (str, optional): Use ``'fock'`` for Fock backend, ``'gaussian'`` for Gaussian backend or + cutoff: The Fock space truncation. Default: ``None`` + backend: Use ``'fock'`` for Fock backend, ``'gaussian'`` for Gaussian backend or ``'bosonic'`` for Bosonic backend. Default: ``'fock'`` - basis (bool, optional): Whether to use the representation of Fock basis state for the initial state. - Default: ``True`` - den_mat (bool, optional): Whether to use density matrix representation. Only valid for Fock state tensor. - Default: ``False`` - detector (str, optional): For Gaussian backend, use ``'pnrd'`` for the photon-number-resolving detector - or ``'threshold'`` for the threshold detector. Default: ``'pnrd'`` - name (str or None, optional): The name of the circuit. Default: ``None`` - mps (bool, optional): Whether to use matrix product state representation. Default: ``False`` - chi (int or None, optional): The bond dimension for matrix product state representation. - Default: ``None`` - noise (bool, optional): Whether to introduce Gaussian noise. Default: ``False`` - mu (float, optional): The mean of Gaussian noise. Default: 0 - sigma (float, optional): The standard deviation of Gaussian noise. Default: 0.1 + basis: Whether to use the representation of Fock basis state for the initial state. Default: ``True`` + den_mat: Whether to use density matrix representation. Only valid for Fock state tensor. Default: ``False`` + detector: For Gaussian backend, use ``'pnrd'`` for the photon-number-resolving detector or + ``'threshold'`` for the threshold detector. Default: ``'pnrd'`` + name: The name of the circuit. Default: ``None`` + mps: Whether to use matrix product state representation. Default: ``False`` + chi: The bond dimension for matrix product state representation. Default: ``None`` + noise: Whether to introduce Gaussian noise. Default: ``False`` + mu: The mean of Gaussian noise. Default: 0 + sigma: The standard deviation of Gaussian noise. Default: 0.1 """ def __init__( @@ -284,21 +281,19 @@ def forward( """Perform a forward pass of the photonic quantum circuit and return the final-state-related result. Args: - data (torch.Tensor or None, optional): The input data for the ``encoders``. Default: ``None`` - state (Any, optional): The initial state for the photonic quantum circuit. Default: ``None`` - is_prob (bool or None, optional): For Fock backend, whether to return probabilities or amplitudes. + data: The input data for the ``encoders``. Default: ``None`` + state: The initial state for the photonic quantum circuit. Default: ``None`` + is_prob: For Fock backend, whether to return probabilities or amplitudes. For Gaussian (Bosonic) backend, whether to return probabilities or the final Gaussian (Bosonic) state. For Fock backend with ``basis=True``, set ``None`` to return the unitary matrix. Default: ``None`` - detector (str or None, optional): For Gaussian backend, use ``'pnrd'`` for the photon-number-resolving - detector or ``'threshold'`` for the threshold detector. Default: ``None`` - sort (bool, optional): Whether to sort dictionary of Fock basis states in the descending - order of probabilities. Default: ``True`` - stepwise (bool, optional): Whether to use the forward function of each operator for Gaussian backend. - Default: ``False`` + detector: For Gaussian backend, use ``'pnrd'`` for the photon-number-resolving detector or + ``'threshold'`` for the threshold detector. Default: ``None`` + sort: Whether to sort dictionary of Fock basis states in the descending order of probabilities. + Default: ``True`` + stepwise: Whether to use the forward function of each operator for Gaussian backend. Default: ``False`` Returns: - Union[torch.Tensor, Dict, List[torch.Tensor]]: The result of the photonic quantum circuit after - applying the ``operators``. + The result of the photonic quantum circuit after applying the ``operators``. """ if self.backend == 'fock': return self._forward_fock(data, state, is_prob, sort) @@ -311,16 +306,16 @@ def _forward_fock( """Perform a forward pass based on the Fock backend. Args: - data (torch.Tensor or None, optional): The input data for the ``encoders``. Default: ``None`` - state (Any, optional): The initial state for the photonic quantum circuit. Default: ``None`` - is_prob (bool or None, optional): Whether to return probabilities or amplitudes. - When ``basis=True``, set ``None`` to return the unitary matrix. Default: ``None`` - sort (bool, optional): Whether to sort dictionary of Fock basis states in the descending - order of probabilities. Default: ``True`` + data: The input data for the ``encoders``. Default: ``None`` + state: The initial state for the photonic quantum circuit. Default: ``None`` + is_prob: Whether to return probabilities or amplitudes. When ``basis=True``, set ``None`` to + return the unitary matrix. Default: ``None`` + sort: Whether to sort dictionary of Fock basis states in the descending order of probabilities. + Default: ``True`` Returns: - Union[torch.Tensor, Dict, List[torch.Tensor]]: Unitary matrix, Fock state tensor, - a dictionary of probabilities or amplitudes, or a list of tensors for MPS. + Unitary matrix, Fock state tensor, a dictionary of probabilities or amplitudes, or + a list of tensors for MPS. """ if self.mps: assert not is_prob @@ -449,17 +444,16 @@ def _forward_cv( """Perform a forward pass based on the Gaussian (Bosonic) backend. Args: - data (torch.Tensor or None, optional): The input data for the ``encoders``. Default: ``None`` - state (Any, optional): The initial state for the photonic quantum circuit. Default: ``None`` - is_prob (bool or None, optional): Whether to return probabilities or the final Gaussian (Bosonic) state. - Default: ``None`` - detector (str or None, optional): Use ``'pnrd'`` for the photon-number-resolving detector or + data: The input data for the ``encoders``. Default: ``None`` + state: The initial state for the photonic quantum circuit. Default: ``None`` + is_prob: Whether to return probabilities or the final Gaussian (Bosonic) state. Default: ``None`` + detector: Use ``'pnrd'`` for the photon-number-resolving detector or ``'threshold'`` for the threshold detector. Only valid when ``is_prob`` is ``True``. Default: ``None`` - stepwise (bool, optional): Whether to use the forward function of each operator. Default: ``False`` + stepwise: Whether to use the forward function of each operator. Default: ``False`` Returns: - Union[List[torch.Tensor], Dict]: The final Gaussian (Bosonic) state or a dictionary of probabilities. + The final Gaussian (Bosonic) state or a dictionary of probabilities. """ if state is None: if self.backend == 'bosonic' and self._bosonic_states is not None: @@ -531,10 +525,10 @@ def _forward_cv_prob( """Get the probabilities of all possible final states for Gaussian (Bosonic) backend by different detectors. Args: - cov (torch.Tensor): The covariance matrices of the Gaussian states. - mean (torch.Tensor): The displacement vectors of the Gaussian states. - weight (torch.Tensor or None, optional): The weights of the Gaussian states. Default: ``None`` - detector (str or None, optional): Use ``'pnrd'`` for the photon-number-resolving detector or + cov: The covariance matrices of the Gaussian states. + mean: The displacement vectors of the Gaussian states. + weight: The weights of the Gaussian states. Default: ``None`` + detector: Use ``'pnrd'`` for the photon-number-resolving detector or ``'threshold'`` for the threshold detector. Default: ``None`` """ assert weight is None, 'Currently Fock probability is not supported in Bosonic backend' @@ -616,8 +610,8 @@ def set_fock_basis(self, state: Any = None, reset_in_forward: bool = False) -> N By default it will generate all Fock basis states according to the inital state. Args: - state (Any, optional): The output Fock basis states. Default: ``None`` - reset_in_forward (bool, optional): Whether to recompute the output Fock basis states in the forward pass. + state: The output Fock basis states. Default: ``None`` + reset_in_forward: Whether to recompute the output Fock basis states in the forward pass. Default: ``False`` """ assert self.basis @@ -863,7 +857,7 @@ def encode(self, data: torch.Tensor | None) -> None: with the input data. Args: - data (torch.Tensor or None): The input data for the ``encoders``, must be a 1D tensor. + data: The input data for the ``encoders``, must be a 1D tensor. """ if data is None: return @@ -969,9 +963,9 @@ def get_amplitude( the amplitudes of the reduced states can not be added, please try ``get_prob`` instead. Args: - final_state (Any): The final Fock basis state. - init_state (Any, optional): The initial Fock basis state. Default: ``None`` - unitary (torch.Tensor or None, optional): The unitary matrix. Default: ``None`` + final_state: The final Fock basis state. + init_state: The initial Fock basis state. Default: ``None`` + unitary: The unitary matrix. Default: ``None`` """ assert self.backend == 'fock' if not isinstance(final_state, torch.Tensor): @@ -1012,9 +1006,9 @@ def get_prob(self, final_state: Any, refer_state: Any = None, unitary: torch.Ten """Get the probability of the final state related to the reference state. Args: - final_state (Any): The final Fock basis state. - refer_state (Any, optional): The initial Fock basis state or the final Gaussian state. Default: ``None`` - unitary (torch.Tensor or None, optional): The unitary matrix. Default: ``None`` + final_state: The final Fock basis state. + refer_state: The initial Fock basis state or the final Gaussian state. Default: ``None`` + unitary: The unitary matrix. Default: ``None`` """ if not isinstance(final_state, torch.Tensor): final_state = torch.tensor(final_state, dtype=torch.long) @@ -1064,9 +1058,9 @@ def _get_prob_fock( """Get the transfer probability between the final state and the initial state for the Fock backend. Args: - final_state (Any): The final Fock basis state. - init_state (Any, optional): The initial Fock basis state. Default: ``None`` - unitary (torch.Tensor or None, optional): The unitary matrix. Default: ``None`` + final_state: The final Fock basis state. + init_state: The initial Fock basis state. Default: ``None`` + unitary: The unitary matrix. Default: ``None`` """ if init_state is None: # when mcmc nmode = self.nmode + self._nloss + self._is_batch_expanded @@ -1186,9 +1180,9 @@ def _get_prob_mps(self, final_state: Any, wires: int | list[int] | None = None) """Get the probability of the given bit string for MPS. Args: - final_state (Any): The final Fock basis state. - wires (int, List[int] or None, optional): The wires to measure. It can be an integer or a list of - integers specifying the indices of the wires. + final_state: The final Fock basis state. + wires: The wires to measure. It can be an integer or a list of integers specifying + the indices of the wires. """ if isinstance(final_state, FockState): final_state = final_state.state.tolist() @@ -1212,14 +1206,14 @@ def measure( """Measure the final state. Args: - shots (int, optional): The number of times to sample from the quantum state. Default: 1024 - with_prob (bool, optional): A flag that indicates whether to return the probabilities along with - the number of occurrences. Default: ``False`` - wires (int, List[int] or None, optional): The wires to measure. It can be an integer or a list of - integers specifying the indices of the wires. Default: ``None`` (which means all wires are measured) - detector (str or None, optional): For Gaussian backend, use ``'pnrd'`` for the photon-number-resolving - detector or ``'threshold'`` for the threshold detector. Default: ``None`` - mcmc (bool, optional): Whether to use MCMC sampling method. Default: ``False`` + shots: The number of times to sample from the quantum state. Default: 1024 + with_prob: A flag that indicates whether to return the probabilities along with the number of occurrences. + Default: ``False`` + wires: The wires to measure. It can be an integer or a list of integers specifying + the indices of the wires. Default: ``None`` (which means all wires are measured) + detector: For Gaussian backend, use ``'pnrd'`` for the photon-number-resolving detector or + ``'threshold'`` for the threshold detector. Default: ``None`` + mcmc: Whether to use MCMC sampling method. Default: ``False`` See https://arxiv.org/pdf/2108.01622 for MCMC. """ @@ -1331,7 +1325,7 @@ def _measure_fock_unitary_helper( """VMAP helper for measuring the final state according to the unitary matrix for Fock backend. Returns: - Dict: A dictionary of probabilities for final states. + A dictionary of probabilities for final states. """ if final_states is None: final_states = self._out_fock_basis @@ -1400,7 +1394,7 @@ def _measure_fock_tensor(self, shots: int, with_prob: bool, wires: list[int]) -> ptrace_probs = probs.sum(dim=sum_idx) for p_state in combi: p_state_b = FockState(list(p_state)) - prob_dict[p_state_b] = ptrace_probs[p_state] + prob_dict[p_state_b] = ptrace_probs[p_state].reshape(-1) results = self._prob_dict_to_measure_result(prob_dict, shots, with_prob) all_results.append(results) return all_results @@ -1410,7 +1404,7 @@ def _measure_mps(self, shots: int, with_prob: bool, wires: list[int]) -> list[di all_results = [] samples = [] for _ in range(shots): - samples.append(self._generate_chain_sample(wires)) + samples.append(self._generate_chain_sample(wires, self.detector)) for j in range(samples[0].shape[0]): samples_j = [tuple(sample[j].tolist()) for sample in samples] samples_j = dict(Counter(samples_j)) @@ -1551,13 +1545,12 @@ def _generate_chain_sample(self, wires: list[int], detector: str) -> torch.Tenso """Generate batched random samples via chain rule. Args: - wires (list[int]): The wires to measure. It can be a list of integers specifying the indices - of the wires. - detector (str): For Gaussian backend, use ``'pnrd'`` for the photon-number-resolving detector - or ``'threshold'`` for the threshold detector. + wires: The wires to measure. It can be a list of integers specifying the indices of the wires. + detector: For Gaussian backend, use ``'pnrd'`` for the photon-number-resolving detector or + ``'threshold'`` for the threshold detector. Returns: - torch.Tensor: Tensor of shape (batch, nwire). + Tensor of shape (batch, nwire). """ sample = [] if self.backend == 'fock': @@ -1579,19 +1572,20 @@ def _generate_chain_sample(self, wires: list[int], detector: str) -> torch.Tenso def _generate_chain_sample_gaussian(self, wires: list[int], detector: str) -> torch.Tensor: """Generate batched random samples via chain rule for Gaussian backend. - See https://research-information.bris.ac.uk/en/studentTheses/classical-simulations-of-gaussian-boson-sampling + See + https://research-information.bris.ac.uk/en/studentTheses/classical-simulations-of-gaussian-boson-sampling Chapter 5 """ def _sample_wire(sample, cov_sub, mean_sub, cutoff, detector): - """Sample for a wire""" + """Sample for a wire.""" states = [torch.tensor(sample + [i], device=cov_sub.device) for i in range(cutoff)] probs = [self._get_probs_gaussian_helper(s, cov_sub, mean_sub, detector) for s in states] sample_wire = torch.multinomial(torch.cat(probs), num_samples=1) return sample_wire def _sample_pure(cov, mean, wires, nmode, cutoff, detector): - """Sample for a pure state""" + """Sample for a pure state.""" wires = torch.tensor(wires, device=cov.device) sample = [] for i in range(1, len(wires) + 1): @@ -1603,7 +1597,7 @@ def _sample_pure(cov, mean, wires, nmode, cutoff, detector): return torch.cat(sample) def _sample_mixed(cov, mean, wires, nmode, cutoff, detector, eps=5e-5): - """Sample for a mixed state""" + """Sample for a mixed state.""" wires = torch.tensor(wires, device=cov.device) _, s = williamson(cov) cov_t = s @ s.mT * dqp.hbar / (4 * dqp.kappa**2) @@ -1652,9 +1646,8 @@ def photon_number_mean_var(self, wires: int | list[int] | None = None) -> tuple[ """Get the expectation value and variance of the photon number operator. Args: - wires (int, List[int] or None, optional): The wires to measure. It can be an integer or a list of - integers specifying the indices of the wires. Default: ``None`` (which means all wires are - measured) + wires: The wires to measure. It can be an integer or a list of integers specifying + the indices of the wires. Default: ``None`` (which means all wires are measured) """ if self.state is None: return @@ -1708,11 +1701,9 @@ def quadrature_mean(self, wires: int | list[int] | None = None, phi: Any | None and the input arguments ``wires`` and ``phi`` are ignored. Args: - wires (int, List[int] or None, optional): The wires to measure. It can be an integer or a list of - integers specifying the indices of the wires. Default: ``None`` (which means all wires are - measured). - phi (Any or None, optional): The phi angles for quadrature operator - :math:`\hat{X}\cos\phi + \hat{P}\sin\phi`. Default: ``None`` + wires: The wires to measure. It can be an integer or a list of integers specifying + the indices of the wires. Default: ``None`` (which means all wires are measured). + phi: The phi angles for quadrature operator :math:`\hat{X}\cos\phi + \hat{P}\sin\phi`. Default: ``None`` """ if len(self.measurements) == 0: if wires is None: @@ -1765,12 +1756,12 @@ def extract_blocks(mat: torch.Tensor, idx: torch.Tensor) -> torch.Tensor: """Extract specified blocks from the input tensor. Args: - mat (torch.Tensor): Input tensor. - idx (torch.Tensor): Index tensor of shape (nblock, block_size), where each row contains - the row/column indices for a block. + mat: Input tensor. + idx: Index tensor of shape (nblock, block_size), where each row contains the row/column indices for + a block. Returns: - torch.Tensor: Output tensor of shape (batch, nblock, block_size, -1) containing all extracted blocks. + Output tensor of shape (batch, nblock, block_size, -1) containing all extracted blocks. """ nblock, block_size = idx.shape if mat.shape[-2] == mat.shape[-1]: # cov @@ -1803,10 +1794,9 @@ def measure_homodyne(self, shots: int = 10, wires: int | list[int] | None = None ``batch`` * ``shots`` can not be too large for Fock backend. Args: - shots (int, optional): The number of times to sample from the quantum state. Default: 10 - wires (int, List[int] or None, optional): The wires to measure for the ideal homodyne. It can be - an integer or a list of integers specifying the indices of the wires. Default: ``None`` (which means - all wires are measured) + shots: The number of times to sample from the quantum state. Default: 10 + wires: The wires to measure for the ideal homodyne. It can be an integer or a list of integers specifying + the indices of the wires. Default: ``None`` (which means all wires are measured) """ if self.state is None: return @@ -1873,8 +1863,8 @@ def draw(self, filename: str | None = None, unroll: bool = False): """Visualize the photonic quantum circuit. Args: - filename (str or None, optional): The path for saving the figure. - unroll (bool, optional): Whether to draw the unrolled circuit. + filename: The path for saving the figure. + unroll: Whether to draw the unrolled circuit. """ if self._with_delay and unroll: self._prepare_unroll_dict() @@ -1928,12 +1918,11 @@ def add(self, op: Operation, encode: bool = False, wires: int | list[int] | None are shared. Args: - op (Operation): The operation to add. It is an instance of ``Operation`` class or its subclasses, - such as ``Gate``, or ``QumodeCircuit``. - encode (bool, optional): Whether the gate is to encode data. Default: ``False`` - wires (int, List[int] or None, optional): The wires to apply the gate on. It can be an integer - or a list of integers specifying the indices of the wires. Default: ``None`` (which means - the gate has its own wires) + op: The operation to add. It is an instance of ``Operation`` class or its subclasses, such as + ``Gate``, or ``QumodeCircuit``. + encode: Whether the gate is to encode data. Default: ``False`` + wires: The wires to apply the gate on. It can be an integer or a list of integers specifying + the indices of the wires. Default: ``None`` (which means the gate has its own wires) Raises: AssertionError: If the input arguments are invalid or incompatible with the quantum circuit. @@ -2864,12 +2853,12 @@ class DistributedQumodeCircuit(QumodeCircuit): """Photonic quantum circuit for a distributed Fock state. Args: - nmode (int): The number of modes in the circuit. - init_state (Any): The initial state of the circuit. It can be a vacuum state with ``'vac'`` or ``'zeros'``. + nmode: The number of modes in the circuit. + init_state: The initial state of the circuit. It can be a vacuum state with ``'vac'`` or ``'zeros'``. It can be a Fock basis state, e.g., ``[1,0,0]``, or a Fock state tensor, e.g., ``[(1/2**0.5, [1,0]), (1/2**0.5, [0,1])]``. - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - name (str or None, optional): The name of the circuit. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` + name: The name of the circuit. Default: ``None`` """ def __init__(self, nmode: int, init_state: Any, cutoff: int | None = None, name: str | None = None) -> None: @@ -2908,9 +2897,8 @@ def forward( The ``data`` must be a 1D tensor. Args: - data (torch.Tensor or None, optional): The input data for the ``encoders``. Default: ``None`` - state (DistributedFockState or None, optional): The initial state for the photonic quantum circuit. - Default: ``None`` + data: The input data for the ``encoders``. Default: ``None`` + state: The initial state for the photonic quantum circuit. Default: ``None`` """ if state is None: self.init_state.reset() @@ -2926,12 +2914,12 @@ def measure( """Measure the final state. Args: - shots (int, optional): The number of times to sample from the quantum state. Default: 1024 - with_prob (bool, optional): A flag that indicates whether to return the probabilities along with - the number of occurrences. Default: ``False`` - wires (int, List[int] or None, optional): The wires to measure. It can be an integer or a list of - integers specifying the indices of the wires. Default: ``None`` (which means all wires are measured) - block_size (int, optional): The block size for sampling. Default: 2 ** 24 + shots: The number of times to sample from the quantum state. Default: 1024 + with_prob: A flag that indicates whether to return the probabilities along with the number of occurrences. + Default: ``False`` + wires: The wires to measure. It can be an integer or a list of integers specifying + the indices of the wires. Default: ``None`` (which means all wires are measured) + block_size: The block size for sampling. Default: 2**24 """ if wires is None: wires = list(range(self.nmode)) diff --git a/src/deepquantum/photonic/decompose.py b/src/deepquantum/photonic/decompose.py index 40d478c..c21c606 100644 --- a/src/deepquantum/photonic/decompose.py +++ b/src/deepquantum/photonic/decompose.py @@ -10,9 +10,9 @@ class UnitaryDecomposer: """This class is to decompose a unitary matrix into the Clements/Reck architecture. Args: - unitary (np.ndarray or torch.Tensor): The unitary matrix to be decomposed. - method (str, optional): The decomposition method, only 16 values (``'rssr'``, ``'rsdr'``, ``'rdsr'``, - ``'rddr'``, ``'rssl'``, ``'rsdl'``, ``'rdsl'``, ``'rddl'``, ``'cssr'``, ``'csdr'``, ``'cdsr'``, ``'cddr'``, + unitary: The unitary matrix to be decomposed. + method: The decomposition method, only 16 values (``'rssr'``, ``'rsdr'``, ``'rdsr'``, ``'rddr'``, + ``'rssl'``, ``'rsdl'``, ``'rdsl'``, ``'rddl'``, ``'cssr'``, ``'csdr'``, ``'cdsr'``, ``'cddr'``, ``'cssl'``, ``'csdl'``, ``'cdsl'``, ``'cddl'``) are valid. The first char denotes the Clements or Reck architecture. The second char denotes single or double arms of outer phase shifters. diff --git a/src/deepquantum/photonic/draw.py b/src/deepquantum/photonic/draw.py index 77bec00..c496ca6 100644 --- a/src/deepquantum/photonic/draw.py +++ b/src/deepquantum/photonic/draw.py @@ -48,10 +48,10 @@ class DrawCircuit: """Draw the photonic quantum circuit. Args: - circuit_name (str): The name of the circuit. - circuit_nmode (int): The number of modes in the circuit. - circuit_operators (nn.Sequential): The operators of the circuit. - measurements (nn.ModuleList): The measurements of the circuit. + circuit_name: The name of the circuit. + circuit_nmode: The number of modes in the circuit. + circuit_operators: The operators of the circuit. + measurements: The measurements of the circuit. """ def __init__( @@ -502,12 +502,11 @@ class DrawClements: """Draw the n-mode Clements architecture. Args: - nmode (int): The number of modes of the Clements architecture. - mzi_info (Dict): The dictionary for mzi parameters, resulting from the decompose function. - cl (str, optional): The color for plotting. Default: ``'dodgerblue'`` - fs (int, optional): The fontsize. Default: 30 - method (str, optional): The way for Clements decomposition, ``'cssr'`` or ``'cssl'``. - Default: ``'cssr'`` + nmode: The number of modes of the Clements architecture. + mzi_info: The dictionary for mzi parameters, resulting from the decompose function. + cl: The color for plotting. Default: ``'dodgerblue'`` + fs: The fontsize. Default: 30 + method: The way for Clements decomposition, ``'cssr'`` or ``'cssl'``. Default: ``'cssr'`` """ def __init__(self, nmode: int, mzi_info: dict, cl: str = 'dodgerblue', fs: int = 30, method: str = 'cssr') -> None: diff --git a/src/deepquantum/photonic/gate.py b/src/deepquantum/photonic/gate.py index 4923c50..1e8d125 100644 --- a/src/deepquantum/photonic/gate.py +++ b/src/deepquantum/photonic/gate.py @@ -18,18 +18,17 @@ class SingleGate(Gate): """A base class for single-mode photonic quantum gates. Args: - name (str or None, optional): The name of the gate. Default: ``None`` - inputs (Any, optional): The parameters of the gate. Default: ``None`` - nmode (int, optional): The number of modes that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - requires_grad (bool, optional): Whether the parameter is ``nn.Parameter`` or ``buffer``. + name: The name of the gate. Default: ``None`` + inputs: The parameters of the gate. Default: ``None`` + nmode: The number of modes that the quantum operation acts on. Default: 1 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + requires_grad: Whether the parameter is ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) - noise (bool, optional): Whether to introduce Gaussian noise. Default: ``False`` - mu (float, optional): The mean of Gaussian noise. Default: 0 - sigma (float, optional): The standard deviation of Gaussian noise. Default: 0.1 + noise: Whether to introduce Gaussian noise. Default: ``False`` + mu: The mean of Gaussian noise. Default: 0 + sigma: The standard deviation of Gaussian noise. Default: 0.1 """ def __init__( @@ -57,18 +56,17 @@ class DoubleGate(Gate): """A base class for two-mode photonic quantum gates. Args: - name (str or None, optional): The name of the gate. Default: ``None`` - inputs (Any, optional): The parameters of the gate. Default: ``None`` - nmode (int, optional): The number of modes that the quantum operation acts on. Default: 2 - wires (int, List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - requires_grad (bool, optional): Whether the parameter is ``nn.Parameter`` or ``buffer``. + name: The name of the gate. Default: ``None`` + inputs: The parameters of the gate. Default: ``None`` + nmode: The number of modes that the quantum operation acts on. Default: 2 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + requires_grad: Whether the parameter is ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) - noise (bool, optional): Whether to introduce Gaussian noise. Default: ``False`` - mu (float, optional): The mean of Gaussian noise. Default: 0 - sigma (float, optional): The standard deviation of Gaussian noise. Default: 0.1 + noise: Whether to introduce Gaussian noise. Default: ``False`` + mu: The mean of Gaussian noise. Default: 0 + sigma: The standard deviation of Gaussian noise. Default: 0.1 """ def __init__( @@ -123,18 +121,17 @@ class PhaseShift(SingleGate): \end{pmatrix} Args: - inputs (Any, optional): The parameter of the gate. Default: ``None`` - nmode (int, optional): The number of modes that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - requires_grad (bool, optional): Whether the parameter is ``nn.Parameter`` or ``buffer``. + inputs: The parameter of the gate. Default: ``None`` + nmode: The number of modes that the quantum operation acts on. Default: 1 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + requires_grad: Whether the parameter is ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) - noise (bool, optional): Whether to introduce Gaussian noise. Default: ``False`` - mu (float, optional): The mean of Gaussian noise. Default: 0 - sigma (float, optional): The standard deviation of Gaussian noise. Default: 0.1 - inv_mode (bool, optional): Whether the rotation in the phase space is clockwise. Default: ``False`` + noise: Whether to introduce Gaussian noise. Default: ``False`` + mu: The mean of Gaussian noise. Default: 0 + sigma: The standard deviation of Gaussian noise. Default: 0.1 + inv_mode: Whether the rotation in the phase space is clockwise. Default: ``False`` """ def __init__( @@ -270,17 +267,16 @@ class BeamSplitter(DoubleGate): \end{pmatrix} Args: - inputs (Any, optional): The parameters of the gate (:math:`\theta` and :math:`\phi`). Default: ``None`` - nmode (int, optional): The number of modes that the quantum operation acts on. Default: 2 - wires (List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - requires_grad (bool, optional): Whether the parameters are ``nn.Parameter`` or ``buffer``. + inputs: The parameters of the gate (:math:`\theta` and :math:`\phi`). Default: ``None`` + nmode: The number of modes that the quantum operation acts on. Default: 2 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + requires_grad: Whether the parameters are ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) - noise (bool, optional): Whether to introduce Gaussian noise. Default: ``False`` - mu (float, optional): The mean of Gaussian noise. Default: 0 - sigma (float, optional): The standard deviation of Gaussian noise. Default: 0.1 + noise: Whether to introduce Gaussian noise. Default: ``False`` + mu: The mean of Gaussian noise. Default: 0 + sigma: The standard deviation of Gaussian noise. Default: 0.1 """ def __init__( @@ -465,18 +461,17 @@ class MZI(BeamSplitter): \end{pmatrix} Args: - inputs (Any, optional): The parameters of the gate (:math:`\theta` and :math:`\phi`). Default: ``None`` - nmode (int, optional): The number of modes that the quantum operation acts on. Default: 2 - wires (List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - phi_first (bool, optional): Whether :math:`\phi` is the first phase shifter. Default: ``True`` - requires_grad (bool, optional): Whether the parameters are ``nn.Parameter`` or ``buffer``. + inputs: The parameters of the gate (:math:`\theta` and :math:`\phi`). Default: ``None`` + nmode: The number of modes that the quantum operation acts on. Default: 2 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + phi_first: Whether :math:`\phi` is the first phase shifter. Default: ``True`` + requires_grad: Whether the parameters are ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) - noise (bool, optional): Whether to introduce Gaussian noise. Default: ``False`` - mu (float, optional): The mean of Gaussian noise. Default: 0 - sigma (float, optional): The standard deviation of Gaussian noise. Default: 0.1 + noise: Whether to introduce Gaussian noise. Default: ``False`` + mu: The mean of Gaussian noise. Default: 0 + sigma: The standard deviation of Gaussian noise. Default: 0.1 """ def __init__( @@ -557,17 +552,16 @@ class BeamSplitterTheta(BeamSplitter): \end{pmatrix} Args: - inputs (Any, optional): The parameter of the gate. Default: ``None`` - nmode (int, optional): The number of modes that the quantum operation acts on. Default: 2 - wires (List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - requires_grad (bool, optional): Whether the parameter is ``nn.Parameter`` or ``buffer``. + inputs: The parameter of the gate. Default: ``None`` + nmode: The number of modes that the quantum operation acts on. Default: 2 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + requires_grad: Whether the parameter is ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) - noise (bool, optional): Whether to introduce Gaussian noise. Default: ``False`` - mu (float, optional): The mean of Gaussian noise. Default: 0 - sigma (float, optional): The standard deviation of Gaussian noise. Default: 0.1 + noise: Whether to introduce Gaussian noise. Default: ``False`` + mu: The mean of Gaussian noise. Default: 0 + sigma: The standard deviation of Gaussian noise. Default: 0.1 """ def __init__( @@ -655,17 +649,16 @@ class BeamSplitterPhi(BeamSplitter): \end{pmatrix} Args: - inputs (Any, optional): The parameter of the gate. Default: ``None`` - nmode (int, optional): The number of modes that the quantum operation acts on. Default: 2 - wires (List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - requires_grad (bool, optional): Whether the parameter is ``nn.Parameter`` or ``buffer``. + inputs: The parameter of the gate. Default: ``None`` + nmode: The number of modes that the quantum operation acts on. Default: 2 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + requires_grad: Whether the parameter is ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) - noise (bool, optional): Whether to introduce Gaussian noise. Default: ``False`` - mu (float, optional): The mean of Gaussian noise. Default: 0 - sigma (float, optional): The standard deviation of Gaussian noise. Default: 0.1 + noise: Whether to introduce Gaussian noise. Default: ``False`` + mu: The mean of Gaussian noise. Default: 0 + sigma: The standard deviation of Gaussian noise. Default: 0.1 """ def __init__( @@ -775,19 +768,18 @@ class BeamSplitterSingle(BeamSplitter): \end{pmatrix} Args: - inputs (Any, optional): The parameter of the gate. Default: ``None`` - nmode (int, optional): The number of modes that the quantum operation acts on. Default: 2 - wires (List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - convention (str, optional): The convention of the type of the beam splitter, including ``'rx'``, - ``'ry'`` and ``'h'``. Default: ``'rx'`` - requires_grad (bool, optional): Whether the parameter is ``nn.Parameter`` or ``buffer``. + inputs: The parameter of the gate. Default: ``None`` + nmode: The number of modes that the quantum operation acts on. Default: 2 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + convention: The convention of the type of the beam splitter, including ``'rx'``, ``'ry'`` and ``'h'``. + Default: ``'rx'`` + requires_grad: Whether the parameter is ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) - noise (bool, optional): Whether to introduce Gaussian noise. Default: ``False`` - mu (float, optional): The mean of Gaussian noise. Default: 0 - sigma (float, optional): The standard deviation of Gaussian noise. Default: 0.1 + noise: Whether to introduce Gaussian noise. Default: ``False`` + mu: The mean of Gaussian noise. Default: 0 + sigma: The standard deviation of Gaussian noise. Default: 0.1 """ def __init__( @@ -888,15 +880,14 @@ class UAnyGate(Gate): """Arbitrary unitary gate. Args: - unitary (Any): Any given unitary matrix. - nmode (int, optional): The number of modes that the quantum operation acts on. Default: 1 - wires (List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - minmax (List[int] or None, optional): The minimum and maximum indices of the modes that the quantum + unitary: Any given unitary matrix. + nmode: The number of modes that the quantum operation acts on. Default: 1 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + minmax: The minimum and maximum indices of the modes that the quantum operation acts on. Only valid when ``wires`` is ``None``. Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - name (str, optional): The name of the gate. Default: ``'UAnyGate'`` + cutoff: The Fock space truncation. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + name: The name of the gate. Default: ``'UAnyGate'`` """ def __init__( @@ -1021,17 +1012,16 @@ class Squeezing(SingleGate): \end{pmatrix} Args: - inputs (Any, optional): The parameters of the gate (:math:`r` and :math:`\theta`). Default: ``None`` - nmode (int, optional): The number of modes that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - requires_grad (bool, optional): Whether the parameters are ``nn.Parameter`` or ``buffer``. + inputs: The parameters of the gate (:math:`r` and :math:`\theta`). Default: ``None`` + nmode: The number of modes that the quantum operation acts on. Default: 1 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + requires_grad: Whether the parameters are ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) - noise (bool, optional): Whether to introduce Gaussian noise. Default: ``False`` - mu (float, optional): The mean of Gaussian noise. Default: 0 - sigma (float, optional): The standard deviation of Gaussian noise. Default: 0.1 + noise: Whether to introduce Gaussian noise. Default: ``False`` + mu: The mean of Gaussian noise. Default: 0 + sigma: The standard deviation of Gaussian noise. Default: 0.1 """ def __init__( @@ -1188,17 +1178,16 @@ class Squeezing2(DoubleGate): \end{pmatrix} Args: - inputs (Any, optional): The parameters of the gate (:math:`r` and :math:`\theta`). Default: ``None`` - nmode (int, optional): The number of modes that the quantum operation acts on. Default: 2 - wires (int, List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - requires_grad (bool, optional): Whether the parameters are ``nn.Parameter`` or ``buffer``. + inputs: The parameters of the gate (:math:`r` and :math:`\theta`). Default: ``None`` + nmode: The number of modes that the quantum operation acts on. Default: 2 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + requires_grad: Whether the parameters are ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) - noise (bool, optional): Whether to introduce Gaussian noise. Default: ``False`` - mu (float, optional): The mean of Gaussian noise. Default: 0 - sigma (float, optional): The standard deviation of Gaussian noise. Default: 0.1 + noise: Whether to introduce Gaussian noise. Default: ``False`` + mu: The mean of Gaussian noise. Default: 0 + sigma: The standard deviation of Gaussian noise. Default: 0.1 """ def __init__( @@ -1362,17 +1351,16 @@ class Displacement(SingleGate): \end{pmatrix} Args: - inputs (Any, optional): The parameters of the gate (:math:`r` and :math:`\theta`). Default: ``None`` - nmode (int, optional): The number of modes that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - requires_grad (bool, optional): Whether the parameters are ``nn.Parameter`` or ``buffer``. + inputs: The parameters of the gate (:math:`r` and :math:`\theta`). Default: ``None`` + nmode: The number of modes that the quantum operation acts on. Default: 1 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + requires_grad: Whether the parameters are ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) - noise (bool, optional): Whether to introduce Gaussian noise. Default: ``False`` - mu (float, optional): The mean of Gaussian noise. Default: 0 - sigma (float, optional): The standard deviation of Gaussian noise. Default: 0.1 + noise: Whether to introduce Gaussian noise. Default: ``False`` + mu: The mean of Gaussian noise. Default: 0 + sigma: The standard deviation of Gaussian noise. Default: 0.1 """ def __init__( @@ -1518,17 +1506,16 @@ class DisplacementPosition(Displacement): \end{pmatrix} Args: - inputs (Any, optional): The parameter of the gate. Default: ``None`` - nmode (int, optional): The number of modes that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - requires_grad (bool, optional): Whether the parameter is ``nn.Parameter`` or ``buffer``. + inputs: The parameter of the gate. Default: ``None`` + nmode: The number of modes that the quantum operation acts on. Default: 1 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + requires_grad: Whether the parameter is ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) - noise (bool, optional): Whether to introduce Gaussian noise. Default: ``False`` - mu (float, optional): The mean of Gaussian noise. Default: 0 - sigma (float, optional): The standard deviation of Gaussian noise. Default: 0.1 + noise: Whether to introduce Gaussian noise. Default: ``False`` + mu: The mean of Gaussian noise. Default: 0 + sigma: The standard deviation of Gaussian noise. Default: 0.1 """ def __init__( @@ -1603,17 +1590,16 @@ class DisplacementMomentum(Displacement): \end{pmatrix} Args: - inputs (Any, optional): The parameter of the gate. Default: ``None`` - nmode (int, optional): The number of modes that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - requires_grad (bool, optional): Whether the parameter is ``nn.Parameter`` or ``buffer``. + inputs: The parameter of the gate. Default: ``None`` + nmode: The number of modes that the quantum operation acts on. Default: 1 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + requires_grad: Whether the parameter is ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) - noise (bool, optional): Whether to introduce Gaussian noise. Default: ``False`` - mu (float, optional): The mean of Gaussian noise. Default: 0 - sigma (float, optional): The standard deviation of Gaussian noise. Default: 0.1 + noise: Whether to introduce Gaussian noise. Default: ``False`` + mu: The mean of Gaussian noise. Default: 0 + sigma: The standard deviation of Gaussian noise. Default: 0.1 """ def __init__( @@ -1722,17 +1708,16 @@ class QuadraticPhase(SingleGate): \phi = -\sign(s)\frac{\pi}{2} - \theta`. Args: - inputs (Any, optional): The parameter of the gate. Default: ``None`` - nmode (int, optional): The number of modes that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - requires_grad (bool, optional): Whether the parameters are ``nn.Parameter`` or ``buffer``. + inputs: The parameter of the gate. Default: ``None`` + nmode: The number of modes that the quantum operation acts on. Default: 1 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + requires_grad: Whether the parameters are ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) - noise (bool, optional): Whether to introduce Gaussian noise. Default: ``False`` - mu (float, optional): The mean of Gaussian noise. Default: 0 - sigma (float, optional): The standard deviation of Gaussian noise. Default: 0.1 + noise: Whether to introduce Gaussian noise. Default: ``False`` + mu: The mean of Gaussian noise. Default: 0 + sigma: The standard deviation of Gaussian noise. Default: 0.1 """ def __init__( @@ -1902,17 +1887,16 @@ class ControlledX(DoubleGate): \sinh(r) = -\frac{s}{2}`. Args: - inputs (Any, optional): The parameter of the gate. Default: ``None`` - nmode (int, optional): The number of modes that the quantum operation acts on. Default: 2 - wires (int, List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - requires_grad (bool, optional): Whether the parameters are ``nn.Parameter`` or ``buffer``. + inputs: The parameter of the gate. Default: ``None`` + nmode: The number of modes that the quantum operation acts on. Default: 2 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + requires_grad: Whether the parameters are ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) - noise (bool, optional): Whether to introduce Gaussian noise. Default: ``False`` - mu (float, optional): The mean of Gaussian noise. Default: 0 - sigma (float, optional): The standard deviation of Gaussian noise. Default: 0.1 + noise: Whether to introduce Gaussian noise. Default: ``False`` + mu: The mean of Gaussian noise. Default: 0 + sigma: The standard deviation of Gaussian noise. Default: 0.1 """ def __init__( @@ -2086,17 +2070,16 @@ class ControlledZ(DoubleGate): CZ(s) = PS_2(\pi/2) CX(s) PS_2^\dagger(\pi/2) Args: - inputs (Any, optional): The parameter of the gate. Default: ``None`` - nmode (int, optional): The number of modes that the quantum operation acts on. Default: 2 - wires (int, List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - requires_grad (bool, optional): Whether the parameters are ``nn.Parameter`` or ``buffer``. + inputs: The parameter of the gate. Default: ``None`` + nmode: The number of modes that the quantum operation acts on. Default: 2 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + requires_grad: Whether the parameters are ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) - noise (bool, optional): Whether to introduce Gaussian noise. Default: ``False`` - mu (float, optional): The mean of Gaussian noise. Default: 0 - sigma (float, optional): The standard deviation of Gaussian noise. Default: 0.1 + noise: Whether to introduce Gaussian noise. Default: ``False`` + mu: The mean of Gaussian noise. Default: 0 + sigma: The standard deviation of Gaussian noise. Default: 0.1 """ def __init__( @@ -2223,17 +2206,16 @@ class CubicPhase(SingleGate): CP^\dagger(\gamma) \hat{p} CP(\gamma) &= \hat{p} + \gamma\hat{x}^2. Args: - inputs (Any, optional): The parameter of the gate. Default: ``None`` - nmode (int, optional): The number of modes that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - requires_grad (bool, optional): Whether the parameters are ``nn.Parameter`` or ``buffer``. + inputs: The parameter of the gate. Default: ``None`` + nmode: The number of modes that the quantum operation acts on. Default: 1 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + requires_grad: Whether the parameters are ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) - noise (bool, optional): Whether to introduce Gaussian noise. Default: ``False`` - mu (float, optional): The mean of Gaussian noise. Default: 0 - sigma (float, optional): The standard deviation of Gaussian noise. Default: 0.1 + noise: Whether to introduce Gaussian noise. Default: ``False`` + mu: The mean of Gaussian noise. Default: 0 + sigma: The standard deviation of Gaussian noise. Default: 0.1 """ def __init__( @@ -2320,17 +2302,16 @@ class Kerr(SingleGate): = e^{i \kappa (2 \hat{a}^\dagger \hat{a} + 1)} \hat{a}^\dagger. Args: - inputs (Any, optional): The parameter of the gate. Default: ``None`` - nmode (int, optional): The number of modes that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - requires_grad (bool, optional): Whether the parameters are ``nn.Parameter`` or ``buffer``. + inputs: The parameter of the gate. Default: ``None`` + nmode: The number of modes that the quantum operation acts on. Default: 1 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + requires_grad: Whether the parameters are ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) - noise (bool, optional): Whether to introduce Gaussian noise. Default: ``False`` - mu (float, optional): The mean of Gaussian noise. Default: 0 - sigma (float, optional): The standard deviation of Gaussian noise. Default: 0.1 + noise: Whether to introduce Gaussian noise. Default: ``False`` + mu: The mean of Gaussian noise. Default: 0 + sigma: The standard deviation of Gaussian noise. Default: 0.1 """ def __init__( @@ -2420,17 +2401,16 @@ class CrossKerr(DoubleGate): = \hat{a}_2^\dagger e^{-i \kappa \hat{n}_1}. Args: - inputs (Any, optional): The parameter of the gate. Default: ``None`` - nmode (int, optional): The number of modes that the quantum operation acts on. Default: 2 - wires (int, List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - requires_grad (bool, optional): Whether the parameters are ``nn.Parameter`` or ``buffer``. + inputs: The parameter of the gate. Default: ``None`` + nmode: The number of modes that the quantum operation acts on. Default: 2 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + requires_grad: Whether the parameters are ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) - noise (bool, optional): Whether to introduce Gaussian noise. Default: ``False`` - mu (float, optional): The mean of Gaussian noise. Default: 0 - sigma (float, optional): The standard deviation of Gaussian noise. Default: 0.1 + noise: Whether to introduce Gaussian noise. Default: ``False`` + mu: The mean of Gaussian noise. Default: 0 + sigma: The standard deviation of Gaussian noise. Default: 0.1 """ def __init__( @@ -2502,19 +2482,18 @@ class DelayBS(Delay): r"""Delay loop with ``BeamSplitterTheta`` and ``PhaseShift``. Args: - inputs (Any, optional): The parameters of the gate. Default: ``None`` - ntau (int, optional): The number of modes in the delay loop. Default: 1 - nmode (int, optional): The number of spatial modes that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - requires_grad (bool, optional): Whether the parameters are ``nn.Parameter`` or ``buffer``. + inputs: The parameters of the gate. Default: ``None`` + ntau: The number of modes in the delay loop. Default: 1 + nmode: The number of spatial modes that the quantum operation acts on. Default: 1 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + requires_grad: Whether the parameters are ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) - loop_gates (List[Gate] or None, optional): The list of gates added to the delay loop. Default: ``None`` - noise (bool, optional): Whether to introduce Gaussian noise. Default: ``False`` - mu (float, optional): The mean of Gaussian noise. Default: 0 - sigma (float, optional): The standard deviation of Gaussian noise. Default: 0.1 + loop_gates: The list of gates added to the delay loop. Default: ``None`` + noise: Whether to introduce Gaussian noise. Default: ``False`` + mu: The mean of Gaussian noise. Default: 0 + sigma: The standard deviation of Gaussian noise. Default: 0.1 """ def __init__( @@ -2590,19 +2569,18 @@ class DelayMZI(Delay): r"""Delay loop with MZI. Args: - inputs (Any, optional): The parameters of the gate. Default: ``None`` - ntau (int, optional): The number of modes in the delay loop. Default: 1 - nmode (int, optional): The number of spatial modes that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - requires_grad (bool, optional): Whether the parameters are ``nn.Parameter`` or ``buffer``. + inputs: The parameters of the gate. Default: ``None`` + ntau: The number of modes in the delay loop. Default: 1 + nmode: The number of spatial modes that the quantum operation acts on. Default: 1 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + requires_grad: Whether the parameters are ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) - loop_gates (List[Gate] or None, optional): The list of gates added to the delay loop. Default: ``None`` - noise (bool, optional): Whether to introduce Gaussian noise. Default: ``False`` - mu (float, optional): The mean of Gaussian noise. Default: 0 - sigma (float, optional): The standard deviation of Gaussian noise. Default: 0.1 + loop_gates: The list of gates added to the delay loop. Default: ``None`` + noise: Whether to introduce Gaussian noise. Default: ``False`` + mu: The mean of Gaussian noise. Default: 0 + sigma: The standard deviation of Gaussian noise. Default: 0.1 """ def __init__( @@ -2666,10 +2644,9 @@ class Barrier(Gate): """Barrier. Args: - nmode (int, optional): The number of modes that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` + nmode: The number of modes that the quantum operation acts on. Default: 1 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` """ def __init__(self, nmode: int = 1, wires: int | list[int] | None = None, cutoff: int | None = None) -> None: diff --git a/src/deepquantum/photonic/mapper.py b/src/deepquantum/photonic/mapper.py index 4aed46a..711a7b0 100644 --- a/src/deepquantum/photonic/mapper.py +++ b/src/deepquantum/photonic/mapper.py @@ -19,15 +19,13 @@ class UnitaryMapper: """Map the quantum gate to the unitary matrix of the photonic quantum circuit based on dual-rail encoding. Args: - nqubit (int): The number of qubits of the quantum gates. - nmode (int): The number of modes in the circuit. - ugate (Any): The target quantum gate. - success (float): The square root of the probability of the target quantum gate. + nqubit: The number of qubits of the quantum gates. + nmode: The number of modes in the circuit. + ugate: The target quantum gate. + success: The square root of the probability of the target quantum gate. The preferred value is 1/3 for 2 qubits or 1/4 for 3 qubits. - aux (List or None, optional): Two auxiliary modes in the circuit, which could be ``[0,0]`` or ``[1,0]``. - Default: ``None`` - aux_pos (List or None, optional): The positions of the auxiliary modes. - Default: ``None`` (which means the last two modes). + aux: Two auxiliary modes in the circuit, which could be ``[0,0]`` or ``[1,0]``. Default: ``None`` + aux_pos: The positions of the auxiliary modes. Default: ``None`` (which means the last two modes). """ def __init__( diff --git a/src/deepquantum/photonic/measurement.py b/src/deepquantum/photonic/measurement.py index d0867ef..094917d 100644 --- a/src/deepquantum/photonic/measurement.py +++ b/src/deepquantum/photonic/measurement.py @@ -20,16 +20,15 @@ class Generaldyne(Operation): """General-dyne measurement. Args: - cov_m (Any): The covariance matrix for the general-dyne measurement. - nmode (int, optional): The number of modes that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - name (str, optional): The name of the measurement. Default: ``'Generaldyne'`` - noise (bool, optional): Whether to introduce Gaussian noise. Default: ``False`` - mu (float, optional): The mean of Gaussian noise. Default: 0 - sigma (float, optional): The standard deviation of Gaussian noise. Default: 0.1 + cov_m: The covariance matrix for the general-dyne measurement. + nmode: The number of modes that the quantum operation acts on. Default: 1 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + name: The name of the measurement. Default: ``'Generaldyne'`` + noise: Whether to introduce Gaussian noise. Default: ``False`` + mu: The mean of Gaussian noise. Default: 0 + sigma: The standard deviation of Gaussian noise. Default: 0.1 """ def __init__( @@ -128,19 +127,18 @@ class Homodyne(Generaldyne): """Homodyne measurement. Args: - phi (Any, optional): The homodyne measurement angle. Default: ``None`` - nmode (int, optional): The number of modes that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - eps (float, optional): The measurement accuracy. Default: 2e-4 - requires_grad (bool, optional): Whether the parameter is ``nn.Parameter`` or ``buffer``. + phi: The homodyne measurement angle. Default: ``None`` + nmode: The number of modes that the quantum operation acts on. Default: 1 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + eps: The measurement accuracy. Default: 2e-4 + requires_grad: Whether the parameter is ``nn.Parameter`` or ``buffer``. Default: ``False`` (which means ``buffer``) - noise (bool, optional): Whether to introduce Gaussian noise. Default: ``False`` - mu (float, optional): The mean of Gaussian noise. Default: 0 - sigma (float, optional): The standard deviation of Gaussian noise. Default: 0.1 - name (str, optional): The name of the measurement. Default: ``'Homodyne'`` + noise: Whether to introduce Gaussian noise. Default: ``False`` + mu: The mean of Gaussian noise. Default: 0 + sigma: The standard deviation of Gaussian noise. Default: 0.1 + name: The name of the measurement. Default: ``'Homodyne'`` """ def __init__( @@ -259,13 +257,12 @@ class GeneralBosonic(Operation): """General Bosonic measurement. Args: - cov (Any): The covariance matrices for the general Bosonic measurement. - weight (Any): The weights for the general Bosonic measurement. - nmode (int, optional): The number of modes that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - name (str, optional): The name of the measurement. Default: ``'GeneralBosonic'`` + cov: The covariance matrices for the general Bosonic measurement. + weight: The weights for the general Bosonic measurement. + nmode: The number of modes that the quantum operation acts on. Default: 1 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` + name: The name of the measurement. Default: ``'GeneralBosonic'`` """ def __init__( @@ -366,13 +363,12 @@ class PhotonNumberResolvingBosonic(GeneralBosonic): """Photon-number-resolving measurement for Bosonic state. Args: - n (int): Photon number. - r (Any, optional): The quality parameter for the approximation. Default: 0.05 - nmode (int, optional): The number of modes that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - name (str, optional): The name of the measurement. Default: ``'PhotonNumberResolvingBosonic'`` + n: Photon number. + r: The quality parameter for the approximation. Default: 0.05 + nmode: The number of modes that the quantum operation acts on. Default: 1 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` + name: The name of the measurement. Default: ``'PhotonNumberResolvingBosonic'`` """ def __init__( diff --git a/src/deepquantum/photonic/operation.py b/src/deepquantum/photonic/operation.py index 2e1b2d2..73c5ebe 100644 --- a/src/deepquantum/photonic/operation.py +++ b/src/deepquantum/photonic/operation.py @@ -16,15 +16,14 @@ class Operation(nn.Module): """A base class for quantum operations. Args: - name (str or None, optional): The name of the quantum operation. Default: ``None`` - nmode (int, optional): The number of modes that the quantum operation acts on. Default: 1 - wires (int, List or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int, optional): The Fock space truncation. Default: 2 - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - noise (bool, optional): Whether to introduce Gaussian noise. Default: ``False`` - mu (float, optional): The mean of Gaussian noise. Default: 0 - sigma (float, optional): The standard deviation of Gaussian noise. Default: 0.1 + name: The name of the quantum operation. Default: ``None`` + nmode: The number of modes that the quantum operation acts on. Default: 1 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: 2 + den_mat: Whether to use density matrix representation. Default: ``False`` + noise: Whether to introduce Gaussian noise. Default: ``False`` + mu: The mean of Gaussian noise. Default: 0 + sigma: The standard deviation of Gaussian noise. Default: 0.1 """ def __init__( @@ -87,15 +86,14 @@ class Gate(Operation): r"""A base class for photonic quantum gates. Args: - name (str or None, optional): The name of the gate. Default: ``None`` - nmode (int, optional): The number of modes that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - noise (bool, optional): Whether to introduce Gaussian noise. Default: ``False`` - mu (float, optional): The mean of Gaussian noise. Default: 0 - sigma (float, optional): The standard deviation of Gaussian noise. Default: 0.1 + name: The name of the gate. Default: ``None`` + nmode: The number of modes that the quantum operation acts on. Default: 1 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + noise: Whether to introduce Gaussian noise. Default: ``False`` + mu: The mean of Gaussian noise. Default: 0 + sigma: The standard deviation of Gaussian noise. Default: 0.1 """ def __init__( @@ -280,11 +278,10 @@ class Channel(Operation): r"""A base class for photonic quantum channels. Args: - name (str or None, optional): The name of the channel. Default: ``None`` - nmode (int, optional): The number of modes that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` + name: The name of the channel. Default: ``None`` + nmode: The number of modes that the quantum operation acts on. Default: 1 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` """ def __init__( @@ -349,16 +346,15 @@ class Delay(Operation): r"""Delay loop. Args: - name (str or None, optional): The name of the quantum operation. Default: ``'Delay'`` - ntau (int, optional): The number of modes in the delay loop. Default: 1 - nmode (int, optional): The number of spatial modes that the quantum operation acts on. Default: 1 - wires (int, List[int] or None, optional): The indices of the modes that the quantum operation acts on. - Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - noise (bool, optional): Whether to introduce Gaussian noise. Default: ``False`` - mu (float, optional): The mean of Gaussian noise. Default: 0 - sigma (float, optional): The standard deviation of Gaussian noise. Default: 0.1 + name: The name of the quantum operation. Default: ``'Delay'`` + ntau: The number of modes in the delay loop. Default: 1 + nmode: The number of spatial modes that the quantum operation acts on. Default: 1 + wires: The indices of the modes that the quantum operation acts on. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` + den_mat: Whether to use density matrix representation. Default: ``False`` + noise: Whether to introduce Gaussian noise. Default: ``False`` + mu: The mean of Gaussian noise. Default: 0 + sigma: The standard deviation of Gaussian noise. Default: 0.1 """ def __init__( diff --git a/src/deepquantum/photonic/qmath.py b/src/deepquantum/photonic/qmath.py index 2ef4ea3..1bdf8e3 100644 --- a/src/deepquantum/photonic/qmath.py +++ b/src/deepquantum/photonic/qmath.py @@ -57,9 +57,9 @@ def sub_matrix(u: torch.Tensor, input_state: torch.Tensor, output_state: torch.T The rows are chosen according to the output state and the columns are chosen according to the input state. Args: - u (torch.Tensor): The unitary matrix. - input_state (torch.Tensor): The input state. - output_state (torch.Tensor): The output state. + u: The unitary matrix. + input_state: The input state. + output_state: The output state. """ with warnings.catch_warnings(): warnings.filterwarnings('ignore') # local warning @@ -138,18 +138,17 @@ def product_factorial(state: torch.Tensor) -> torch.Tensor: return torch.exp(torch.lgamma(state.double() + 1).sum(-1, keepdim=True)) # nature log gamma function -def fock_combinations(nmode: int, nphoton: int, cutoff: int | None = None, nancilla: int = 0) -> list: +def fock_combinations(nmode: int, nphoton: int, cutoff: int | None = None, nancilla: int = 0) -> list[list[int]]: """Generate all possible combinations of Fock states for a given number of modes, photons, and cutoff. Args: - nmode (int): The number of modes in the system. - nphoton (int): The total number of photons in the system. - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - nancilla (int, optional): The number of ancilla modes (NOT limited by ``cutoff``). Default: ``0`` + nmode: The number of modes in the system. + nphoton: The total number of photons in the system. + cutoff: The Fock space truncation. Default: ``None`` + nancilla: The number of ancilla modes (NOT limited by ``cutoff``). Default: ``0`` Returns: - List[List[int]]: A list of all possible Fock states, each represented by a list of - occupation numbers for each mode. + A list of all possible Fock states, each represented by a list of occupation numbers for each mode. Examples: >>> fock_combinations(2, 3) @@ -167,9 +166,9 @@ def backtrack(state: list[int], length: int, num_sum: int) -> None: """A helper function that uses backtracking to generate all possible Fock states. Args: - state (List[int]): The current Fock state being constructed. - length (int): The remaining number of modes to be filled. - num_sum (int): The remaining number of photons to be distributed. + state: The current Fock state being constructed. + length: The remaining number of modes to be filled. + num_sum: The remaining number of photons to be distributed. """ if length == 0: if num_sum == 0: @@ -230,8 +229,8 @@ def quadrature_to_ladder(tensor: torch.Tensor, symplectic: bool = False) -> torc """Transform the representation in ``xxpp`` ordering to the representation in ``aaa^+a^+`` ordering. Args: - tensor (torch.Tensor): The input tensor in ``xxpp`` ordering. - symplectic (bool, optional): Whether the transformation is applied for symplectic matrix or Gaussian state. + tensor: The input tensor in ``xxpp`` ordering. + symplectic: Whether the transformation is applied for symplectic matrix or Gaussian state. Default: ``False`` (which means covariance matrix or displacement vector) """ nmode = tensor.shape[-2] // 2 @@ -251,8 +250,8 @@ def ladder_to_quadrature(tensor: torch.Tensor, symplectic: bool = False) -> torc """Transform the representation in ``aaa^+a^+`` ordering to the representation in ``xxpp`` ordering. Args: - tensor (torch.Tensor): The input tensor in ``aaa^+a^+`` ordering. - symplectic (bool, optional): Whether the transformation is applied for symplectic matrix or Gaussian state. + tensor: The input tensor in ``aaa^+a^+`` ordering. + symplectic: Whether the transformation is applied for symplectic matrix or Gaussian state. Default: ``False`` (which means covariance matrix or displacement vector) """ nmode = tensor.shape[-2] // 2 @@ -470,15 +469,14 @@ def measure_fock_tensor( r"""Measure the batched Fock state tensors. Args: - state (torch.Tensor): The quantum state to measure. It should be a tensor of shape + state: The quantum state to measure. It should be a tensor of shape :math:`(\text{batch}, \text{cutoff}, ..., \text{cutoff})`. - shots (int, optional): The number of times to sample from the quantum state. Default: 1024 - with_prob (bool, optional): A flag that indicates whether to return the probabilities along with - the number of occurrences. Default: ``False`` - wires (int, List[int] or None, optional): The wires to measure. It can be an integer or a list of - integers specifying the indices of the wires. Default: ``None`` (which means all wires are - measured) - block_size (int, optional): The block size for sampling. Default: 2 ** 24 + shots: The number of times to sample from the quantum state. Default: 1024 + with_prob: A flag that indicates whether to return the probabilities along with the number of occurrences. + Default: ``False`` + wires: The wires to measure. It can be an integer or a list of integers specifying + the indices of the wires. Default: ``None`` (which means all wires are measured) + block_size: The block size for sampling. Default: 2**24 """ from .state import FockState @@ -642,17 +640,16 @@ def fock_to_wigner( See https://qutip.org/docs/4.7/modules/qutip/wigner.html Args: - state (torch.Tensor): The input Fock state tensor or density matrix. - wire (int): The Wigner function for the given wire. - nmode (int): The mode number of the Fock state. - cutoff (int): The Fock space truncation. - den_mat (bool, optional): Whether to use density matrix representation. Only valid for Fock state tensor. - Default: ``False`` - xrange (int or List, optional): The range of quadrature x. Default: 10 - prange (int or List, optional): The range of quadrature p. Default: 10 - npoints (int or List, optional): The number of discretization points for quadratures. Default: 100 - plot (bool, optional): Whether to plot the Wigner function. Default: ``True`` - k (int, optional): The index of the Wigner function within the batch to plot. Default: 0 + state: The input Fock state tensor or density matrix. + wire: The Wigner function for the given wire. + nmode: The mode number of the Fock state. + cutoff: The Fock space truncation. + den_mat: Whether to use density matrix representation. Only valid for Fock state tensor. Default: ``False`` + xrange: The range of quadrature x. Default: 10 + prange: The range of quadrature p. Default: 10 + npoints: The number of discretization points for quadratures. Default: 100 + plot: Whether to plot the Wigner function. Default: ``True`` + k: The index of the Wigner function within the batch to plot. Default: 0 """ if den_mat: rho = state.reshape(-1, cutoff**nmode, cutoff**nmode) @@ -719,14 +716,14 @@ def cv_to_wigner( """Get the discretized Wigner function of the specified mode from a CV state. Args: - state (List): The input ``Gaussianstate`` or ``BosonicState``. - wire (int): The Wigner function for the given wire. - xrange (int or List, optional): The range of quadrature x. Default: 10 - prange (int or List, optional): The range of quadrature p. Default: 10 - npoints (int or List, optional): The number of discretization points for quadratures. Default: 100 - plot (bool, optional): Whether to plot the Wigner function. Default: ``True`` - k (int, optional): The index of the Wigner function within the batch to plot. Default: 0 - normalize (bool, optional): Whether to normalize the Wigner function. Default: ``True`` + state: The input ``Gaussianstate`` or ``BosonicState``. + wire: The Wigner function for the given wire. + xrange: The range of quadrature x. Default: 10 + prange: The range of quadrature p. Default: 10 + npoints: The number of discretization points for quadratures. Default: 100 + plot: Whether to plot the Wigner function. Default: ``True`` + k: The index of the Wigner function within the batch to plot. Default: 0 + normalize: Whether to normalize the Wigner function. Default: ``True`` """ cov, mean = state[:2] xlist = [-xrange, xrange] if isinstance(xrange, int) else xrange @@ -787,10 +784,10 @@ def plot_wigner(wigner: torch.Tensor, xvec: torch.Tensor, pvec: torch.Tensor, k: """Plot a 2D contour and a 3D surface of a discretized Wigner function W(x, p). Args: - wigner (torch.Tensor): Discretized Wigner values with shape (batch, nx, np). - xvec (torch.Tensor): 1D grid for quadrature x. - pvec (torch.Tensor): 1D grid for quadrature p. - k (int, optional): The index of the Wigner function within the batch to plot. Default: 0 + wigner: Discretized Wigner values with shape (batch, nx, np). + xvec: 1D grid for quadrature x. + pvec: 1D grid for quadrature p. + k: The index of the Wigner function within the batch to plot. Default: 0 """ grid_x, grid_y = torch.meshgrid(xvec, pvec, indexing='ij') x = grid_x.cpu() diff --git a/src/deepquantum/photonic/state.py b/src/deepquantum/photonic/state.py index 3fc6d47..5315259 100644 --- a/src/deepquantum/photonic/state.py +++ b/src/deepquantum/photonic/state.py @@ -19,14 +19,13 @@ class FockState(nn.Module): """A Fock state of n modes, including Fock basis states and Fock state tensors. Args: - state (Any): The Fock state. It can be a vacuum state with ``'vac'`` or ``'zeros'``. + state: The Fock state. It can be a vacuum state with ``'vac'`` or ``'zeros'``. It can be a Fock basis state, e.g., ``[1,0,0]``, or a Fock state tensor, e.g., ``[(1/2**0.5, [1,0]), (1/2**0.5, [0,1])]``. Alternatively, it can be a tensor representation. - nmode (int or None, optional): The number of modes in the state. Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - basis (bool, optional): Whether the state is a Fock basis state or not. Default: ``True`` - den_mat (bool, optional): Whether to use density matrix representation. Only valid for Fock state tensor. - Default: ``False`` + nmode: The number of modes in the state. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` + basis: Whether the state is a Fock basis state or not. Default: ``True`` + den_mat: Whether to use density matrix representation. Only valid for Fock state tensor. Default: ``False`` """ def __init__( @@ -126,12 +125,12 @@ def wigner( """Get the discretized Wigner function of the specified mode. Args: - wire (int): The wigner function for given wire. - xrange (int or List, optional): The range of quadrature q. Default: 10 - prange (int or List, optional): The range of quadrature p. Default: 10 - npoints (int or List, optional): The number of discretization points for quadratures. Default: 100 - plot (bool, optional): Whether to plot the wigner function. Default: ``True`` - k (int, optional): The wigner function of kth batch to plot. Default: 0 + wire: The wigner function for given wire. + xrange: The range of quadrature q. Default: 10 + prange: The range of quadrature p. Default: 10 + npoints: The number of discretization points for quadratures. Default: 100 + plot: Whether to plot the wigner function. Default: ``True`` + k: The wigner function of kth batch to plot. Default: 0 """ return fock_to_wigner(self.state, wire, self.nmode, self.cutoff, self.den_mat, xrange, prange, npoints, plot, k) @@ -186,12 +185,12 @@ class GaussianState(nn.Module): r"""A Gaussian state of n modes, representing by covariance matrix and displacement vector. Args: - state (str or List): The Gaussian state. It can be a vacuum state with ``'vac'``, or arbitrary Gaussian state + state: The Gaussian state. It can be a vacuum state with ``'vac'``, or arbitrary Gaussian state with ``[cov, mean]``. ``cov`` and ``mean`` are the covariance matrix and the displacement vector of the Gaussian state, respectively. Use ``xxpp`` convention and :math:`\hbar=2` by default. Default: ``'vac'`` - nmode (int or None, optional): The number of modes in the state. Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` + nmode: The number of modes in the state. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` """ def __init__(self, state: str | list = 'vac', nmode: int | None = None, cutoff: int | None = None) -> None: @@ -247,13 +246,13 @@ def wigner( """Get the discretized Wigner function of the specified mode. Args: - wire (int): The wigner function for given wire. - xrange (int or List, optional): The range of quadrature q. Default: 10 - prange (int or List, optional): The range of quadrature p. Default: 10 - npoints (int or List, optional): The number of discretization points for quadratures. Default: 100 - plot (bool, optional): Whether to plot the wigner function. Default: ``True`` - k (int, optional): The wigner function of kth batch to plot. Default: 0 - normalize (bool, optional): Whether to normalize the wigner function. Default: ``True`` + wire: The wigner function for given wire. + xrange: The range of quadrature q. Default: 10 + prange: The range of quadrature p. Default: 10 + npoints: The number of discretization points for quadratures. Default: 100 + plot: Whether to plot the wigner function. Default: ``True`` + k: The wigner function of kth batch to plot. Default: 0 + normalize: Whether to normalize the wigner function. Default: ``True`` """ return cv_to_wigner([self.cov, self.mean], wire, xrange, prange, npoints, plot, k, normalize) @@ -262,13 +261,13 @@ class BosonicState(nn.Module): r"""A Bosoncic state of n modes, representing by a linear combination of Gaussian states. Args: - state (str or List): The Bosoncic state. It can be a vacuum state with ``'vac'``, or arbitrary + state: The Bosoncic state. It can be a vacuum state with ``'vac'``, or arbitrary linear combinations of Gaussian states with ``[cov, mean, weight]``. ``cov``,``mean`` and ``weight`` are the covariance matrices, the displacement vectors and the weights of the Gaussian states, respectively. Use ``xxpp`` convention and :math:`\hbar=2` by default. Default: ``'vac'`` - nmode (int or None, optional): The number of modes in the state. Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` + nmode: The number of modes in the state. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` """ def __init__(self, state: str | list = 'vac', nmode: int | None = None, cutoff: int | None = None) -> None: @@ -351,13 +350,13 @@ def wigner( """Get the discretized Wigner function of the specified mode. Args: - wire (int): The wigner function for given wire. - xrange (int or List, optional): The range of quadrature q. Default: 10 - prange (int or List, optional): The range of quadrature p. Default: 10 - npoints (int or List, optional): The number of discretization points for quadratures. Default: 100 - plot (bool, optional): Whether to plot the wigner function. Default: ``True`` - k (int, optional): The wigner function of kth batch to plot. Default: 0 - normalize (bool, optional): Whether to normalize the wigner function. Default: ``True`` + wire: The wigner function for given wire. + xrange: The range of quadrature q. Default: 10 + prange: The range of quadrature p. Default: 10 + npoints: The number of discretization points for quadratures. Default: 100 + plot: Whether to plot the wigner function. Default: ``True`` + k: The wigner function of kth batch to plot. Default: 0 + normalize: Whether to normalize the wigner function. Default: ``True`` """ return cv_to_wigner([self.cov, self.mean, self.weight], wire, xrange, prange, npoints, plot, k, normalize) @@ -367,12 +366,12 @@ def marginal( r"""Get the discretized marginal distribution of the specified mode along :math:`x\cos\phi + p\sin\phi`. Args: - wire (int): The marginal function for given wire. - phi (float, optional): The angle used to compute the linear combination of quadratures. Default: 0 - xrange (int or List, optional): The range of quadrature. Default: 10 - npoints (int, optional): The number of discretization points for quadrature. Default: 100 - plot (bool, optional): Whether to plot the marginal function. Default: ``True`` - k (int, optional): The index of the marginal function within the batch to plot. Default: 0 + wire: The marginal function for given wire. + phi: The angle used to compute the linear combination of quadratures. Default: 0 + xrange: The range of quadrature. Default: 10 + npoints: The number of discretization points for quadrature. Default: 100 + plot: Whether to plot the marginal function. Default: ``True`` + k: The index of the marginal function within the batch to plot. Default: 0 """ from .gate import PhaseShift @@ -411,11 +410,11 @@ class CatState(BosonicState): See https://arxiv.org/abs/2103.05530 Section IV B. Args: - r (Any, optional): Displacement magnitude :math:`|r|`. Default: ``None`` - theta (Any, optional): Displacement angle :math:`\theta`. Default: ``None`` - p (int, optional): Parity, where :math:`\theta=p\pi`. ``p=0`` corresponds to an even - cat state, and ``p=1`` an odd cat state. Default: 1 - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` + r: Displacement magnitude :math:`|r|`. Default: ``None`` + theta: Displacement angle :math:`\theta`. Default: ``None`` + p: Parity, where :math:`\theta=p\pi`. ``p=0`` corresponds to an even cat state, and ``p=1`` an odd cat state. + Default: 1 + cutoff: The Fock space truncation. Default: ``None`` """ def __init__(self, r: Any = None, theta: Any = None, p: int = 1, cutoff: int | None = None) -> None: @@ -465,11 +464,11 @@ class GKPState(BosonicState): See https://arxiv.org/abs/2103.05530 Section IV A. Args: - theta (Any, optional): angle :math:`\theta` in Bloch sphere. Default: ``None`` - phi (Any, optional): angle :math:`\phi` in Bloch sphere. Default: ``None`` - amp_cutoff (float, optional): The amplitude threshold for keeping the terms. Default: 0.1 - epsilon (float, optional): The finite energy damping parameter. Default: 0.05 - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` + theta: angle :math:`\theta` in Bloch sphere. Default: ``None`` + phi: angle :math:`\phi` in Bloch sphere. Default: ``None`` + amp_cutoff: The amplitude threshold for keeping the terms. Default: 0.1 + epsilon: The finite energy damping parameter. Default: 0.05 + cutoff: The Fock space truncation. Default: ``None`` """ def __init__( @@ -590,9 +589,9 @@ class FockStateBosonic(BosonicState): See https://arxiv.org/abs/2103.05530 Section IV C. Args: - n (int): Particle number. - r (float, optional): The quality parameter for the approximation. Default: 0.05 - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` + n: Particle number. + r: The quality parameter for the approximation. Default: 0.05 + cutoff: The Fock space truncation. Default: ``None`` """ def __init__(self, n: int, r: Any = 0.05, cutoff: int | None = None) -> None: @@ -615,11 +614,11 @@ class DistributedFockState(nn.Module): """A Fock state of n modes distributed between w nodes. Args: - state (Any): The Fock state. It can be a vacuum state with ``'vac'`` or ``'zeros'``. + state: The Fock state. It can be a vacuum state with ``'vac'`` or ``'zeros'``. It can be a Fock basis state, e.g., ``[1,0,0]``, or a Fock state tensor, e.g., ``[(1/2**0.5, [1,0]), (1/2**0.5, [0,1])]``. - nmode (int or None, optional): The number of modes in the state. Default: ``None`` - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` + nmode: The number of modes in the state. Default: ``None`` + cutoff: The Fock space truncation. Default: ``None`` """ def __init__(self, state: Any, nmode: int | None = None, cutoff: int | None = None) -> None: @@ -683,8 +682,8 @@ def combine_tensors(tensors: list[torch.Tensor], ndim_ds: int = 2) -> torch.Tens """Combine a list of 3D tensors for Bosonic states according to the dimension of direct sum. Args: - tensors (List[torch.Tensor]): The list of 3D tensors to combine. - ndim_ds (int, optional): The dimension of direct sum. Use 1 for direct sum along rows, + tensors: The list of 3D tensors to combine. + ndim_ds: The dimension of direct sum. Use 1 for direct sum along rows, or use 2 for direct sum along both rows and columns. Default: 2 """ assert ndim_ds in (1, 2) @@ -729,9 +728,8 @@ def combine_bosonic_states(states: list[BosonicState], cutoff: int | None = None """Combine multiple Bosonic states into a single state. Args: - states (List[BosonicState]): List of Bosonic states to combine. - cutoff (int or None, optional): The Fock space truncation. If ``None``, the cutoff of the first state is used. - Default: ``None`` + states: List of Bosonic states to combine. + cutoff: The Fock space truncation. If ``None``, the cutoff of the first state is used. Default: ``None`` """ covs = [] means = [] diff --git a/src/deepquantum/photonic/tdm.py b/src/deepquantum/photonic/tdm.py index 5633e11..f9faec0 100644 --- a/src/deepquantum/photonic/tdm.py +++ b/src/deepquantum/photonic/tdm.py @@ -15,17 +15,16 @@ class QumodeCircuitTDM(QumodeCircuit): to avoid issues with non-positive definiteness of the covariance matrix. Args: - nmode (int): The number of spatial modes in the circuit. - init_state (Any): The initial state of the circuit. It can be a vacuum state with ``'vac'``. + nmode: The number of spatial modes in the circuit. + init_state: The initial state of the circuit. It can be a vacuum state with ``'vac'``. For Gaussian backend, it can be arbitrary Gaussian states with ``[cov, mean]``. Use ``xxpp`` convention and :math:`\hbar=2` by default. - cutoff (int or None, optional): The Fock space truncation. Default: ``None`` - backend (str, optional): Use ``'gaussian'`` for Gaussian backend or ``'bosonic'`` for Bosonic backend. - Default: ``'gaussian'`` - name (str or None, optional): The name of the circuit. Default: ``None`` - noise (bool, optional): Whether to introduce Gaussian noise. Default: ``False`` - mu (float, optional): The mean of Gaussian noise. Default: 0 - sigma (float, optional): The standard deviation of Gaussian noise. Default: 0.1 + cutoff: The Fock space truncation. Default: ``None`` + backend: Use ``'gaussian'`` for Gaussian backend or ``'bosonic'`` for Bosonic backend. Default: ``'gaussian'`` + name: The name of the circuit. Default: ``None`` + noise: Whether to introduce Gaussian noise. Default: ``False`` + mu: The mean of Gaussian noise. Default: 0 + sigma: The standard deviation of Gaussian noise. Default: 0.1 """ def __init__( @@ -62,13 +61,13 @@ def forward( r"""Perform a forward pass of the TDM photonic quantum circuit and return the final state. Args: - data (torch.Tensor or None, optional): The input data for the ``encoders`` with the shape of + data: The input data for the ``encoders`` with the shape of :math:`(\text{batch}, \text{ntimes}, \text{nfeat})`. Default: ``None`` - state (Any, optional): The initial state for the photonic quantum circuit. Default: ``None`` - nstep (int or None, optional): The number of the evolved time steps. Default: ``None`` + state: The initial state for the photonic quantum circuit. Default: ``None`` + nstep: The number of the evolved time steps. Default: ``None`` Returns: - List[torch.Tensor]: The covariance matrix and displacement vector of the measured final state. + The covariance matrix and displacement vector of the measured final state. """ assert self._with_delay, 'No delay loop.' for i in range(self.nmode): diff --git a/src/deepquantum/photonic/utils.py b/src/deepquantum/photonic/utils.py index a4d19f3..c668ae8 100644 --- a/src/deepquantum/photonic/utils.py +++ b/src/deepquantum/photonic/utils.py @@ -49,7 +49,8 @@ def save_adj(filename, data): def mem_to_chunksize(device: torch.device, dtype: torch.dtype) -> int | None: """Return the chunk size of vmap according to device free memory and dtype. - Note: Currently only optimized for permanent and complex dtype. + Note: + Currently only optimized for permanent and complex dtype. """ if (device, dtype) in dqp.perm_chunksize_dict: return dqp.perm_chunksize_dict[device, dtype] diff --git a/src/deepquantum/qasm3.py b/src/deepquantum/qasm3.py index 32fd087..c26bdca 100644 --- a/src/deepquantum/qasm3.py +++ b/src/deepquantum/qasm3.py @@ -118,10 +118,10 @@ def cir_to_qasm3(circuit: QubitCircuit) -> str: """Converts ``QubitCircuit`` to an OpenQASM 3.0 string. Args: - circuit (QubitCircuit): The DeepQuantum circuit to convert. + circuit: The DeepQuantum circuit to convert. Returns: - str: A string containing the OpenQASM 3.0 representation of the circuit. + A string containing the OpenQASM 3.0 representation of the circuit. """ qasm_parts = ['OPENQASM 3.0;', 'include "stdgates.inc";'] diff --git a/src/deepquantum/qmath.py b/src/deepquantum/qmath.py index 623920e..9585f91 100644 --- a/src/deepquantum/qmath.py +++ b/src/deepquantum/qmath.py @@ -85,10 +85,10 @@ def inverse_permutation(permute_shape: list[int]) -> list[int]: """Calculate the inversed permutation. Args: - permute_shape (List[int]): Shape of permutation. + permute_shape: Shape of permutation. Returns: - List[int]: A list of integers that is the inverse of ``permute_shape``. + A list of integers that is the inverse of ``permute_shape``. """ # find the index of each element in the range of the list length return [permute_shape.index(i) for i in range(len(permute_shape))] @@ -98,12 +98,12 @@ def is_unitary(matrix: torch.Tensor, rtol: float = 1e-5, atol: float = 1e-4) -> """Check if a tensor is a unitary matrix. Args: - matrix (torch.Tensor): Square matrix. - rtol (float, optional): Relative tolerance. Default: 1e-5 - atol (float, optional): Absolute tolerance. Default: 1e-4 + matrix: Square matrix. + rtol: Relative tolerance. Default: 1e-5 + atol: Absolute tolerance. Default: 1e-4 Returns: - bool: ``True`` if ``matrix`` is unitary, ``False`` otherwise. + ``True`` if ``matrix`` is unitary, ``False`` otherwise. """ if matrix.shape[-1] != matrix.shape[-2]: return False @@ -120,11 +120,11 @@ def is_density_matrix(rho: torch.Tensor) -> bool: A density matrix is a positive semi-definite Hermitian matrix with trace one. Args: - rho (torch.Tensor): The tensor to check. It can be either 2D or 3D. If 3D, the first dimension - is assumed to be the batch dimension. + rho: The tensor to check. It can be either 2D or 3D. If 3D, the first dimension is assumed to be + the batch dimension. Returns: - bool: ``True`` if the tensor is a density matrix, ``False`` otherwise. + ``True`` if the tensor is a density matrix, ``False`` otherwise. """ if not isinstance(rho, torch.Tensor): return False @@ -150,7 +150,7 @@ def is_density_matrix(rho: torch.Tensor) -> bool: def is_positive_definite(mat: torch.Tensor) -> bool: - """Check if the matrix is positive definite""" + """Check if the matrix is positive definite.""" is_herm = torch.equal(mat, mat.mH) diag = torch.linalg.eigvalsh(mat) return is_herm and torch.all(diag > 0).item() @@ -161,10 +161,20 @@ def safe_inverse(x: Any, epsilon: float = 1e-12) -> Any: return x / (x**2 + epsilon) +# ----------------------------------------------------------------------------- +# Adapted from tensorgrad +# Original Copyright (c) 2019 tensorgrad Contributors +# Modified work Copyright (c) 2023-2026 TuringQ +# Licensed under the Apache License, Version 2.0 +# Source: https://github.com/wangleiphy/tensorgrad/blob/732bd6430e86f1b69a8615045ca5b6399ad73061/tensornets/adlib/svd.py#L12 +# +# Modifications: +# - Support complex matrices. +# - Refactored for framework integration and naming consistency. +# ----------------------------------------------------------------------------- class SVD(torch.autograd.Function): """Customized backward of SVD for better numerical stability. - Modified from https://github.com/wangleiphy/tensorgrad/blob/master/tensornets/adlib/svd.py See https://readpaper.com/paper/2971614414 """ @@ -213,7 +223,16 @@ def backward(ctx, du, ds, dvh): return da -# from tensorcircuit +# ----------------------------------------------------------------------------- +# Adapted from TensorCircuit +# Original Copyright (c) 2020 TensorCircuit Contributors +# Modified work Copyright (c) 2023-2026 TuringQ +# Licensed under the Apache License, Version 2.0 +# Source: https://github.com/tencent-quantum-lab/tensorcircuit/blob/cac74977f628e6e623bd34af95454fe55af399c2/tensorcircuit/backends/pytorch_ops.py#L15 +# +# Modifications: +# - Refactored for framework integration and naming consistency. +# ----------------------------------------------------------------------------- def torchqr_grad(a, q, r, dq, dr): """Get the gradient for QR.""" qr_epsilon = 1e-8 @@ -274,7 +293,16 @@ def _qr_grad_square_and_deep_matrices(q, r, dq, dr): return torch.cat([dx, dy], dim=-1) -# from tensorcircuit +# ----------------------------------------------------------------------------- +# Adapted from TensorCircuit +# Original Copyright (c) 2020 TensorCircuit Contributors +# Modified work Copyright (c) 2023-2026 TuringQ +# Licensed under the Apache License, Version 2.0 +# Source: https://github.com/tencent-quantum-lab/tensorcircuit/blob/cac74977f628e6e623bd34af95454fe55af399c2/tensorcircuit/backends/pytorch_ops.py#L87 +# +# Modifications: +# - Refactored for framework integration and naming consistency. +# ----------------------------------------------------------------------------- class QR(torch.autograd.Function): """Customized backward of QR for better numerical stability.""" @@ -363,10 +391,10 @@ def multi_kron(lst: list[torch.Tensor]) -> torch.Tensor: """Calculate the Kronecker/tensor/outer product for a list of tensors. Args: - lst (List[torch.Tensor]): A list of tensors. + lst: A list of tensors. Returns: - torch.Tensor: The Kronecker/tensor/outer product of the input. + The Kronecker/tensor/outer product of the input. """ n = len(lst) if n == 1: @@ -381,14 +409,14 @@ def partial_trace(rho: torch.Tensor, nqudit: int, trace_lst: list[int], qudit: i r"""Calculate the partial trace for a batch of density matrices. Args: - rho (torch.Tensor): Density matrices with the shape of + rho: Density matrices with the shape of :math:`(\text{batch}, \text{qudit}^{\text{nqudit}}, \text{qudit}^{\text{nqudit}})`. - nqudit (int): Total number of qudits. - trace_lst (List[int]): A list of qudits to be traced. - qudit (int, optional): The dimension of the qudits. Default: 2 + nqudit: Total number of qudits. + trace_lst: A list of qudits to be traced. + qudit: The dimension of the qudits. Default: 2 Returns: - torch.Tensor: Reduced density matrices. + Reduced density matrices. """ if rho.ndim == 2: rho = rho.unsqueeze(0) @@ -418,13 +446,12 @@ def amplitude_encoding(data: Any, nqubit: int) -> torch.Tensor: :math:`2^{\text{nqubit}}`, only the first :math:`2^{\text{nqubit}}` elements are used. Args: - data (torch.Tensor or array-like): The input data to be encoded. It should have shape - :math:`(\text{batch}, ...)` where :math:`...` can be any dimensions. If it is not a torch.Tensor object, - it will be converted to one. - nqubit (int): The number of qubits to use for encoding. + data: The input data to be encoded. It should have shape :math:`(\text{batch}, ...)` + where :math:`...` can be any dimensions. If it is not a torch.Tensor object, it will be converted to one. + nqubit: The number of qubits to use for encoding. Returns: - torch.Tensor: The encoded quantum states as complex-valued tensors of shape + The encoded quantum states as complex-valued tensors of shape :math:`(\text{batch}, 2^{\text{nqubit}}, 1)`. Examples: @@ -461,11 +488,11 @@ def evolve_state( """Perform the evolution of quantum states. Args: - state (torch.Tensor): The batched state tensor. - matrix (torch.Tensor): The evolution matrix. - nqudit (int): The number of the qudits. - wires (List[int]): The indices of the qudits that the quantum operation acts on. - qudit (int, optional): The dimension of the qudits. Default: 2 + state: The batched state tensor. + matrix: The evolution matrix. + nqudit: The number of the qudits. + wires: The indices of the qudits that the quantum operation acts on. + qudit: The dimension of the qudits. Default: 2 """ nt = len(wires) wires = [i + 1 for i in wires] @@ -485,11 +512,11 @@ def evolve_den_mat( """Perform the evolution of density matrices. Args: - state (torch.Tensor): The batched state tensor. - matrix (torch.Tensor): The evolution matrix. - nqudit (int): The number of the qudits. - wires (List[int]): The indices of the qudits that the quantum operation acts on. - qudit (int, optional): The dimension of the qudits. Default: 2 + state: The batched state tensor. + matrix: The evolution matrix. + nqudit: The number of the qudits. + wires: The indices of the qudits that the quantum operation acts on. + qudit: The dimension of the qudits. Default: 2 """ nt = len(wires) # left multiply @@ -517,9 +544,9 @@ def block_sample(probs: torch.Tensor, shots: int = 1024, block_size: int = 2**24 """Sample from a probability distribution using block sampling. Args: - probs (torch.Tensor): The probability distribution to sample from. - shots (int, optional): The number of samples to draw. Default: 1024 - block_size (int, optional): The block size for sampling. Default: 2 ** 24 + probs: The probability distribution to sample from. + shots: The number of samples to draw. Default: 1024 + block_size: The block size for sampling. Default: 2**24 """ samples = [] num_blocks = int(np.ceil(len(probs) / block_size)) @@ -554,24 +581,23 @@ def measure( occurrences and the probability. Args: - state (torch.Tensor): The quantum state to measure. It can be a tensor of shape :math:`(2^n,)` or + state: The quantum state to measure. It can be a tensor of shape :math:`(2^n,)` or :math:`(2^n, 1)` representing a state vector, or a tensor of shape :math:`(\text{batch}, 2^n)` or :math:`(\text{batch}, 2^n, 1)` representing a batch of state vectors. It can also be a tensor of shape :math:`(2^n, 2^n)` representing a density matrix or :math:`(\text{batch}, 2^n, 2^n)` representing a batch of density matrices. - shots (int, optional): The number of times to sample from the quantum state. Default: 1024 - with_prob (bool, optional): A flag that indicates whether to return the probabilities along with - the number of occurrences. Default: ``False`` - wires (int, List[int] or None, optional): The wires to measure. It can be an integer or a list of - integers specifying the indices of the wires. Default: ``None`` (which means all wires are - measured) - den_mat (bool, optional): Whether the state is a density matrix or not. Default: ``False`` - block_size (int, optional): The block size for sampling. Default: 2 ** 24 + shots: The number of times to sample from the quantum state. Default: 1024 + with_prob: A flag that indicates whether to return the probabilities along with the number of occurrences. + Default: ``False`` + wires: The wires to measure. It can be an integer or a list of integers specifying the indices of the wires. + Default: ``None`` (which means all wires are measured) + den_mat: Whether the state is a density matrix or not. Default: ``False`` + block_size: The block size for sampling. Default: 2**24 Returns: - Union[Dict, List[Dict]]: The measurement results. If the state is a single state vector, it returns - a dictionary where each key is a bit string representing the measurement outcome, and each value - is either the number of occurrences or a tuple of the number of occurrences and the probability. + The measurement results. If the state is a single state vector, it returns a dictionary + where each key is a bit string representing the measurement outcome, and each value is + either the number of occurrences or a tuple of the number of occurrences and the probability. If the state is a batch of state vectors, it returns a list of dictionaries with the same format for each state vector in the batch. """ @@ -692,12 +718,12 @@ def get_prob_mps(mps_lst: list[torch.Tensor], wire: int) -> torch.Tensor: 3. Computing the final contraction with the target tensor Args: - wire (int): Index of the target qubit to compute probabilities for - mps_lst (List[torch.Tensor]): List of MPS tensors representing the quantum state - Each 3-dimensional tensor should have shape (bond_dim_left, physical_dim, bond_dim_right) + mps_lst: A list of MPS tensors representing the quantum state. + Each 3-dimensional tensor should have shape (bond_dim_left, physical_dim, bond_dim_right). + wire: The index of the target qubit to compute probabilities for. Returns: - torch.Tensor: A tensor containing [P(|0⟩), P(|1⟩)] probabilities for the target qubit + A tensor containing [P(|0⟩), P(|1⟩)] probabilities for the target qubit. """ def contract_conjugate_pair(tensors: list[torch.Tensor]) -> torch.Tensor: @@ -707,10 +733,10 @@ def contract_conjugate_pair(tensors: list[torch.Tensor]) -> torch.Tensor: and their complex conjugates, which is needed for probability calculation. Args: - tensors (List[torch.Tensor]): List of MPS tensors to contract + tensors: A list of MPS tensors to contract. Returns: - torch.Tensor: Contracted tensor + Contracted tensor. """ if not tensors: # Handle empty tensor list case return torch.tensor(1).reshape(1, 1, 1, 1).to(mps_lst[0].dtype).to(mps_lst[0].device) @@ -752,18 +778,18 @@ def inner_product_mps( r"""Computes the inner product of two matrix product states. Args: - tensors0 (List[torch.Tensor]): The tensors of the first MPS, each with shape :math:`(..., d_0, d_1, d_2)`, + tensors0: The tensors of the first MPS, each with shape :math:`(..., d_0, d_1, d_2)`, where :math:`d_0` is the bond dimension of the left site, :math:`d_1` is the physical dimension, and :math:`d_2` is the bond dimension of the right site. - tensors1 (List[torch.Tensor]): The tensors of the second MPS, each with shape :math:`(..., d_0, d_1, d_2)`, + tensors1: The tensors of the second MPS, each with shape :math:`(..., d_0, d_1, d_2)`, where :math:`d_0` is the bond dimension of the left site, :math:`d_1` is the physical dimension, and :math:`d_2` is the bond dimension of the right site. - form (str, optional): The form of the output. If ``'log'``, returns the logarithm of the absolute value - of the inner product. If ``'list'``, returns a list of norms at each step. Otherwise, returns the - inner product as a scalar. Default: ``'norm'`` + form: The form of the output. If ``'log'``, returns the logarithm of the absolute value of the inner product. + If ``'list'``, returns a list of norms at each step. Otherwise, returns the inner product as a scalar. + Default: ``'norm'`` Returns: - Union[torch.Tensor, List[torch.Tensor]]: The inner product of the two MPS, or a list of norms at each step. + The inner product of the two MPS, or a list of norms at each step. Raises: AssertionError: If the tensors have incompatible shapes or lengths. @@ -810,17 +836,16 @@ def expectation( It is a real number that represents the mean of the probability distribution of the measurement outcomes. Args: - state (torch.Tensor or List[torch.Tensor]): The quantum state to measure. It can be a list of tensors - representing a matrix product state, or a tensor representing a density matrix or a state vector. - observable (Observable): The observable to measure. It is an instance of ``Observable`` class that + state: The quantum state to measure. It can be a list of tensors representing a matrix product state, + or a tensor representing a density matrix or a state vector. + observable: The observable to measure. It is an instance of ``Observable`` class that implements the measurement basis and the corresponding gates. - den_mat (bool, optional): Whether to use density matrix representation. Default: ``False`` - chi (int or None, optional): The bond dimension of the matrix product state. It is only used - when the state is a list of tensors. Default: ``None`` (which means no truncation) + den_mat: Whether to use density matrix representation. Default: ``False`` + chi: The bond dimension of the matrix product state. It is only used when the state is a list of tensors. + Default: ``None`` (which means no truncation) Returns: - torch.Tensor: The expectation value of the observable on the quantum state. It is a scalar tensor - with real values. + The expectation value of the observable on the quantum state. It is a scalar tensor with real values. """ if isinstance(state, list): from .state import MatrixProductState @@ -852,10 +877,10 @@ def meyer_wallach_measure(state_tsr: torch.Tensor) -> torch.Tensor: See https://readpaper.com/paper/2945680873 Eq.(19) Args: - state_tsr (torch.Tensor): Input with the shape of :math:`(\text{batch}, 2, ..., 2)`. + state_tsr: Input with the shape of :math:`(\text{batch}, 2, ..., 2)`. Returns: - torch.Tensor: The value of Meyer-Wallach measure. + The value of Meyer-Wallach measure. """ nqubit = len(state_tsr.shape) - 1 batch = state_tsr.shape[0] @@ -877,12 +902,12 @@ def linear_map_mw(state_tsr: torch.Tensor, j: int, b: int) -> torch.Tensor: See https://arxiv.org/pdf/quant-ph/0305094.pdf Eq.(2) Args: - state_tsr (torch.Tensor): Input with the shape of :math:`(\text{batch}, 2, ..., 2)`. - j (int): The ``j`` th qubit to project on, from :math:`0` to :math:`\text{nqubit}-1`. - b (int): The basis of projection, :math:`\ket{0}` or :math:`\ket{1}`. + state_tsr: Input with the shape of :math:`(\text{batch}, 2, ..., 2)`. + j: The ``j`` th qubit to project on, from :math:`0` to :math:`\text{nqubit}-1`. + b: The basis of projection, :math:`\ket{0}` or :math:`\ket{1}`. Returns: - torch.Tensor: Non-normalized state tensor after the linear mapping. + Non-normalized state tensor after the linear mapping. """ assert b in (0, 1), 'b must be 0 or 1' n = len(state_tsr.shape) @@ -902,11 +927,11 @@ def generalized_distance(state1: torch.Tensor, state2: torch.Tensor) -> torch.Te Implemented according to https://arxiv.org/pdf/quant-ph/0310137.pdf Eq.(4) Args: - state1 (torch.Tensor): Input with the shape of :math:`(\text{batch}, 2^n, 1)`. - state2 (torch.Tensor): Input with the shape of :math:`(\text{batch}, 2^n, 1)`. + state1: Input with the shape of :math:`(\text{batch}, 2^n, 1)`. + state2: Input with the shape of :math:`(\text{batch}, 2^n, 1)`. Returns: - torch.Tensor: The generalized distance. + The generalized distance. """ return ((state1.mH @ state1) * (state2.mH @ state2) - (state1.mH @ state2) * (state2.mH @ state1)).real @@ -920,10 +945,10 @@ def meyer_wallach_measure_brennen(state_tsr: torch.Tensor) -> torch.Tensor: This implementation is slower than ``meyer_wallach_measure`` when :math:`\text{nqubit} \ge 8`. Args: - state_tsr (torch.Tensor): Input with the shape of :math:`(\text{batch}, 2, ..., 2)`. + state_tsr: Input with the shape of :math:`(\text{batch}, 2, ..., 2)`. Returns: - torch.Tensor: The value of Meyer-Wallach measure. + The value of Meyer-Wallach measure. """ nqubit = len(state_tsr.shape) - 1 batch = state_tsr.shape[0] diff --git a/src/deepquantum/qpd.py b/src/deepquantum/qpd.py index b1053e0..ec4b9a4 100644 --- a/src/deepquantum/qpd.py +++ b/src/deepquantum/qpd.py @@ -10,18 +10,17 @@ class SingleGateQPD(GateQPD): r"""A base class for single-qubit QPD gates. Args: - bases (List[Tuple[nn.Sequential, ...]]): A list of tuples describing the operations probabilistically used to + bases: A list of tuples describing the operations probabilistically used to simulate an ideal quantum operation. - coeffs (List[float]): The coefficients for quasiprobability representation. - label (int or None, optional): The label of the gate. Default: ``None`` - name (str or None, optional): The name of the quantum operation. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 1 - wires (List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + coeffs: The coefficients for quasiprobability representation. + label: The label of the gate. Default: ``None`` + name: The name of the quantum operation. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 1 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -56,18 +55,17 @@ class DoubleGateQPD(GateQPD): r"""A base class for two-qubit QPD gates. Args: - bases (List[Tuple[nn.Sequential, ...]]): A list of tuples describing the operations probabilistically used to + bases: A list of tuples describing the operations probabilistically used to simulate an ideal quantum operation. - coeffs (List[float]): The coefficients for quasiprobability representation. - label (int or None, optional): The label of the gate. Default: ``None`` - name (str or None, optional): The name of the quantum operation. Default: ``None`` - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 2 - wires (List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + coeffs: The coefficients for quasiprobability representation. + label: The label of the gate. Default: ``None`` + name: The name of the quantum operation. Default: ``None`` + nqubit: The number of qubits that the quantum operation acts on. Default: 2 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( @@ -118,14 +116,13 @@ class MoveQPD(DoubleGateQPD): r"""QPD representation of the move operation. Args: - nqubit (int, optional): The number of qubits that the quantum operation acts on. Default: 2 - wires (List[int] or None, optional): The indices of the qubits that the quantum operation acts on. - Default: ``None`` - label (int or None, optional): The label of the gate. Default: ``None`` - den_mat (bool, optional): Whether the quantum operation acts on density matrices or state vectors. + nqubit: The number of qubits that the quantum operation acts on. Default: 2 + wires: The indices of the qubits that the quantum operation acts on. Default: ``None`` + label: The label of the gate. Default: ``None`` + den_mat: Whether the quantum operation acts on density matrices or state vectors. Default: ``False`` (which means state vectors) - tsr_mode (bool, optional): Whether the quantum operation is in tensor mode, which means the input - and output are represented by a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` + tsr_mode: Whether the quantum operation is in tensor mode, which means the input and output are represented by + a tensor of shape :math:`(\text{batch}, 2, ..., 2)`. Default: ``False`` """ def __init__( diff --git a/src/deepquantum/state.py b/src/deepquantum/state.py index cc8e168..4dbfc7d 100644 --- a/src/deepquantum/state.py +++ b/src/deepquantum/state.py @@ -14,11 +14,12 @@ class QubitState(nn.Module): """A quantum state of n qubits, including both pure states and density matrices. Args: - nqubit (int, optional): The number of qubits in the state. Default: 1 - state (Any, optional): The representation of the state. It can be one of the following strings: - ``'zeros'``, ``'equal'``, ``'entangle'``, ``'GHZ'``, or ``'ghz'``. Alternatively, it can be - a tensor that represents a custom state vector or density matrix. Default: ``'zeros'`` - den_mat (bool, optional): Whether the state is a density matrix or not. Default: ``False`` + nqubit: The number of qubits in the state. Default: 1 + state: The representation of the state. It can be one of the following strings: + ``'zeros'``, ``'equal'``, ``'entangle'``, ``'GHZ'``, or ``'ghz'``. + Alternatively, it can be a tensor that represents a custom state vector or density matrix. + Default: ``'zeros'`` + den_mat: Whether the state is a density matrix or not. Default: ``False`` """ def __init__(self, nqubit: int = 1, state: Any = 'zeros', den_mat: bool = False) -> None: @@ -83,14 +84,16 @@ class MatrixProductState(nn.Module): between qudits. Args: - nsite (int, optional): The number of sites of the MPS. Default: 1 - state (str, List[torch.Tensor] or List[int], optional): The representation of the MPS. - If ``'zeros'`` or ``'vac'``, the MPS is initialized to the all-zero state. If a list of tensors, - the MPS is initialized to the given tensors. The tensors must have the correct shape and dtype. - If a list of integers, the MPS is initialized to the corresponding basis state. Default: ``'zeros'`` - chi (int or None, optional): The maximum bond dimension of the MPS. Default: 10 * ``nsite`` - qudit (int, optional): The local Hilbert space dimension of each qudit. Default: 2 - normalize (bool, optional): Whether to normalize the MPS after each operation. Default: ``True`` + nsite: The number of sites of the MPS. Default: 1 + state: The representation of the MPS. + If ``'zeros'`` or ``'vac'``, the MPS is initialized to the all-zero state. + If a list of tensors, the MPS is initialized to the given tensors. + The tensors must have the correct shape and dtype. + If a list of integers, the MPS is initialized to the corresponding basis state. + Default: ``'zeros'`` + chi: The maximum bond dimension of the MPS. Default: None (which means 10 * ``nsite``) + qudit: The local Hilbert space dimension of each qudit. Default: 2 + normalize: Whether to normalize the MPS after each operation. Default: ``True`` """ def __init__( @@ -239,10 +242,9 @@ def orthogonalize_left2right(self, site: int, dc: int = -1, normalize: bool = Fa The tensor at ``site`` + 1 is updated by :math:`R`. Args: - site (int): The site of tensor to be orthogonalized. - dc (int, optional): Keep the first ``dc`` singular values after truncation. - Default: -1 (which means no truncation) - normalize (bool, optional): Whether to normalize the tensor :math:`R`. Default: ``False`` + site: The site of tensor to be orthogonalized. + dc: Keep the first ``dc`` singular values after truncation. Default: -1 (which means no truncation) + normalize: Whether to normalize the tensor :math:`R`. Default: ``False`` """ assert site < self.nsite - 1 tensors = self.tensors @@ -275,10 +277,9 @@ def orthogonalize_right2left(self, site: int, dc: int = -1, normalize: bool = Fa updated by :math:`L`. Args: - site (int): The site of tensor to be orthogonalized. - dc (int, optional): Keep the first ``dc`` singular values after truncation. - Default: -1 (which means no truncation) - normalize (bool, optional): Whether to normalize the tensor :math:`L`. Default: ``False`` + site: The site of tensor to be orthogonalized. + dc: Keep the first ``dc`` singular values after truncation. Default: -1 (which means no truncation) + normalize: Whether to normalize the tensor :math:`L`. Default: ``False`` """ assert site > 0 tensors = self.tensors @@ -341,7 +342,7 @@ class DistributedQubitState(nn.Module): """A quantum state of n qubits distributed between w nodes. Args: - nqubit (int): The number of qubits in the state. + nqubit: The number of qubits in the state. """ def __init__(self, nqubit: int) -> None: diff --git a/tests/test_with_xanadu.py b/tests/test_with_xanadu.py index c09fa92..e7424c2 100644 --- a/tests/test_with_xanadu.py +++ b/tests/test_with_xanadu.py @@ -94,9 +94,9 @@ def test_gaussian_prob_random_circuit(): def test_measure_homodyne(): n = 3 - r1 = np.random.rand(1) - r2 = np.random.rand(1) - r3 = np.random.rand(1) + r1 = np.random.rand(1)[0] + r2 = np.random.rand(1)[0] + r3 = np.random.rand(1)[0] bs1 = np.random.rand(2) bs2 = np.random.rand(2) phi = np.random.rand(2)