Noise_EN.ipynb 40.4 KB
Newer Older
Q
Quleaf 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Simulating noisy quantum circuits with Paddle Quantum\n",
    "\n",
    "<em> Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved. </em>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction to quantum noises\n",
    "\n",
    "In ideal models, we usually assume that quantum circuits are operating on a **closed physical system**. However, real quantum devices suffer from **incoherent noises** introduced by unwanted interactions between the system and the environment. This type of noise can significantly change the performance of quantum computation tasks and hence can hardly be ignored for near-term quantum devices. Consequently, designing robust quantum algorithms under the presence of noise is crucial for utilizing quantum computation in the real world. With the noise module of Paddle Quantum, we can now not only design and simulate quantum algorithms but also examine various noises' influence and further develop error mitigation schemes.\n",
    "\n",
    "## Building noise models in Paddle Quantum\n",
    "\n",
    "### Noise model and quantum channel\n",
    " \n",
    "The evolution of a closed quantum system is always unitary. Mathematically, we can describe such a process as implementing a parameterized quantum circuit $U(\\vec{\\theta})$,\n",
    "\n",
    "$$\n",
    "\\rho \\longrightarrow U(\\vec{\\theta}) \\rho U^\\dagger(\\vec{\\theta}),\n",
    "\\tag{1}\n",
    "$$\n",
    "\n",
    "where $\\rho$ is the initial quantum state, $\\vec{\\theta}$ is a vector containing all the parameters. The most intuitive type of noise one can think of is the error that appears in these parameters, \n",
    "$$\n",
    "\\rho \\longrightarrow U(\\vec{\\theta}+\\vec{\\epsilon}) \\rho U^\\dagger(\\vec{\\theta}+\\vec{\\epsilon}),\n",
    "\\tag{2}\n",
    "$$\n",
    "\n",
    "$\\vec{\\epsilon}$ can be a white noise sampled from Gaussian distributions. This kind of noise is a specific example of **coherent noises**. Coherent noise usually occurs due to device calibration errors or quantum control errors. We want to emphasize that one also uses unitary transformation $U(\\vec{\\epsilon})$ to describe coherent noises. In certain cases, coherent noises can be more damaging than incoherent noises [1].  \n",
    "\n",
    "Most of the time, the real problem lies on the evolution of an **open quantum system** that is non-unitary. Under this circumstance, we need a more general description beyond the unitary transformation to characterize incoherent noises, the language of **quantum channels**. To keep the discussion precise, we use *operator-sum representation* [2] to introduce a quantum channel as \n",
    "\n",
    "$$\n",
    "\\mathcal{E}(\\rho) =  \\sum_{k=0}^{m-1} E_k \\rho E_k^{\\dagger},\n",
    "\\tag{3}\n",
    "$$\n",
    "\n",
    "where $\\{E_k\\}$ are *Kraus* operators, and they satisfy the completeness condition  $\\sum_k E_k^\\dagger E_k = I$. Mathematically, a quantum channel is completely positive and trace-preserving [2].\n",
    "\n",
    "Under this representation, we can explicitly observe the results of implementing a quantum channel: Suppose we start with a pure state $\\rho = |\\psi\\rangle\\langle \\psi|$, then we send it through a noisy quantum channel (e.g., $m = 2$ ). Eventually, we will get a mixed state $\\mathcal{E}(\\rho) = E_0 \\rho E_0^\\dagger + E_1 \\rho E_1^\\dagger$. Let's take the bit flip noise as an example: \n",
    "\n",
    "$$\n",
    "\\mathcal{E}_{BF}(\\rho) = (1 - p) I \\rho I+ p X \\rho X,\n",
    "\\tag{4}\n",
    "$$\n",
    "\n",
    "where $X,I$ are Pauli operators. The corresponding *Kraus* operators are:\n",
    "\n",
    "$$\n",
    "E_0 = \\sqrt{1-p}\n",
    "\\begin{bmatrix}\n",
    "1&0 \\\\\n",
    "0&1\n",
    "\\end{bmatrix},\n",
    "E_1 = \\sqrt{p}\n",
    "\\begin{bmatrix}\n",
    "0& 1 \\\\\n",
    "1 &0\n",
    "\\end{bmatrix}.\n",
    "\\tag{5}\n",
    "$$\n",
    "\n",
Q
Quleaf 已提交
71
    "The physical meaning of this quantum channel is there exist a  probability $p$ that the state $|0\\rangle$ will flip into $|1\\rangle$, and vice versa. In Paddle Quantum, we can use this quantum channel by `Circuit.bit_flip(p, which_qubit)`, where `p` is the noise level.\n",
Q
Quleaf 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
    "\n",
    "**Note:** For a quantum channel, the Kraus operator representation is not necessarily unique [3]."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Implementation with Paddle Quantum\n",
    "\n",
    "In this section, we will learn how to build a noise model in Paddle Quantum. First, we initialize a qubit to $|0\\rangle$. "
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
87
   "execution_count": 1,
Q
Quleaf 已提交
88 89 90 91 92 93 94
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-09T02:32:24.919291Z",
     "start_time": "2021-04-09T02:32:22.237264Z"
    }
   },
   "outputs": [
Q
Quleaf 已提交
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/zl/miniconda3/envs/pq/lib/python3.8/site-packages/openfermion/hamiltonians/hartree_fock.py:11: DeprecationWarning: Please use `OptimizeResult` from the `scipy.optimize` namespace, the `scipy.optimize.optimize` namespace is deprecated.\n",
      "  from scipy.optimize.optimize import OptimizeResult\n",
      "/home/zl/miniconda3/envs/pq/lib/python3.8/site-packages/paddle/tensor/creation.py:125: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. \n",
      "Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\n",
      "  if data.dtype == np.object:\n",
      "/home/zl/miniconda3/envs/pq/lib/python3.8/site-packages/paddle/tensor/creation.py:125: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. \n",
      "Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\n",
      "  if data.dtype == np.object:\n",
      "/home/zl/miniconda3/envs/pq/lib/python3.8/site-packages/paddle/fluid/framework.py:1104: DeprecationWarning: `np.bool` is a deprecated alias for the builtin `bool`. To silence this warning, use `bool` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.bool_` here.\n",
      "Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\n",
      "  elif dtype == np.bool:\n"
     ]
    },
Q
Quleaf 已提交
112 113
    {
     "data": {
Q
Quleaf 已提交
114
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYIAAAEDCAYAAAA4FgP0AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8qNh9FAAAACXBIWXMAAAsTAAALEwEAmpwYAAARcklEQVR4nO3debRdZX3G8e+TMKngBKlVkgDW0DYOoEZwaQdUsGBVnKogDlgktoKVpdJiq2DRrjq7akVrHCrqEkSrNNUIWgVtHQnIYILRiCBBXYIgDlQQ+fWPs5HD5d57TvDuc0ne72ets+7e7373Pr9kZeW5+333kKpCktSuBfNdgCRpfhkEktQ4g0CSGmcQSFLjDAJJapxBIEmN22a+C9hcu+yyS+2+++7zXYYkbVHOPffcq6pq0XTbtrgg2H333Vm7du18lyFJW5Qkl820zaEhSWqcQSBJjTMIJKlxBoEkNc4gkKTG9RYESd6b5EdJvjHD9iR5a5KNSS5M8pC+apEkzazPM4L3AQfOsv0gYFn3WQm8o8daJEkz6C0IquoLwNWzdDkYeH8NfAW4e5J791WPJGl683lD2a7A5UPrm7q2H0ztmGQlg7MGli5deru/cPfjPnm799XW79LX/vl8lyDNiy1isriqVlXViqpasWjRtHdIS5Jup/kMgiuAJUPri7s2SdIEzWcQrAae01099HDg2qq6zbCQJKlfvc0RJDkF2A/YJckm4ARgW4Cq+jdgDfA4YCNwHfC8vmqRJM2styCoqkNHbC/gqL6+X5I0ni1isliS1B+DQJIaZxBI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mwwdkAAAAASUVORK5CYII=",
Q
Quleaf 已提交
115 116 117 118 119 120 121 122 123 124 125 126
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
Q
Quleaf 已提交
127
       "{'0': 1.0, '1': 0.0}"
Q
Quleaf 已提交
128 129
      ]
     },
Q
Quleaf 已提交
130
     "execution_count": 1,
Q
Quleaf 已提交
131 132 133 134 135
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
Q
Quleaf 已提交
136 137 138 139 140
    "import paddle_quantum\n",
    "from paddle_quantum.ansatz import Circuit\n",
    "\n",
    "# Change to density matrix mode\n",
    "paddle_quantum.set_backend('density_matrix')\n",
Q
Quleaf 已提交
141 142 143 144 145
    "\n",
    "# Define the number of qubits, here we use one single qubit\n",
    "num_qubits = 1\n",
    "\n",
    "# Initialize the quantum circuit\n",
Q
Quleaf 已提交
146
    "cir = Circuit(num_qubits)\n",
Q
Quleaf 已提交
147 148
    "\n",
    "# Initialize the qubit to |0><0| \n",
Q
Quleaf 已提交
149
    "init_state = paddle_quantum.state.zero_state(num_qubits)\n",
Q
Quleaf 已提交
150 151
    "\n",
    "# Mesure in the computational basis \n",
Q
Quleaf 已提交
152
    "cir(init_state).measure(shots = 1024, plot = True)"
Q
Quleaf 已提交
153 154 155 156 157 158 159 160 161 162 163 164
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then, we add a bit flip channel with $p=0.1$, and measure the qubit after this channel.\n",
    "**Note:** Noisy module in Paddle Quantum only supports density matrix operation mode."
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
165
   "execution_count": 2,
Q
Quleaf 已提交
166 167 168 169 170 171 172 173 174 175
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-09T02:32:25.168455Z",
     "start_time": "2021-04-09T02:32:24.926709Z"
    },
    "scrolled": true
   },
   "outputs": [
    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n4MXM7g/olNuReDFyg9DPgicOKM47wT+C7wpOEQ6Lb9kMHb965IcmqSI5LMq6ovd+3HVdVeVfUt4GNV9ZjuzOFi4KiN9FsJvLyqHg28Gnj3Zv9vSBvhfQTSaLcAH+6WP8hgiGliVfXiJI8A9mfwi/sA4MgRXR+e5I3AfYEdGbzR73aS7Ag8HvjIYLQLgLHzHNKkDALNZesYDP/8Wjc09JsMhnQezu3PinfYxLE2ewy1qi4CLkryAeDbjA6C9wPPrKoLkhwJ7DeizzzgR1W11+bWIE3CoSHNZZ8H7pnkjwCSzAfeDryrG7u/HNgrybwkixjcdX2redwWIs8H/mfE8W8EdprZmGTHJPsNNe3Fbc94mrnPTsD3ugnmI0YduxvO+naSP+yOnyR7buofLm0Og0BzVg2uhHgW8JzuGUvXAbdU1d92Xc5h8Jf6OuCdwHlDu/8U2CfJ/zKY0D1pxLdYCXwmyVkz2gP8RZL1Sc4H/obbzgZOA47rLi39LeB1wNe6WoYnf2f2OwI4KskFwFoG75WQtgivGlIzuqt2TgWeVVXnjesvtcIgkKTGOTQkSY0zCCSpcQaBJDXOIJCkxhkEktQ4g0CSGmcQSFLj/h+FihdAQLomqQAAAABJRU5ErkJggg==",
Q
Quleaf 已提交
177 178 179 180 181 182 183 184 185 186 187 188 189 190
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Quantum state after the bit flip quantum channel:\n",
Q
Quleaf 已提交
191 192
      " [[0.8999999+0.j 0.       +0.j]\n",
      " [0.       +0.j 0.1      +0.j]]\n"
Q
Quleaf 已提交
193 194 195 196 197 198 199 200 201 202 203 204
     ]
    }
   ],
   "source": [
    "# Noise level\n",
    "p = 0.1\n",
    "\n",
    "# Add the bit flip noisy channel\n",
    "cir.bit_flip(p, 0)\n",
    "\n",
    "# Execute the circuit\n",
    "# Note: Noisy module in Paddle Quantum only supports density matrix operation mode\n",
Q
Quleaf 已提交
205
    "fin_state =  cir(init_state)\n",
Q
Quleaf 已提交
206 207
    "\n",
    "# Measure in the computational basis\n",
Q
Quleaf 已提交
208 209
    "fin_state.measure(shots = 1024, plot = True)\n",
    "print('Quantum state after the bit flip quantum channel:\\n', fin_state.data.numpy())"
Q
Quleaf 已提交
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As we can see, the quantum state has been transformed to a mixed state $0.9 | 0 \\rangle \\langle 0 | + 0.1 | 1 \\rangle \\langle 1 |$ (with probability $p=0.1$ ) after the bit flip channel.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Common quantum channels\n",
    "\n",
    "Paddle Quantum supports many other common noisy channels.\n",
    "\n",
    "- **Phase Flip Channel**\n",
    "\n",
    "  Similar to the bit-flip channel, the phase flip channel flips the phase of a qubit with probability $p$, \n",
    "  \n",
    "  $$\n",
    "  \\mathcal{E}_{PF}(\\rho) =  (1 - p) \\rho + p Z \\rho Z.\n",
    "  \\tag{6}\n",
    "  $$\n",
    "\n",
    "\n",
    "- **Bit-Phase Flip Channel**\n",
    "\n",
    "  $$\n",
    "  \\mathcal{E}_{BPF}(\\rho) = (1-p) \\rho + p Y \\rho Y.\n",
    "  \\tag{7}\n",
    "  $$\n",
    "\n",
    "\n",
    "- **Depolarizing Channel**\n",
    "\n",
    "  The quantum state will be in the maximally mixed state $I/2$ with probability $p$ or in the original state with probability $1-p$ after the single qubit depolarizing channel. The depolarizing channel can also be understood as applying Pauli noises symmetrically, \n",
    "  \n",
    "  $$\n",
    "  \\mathcal{E}_{D}(\\rho) = (1 - p) \\rho + \\frac{p}{3}\n",
    "  \\left( X \\rho X+ Y \\rho Y + Z \\rho Z \\right).\n",
    "  \\tag{8}\n",
    "  $$\n",
    "\n",
    "\n",
    "- **Pauli Channel**\n",
    "\n",
    "  The Pauli channel applies Pauli noises asymmetrically, \n",
    "  \n",
    "  $$\n",
    "  \\mathcal{E}_{Pauli}(\\rho) = (1 - p_x - p_y - p_z) \\rho + p_x X \\rho X + p_y Y \\rho Y + p_z Z \\rho Z.\n",
    "  \\tag{9}\n",
    "  $$\n",
    "\n",
    "\n",
    "- **Amplitude Damping Channel**\n",
    "\n",
    "  The amplitude damping channel can be used to model the process of **energy dissipation**, \n",
    "  \n",
    "  $$\n",
    "  \\mathcal{E}_{AD}(\\rho) = E_0 \\rho E_0^\\dagger + E_1 \\rho E_1^\\dagger,\n",
    "  \\tag{10}\n",
    "  $$\n",
    "  \n",
    "  where $\\gamma$ is the damping factor,\n",
    "  \n",
    "  $$\n",
    "  E_0 = \n",
    "  \\begin{bmatrix}\n",
    "   1 & 0 \\\\ 0 & \\sqrt{1 - \\gamma}\n",
    "  \\end{bmatrix},\n",
    "  E_1 = \n",
    "  \\begin{bmatrix}\n",
    "   0 & \\sqrt{\\gamma} \\\\ 0 & 0\n",
    "  \\end{bmatrix}.\n",
    "  \\tag{11}\n",
    "  $$ \n",
    "\n",
    "\n",
    "- **Phase Damping Channel**\n",
    "\n",
    "  The phase damping channel describes the loss of **quantum information** without loss of energy, \n",
    "  \n",
    "  $$\n",
    "  \\mathcal{E}_{PD}(\\rho) = E_0 \\rho E_0^\\dagger + E_1 \\rho E_1^\\dagger,\n",
    "  \\tag{12}\n",
    "  $$\n",
    "  \n",
    "  where $\\gamma$ is the damping factor,\n",
    "  \n",
    "  $$\n",
    "  E_0 = \n",
    "  \\begin{bmatrix}\n",
    "   1 & 0 \\\\ 0 & \\sqrt{1 - \\gamma}\n",
    "  \\end{bmatrix}, \n",
    "  E_1 = \n",
    "  \\begin{bmatrix}\n",
    "   0 & 0 \\\\ 0 & \\sqrt{\\gamma}\n",
    "  \\end{bmatrix}.\n",
    "  \\tag{13}\n",
    "  $$\n",
    "\n",
    "\n",
    "- **Generalized Amplitude Damping Channel**\n",
    "\n",
    "  The generalized amplitude damping channel describes energy exchange between the system and the environment at **finite temperatures**. It is a common noise in superconducting quantum computations [4]. Interested readers can find more information here [API document](https://qml.baidu.com/api/paddle_quantum.circuit.uansatz.html).\n",
    "\n",
    "\n",
Q
Quleaf 已提交
319
    "**Note:** In Paddle Quantum, we can use these noisy channels through `Circuit.phase_flip()`, `Circuit.bit_phase_flip()`, `Circuit.depolarizing()`, `Circuit.pauli_channel()`, `Circuit.amplitude_damping()`, `Circuit.phase_damping()`, and `Circuit.generalized_amplitude_damping()`.\n",
Q
Quleaf 已提交
320 321 322 323 324 325 326 327 328 329
    "\n",
    "**Note:** One usually choose the amplitude damping channel and the phase damping channel to model noises since they describe the physical process in real quantum systems (modeling $T_1$ and $T_2$ process)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Customized Channel\n",
    "\n",
Q
Quleaf 已提交
330
    "One can also use `Circuit.customized_channel()` in Paddle Quantum to add customized noisy channels. This is accomplished through user-defined Kraus operators. Here, we provide an example to reproduce the bit flip channel using customized_channel function:"
Q
Quleaf 已提交
331 332 333 334
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
335
   "execution_count": 3,
Q
Quleaf 已提交
336 337 338 339 340 341 342 343 344 345 346 347
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-09T02:54:20.758898Z",
     "start_time": "2021-04-09T02:54:20.599327Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "quantum state after the customized channel:\n",
Q
Quleaf 已提交
348 349
      " [[0.90000004+0.j 0.        +0.j]\n",
      " [0.        +0.j 0.1       +0.j]]\n",
Q
Quleaf 已提交
350 351
      "\n",
      " quantum state after the bit flip channel:\n",
Q
Quleaf 已提交
352 353
      " [[0.8999999+0.j 0.       +0.j]\n",
      " [0.       +0.j 0.1      +0.j]]\n",
Q
Quleaf 已提交
354 355 356 357 358 359 360 361 362 363 364 365 366
      "\n",
      " are the two the same? True\n"
     ]
    }
   ],
   "source": [
    "import paddle\n",
    "import numpy as np\n",
    "\n",
    "# Noise level\n",
    "p = 0.1\n",
    "\n",
    "# We use customized Kraus operator to represent the bit flip channel\n",
Q
Quleaf 已提交
367 368 369
    "complex_dtype = paddle_quantum.get_dtype()\n",
    "a_0 = paddle.to_tensor(np.sqrt(1 - p) * np.array([[1, 0], [0, 1]], dtype=complex_dtype))\n",
    "a_1 = paddle.to_tensor(np.sqrt(p) * np.array([[0, 1], [1, 0]], dtype=complex_dtype))\n",
Q
Quleaf 已提交
370 371 372 373
    "Kraus_ops = [a_0, a_1]\n",
    "\n",
    "# Initialize the circuit\n",
    "num_qubits = 1\n",
Q
Quleaf 已提交
374
    "cir = Circuit(num_qubits)\n",
Q
Quleaf 已提交
375 376
    "\n",
    "# Add customized channel, input is a list of Kraus operators\n",
Q
Quleaf 已提交
377
    "cir.kraus_channel(Kraus_ops, 0)\n",
Q
Quleaf 已提交
378 379
    "\n",
    "# Execute the circuit\n",
Q
Quleaf 已提交
380
    "fin_state =  cir(init_state)\n",
Q
Quleaf 已提交
381 382
    "\n",
    "# Compare the results\n",
Q
Quleaf 已提交
383
    "cir_1 = Circuit(num_qubits)\n",
Q
Quleaf 已提交
384
    "cir_1.bit_flip(p, 0)\n",
Q
Quleaf 已提交
385 386 387 388
    "fin_state_1 = cir_1(init_state)\n",
    "print('quantum state after the customized channel:\\n', fin_state.data.numpy())\n",
    "print('\\n quantum state after the bit flip channel:\\n', fin_state_1.data.numpy())\n",
    "print('\\n are the two the same?', bool((fin_state.data - fin_state_1.data).abs().sum() < 1e-6))"
Q
Quleaf 已提交
389 390 391 392 393 394 395 396
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Discussion: Simulating noisy entanglement resources with Paddle Quantum\n",
    "\n",
Q
Quleaf 已提交
397
    "Many important quantum technologies require pre-shared entanglement resources, including quantum teleportation, state transformation, and distributed quantum computing. For instance, we want the allocated entanglement resources are in **maximally entangled states** under ideal circumstances. But in reality, noise always exists due to interactions between the system and the environment during preparation stage, transmission, and preservation. Here, we use the depolarizing channel to simulate how a white noise could affect Bell states: "
Q
Quleaf 已提交
398 399 400 401
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
402
   "execution_count": 4,
Q
Quleaf 已提交
403 404 405 406 407 408 409 410 411 412 413 414
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-09T02:58:30.352039Z",
     "start_time": "2021-04-09T02:58:30.311223Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Fidelity between the initial state and the Bell state 1\n",
Q
Quleaf 已提交
415 416
      "after transmission (depolarizing channel), the fidelity between the entangled state and Bell state 0.85750\n",
      "after preservation (amplitude damping channel), the fidelity between the entangled state and Bell state 0.73556\n"
Q
Quleaf 已提交
417 418 419 420 421 422
     ]
    }
   ],
   "source": [
    "import paddle\n",
    "from paddle import matmul, trace\n",
Q
Quleaf 已提交
423
    "from paddle_quantum.ansatz import Circuit\n",
Q
Quleaf 已提交
424 425 426 427 428 429 430 431
    "from paddle_quantum.state import bell_state\n",
    "\n",
    "# Noise level\n",
    "p_trans = 0.1\n",
    "p_store = 0.01\n",
    "\n",
    "# Initialize the circuit\n",
    "num_qubits = 2\n",
Q
Quleaf 已提交
432
    "cir = Circuit(num_qubits)\n",
Q
Quleaf 已提交
433 434
    "\n",
    "# The initial state is Bell state\n",
Q
Quleaf 已提交
435
    "init_state = bell_state(2)\n",
Q
Quleaf 已提交
436
    "\n",
Q
Quleaf 已提交
437
    "# Apply the depolarizing channel to each qubit, modeling the noise introduced by transmission\n",
Q
Quleaf 已提交
438 439 440 441
    "cir.depolarizing(p_trans, 0)\n",
    "cir.depolarizing(p_trans, 1)\n",
    "\n",
    "# Execute the circuit \n",
Q
Quleaf 已提交
442
    "status_mid = cir(init_state)\n",
Q
Quleaf 已提交
443 444 445 446 447 448
    "\n",
    "# Apply the amplitude damping channel to each qubit, modeling the noise introduced by storage\n",
    "cir.amplitude_damping(p_store, 0)\n",
    "cir.amplitude_damping(p_store, 1)\n",
    "\n",
    "# Execute the circuit\n",
Q
Quleaf 已提交
449 450 451
    "status_fin = cir(status_mid)\n",
    "fidelity_mid = paddle.real(trace(matmul(init_state.data, status_mid.data)))\n",
    "fidelity_fin = paddle.real(trace(matmul(init_state.data, status_fin.data)))\n",
Q
Quleaf 已提交
452 453
    "\n",
    "print(\"Fidelity between the initial state and the Bell state\", 1)\n",
Q
Quleaf 已提交
454
    "print(\"after transmission (depolarizing channel), the fidelity between the entangled state and Bell state {:.5f}\".format(fidelity_mid.numpy()[0]))\n",
Q
Quleaf 已提交
455 456 457 458 459 460 461
    "print(\"after preservation (amplitude damping channel), the fidelity between the entangled state and Bell state {:.5f}\".format(fidelity_fin.numpy()[0]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Q
Quleaf 已提交
462
    "**Note:** Interested readers can check tutorials on the LOCCNet module of Paddle Quantum, where we discuss the concept of [entanglement distillation](../locc/EntanglementDistillation_LOCCNET_EN.ipynb)."
Q
Quleaf 已提交
463 464 465 466 467 468 469 470 471
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Application: Simulating noisy VQE with Paddle Quantum\n",
    "\n",
    "\n",
Q
Quleaf 已提交
472
    "Variational Quantum Eigensolver (VQE) [5] is designed to find the ground state energy of a given molecular Hamiltonian using variational quantum circuits. Interested readers can find more details from the previous tutorial [VQE](../quantum_simulation/VQE_EN.ipynb).\n",
Q
Quleaf 已提交
473 474 475 476 477 478 479 480 481 482 483 484 485
    "\n",
    "For illustration purposes, we use VQE to find the ground state energy for the following Hamiltonian: \n",
    "\n",
    "$$ \n",
    "H = 0.4 \\, Z \\otimes I + 0.4 \\, I \\otimes Z + 0.2 \\, X \\otimes X. \n",
    "\\tag{14}\n",
    "$$\n",
    "\n",
    "Then, we add the amplitude damping channel and compare the performance of the noisy circuit and the noiseless circuit on this task:"
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
486
   "execution_count": 5,
Q
Quleaf 已提交
487 488 489 490 491 492 493 494 495 496
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-09T03:06:13.534545Z",
     "start_time": "2021-04-09T03:06:13.523978Z"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import paddle\n",
Q
Quleaf 已提交
497 498
    "from paddle_quantum.ansatz import Circuit\n",
    "from paddle_quantum.qinfo import pauli_str_to_matrix\n",
Q
Quleaf 已提交
499 500 501 502 503 504 505
    "\n",
    "# Hyperparameters\n",
    "num_qubits = 2\n",
    "theta_size = 4\n",
    "ITR = 100\n",
    "LR = 0.4\n",
    "SEED = 999    \n",
Q
Quleaf 已提交
506 507 508 509 510 511 512 513
    "p = 0.1\n",
    "\n",
    "# Construct Hamiltonian using Pauli string\n",
    "H_info = [[0.4, 'z0'], [0.4, 'z1'], [0.2, 'x0,x1']]\n",
    "\n",
    "# Convert the Pauli string to a matrix\n",
    "complex_dtype = paddle_quantum.get_dtype()\n",
    "H_matrix = pauli_str_to_matrix(H_info, num_qubits).numpy().astype(complex_dtype)"
Q
Quleaf 已提交
514 515 516 517
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
518
   "execution_count": 6,
Q
Quleaf 已提交
519 520 521 522 523 524 525 526 527 528 529 530
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-09T03:06:36.986422Z",
     "start_time": "2021-04-09T03:06:32.444713Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "========== Training Noisy VQE ==========\n",
Q
Quleaf 已提交
531 532 533 534 535 536 537 538
      "iter: 0   loss: -0.2233\n",
      "iter: 10   loss: -0.6082\n",
      "iter: 20   loss: -0.6373\n",
      "iter: 30   loss: -0.6554\n",
      "iter: 40   loss: -0.6618\n",
      "iter: 50   loss: -0.6614\n",
      "iter: 60   loss: -0.6621\n",
      "iter: 70   loss: -0.6620\n",
Q
Quleaf 已提交
539 540 541
      "iter: 80   loss: -0.6621\n",
      "iter: 90   loss: -0.6621\n",
      "========== Training Noise Free VQE ==========\n",
Q
Quleaf 已提交
542 543 544 545 546 547 548
      "iter: 0   loss: -0.1235\n",
      "iter: 10   loss: -0.7679\n",
      "iter: 20   loss: -0.7933\n",
      "iter: 30   loss: -0.8177\n",
      "iter: 40   loss: -0.8219\n",
      "iter: 50   loss: -0.8239\n",
      "iter: 60   loss: -0.8244\n",
Q
Quleaf 已提交
549
      "iter: 70   loss: -0.8245\n",
Q
Quleaf 已提交
550
      "iter: 80   loss: -0.8245\n",
Q
Quleaf 已提交
551 552
      "iter: 90   loss: -0.8246\n",
      "\n",
Q
Quleaf 已提交
553 554
      "Ground state energy from noisy circuit:  -0.6621509 Ha\n",
      "Ground state energy from noiseless circuit:  -0.82461375 Ha\n",
Q
Quleaf 已提交
555
      "Actual ground state energy:  -0.82462114 Ha\n"
Q
Quleaf 已提交
556 557 558 559 560 561
     ]
    }
   ],
   "source": [
    "class vqe_noisy(paddle.nn.Layer):\n",
    "    \n",
Q
Quleaf 已提交
562
    "    def __init__(self):\n",
Q
Quleaf 已提交
563
    "        super(vqe_noisy, self).__init__()\n",
Q
Quleaf 已提交
564
    "\n",
Q
Quleaf 已提交
565
    "        # Initialize circuit\n",
Q
Quleaf 已提交
566
    "        self.cir = Circuit(num_qubits)\n",
Q
Quleaf 已提交
567 568
    "        \n",
    "        # Add parameterized gates\n",
Q
Quleaf 已提交
569
    "        self.cir.ry([0, 1])\n",
Q
Quleaf 已提交
570
    "        \n",
Q
Quleaf 已提交
571
    "        self.cir.cnot([0, 1])\n",
Q
Quleaf 已提交
572
    "        \n",
Q
Quleaf 已提交
573
    "        self.cir.ry([0, 1])\n",
Q
Quleaf 已提交
574 575
    "        \n",
    "        # Add amplitude damping channel\n",
Q
Quleaf 已提交
576 577 578 579 580
    "        self.cir.amplitude_damping(p, [0, 1])\n",
    "          \n",
    "    # Define loss function and forward function\n",
    "    def forward(self):\n",
    "          \n",
Q
Quleaf 已提交
581
    "        # Execute the circuit\n",
Q
Quleaf 已提交
582
    "        state = self.cir(init_state)\n",
Q
Quleaf 已提交
583 584
    "        \n",
    "        # Expectation value of Hamiltonian \n",
Q
Quleaf 已提交
585
    "        loss = loss_func(state)\n",
Q
Quleaf 已提交
586
    "        \n",
Q
Quleaf 已提交
587
    "        return loss, self.cir\n",
Q
Quleaf 已提交
588 589 590 591
    "    \n",
    "# Construct a noiseless circuit\n",
    "class vqe_noise_free(paddle.nn.Layer):\n",
    "    \n",
Q
Quleaf 已提交
592
    "    def __init__(self):\n",
Q
Quleaf 已提交
593 594
    "        super(vqe_noise_free, self).__init__()\n",
    "        \n",
Q
Quleaf 已提交
595 596 597 598 599
    "        self.cir = Circuit(num_qubits)\n",
    "        self.cir.ry([0, 1])\n",
    "        self.cir.cnot([0, 1])\n",
    "        self.cir.ry([0, 1])\n",
    "\n",
Q
Quleaf 已提交
600 601
    "    def forward(self):\n",
    "        \n",
Q
Quleaf 已提交
602 603
    "        state = self.cir(init_state)\n",
    "        loss = loss_func(state)\n",
Q
Quleaf 已提交
604
    "        \n",
Q
Quleaf 已提交
605
    "        return loss, self.cir\n",
Q
Quleaf 已提交
606 607 608 609 610 611 612
    "    \n",
    "# Train noisy VQE circuit\n",
    "print('========== Training Noisy VQE ==========')\n",
    "loss_list = []\n",
    "parameter_list = []\n",
    "\n",
    "# Define the dimension of parameters\n",
Q
Quleaf 已提交
613
    "vqe = vqe_noisy()\n",
Q
Quleaf 已提交
614 615
    "\n",
    "# Generally, we use Adam optimizer to get a better convergence, you can change to SVG or RMS prop.\n",
Q
Quleaf 已提交
616 617 618 619 620 621 622
    "opt = paddle.optimizer.Adam(learning_rate = LR, parameters = vqe.parameters()) \n",
    "\n",
    "# Define initial state\n",
    "init_state = paddle_quantum.state.zero_state(num_qubits)\n",
    "\n",
    "# Define loss function\n",
    "loss_func = paddle_quantum.loss.ExpecVal(paddle_quantum.Hamiltonian(H_info))\n",
Q
Quleaf 已提交
623 624 625 626 627
    "\n",
    "# Optimization iteration\n",
    "for itr in range(ITR):\n",
    "\n",
    "    # Forward, to calculate loss function\n",
Q
Quleaf 已提交
628
    "    loss, cir = vqe()\n",
Q
Quleaf 已提交
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
    "\n",
    "    # Backpropagate to minimize the loss function\n",
    "    loss.backward()\n",
    "    opt.minimize(loss)\n",
    "    opt.clear_grad()\n",
    "\n",
    "    # Record the learning curve\n",
    "    loss_list.append(loss.numpy()[0])\n",
    "    parameter_list.append(vqe.parameters()[0].numpy())\n",
    "    if itr % 10 == 0:\n",
    "        print('iter:', itr, '  loss: %.4f' % loss.numpy())\n",
    "        \n",
    "# Train the noiseless VQE in the same way\n",
    "print('========== Training Noise Free VQE ==========')\n",
    "loss_list_no_noise = []\n",
    "parameter_list_no_noise = []\n",
    "\n",
Q
Quleaf 已提交
646
    "vqe_no_noise = vqe_noise_free()\n",
Q
Quleaf 已提交
647 648 649 650
    "opt_no_noise = paddle.optimizer.Adam(learning_rate = LR, parameters = vqe_no_noise.parameters())    \n",
    "\n",
    "for itr in range(ITR):\n",
    "\n",
Q
Quleaf 已提交
651
    "    loss, cir = vqe_no_noise()\n",
Q
Quleaf 已提交
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
    "\n",
    "    loss.backward()\n",
    "    opt_no_noise.minimize(loss)\n",
    "    opt_no_noise.clear_grad()\n",
    "\n",
    "    loss_list_no_noise.append(loss.numpy()[0])\n",
    "    parameter_list_no_noise.append(vqe_no_noise.parameters()[0].numpy())\n",
    "    if itr % 10 == 0:\n",
    "        print('iter:', itr, '  loss: %.4f' % loss.numpy())\n",
    "\n",
    "\n",
    "print('\\nGround state energy from noisy circuit: ', loss_list[-1], \"Ha\")\n",
    "print('Ground state energy from noiseless circuit: ', loss_list_no_noise[-1], \"Ha\")\n",
    "print('Actual ground state energy: ', np.linalg.eigh(H_matrix)[0][0], \"Ha\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As we can see, noisy VQE behaves much worse than the noiseless version as expected and couldn't satisfy chemical accuracy $\\varepsilon = 0.0016$ Ha."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Conclusion\n",
    "\n",
    "Noise is an unavoidable feature of quantum devices in the NISQ era. Therefore, designing robust quantum algorithms under the presence of noise and further developing error mitigation schemes are two important research directions. With the noise module in Paddle Quantum, we hope to provide a platform simulating real physical systems and help developing near-term quantum computation applications. Standing together with the research community, the noise module will help us explore what we can achieve with noisy devices, design more robust quantum algorithms, and eventually leads to trustworthy quantum solutions in areas including AI and quantum chemistry.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## References\n",
    "\n",
    "[1] Iverson, J. K., & Preskill, J. Coherence in logical quantum channels. [New Journal of Physics, 22(7), 073066 (2020).](https://iopscience.iop.org/article/10.1088/1367-2630/ab8e5c)\n",
    "\n",
    "[2] Nielsen, M. A. & Chuang, I. L. Quantum computation and quantum information. Cambridge university press (2010).\n",
    "\n",
    "[3] Preskill, J. Quantum Information Lecture Notes. Chapter 3 (2018).\n",
    "\n",
    "[4] Chirolli, L., & Burkard, G. Decoherence in solid-state qubits. [Advances in Physics, 57(3), 225-285 (2008).](https://www.tandfonline.com/doi/abs/10.1080/00018730802218067)\n",
    "\n",
    "[5] Peruzzo, A. et al. A variational eigenvalue solver on a photonic quantum processor. [Nat. Commun. 5, 4213 (2014).](https://www.nature.com/articles/ncomms5213)"
   ]
  }
 ],
 "metadata": {
Q
Quleaf 已提交
705 706 707
  "interpreter": {
   "hash": "4261e4eef114648d37e4a637967bd8d2966507f48b194e5e336ba3366b740269"
  },
Q
Quleaf 已提交
708
  "kernelspec": {
Q
Quleaf 已提交
709
   "display_name": "Python 3.8.13 ('pq-ns-icode')",
Q
Quleaf 已提交
710 711 712 713 714 715 716 717 718 719 720 721 722
   "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",
Q
Quleaf 已提交
723
   "version": "3.8.13"
Q
Quleaf 已提交
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}