{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Variational Quantum Circuit\n", "\n", "Translator: [Wei_zz](https://gitee.com/wei-zz)\n", "\n", "[![Download Notebook](https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/website-images/master/resource/_static/logo_notebook_en.svg)](https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/notebook/master/mindquantum/en/beginner/mindspore_parameterized_quantum_circuit.ipynb) \n", "[![Download Code](https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/website-images/master/resource/_static/logo_download_code_en.svg)](https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/notebook/master/mindquantum/en/beginner/mindspore_parameterized_quantum_circuit.py) \n", "[![View source on Gitee](https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/website-images/master/resource/_static/logo_source_en.svg)](https://gitee.com/mindspore/docs/blob/master/docs/mindquantum/docs/source_en/beginner/parameterized_quantum_circuit.ipynb)\n", "\n", "## Summary\n", "\n", "Variational quantum circuit(VQC), is an approach for Quantum Machine Learning. The MindSpore Quantum (hybrid framework of quantum and classic machine learning) can process variational quantum circuit and get the derivation of all observation to every parameter respectively by auto differentiating the circuit using quantum neural network.\n", "The process of constructing a quantum circuit and circuit evolution by parameterized simulator operators is as follows:\n", "\n", "- Initialize a quantum circuit.\n", "\n", "- According to requirements, add parameterized quantum gates or non-parameterized quantum gates to the circuit.\n", "\n", "- Process gradient solution or state of evolution by PQC simulator operators.\n", "\n", "## Preparing Environment\n", "\n", "Import required modules." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import numpy as np # Import numpy library and abbreviate to np\n", "from mindquantum.core.gates import X, Y, Z, H, RX, RY, RZ # Import the quantum gate H, X, Y, Z, RX, RY, RZ" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note:\n", "\n", "1. numpy is a powerful Python library for performing calculations on multidimensional arrays, supporting a large number of dimensional arrays and matrices, in addition to providing a large library of mathematical functions for arrays.\n", "\n", "2. mindquantum, a hybrid quantum-classical computing framework, supports the training and inference of a wide range of quantum neural networks.\n", "\n", "3. The quantum gates to be executed in the built quantum circuit need to be imported from the mindquantum.core module.\n", "\n", "## Quantum Gate\n", "\n", "A quantum gate is the basic logic unit to operate quantum bit. For a classic circuit, any logic circuit can consist of some basic logic gates, similarly, any quantum circuit can consist of some basic quantum gates like gates or C-NOT gates acting on a single bit. Commonly used quantum gates include [X](https://www.mindspore.cn/mindquantum/docs/en/master/core/gates/mindquantum.core.gates.XGate.html) gates, [Y](https://www.mindspore.cn/mindquantum/docs/en/master/core/gates/mindquantum.core.gates.YGate.html) gates, [Z](https://www.mindspore.cn/mindquantum/docs/en/master/core/gates/mindquantum.core.gates.ZGate.html) gates, [Hadamard](https://www.mindspore.cn/mindquantum/docs/en/master/core/gates/mindquantum.core.gates.HGate.html) gates, [CNOT](https://www.mindspore.cn/mindquantum/docs/en/master/core/gates/mindquantum.core.gates.CNOTGate.html) gates and some rotation gates.\n", "\n", "In general, quantum gates can be classified into parametric and non-parametric quantum gates. For example, the non-parametric quantum gates are [X](https://www.mindspore.cn/mindquantum/docs/en/master/core/gates/mindquantum.core.gates.XGate.html) gate, [Y](https://www.mindspore.cn/mindquantum/docs/en/master/core/gates/mindquantum.core.gates.YGate.html) gate, [Z](https://www.mindspore.cn/mindquantum/docs/en/master/core/gates/mindquantum.core.gates.ZGate.html) gate, [Hadamard](https://www.mindspore.cn/mindquantum/docs/en/master/core/gates/mindquantum.core.gates.HGate.html) gate and [CNOT](https://www.mindspore.cn/mindquantum/docs/en/master/core/gates/mindquantum.core.gates.CNOTGate.html) gate, which have the following matrix forms, respectively:\n", "\n", "$$\n", "\\text{X}=\n", "\\left(\n", " \\begin{matrix}\n", " 0&1\\\\\n", " 1&0\n", " \\end{matrix}\n", "\\right),\n", "\\text{Y}=\n", "\\left(\n", " \\begin{matrix}\n", " 0&-i\\\\\n", " i&0\n", " \\end{matrix}\n", "\\right),\n", "\\text{Z}=\n", "\\left(\n", " \\begin{matrix}\n", " 1&0\\\\\n", " 0&-1\n", " \\end{matrix}\n", "\\right),\n", "\\text{H}=\\frac{1}{\\sqrt{2}}\n", "\\left(\n", " \\begin{matrix}\n", " 1&1\\\\\n", " 1&-1\n", " \\end{matrix}\n", "\\right),\n", "\\text{CNOT}=\n", "\\left(\n", " \\begin{matrix}\n", " 1&0&0&0\\\\\n", " 0&1&0&0\\\\\n", " 0&0&0&1\\\\\n", " 0&0&1&0\n", " \\end{matrix}\n", "\\right).$$\n", "\n", "Print the matrix form of the above quantum gates separately and we can get:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gate name: X\n" ] }, { "data": { "text/plain": [ "array([[0, 1],\n", " [1, 0]])" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "print('Gate name:', X)\n", "X.matrix()" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gate name: Y\n" ] }, { "data": { "text/plain": [ "array([[ 0.+0.j, -0.-1.j],\n", " [ 0.+1.j, 0.+0.j]])" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "print('Gate name:', Y)\n", "Y.matrix()" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gate name: Z\n" ] }, { "data": { "text/plain": [ "array([[ 1, 0],\n", " [ 0, -1]])" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "print('Gate name:', Z)\n", "Z.matrix()" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gate name: H\n" ] }, { "data": { "text/plain": [ "array([[ 0.70710678, 0.70710678],\n", " [ 0.70710678, -0.70710678]])" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "print('Gate name:', H)\n", "H.matrix()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For [CNOT](https://www.mindspore.cn/mindquantum/docs/en/master/core/gates/mindquantum.core.gates.CNOTGate.html) gates, they are essentially Controlled-[X](https://www.mindspore.cn/mindquantum/docs/en/master/core/gates/mindquantum.core.gates.XGate.html) gates, so in MindSpore Quantum, if we need to execute a [CNOT](https://www.mindspore.cn/mindquantum/docs/en/master/core/gates/mindquantum.core.gates.CNOTGate.html) gate, we only need to set the control bits and the target bits of the [X](https://www.mindspore.cn/mindquantum/docs/en/master/core/gates/mindquantum.core.gates.XGate.html) gate (in fact, for any quantum gate we can set the control bits and the target bits of the desired quantum gate operation). For example:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "X(0 <-: 1)\n" ] } ], "source": [ "cnot = X.on(0, 1) # X gate acts on bit 0 quantum bit and is controlled by bit 1 quantum bit\n", "print(cnot)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note:\n", "\n", "1. The `X(1 <-: 0)` denotes that the bit 0 quantum bit is the target bit, the bit 1 quantum bit is the control bit, and the bit 0 quantum bit is controlled by the bit 1 quantum bit. Perform [X](https://www.mindspore.cn/mindquantum/docs/en/master/core/gates/mindquantum.core.gates.XGate.html)-gate operation on bit 0 quantum bit if bit 1 is 1, otherwise no operation is performed.\n", "\n", "The above describes some quantum gates without parameters. Next, we will introduce some quantum gates with parameters (such as the rotation gate [RX](https://www.mindspore.cn/mindquantum/docs/en/master/core/gates/mindquantum.core.gates.RX.html) gate, [RY](https://www.mindspore.cn/mindquantum/docs/en/master/core/gates/mindquantum.core.gates.RY.html) gate and [RZ](https://www.mindspore.cn/mindquantum/docs/en/master/core/gates/mindquantum.core.gates.RZ.html) gate), which can be obtained by giving certain definite values of the rotation angle $\\theta$ that act differently. In addition, these quantum gates with parameters are important building blocks for the subsequent construction of quantum neural networks.\n", "\n", "For example, the [RX](https://www.mindspore.cn/mindquantum/docs/en/master/core/gates/mindquantum.core.gates.RX.html) gate, [RY](https://www.mindspore.cn/mindquantum/docs/en/master/core/gates/mindquantum.core.gates.RY.html) gate and [RZ](https://www.mindspore.cn/mindquantum/docs/en/master/core/gates/mindquantum.core.gates.RZ.html) gate have the following matrix form:\n", "\n", "$$\\text{RX}(\\theta)= e^{-\\frac{i\\theta X}{2}}=\\cos\\left(\\frac{\\theta}{2}\\right)\\cdot I-i\\sin\\left(\\frac{\\theta}{2}\\right)\\cdot X=\n", "\\left(\n", " \\begin{matrix}\n", " \\cos\\left(\\frac{\\theta}{2}\\right)&-i\\sin\\left(\\frac{\\theta}{2}\\right)\\\\\n", " -i\\sin\\left(\\frac{\\theta}{2}\\right)&\\cos\\left(\\frac{\\theta}{2}\\right)\n", " \\end{matrix}\n", "\\right),$$\n", "\n", "$$\\text{RY}(\\theta)= e^{-\\frac{i\\theta Y}{2}}=\\cos\\left(\\frac{\\theta}{2}\\right)\\cdot I-i\\sin\\left(\\frac{\\theta}{2}\\right)\\cdot Y=\n", "\\left(\n", " \\begin{matrix}\n", " \\cos\\left(\\frac{\\theta}{2}\\right)&-\\sin\\left(\\frac{\\theta}{2}\\right)\\\\\n", " \\sin\\left(\\frac{\\theta}{2}\\right)&\\cos\\left(\\frac{\\theta}{2}\\right)\n", " \\end{matrix}\n", "\\right),$$\n", "\n", "$$\\text{RZ}(\\theta)= e^{-\\frac{i\\theta Z}{2}}=\\cos\\left(\\frac{\\theta}{2}\\right)\\cdot I-i\\sin\\left(\\frac{\\theta}{2}\\right)\\cdot Z=\n", "\\left(\n", " \\begin{matrix}\n", " e^{-\\frac{i\\theta}{2}}&0\\\\\n", " 0&e^{\\frac{i\\theta}{2}}\n", " \\end{matrix}\n", "\\right).$$\n", "\n", "We make $\\theta$ be $0$ and $\\pi$, respectively, and then print the matrix forms of $\\text{RX}(0)$ gates, $\\text{RY}(\\pi)$ gates and $\\text{RZ}(\\pi)$ gates. And we can obtain:\n" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gate name: RX(theta)\n" ] }, { "data": { "text/plain": [ "array([[1.+0.j, 0.+0.j],\n", " [0.+0.j, 1.+0.j]])" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "rx = RX('theta')\n", "print('Gate name:', rx)\n", "rx.matrix({'theta': 0}) # Assign a value of theta to 0" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When $\\theta=0$, at this point the $\\text{RX}(0)$ gate is the familiar [I](https://www.mindspore.cn/mindquantum/docs/en/master/core/gates/mindquantum.core.gates.IGate.html) gate." ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gate name: RY(theta)\n" ] }, { "data": { "text/plain": [ "array([[ 0.+0.j, -1.+0.j],\n", " [ 1.+0.j, 0.+0.j]])" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "ry = RY('theta')\n", "print('Gate name:', ry)\n", "np.round(ry.matrix({'theta': np.pi})) # pi needs to be imported from np, assigning the value of theta to pi" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When $\\theta=\\pi$, at this point the $\\text{RY}(\\pi)$ gate is the familiar [Y](https://www.mindspore.cn/mindquantum/docs/en/master/core/gates/mindquantum.core.gates.YGate.html) gate. (differing by one global phase $i$)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gate name: RZ(theta)\n" ] }, { "data": { "text/plain": [ "array([[0.-1.j, 0.+0.j],\n", " [0.+0.j, 0.+1.j]])" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "rz = RZ('theta')\n", "print('Gate name:', rz)\n", "np.round(rz.matrix({'theta': np.pi})) # The value of pi is assigned to theta, and because of the problem of imprecise floating point numbers in computers, the rounded value of the floating point number is returned by the function np.round." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When $\\theta=\\pi$, at this point the $\\text{RZ}(\\pi)$ gate is the familiar [Z](https://www.mindspore.cn/mindquantum/docs/en/master/core/gates/mindquantum.core.gates.ZGate.html) gate. (differing by one global phase $-i$)\n", "\n", "## Quantum Circuit\n", "\n", "Quantum circuit is a structure used to effectively organize various quantum logic gates. We can initialize the quantum circuit through the list of quantum gates, or expand the quantum circuit by adding a quantum gate or circuit through addition(`+`), and multiplying by an integer through multiplication(`*`). Here we will construct the following quantum circuit and print the relevant information of the quantum circuit. In the following figure, `q0`, `q1` and `q2` represent three qubits respectively. The quantum circuit consists of three quantum gates, namely the [Hadamard](https://www.mindspore.cn/mindquantum/docs/en/master/core/gates/mindquantum.core.gates.HGate.html) gate acting on `q0` bit, the [CNOT](https://www.mindspore.cn/mindquantum/docs/en/master/core/gates/mindquantum.core.gates.CNOTGate.html) gate acting on `q1` bit and controlled by `q0` bit, and the [RY](https://www.mindspore.cn/mindquantum/docs/en/master/core/gates/mindquantum.core.gates.RY.html) rotation gate acting on `q2` bit.\n", "\n", "![quantum circuit](https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/website-images/master/docs/mindquantum/docs/source_en/images/quantum_circuit.png)\n", "\n", "The construction of a quantum circuit can be accomplished quickly by adding quantum gates acting on different quantum bits in the quantum circuit." ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " ┏━━━┓ \n", "q0: ──┨ H ┠───■───────\n", " ┗━━━┛ ┃ \n", " ┏━┻━┓ \n", "q1: ────────┨╺╋╸┠─────\n", " ┗━━━┛ \n", " ┏━━━━━━━━━━━┓ \n", "q2: ──┨ RY(theta) ┠───\n", " ┗━━━━━━━━━━━┛ \n" ] }, { "data": { "text/html": [ "
        Circuit Summary         \n",
       "╭──────────────────────┬───────╮\n",
       "│ Info                  value │\n",
       "├──────────────────────┼───────┤\n",
       "│ Number of qubit      │ 3     │\n",
       "├──────────────────────┼───────┤\n",
       "│ Total number of gate │ 3     │\n",
       "│ Barrier              │ 0     │\n",
       "│ Noise Channel        │ 0     │\n",
       "│ Measurement          │ 0     │\n",
       "├──────────────────────┼───────┤\n",
       "│ Parameter gate       │ 1     │\n",
       "│ 1 ansatz parameter   │ theta │\n",
       "╰──────────────────────┴───────╯\n",
       "
\n" ], "text/plain": [ "\u001b[1;38;2;255;0;0m Circuit Summary \u001b[0m\n", "╭──────────────────────┬───────╮\n", "│\u001b[1m \u001b[0m\u001b[1;38;2;59;59;149mInfo\u001b[0m\u001b[1m \u001b[0m\u001b[1m \u001b[0m│\u001b[1m \u001b[0m\u001b[1;38;2;59;59;149mvalue\u001b[0m\u001b[1m \u001b[0m│\n", "├──────────────────────┼───────┤\n", "│ \u001b[1mNumber of qubit\u001b[0m │ 3 │\n", "├──────────────────────┼───────┤\n", "│ \u001b[1mTotal number of gate\u001b[0m │ 3 │\n", "│ Barrier │ 0 │\n", "│ Noise Channel │ 0 │\n", "│ Measurement │ 0 │\n", "├──────────────────────┼───────┤\n", "│ \u001b[1mParameter gate\u001b[0m │ 1 │\n", "│ 1 ansatz parameter │ \u001b[38;2;72;201;176mtheta\u001b[0m │\n", "╰──────────────────────┴───────╯\n" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "from mindquantum.core.circuit import Circuit # Import Circuit module for building quantum circuit\n", "\n", "encoder = Circuit() # Initialize quantum circuit\n", "encoder += H.on(0) # H-gate acts at bit 0 quantum bit\n", "encoder += X.on(1, 0) # The X gate acts on the bit 1 quantum bit and is controlled by the bit 0 quantum bit\n", "encoder += RY('theta').on(2) # RY(theta) gate acts on the bit 2 quantum bit\n", "\n", "print(encoder) # Print Encoder\n", "encoder.summary() # Summarize Encoder quantum circuit" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the Jupyter Notebook environment, you can call the [.svg()](https://www.mindspore.cn/mindquantum/docs/en/master/core/circuit/mindquantum.core.circuit.Circuit.html#mindquantum.core.circuit.Circuit.svg) method of the quantum [circuit](https://www.mindspore.cn/mindquantum/docs/en/master/core/circuit/mindquantum.core.circuit.Circuit.html) to draw the image format of the quantum circuit. Calling the `.svg().to_file(filename='circuit.svg')` method of the quantum [circuit](https://www.mindspore.cn/mindquantum/docs/en/master/core/circuit/mindquantum.core.circuit.Circuit.html) saves the svg image of the quantum circuit to local." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "image/svg+xml": [ "q0: q1: q2: H RY theta " ], "text/plain": [ "" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "encoder.svg()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "From the Summary of Encoder, we can see that the quantum circuit consists of three quantum gates, one of which is a quantum gate with parameters and has the parameter theta, and the number of quantum bits regulated by this quantum circuit is 3.\n", "\n", "Therefore, we can build the corresponding quantum circuit according to the problem we need to solve. Go and build your first [quantum circuit](https://www.mindspore.cn/mindquantum/docs/en/master/core/circuit/mindquantum.core.circuit.Circuit.html)!" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", " \n", " \n", " \n", " \n", "\n", "\n", "\n", "\n", " \n", " \n", "\n", "\n", "
SoftwareVersion
mindquantum0.9.11
scipy1.10.1
numpy1.23.5
SystemInfo
Python3.9.16
OSLinux x86_64
Memory8.3 GB
CPU Max Thread8
DateSun Dec 31 23:30:17 2023
\n" ], "text/plain": [ "" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from mindquantum.utils.show_info import InfoTable\n", "\n", "InfoTable('mindquantum', 'scipy', 'numpy')" ] } ], "metadata": { "kernelspec": { "display_name": "base", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.16" } }, "nbformat": 4, "nbformat_minor": 2 }