{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 变分量子线路梯度计算进阶\n",
    "\n",
    "[![下载Notebook](https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/website-images/r2.2/resource/_static/logo_notebook.svg)](https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/notebook/r2.2/mindquantum/zh_cn/advanced/mindspore_get_gradient_of_PQC_with_mindquantum.ipynb) \n",
    "[![下载样例代码](https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/website-images/r2.2/resource/_static/logo_download_code.svg)](https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/notebook/r2.2/mindquantum/zh_cn/advanced/mindspore_get_gradient_of_PQC_with_mindquantum.py) \n",
    "[![查看源文件](https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/website-images/r2.2/resource/_static/logo_source.svg)](https://gitee.com/mindspore/docs/blob/r2.2/docs/mindquantum/docs/source_zh_cn/advanced/get_gradient_of_PQC_with_mindquantum.ipynb)\n",
    "[![在ModelArts平台运行](https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/website-images/r2.2/resource/_static/logo_modelarts.svg)](https://authoring-modelarts-cnnorth4.huaweicloud.com/console/lab?share-url-b64=aHR0cHM6Ly9taW5kc3BvcmUtd2Vic2l0ZS5vYnMuY24tbm9ydGgtNC5teWh1YXdlaWNsb3VkLmNvbS9ub3RlYm9vay9yMi4yL21pbmRxdWFudHVtL3poX2NuL2FkdmFuY2VkL21pbmRzcG9yZV9nZXRfZ3JhZGllbnRfb2ZfUFFDX3dpdGhfbWluZHF1YW50dW0uaXB5bmI%3D&imageid=73522c7f-6d98-43d8-b306-8ff374c7d3a7)\n",
    "\n",
    "在MindSpore Quantum中,我们可以通过 [Simulator](https://www.mindspore.cn/mindquantum/docs/zh-CN/r0.9/simulator/mindquantum.simulator.Simulator.html) 类的[get_expectation_with_grad](https://www.mindspore.cn/mindquantum/docs/zh-CN/r0.9/simulator/mindquantum.simulator.Simulator.html#mindquantum.simulator.Simulator.get_expectation_with_grad) 方法来获得一个变分量子线路的梯度,在这篇教程中,我们将更进一步的介绍该方法的其他功能,帮助大家来实现更高级的使用方法。\n",
    "\n",
    "## 模型介绍\n",
    "\n",
    "[get_expectation_with_grad](https://www.mindspore.cn/mindquantum/docs/zh-CN/r0.9/simulator/mindquantum.simulator.Simulator.html#mindquantum.simulator.Simulator.get_expectation_with_grad) 方法主要是用来计算如下表达式的值和线路中参数的梯度。\n",
    "\n",
    "$$E(\\boldsymbol{\\theta})=\\left<\\varphi\\right|U^\\dagger_l(\\boldsymbol{\\theta})HU_r(\\boldsymbol{\\theta})\\left|\\psi\\right>$$\n",
    "\n",
    "该方法的接口定义如下\n",
    "\n",
    "```python\n",
    "Simulator.get_expectation_with_grad(\n",
    "    hams,\n",
    "    circ_right,\n",
    "    circ_left=None,\n",
    "    simulator_left=None,\n",
    "    parallel_worker=None\n",
    ")\n",
    "```\n",
    "\n",
    "下面,我们将一一介绍每个参数的意义。\n",
    "\n",
    "1. `hams`。线路中的哈密顿量,所需要的类型为MindSpore Quantum中的 [Hamiltonian](https://www.mindspore.cn/mindquantum/docs/zh-CN/r0.9/core/operators/mindquantum.core.operators.Hamiltonian.html),或者一个包含多个 [Hamiltonian](https://www.mindspore.cn/mindquantum/docs/zh-CN/r0.9/core/operators/mindquantum.core.operators.Hamiltonian.html) 的`list`数组,对于后一种情况,框架会同时计算出线路关于所有哈密顿量的期望值,和每个期望值关于线路参数的梯度\n",
    "\n",
    "2. `circ_right`。为公式中的$U_r(\\boldsymbol{\\theta})$\n",
    "\n",
    "3. `circ_left`。为公式中的$U_l(\\boldsymbol{\\theta})$,当为默认值`None`时,`circ_left`和`circ_right`为同一线路,若需要空线路可单独使用[Circuit()](https://www.mindspore.cn/mindquantum/docs/zh-CN/r0.9/core/circuit/mindquantum.core.circuit.Circuit.html)创建。\n",
    "\n",
    "4. `simulator_left`。为包含公式中$\\left|\\varphi\\right>$的模拟器,你可以通过模拟器的 [set_qs](https://www.mindspore.cn/mindquantum/docs/zh-CN/r0.9/simulator/mindquantum.simulator.Simulator.html#mindquantum.simulator.Simulator.set_qs)、[apply_gate](https://www.mindspore.cn/mindquantum/docs/zh-CN/r0.9/simulator/mindquantum.simulator.Simulator.html#mindquantum.simulator.Simulator.apply_gate) 或 [apply_circuit](https://www.mindspore.cn/mindquantum/docs/zh-CN/r0.9/simulator/mindquantum.simulator.Simulator.html#mindquantum.simulator.Simulator.apply_circuit) 方法来设置该模拟器的状态为你需要的状态。当为默认值`None`时,$\\left|\\varphi\\right>=\\left|\\psi\\right>$,而$\\left|\\psi\\right>$为当前模拟器所包含的量子态。\n",
    "\n",
    "5. `parallel_worker`。当`hams`包含多个哈密顿量或者encoder的输入包含多个样本点时,MindSpore Quantum会根据此整数为参考来合理地进行并行运算。\n",
    "\n",
    "在MindSpore Quantum中,量子线路中的参数可以是encoder参数,用于将经典数据编码成量子态,类似于经典神经网络中的输入部分,encoder参数接受一个二维数据,第一个维度表示样本点个数,第二个维度表示经典数据的特征数,相当于经典机器学习中的一个batch;另一部分参数可以是ansatz参数,类似于经典神经网络中的训练参数,用于训练出特定的量子线路。下面我们构建一个即含有encoder参数又含有ansatz参数的量子线路。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "encoder parameters: ['a', 'c']\n",
      "ansatz parameters: ['b']\n"
     ]
    }
   ],
   "source": [
    "from mindquantum.core.circuit import Circuit\n",
    "\n",
    "circ1 = Circuit().rx('a', 0).as_encoder()                       # 将量子线路设置成encoder线路\n",
    "circ2 = Circuit().ry('b', 0).as_ansatz()                        # 将量子线路设置成ansatz线路,默认情况,所有量子线路都是ansatz线路。\n",
    "circ3 = Circuit().rz('c', 0).as_encoder()  # 将量子线路设置成encoder线路\n",
    "\n",
    "circ = circ1 + circ2 + circ3\n",
    "print(f\"encoder parameters: {circ.encoder_params_name}\")\n",
    "print(f\"ansatz parameters: {circ.ansatz_params_name}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "下面我们利用MindSpore Quantum来计算上述量子线路关于哈密顿量 $Z$的期望值。首先我们定义问题哈密顿量。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 [Z0]\n"
     ]
    }
   ],
   "source": [
    "from mindquantum.core.operators import QubitOperator                   # 导入QubitOperator模块,生成泡利算符\n",
    "from mindquantum.core.operators import Hamiltonian                     # 导入Hamiltonian模块,生成哈密顿量\n",
    "\n",
    "ham = Hamiltonian(QubitOperator('Z0'))\n",
    "print(ham)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "接下来,我们利用MindSpore Quantum生成计算期望值和期望值关于各个参数导数的算符。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<mindquantum.simulator.utils.GradOpsWrapper object at 0x7fb9f2f57d30>\n"
     ]
    }
   ],
   "source": [
    "from mindquantum.simulator import Simulator\n",
    "\n",
    "sim = Simulator('mqvector', 1)\n",
    "grad_ops = sim.get_expectation_with_grad(ham, circ)\n",
    "print(grad_ops)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这里我们计算 $a=1, b=2, c=3$时,线路关于泡利$Z$算符的期望值。根据上述说明,我们选择encoder数据为 `[[1, 3]]`,第一个维度表示经典数据样本点个数,第二个维度表示有两个经典特征,分别为`a`和`c`;选择待训练参数 $b$ 的初始值为`[2]`。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "expectation value:\n",
      "[[-0.2248451+0.j]]\n",
      " with shape (1, 1)\n",
      "gradient value w.r.t encoder parametres:\n",
      "[[[0.35017549+0.j 0.        +0.j]]]\n",
      " with shape (1, 1, 2)\n",
      "gradient value w.r.t ansatz parametres:\n",
      "[[[-0.4912955+0.j]]]\n",
      " with shape (1, 1, 1)\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "\n",
    "encoder_data = np.array([[1, 3]])\n",
    "ansatz_data = np.array([2])\n",
    "f, g_e, g_a = grad_ops(encoder_data, ansatz_data)\n",
    "print(f\"expectation value:\\n{f}\\n with shape {f.shape}\")\n",
    "print(\n",
    "    f\"gradient value w.r.t encoder parametres:\\n{g_e}\\n with shape {g_e.shape}\")\n",
    "print(\n",
    "    f\"gradient value w.r.t ansatz parametres:\\n{g_a}\\n with shape {g_a.shape}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "为了验证encoder数据可以同时取不同的样本点,我们同时计算$a=1, c=3$和$a=4, c=5$时的期望值和梯度。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "expectation value:\n",
      "[[-0.2248451 +0.j]\n",
      " [ 0.27201173+0.j]]\n",
      " with shape (2, 1)\n",
      "gradient value w.r.t encoder parametres:\n",
      "[[[ 0.35017549+0.j  0.        +0.j]]\n",
      "\n",
      " [[-0.31494096+0.j  0.        +0.j]]]\n",
      " with shape (2, 1, 2)\n",
      "gradient value w.r.t ansatz parametres:\n",
      "[[[-0.4912955 +0.j]]\n",
      "\n",
      " [[ 0.59435646+0.j]]]\n",
      " with shape (2, 1, 1)\n"
     ]
    }
   ],
   "source": [
    "encoder_data = np.array([[1, 3], [4, 5]])\n",
    "ansatz_data = np.array([2])\n",
    "f, g_e, g_a = grad_ops(encoder_data, ansatz_data)\n",
    "print(f\"expectation value:\\n{f}\\n with shape {f.shape}\")\n",
    "print(\n",
    "    f\"gradient value w.r.t encoder parametres:\\n{g_e}\\n with shape {g_e.shape}\")\n",
    "print(f\"gradient value w.r.t ansatz parametres:\\n{g_a}\\n with shape {g_a.shape}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 期望值结果分析\n",
    "\n",
    "在上述结果中,我们发现期望值是一个二维数组,维度为 $(2, 1)$,其中第一维表示样本点的个数,第二维表示哈密顿量的个数。在MindSpore Quantum中,我们除了能够批量的样本点外,还可以同时计算不同的哈密顿量关于线路的期望值和参数的导数。因此在上述结果中,当 $a=1, b=2, c=3$ 时,期望值为 $-0.2248451$,而当 $a=4, b=2, c=5$ 时,期望值为 $0.27201173$ 。\n",
    "\n",
    "### 梯度分析\n",
    "\n",
    "在上述结果中,我们发现期望值关于encoder参数的梯度是一个三维数组,维度为 $(2, 1, 2)$ ,其中第一维表示样本点个数,第二维表示哈密顿量个数,第三维表示encoder参数的个数。ansatz参数的梯度也是一个三维数组,维度为 $(2, 1, 1)$ ,其中第一维表示样本点个数,第二维表示哈密顿量个数,第三维表示ansatz参数的个数。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 多个哈密顿量在多个输入样本点下的期望值\n",
    "\n",
    "在本任务中,我们想计算如下量子线路在$\\alpha=\\text{arctan}(\\sqrt{2}), \\pi/2$时,关于哈密顿量$Z_0, X_0, Y_0$的期望值。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/svg+xml": [
       "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"1216.8\" height=\"80.0\" xmlns:xlink=\"http://www.w3.org/1999/xlink\"><rect x=\"0\" y=\"0.0\" width=\"1216.8\" height=\"80.0\" fill=\"#ffffff\" /><text x=\"20.0\" y=\"40.0\" font-size=\"16px\" dominant-baseline=\"middle\" text-anchor=\"start\" font-family=\"Arial\" font-weight=\"normal\" fill=\"#252b3a\" >q0: </text><line x1=\"48.8\" x2=\"1196.8\" y1=\"40.0\" y2=\"40.0\" stroke=\"#adb0b8\" stroke-width=\"1\" /><rect x=\"72.8\" y=\"20.0\" width=\"120.0\" height=\"40\" rx=\"4\" ry=\"4\" stroke=\"#ffffff\" stroke-width=\"0\" fill=\"#fac209\" fill-opacity=\"1\" /><text x=\"132.8\" y=\"36.0\" font-size=\"20px\" dominant-baseline=\"middle\" text-anchor=\"middle\" font-family=\"Arial\" font-weight=\"normal\" fill=\"#ffffff\" >RY </text><text x=\"132.8\" y=\"52.0\" font-size=\"14.0px\" dominant-baseline=\"middle\" text-anchor=\"middle\" font-family=\"Arial\" font-weight=\"normal\" fill=\"#ffffff\" >√2/8*alpha </text><rect x=\"212.8\" y=\"20.0\" width=\"120.0\" height=\"40\" rx=\"4\" ry=\"4\" stroke=\"#ffffff\" stroke-width=\"0\" fill=\"#fac209\" fill-opacity=\"1\" /><text x=\"272.8\" y=\"36.0\" font-size=\"20px\" dominant-baseline=\"middle\" text-anchor=\"middle\" font-family=\"Arial\" font-weight=\"normal\" fill=\"#ffffff\" >RX </text><text x=\"272.8\" y=\"52.0\" font-size=\"14.0px\" dominant-baseline=\"middle\" text-anchor=\"middle\" font-family=\"Arial\" font-weight=\"normal\" fill=\"#ffffff\" >-√2/8*alpha </text><rect x=\"352.8\" y=\"20.0\" width=\"120.0\" height=\"40\" rx=\"4\" ry=\"4\" stroke=\"#ffffff\" stroke-width=\"0\" fill=\"#fac209\" fill-opacity=\"1\" /><text x=\"412.8\" y=\"36.0\" font-size=\"20px\" dominant-baseline=\"middle\" text-anchor=\"middle\" font-family=\"Arial\" font-weight=\"normal\" fill=\"#ffffff\" >RY </text><text x=\"412.8\" y=\"52.0\" font-size=\"14.0px\" dominant-baseline=\"middle\" text-anchor=\"middle\" font-family=\"Arial\" font-weight=\"normal\" fill=\"#ffffff\" >√2/8*alpha </text><rect x=\"492.8\" y=\"20.0\" width=\"120.0\" height=\"40\" rx=\"4\" ry=\"4\" stroke=\"#ffffff\" stroke-width=\"0\" fill=\"#fac209\" fill-opacity=\"1\" /><text x=\"552.8\" y=\"36.0\" font-size=\"20px\" dominant-baseline=\"middle\" text-anchor=\"middle\" font-family=\"Arial\" font-weight=\"normal\" fill=\"#ffffff\" >RX </text><text x=\"552.8\" y=\"52.0\" font-size=\"14.0px\" dominant-baseline=\"middle\" text-anchor=\"middle\" font-family=\"Arial\" font-weight=\"normal\" fill=\"#ffffff\" >-√2/8*alpha </text><rect x=\"632.8\" y=\"20.0\" width=\"120.0\" height=\"40\" rx=\"4\" ry=\"4\" stroke=\"#ffffff\" stroke-width=\"0\" fill=\"#fac209\" fill-opacity=\"1\" /><text x=\"692.8\" y=\"36.0\" font-size=\"20px\" dominant-baseline=\"middle\" text-anchor=\"middle\" font-family=\"Arial\" font-weight=\"normal\" fill=\"#ffffff\" >RY </text><text x=\"692.8\" y=\"52.0\" font-size=\"14.0px\" dominant-baseline=\"middle\" text-anchor=\"middle\" font-family=\"Arial\" font-weight=\"normal\" fill=\"#ffffff\" >√2/8*alpha </text><rect x=\"772.8\" y=\"20.0\" width=\"120.0\" height=\"40\" rx=\"4\" ry=\"4\" stroke=\"#ffffff\" stroke-width=\"0\" fill=\"#fac209\" fill-opacity=\"1\" /><text x=\"832.8\" y=\"36.0\" font-size=\"20px\" dominant-baseline=\"middle\" text-anchor=\"middle\" font-family=\"Arial\" font-weight=\"normal\" fill=\"#ffffff\" >RX </text><text x=\"832.8\" y=\"52.0\" font-size=\"14.0px\" dominant-baseline=\"middle\" text-anchor=\"middle\" font-family=\"Arial\" font-weight=\"normal\" fill=\"#ffffff\" >-√2/8*alpha </text><rect x=\"912.8\" y=\"20.0\" width=\"120.0\" height=\"40\" rx=\"4\" ry=\"4\" stroke=\"#ffffff\" stroke-width=\"0\" fill=\"#fac209\" fill-opacity=\"1\" /><text x=\"972.8\" y=\"36.0\" font-size=\"20px\" dominant-baseline=\"middle\" text-anchor=\"middle\" font-family=\"Arial\" font-weight=\"normal\" fill=\"#ffffff\" >RY </text><text x=\"972.8\" y=\"52.0\" font-size=\"14.0px\" dominant-baseline=\"middle\" text-anchor=\"middle\" font-family=\"Arial\" font-weight=\"normal\" fill=\"#ffffff\" >√2/8*alpha </text><rect x=\"1052.8\" y=\"20.0\" width=\"120.0\" height=\"40\" rx=\"4\" ry=\"4\" stroke=\"#ffffff\" stroke-width=\"0\" fill=\"#fac209\" fill-opacity=\"1\" /><text x=\"1112.8\" y=\"36.0\" font-size=\"20px\" dominant-baseline=\"middle\" text-anchor=\"middle\" font-family=\"Arial\" font-weight=\"normal\" fill=\"#ffffff\" >RX </text><text x=\"1112.8\" y=\"52.0\" font-size=\"14.0px\" dominant-baseline=\"middle\" text-anchor=\"middle\" font-family=\"Arial\" font-weight=\"normal\" fill=\"#ffffff\" >-√2/8*alpha </text></svg>"
      ],
      "text/plain": [
       "<mindquantum.io.display.circuit_svg_drawer.SVGCircuit at 0x7fb9f2f0aeb0>"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "from mindquantum.core.operators import QubitOperator, TimeEvolution, Hamiltonian\n",
    "from mindquantum.simulator import Simulator\n",
    "from mindquantum.core.circuit import Circuit\n",
    "from mindquantum.core.gates import H\n",
    "\n",
    "# 定义希尔伯特空间中的旋转轴\n",
    "axis = QubitOperator('Y0', 1 / np.sqrt(2)) + QubitOperator('X0', -1 / np.sqrt(2))\n",
    "# 定义trotter分解的阶数\n",
    "trotter_order = 4\n",
    "# 利用TimeEvolution来对旋转进行trotter分解\n",
    "encoder = TimeEvolution(axis, {'alpha': 0.5 / trotter_order}).circuit * trotter_order\n",
    "encoder.as_encoder()\n",
    "encoder.svg()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "下面定义待求期望值的哈密顿量:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1 [X0], 1 [Y0], 1 [Z0]]"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 定义哈密顿量集合\n",
    "hams = [Hamiltonian(QubitOperator('X0')), Hamiltonian(QubitOperator('Y0')), Hamiltonian(QubitOperator('Z0'))]\n",
    "hams"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "获取求期望值和梯度的算子:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<mindquantum.simulator.utils.GradOpsWrapper at 0x7fb9f2eb46a0>"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "grad_ops = Simulator('mqvector', 1).get_expectation_with_grad(hams, encoder, parallel_worker=6)\n",
    "grad_ops"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "定义`alpha`的值:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0.95531662],\n",
       "       [1.57079633]])"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "alpha = np.array([[np.arctan(np.sqrt(2))], [np.pi/2]])\n",
    "alpha"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0.59389047+0.00000000e+00j 0.55828416+1.38777878e-17j\n",
      "  0.57932107+0.00000000e+00j]\n",
      " [0.77269648+0.00000000e+00j 0.63465887-1.38777878e-17j\n",
      "  0.01217645+0.00000000e+00j]]\n",
      "shape: (2, 3)\n",
      "\n",
      "\n",
      "[[[ 0.45790207+0.j]\n",
      "  [ 0.35200884+0.j]\n",
      "  [-0.80864423+0.j]]\n",
      "\n",
      " [[ 0.10989151+0.j]\n",
      "  [-0.11512098+0.j]\n",
      "  [-0.9732094 +0.j]]]\n",
      "shape: (2, 3, 1)\n"
     ]
    }
   ],
   "source": [
    "f, g = grad_ops(alpha)\n",
    "print(f)\n",
    "print(f'shape: {f.shape}')\n",
    "print('\\n')\n",
    "print(g)\n",
    "print(f'shape: {g.shape}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 结果分析\n",
    "\n",
    "根据上面结果我们可以看到,期望值`f`的维度为`(2, 3)`,不难发现,`f`的每一行对应每一个样本点不同哈密顿量期望值,`f`的每一列对应每个哈密顿量在不同样本的下的期望值。而对于梯度`g`来说,我们也有相似的结论,只不过最后一个维度表示的是不同的线路参数。\n",
    "\n",
    "## 计算不同量子态的内积\n",
    "\n",
    "根据模型,我们只需将哈密顿量设置为单位算符,$U_l(\\boldsymbol{\\theta})$ 设置为空的量子线路,那么我们就可以利用 $U_r(\\boldsymbol{\\theta})$ 来将 $\\left|\\psi\\right>$ 旋转到 $\\left|\\varphi\\right>$上,而这需要计算出 $\\left|\\varphi\\right>$和旋转后的量子态之间的内积。\n",
    "\n",
    "这里,我们计算如下量子线路对零态进行演化过后的量子态与均匀叠加态之间的内积。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/svg+xml": [
       "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"276.8\" height=\"80.0\" xmlns:xlink=\"http://www.w3.org/1999/xlink\"><rect x=\"0\" y=\"0.0\" width=\"276.8\" height=\"80.0\" fill=\"#ffffff\" /><text x=\"20.0\" y=\"40.0\" font-size=\"16px\" dominant-baseline=\"middle\" text-anchor=\"start\" font-family=\"Arial\" font-weight=\"normal\" fill=\"#252b3a\" >q0: </text><line x1=\"48.8\" x2=\"256.8\" y1=\"40.0\" y2=\"40.0\" stroke=\"#adb0b8\" stroke-width=\"1\" /><rect x=\"72.8\" y=\"20.0\" width=\"40.0\" height=\"40\" rx=\"4\" ry=\"4\" stroke=\"#ffffff\" stroke-width=\"0\" fill=\"#fac209\" fill-opacity=\"1\" /><text x=\"92.8\" y=\"36.0\" font-size=\"20px\" dominant-baseline=\"middle\" text-anchor=\"middle\" font-family=\"Arial\" font-weight=\"normal\" fill=\"#ffffff\" >RY </text><text x=\"92.8\" y=\"52.0\" font-size=\"14.0px\" dominant-baseline=\"middle\" text-anchor=\"middle\" font-family=\"Arial\" font-weight=\"normal\" fill=\"#ffffff\" >a </text><rect x=\"132.8\" y=\"20.0\" width=\"40.0\" height=\"40\" rx=\"4\" ry=\"4\" stroke=\"#ffffff\" stroke-width=\"0\" fill=\"#fac209\" fill-opacity=\"1\" /><text x=\"152.8\" y=\"36.0\" font-size=\"20px\" dominant-baseline=\"middle\" text-anchor=\"middle\" font-family=\"Arial\" font-weight=\"normal\" fill=\"#ffffff\" >RZ </text><text x=\"152.8\" y=\"52.0\" font-size=\"14.0px\" dominant-baseline=\"middle\" text-anchor=\"middle\" font-family=\"Arial\" font-weight=\"normal\" fill=\"#ffffff\" >b </text><rect x=\"192.8\" y=\"20.0\" width=\"40.0\" height=\"40\" rx=\"4\" ry=\"4\" stroke=\"#ffffff\" stroke-width=\"0\" fill=\"#fac209\" fill-opacity=\"1\" /><text x=\"212.8\" y=\"36.0\" font-size=\"20px\" dominant-baseline=\"middle\" text-anchor=\"middle\" font-family=\"Arial\" font-weight=\"normal\" fill=\"#ffffff\" >RY </text><text x=\"212.8\" y=\"52.0\" font-size=\"14.0px\" dominant-baseline=\"middle\" text-anchor=\"middle\" font-family=\"Arial\" font-weight=\"normal\" fill=\"#ffffff\" >c </text></svg>"
      ],
      "text/plain": [
       "<mindquantum.io.display.circuit_svg_drawer.SVGCircuit at 0x7fb9f2f579a0>"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "circuit = Circuit().ry('a', 0).rz('b', 0).ry('c', 0)\n",
    "circuit.svg()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "制备包含均匀叠加态的模拟器:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "mqvector simulator with 1 qubit (little endian), dtype: mindquantum.complex128.\n",
       "Current quantum state:\n",
       "√2/2¦0⟩\n",
       "√2/2¦1⟩"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sim_l = Simulator('mqvector', 1)\n",
    "sim_l.apply_gate(H.on(0))\n",
    "sim_l"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "制备单位哈密顿量:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "ham = Hamiltonian(QubitOperator(\"\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "获取内积和梯度计算算子:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "grad_ops = Simulator('mqvector', 1).get_expectation_with_grad(ham, circuit, Circuit(), simulator_left=sim_l)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "选择合适的参数:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "rot_angle = np.array([7.902762e-01, 2.139225e-04, 7.795934e-01])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0.99999989-7.52279618e-05j]]\n",
      "\n",
      "\n",
      "[[[ 2.31681689e-04+3.80179652e-05j -5.34806192e-05-3.51659884e-01j\n",
      "    2.31681689e-04-3.80179652e-05j]]]\n"
     ]
    }
   ],
   "source": [
    "f, g = grad_ops(rot_angle)\n",
    "print(f)\n",
    "print('\\n')\n",
    "print(g)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 结果分析\n",
    "\n",
    "通过计算结果,我们发现最后两个态的内积接近与1,说明我们能够通过如上线路以很高的保真度制备均匀叠加态 $\\left(\\left|0\\right> + \\left|1\\right>\\right)/\\sqrt{2}$。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(0.7074343486186319-0.00010695972396782116j)¦0⟩\n",
      "(0.7067790538448511+√5/3906250j)¦1⟩\n"
     ]
    }
   ],
   "source": [
    "print(circuit.get_qs(pr=rot_angle, ket=True))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<table border=\"1\">\n",
       "  <tr>\n",
       "    <th>Software</th>\n",
       "    <th>Version</th>\n",
       "  </tr>\n",
       "<tr><td>mindquantum</td><td>0.9.11</td></tr>\n",
       "<tr><td>scipy</td><td>1.10.1</td></tr>\n",
       "<tr><td>numpy</td><td>1.23.5</td></tr>\n",
       "<tr>\n",
       "    <th>System</th>\n",
       "    <th>Info</th>\n",
       "</tr>\n",
       "<tr><td>Python</td><td>3.9.16</td></tr><tr><td>OS</td><td>Linux x86_64</td></tr><tr><td>Memory</td><td>8.3 GB</td></tr><tr><td>CPU Max Thread</td><td>8</td></tr><tr><td>Date</td><td>Sun Dec 31 23:05:22 2023</td></tr>\n",
       "</table>\n"
      ],
      "text/plain": [
       "<mindquantum.utils.show_info.InfoTable at 0x7fba7c1f57c0>"
      ]
     },
     "execution_count": 18,
     "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"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}