VAns_EN.ipynb 31.9 KB
Newer Older
Q
Quleaf 已提交
1 2 3 4 5 6
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Q
Quleaf 已提交
7
    "# VAns: Variable Ansatz"
Q
Quleaf 已提交
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
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Copyright (c) 2022 Institute for Quantum Computing, Baidu Inc. All Rights Reserved."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Overview"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Variational Quantum Algorithms (VQA) are about to tune parameters of quantum circuits to minimize an objective function of interest. The commonly used VQAs, like Variational Quantum Eigensolvers (VQE) and Quantum Approximate Optimization Algorithm (QAOA), perform optimization using a user-defined ansatz with fixed structure. However, if the ansatz is too simple or shallow, the expressivity of the circuit will not be insufficient to get the optimal value for the objective function. On the other side, if the ansatz is overly complicated or long, we may encounter barren plateau effect, which impedes us from obtaining the global minimum value. Thus, a circuit structure design search algorithm will be helpful to find the appropriate circuit for a specific task.\n",
    "\n",
    "In this tutorial, we will discuss a circuit architecture design search algorithm called Variable ansatz (VAns) [1]. Starting with an initial circuit, VAns keeps inserting and deleting gates during the optimization process in order to minimize the loss function as well as keep the circuit shallow. We will use this method to accomplish an adjusted version of VQE task and compare the resulting circuit with the original VQE circuit."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Pipeline"
   ]
  },
  {
Q
Quleaf 已提交
41
   "attachments": {},
Q
Quleaf 已提交
42 43 44 45 46 47 48
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "VAns consists of the following steps:  \n",
    "1. Start with an initial circuit. Run the inner optimization, which is just the original VQE process, and get the optimal value. \n",
    "2. Randomly choose a block from the 'pool' (As the following figure shows, each block only consists of $R_y$, $R_z$, and $CNOT$ gates), and insert the block at the end of circuit. Qubits that the block is applied on are also uniformly sampled. The parameters of the inserted gates are initialized to $0$ so that the inserted circuit is equivalent to identity. \n",
    "\n",
Q
Quleaf 已提交
49
    "![Inserting Blocks](figures/vans-fig-blocks.png)\n",
Q
Quleaf 已提交
50 51 52
    "\n",
    "3. Simplify the circuit according to the following rules. Run the optimization process, and get the optimal value of loss function. Compare the loss value to the previously stored one, decide whether to accept the new circuit or not according to a pre-defined threshold. If the circuit is accepted, remove gates that do not lower the loss, set the circuit as the current circuit and store the corresponding loss value.\n",
    "\n",
Q
Quleaf 已提交
53
    "![Simplification rules](figures/vans-fig-rules.png)\n",
Q
Quleaf 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
    "\n",
    "4. Repeat steps 2-3 for chosen number of iterations, output the resulting circuit and the optimal loss value.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Paddle Quantum Implementation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We consider to get the ground state energy of Hydrogen molecule using [Variation Quantum Eigensolver (VQE)](https://qml.baidu.com/tutorials/quantum-simulation/variational-quantum-eigensolver.html) together with VAns to optimize the circuit structure as well. First, we import the required packages."
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
74
   "execution_count": 1,
Q
Quleaf 已提交
75
   "metadata": {},
Q
Quleaf 已提交
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/v_zhanglei48/opt/anaconda3/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",
      "/Users/v_zhanglei48/opt/anaconda3/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"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<paddle.fluid.core_noavx.Generator at 0x7fcf214498f0>"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
Q
Quleaf 已提交
100 101 102 103 104 105 106
   "source": [
    "import paddle\n",
    "import paddle_quantum\n",
    "import paddle_quantum.qchem as qchem\n",
    "import numpy as np\n",
    "from paddle_quantum.ansatz import Circuit\n",
    "from paddle_quantum.ansatz.vans import Inserter, Simplifier, VAns, cir_decompose\n",
Q
Quleaf 已提交
107
    "from paddle_quantum.loss import ExpecVal\n",
Q
Quleaf 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120 121
    "\n",
    "np.random.seed(11)\n",
    "paddle.seed(11)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Before using the VAns algorithm, we need to get the Hamiltonian for Hydrogen. Details can be found in the VQE tutorial."
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
122
   "execution_count": 2,
Q
Quleaf 已提交
123
   "metadata": {},
Q
Quleaf 已提交
124 125 126 127 128 129 130 131 132
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "converged SCF energy = -1.11675930739643\n"
     ]
    }
   ],
Q
Quleaf 已提交
133
   "source": [
Q
Quleaf 已提交
134 135 136 137 138 139
    "# `driver` is used to calculate various molecular integrals.\n",
    "driver = qchem.PySCFDriver()\n",
    "\n",
    "# Build a Molecule class based on its properties, note, the length unit is Angstrom.\n",
    "mol = qchem.Molecule(\n",
    "    geometry=[(\"H\", [0.0, 0.0, 0.0]), (\"H\", [0.0, 0.0, 0.74])],\n",
Q
Quleaf 已提交
140
    "    basis=\"sto-3g\",\n",
Q
Quleaf 已提交
141 142
    "    multiplicity=1,   \n",
    "    driver=driver\n",
Q
Quleaf 已提交
143
    ")\n",
Q
Quleaf 已提交
144
    "\n",
Q
Quleaf 已提交
145
    "# Recall Hamiltonian\n",
Q
Quleaf 已提交
146 147
    "molecular_hamiltonian = mol.get_molecular_hamiltonian()\n",
    "\n",
Q
Quleaf 已提交
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
    "# n is the number of qubits\n",
    "n = molecular_hamiltonian.n_qubits"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then we define the loss function, which is simply the expectation value of the Hamiltonian."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define the loss function\n",
Q
Quleaf 已提交
166 167 168 169
    "expec_val = ExpecVal(molecular_hamiltonian)\n",
    "\n",
    "def loss_func(cir: Circuit) -> paddle.Tensor:\n",
    "    return expec_val(cir())"
Q
Quleaf 已提交
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, we also need to set some training hyper-parameters before training."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "EPSI = 0.001 # set the epsilon\n",
    "IR = 1 # set the insertion rate\n",
    "ITERI = 120 # set the number of iterations used for VQE\n",
    "ITERO = 5 # set the number of iterations used for structure optimization\n",
    "LR = 0.1 # set the learning rate\n",
    "T = 0.01 # set the threshold\n",
    "A = 100 # set the accept wall\n",
    "IS0 = True # if the initial state is |0>, set to true\n",
    "\n",
    "paddle_quantum.set_backend('state_vector') # set the backend to state vector"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# initialize the framework\n",
Q
Quleaf 已提交
204
    "vans = VAns(n, loss_func,\n",
Q
Quleaf 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
    "           epsilon=EPSI,\n",
    "           insert_rate=IR,\n",
    "           iter=ITERI,\n",
    "           iter_out=ITERO,\n",
    "           LR=LR,\n",
    "           threshold=T,\n",
    "           accept_wall=A,\n",
    "           zero_init_state=IS0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Initial Circuit"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We give a default initial circuit with uniformly sampled parameters. Then run the optimization process to get the optimal parameters in this initial circuit. The optimization process is the same as in the original VQE. Hyperparameters **iter** and **LR** are used in this process.The obtained loss function and the circuit with optimized parameters will be the initial point for the architecture optimization process. Note that the circuit is simplified when we decided to use this optimized circuit as the current starting point. Details of simplification can be found later."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
Q
Quleaf 已提交
234 235 236 237
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
Q
Quleaf 已提交
238
      "/Users/v_zhanglei48/opt/anaconda3/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",
Q
Quleaf 已提交
239
      "Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\n",
Q
Quleaf 已提交
240
      "  elif dtype == np.bool:\n"
Q
Quleaf 已提交
241 242
     ]
    },
Q
Quleaf 已提交
243 244 245 246
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
Q
Quleaf 已提交
247 248 249 250 251 252
      "iter: 20 loss: [-0.99608564]\n",
      "iter: 40 loss: [-1.0926807]\n",
      "iter: 60 loss: [-1.1136395]\n",
      "iter: 80 loss: [-1.116332]\n",
      "iter: 100 loss: [-1.1167176]\n",
      "iter: 120 loss: [-1.1167545]\n",
Q
Quleaf 已提交
253
      "Current circuit is:\n",
Q
Quleaf 已提交
254
      "--Rx(3.144)----Rz(3.512)----*----Rx(6.286)----Rz(1.375)-------------------------------------------------------------x--\n",
Q
Quleaf 已提交
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
      "                            |                                                                                       |  \n",
      "----------------------------x----Rx(4.249)----Rz(3.141)----Rx(4.246)----Rz(5.477)----*------------------------------|--\n",
      "                                                                                     |                              |  \n",
      "--Rx(0.001)----Rz(5.499)----*--------------------------------------------------------x----Rx(3.141)----Rz(2.688)----|--\n",
      "                            |                                                                                       |  \n",
      "----------------------------x----Rx(0.003)----Rz(2.362)----Rx(0.003)----Rz(1.500)-----------------------------------*--\n",
      "                                                                                                                       \n"
     ]
    }
   ],
   "source": [
    "# Optimize the initial circuit\n",
    "itr_loss = vans.optimization(vans.cir) \n",
    "\n",
    "# Update the loss\n",
    "vans.loss = itr_loss\n",
    "\n",
    "# Print out the current circuit\n",
    "print(\"Current circuit is:\\n\" + str(vans.cir))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Insertion"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Q
Quleaf 已提交
287
    "Now, we randomly choose a block from the 'pool', and insert the block within the circuit. Qubits that the block is applied on are also uniformly sampled. The parameters of the inserted set of gates are initialized to $0$ so that the new circuit can take the advantage of the previously optimized circuit since they act as identity. The code below inserts sets of gates into the circuit. The number of sets of gates depends on the hyperparameter **insert_rate**. Another hyperparameter **epsilon** is used to determine the variance from $0$ of initial parameters."
Q
Quleaf 已提交
288 289 290 291 292 293 294 295 296 297 298 299
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Circuit after insertion:\n",
Q
Quleaf 已提交
300
      "--Rx(3.144)----Rz(3.512)----*----Rx(6.286)----Rz(1.375)----------------------------------------------------------------------------------------------------x--\n",
Q
Quleaf 已提交
301
      "                            |                                                                                                                              |  \n",
Q
Quleaf 已提交
302
      "----------------------------x----Rz(0.000)----Rx(0.000)----Rz(-0.00)----Rx(4.249)----Rz(3.141)----Rx(4.246)----Rz(5.477)----*------------------------------|--\n",
Q
Quleaf 已提交
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
      "                                                                                                                            |                              |  \n",
      "--Rx(0.001)----Rz(5.499)----*-----------------------------------------------------------------------------------------------x----Rx(3.141)----Rz(2.688)----|--\n",
      "                            |                                                                                                                              |  \n",
      "----------------------------x----Rx(0.003)----Rz(2.362)----Rx(0.003)----Rz(1.500)--------------------------------------------------------------------------*--\n",
      "                                                                                                                                                              \n"
     ]
    }
   ],
   "source": [
    "# Insert indentity blocks into the current circuit, before doing so, need to\n",
    "# decompose the circuit from layers to gates\n",
    "new_cir = cir_decompose(vans.cir)\n",
    "new_cir = Inserter.insert_identities(new_cir, vans.insert_rate, vans.epsilon)\n",
    "\n",
    "# Print the updated circuit\n",
    "print(\"Circuit after insertion:\\n\" + str(new_cir))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Simplification"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then we will simplify the new circuit. Rules are pretty simple:\n",
    "1. Combine consecutive $CNOT$ gates.\n",
    "2. Combine rotations gates.\n",
    "3. Remove $CNOT$ gates and $Rz$ gates in the front of the circuit if the initial state is $|0\\rangle$.\n",
    "4. Commute rotation gates and $CNOT$ gates if the circuit can be further simplified in doing so.\n",
    "\n",
    "Then we run the parameter optimization process again and get the new minimized value for the loss function. If the new value is smaller than the previous value or the difference between them is smaller than a value that depends on the hyperparameter **accept_wall**, we accpet the new circuit as the current circuit. After accepting the new circuit, we will remove gates that do not lower the loss or lower the loss within a **threshold**."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
Q
Quleaf 已提交
346 347 348 349
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
Q
Quleaf 已提交
350
      "/Users/v_zhanglei48/opt/anaconda3/envs/pq/lib/python3.8/site-packages/paddle/fluid/dygraph/math_op_patch.py:276: UserWarning: The dtype of left and right variables are not the same, left dtype is paddle.float64, but right dtype is paddle.float32, the right dtype will convert to paddle.float64\n",
Q
Quleaf 已提交
351 352 353
      "  warnings.warn(\n"
     ]
    },
Q
Quleaf 已提交
354 355 356 357
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
Q
Quleaf 已提交
358
      "--Rx(3.144)----Rz(3.512)----*----Rx(6.286)----Rz(1.375)------------------------------------------------x--\n",
Q
Quleaf 已提交
359
      "                            |                                                                          |  \n",
Q
Quleaf 已提交
360
      "----------------------------x----Rz(5.962)----Rx(5.858)----Rz(9.426)----*------------------------------|--\n",
Q
Quleaf 已提交
361 362 363 364 365
      "                                                                        |                              |  \n",
      "--Rx(0.001)----Rz(5.499)----*-------------------------------------------x----Rx(3.141)----Rz(2.688)----|--\n",
      "                            |                                                                          |  \n",
      "----------------------------x----Rz(3.604)----Rx(5.126)----Rz(4.462)-----------------------------------*--\n",
      "                                                                                                          \n",
Q
Quleaf 已提交
366 367
      "iter: 20 loss: [-1.104097]\n",
      "iter: 40 loss: [-1.1159214]\n",
Q
Quleaf 已提交
368 369 370 371
      "iter: 60 loss: [-1.1165943]\n",
      "iter: 80 loss: [-1.116723]\n",
      "iter: 100 loss: [-1.1167536]\n",
      "iter: 120 loss: [-1.1167593]\n",
Q
Quleaf 已提交
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
      "Accpet the new circuit!\n",
      "     start deleting gates\n",
      "         Deletion: reject deletion\n",
      "         Deletion: accept deletion with acceptable loss\n",
      "         Deletion: accept deletion with acceptable loss\n",
      "         Deletion: accept deletion with acceptable loss\n",
      "         Deletion: accept deletion with acceptable loss\n",
      "         Deletion: accept deletion with acceptable loss\n",
      "         Deletion: accept deletion with acceptable loss\n",
      "         Deletion: accept deletion with acceptable loss\n",
      "         Deletion: accept deletion with acceptable loss\n",
      "         Deletion: accept deletion with acceptable loss\n",
      "         Deletion: accept deletion with acceptable loss\n",
      "         Deletion: reject deletion\n",
      "         Deletion: accept deletion with acceptable loss\n",
      "         Deletion: accept deletion with acceptable loss\n",
      "      12  gates are deleted!\n"
     ]
    }
   ],
   "source": [
    "# Simplify the updated circuit according to the simplification rules\n",
    "new_cir = Simplifier.simplify_circuit(new_cir, vans.zero_init_state)\n",
    "\n",
    "# Print the simplied circuits\n",
    "print(new_cir)\n",
    "\n",
    "# Then optimize the simplified circuits\n",
    "itr_loss = vans.optimization(new_cir)\n",
    "\n",
    "# Calculate the change of loss\n",
    "relative_diff = (itr_loss - vans.loss) / np.abs(itr_loss)\n",
    "\n",
    "# If the loss is decreased or increased within a threshold, accept the new circuit\n",
    "if relative_diff <= 0 or np.random.random() <= np.exp(\n",
    "    -relative_diff * vans.accept_wall\n",
    "):\n",
    "    print(\"Accpet the new circuit!\")\n",
    "\n",
    "    # Remove gates that do not lower the loss\n",
    "    new_cir = vans.delete_gates(new_cir, itr_loss)\n",
    "    new_cir = Simplifier.simplify_circuit(new_cir, vans.zero_init_state)\n",
    "    itr_loss = loss_func(new_cir, *vans.loss_args)\n",
    "    vans.loss = itr_loss\n",
    "else:\n",
    "    print(\"Decline the new circuit!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then we update the current circuit to the new circuit."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The current circuit:\n",
Q
Quleaf 已提交
437
      "--Rx(3.141)----*----------------------x--\n",
Q
Quleaf 已提交
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
      "               |                      |  \n",
      "---------------x----*-----------------|--\n",
      "                    |                 |  \n",
      "--------------------x----Rx(3.142)----|--\n",
      "                                      |  \n",
      "--------------------------------------*--\n",
      "                                         \n"
     ]
    }
   ],
   "source": [
    "# Update the current circuit\n",
    "vans.cir = new_cir\n",
    "\n",
    "print(\"The current circuit:\\n\" + str(vans.cir))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The insertion and simplification together forms one iteration for the architecture optimization process. The number of iterations is determined by the hyperparameter **iter_out**. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Simple version"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "While you can customize your own optimization process by adjusting insertion and simplification processes and implementing the training process, Paddle Quantum provides an elegant version of VAns. You can complete the architecture optimization all at once."
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
478
   "execution_count": 10,
Q
Quleaf 已提交
479 480 481 482 483 484 485
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Out iteration 1 for structure optimization:\n",
Q
Quleaf 已提交
486 487
      "iter: 20 loss: [-1.1167216]\n",
      "iter: 40 loss: [-1.1166946]\n",
Q
Quleaf 已提交
488
      "iter: 60 loss: [-1.1167494]\n",
Q
Quleaf 已提交
489
      "iter: 80 loss: [-1.1167588]\n",
Q
Quleaf 已提交
490
      "iter: 100 loss: [-1.1167591]\n",
Q
Quleaf 已提交
491 492
      "iter: 120 loss: [-1.1167594]\n",
      " Current loss: [-1.1167594]\n",
Q
Quleaf 已提交
493
      " Current cir:\n",
Q
Quleaf 已提交
494
      "--Rx(3.141)----*----------------------x--\n",
Q
Quleaf 已提交
495 496 497
      "               |                      |  \n",
      "---------------x----*-----------------|--\n",
      "                    |                 |  \n",
Q
Quleaf 已提交
498
      "--------------------x----Rx(3.141)----|--\n",
Q
Quleaf 已提交
499 500 501 502 503
      "                                      |  \n",
      "--------------------------------------*--\n",
      "                                          \n",
      "\n",
      "Out iteration 2 for structure optimization:\n",
Q
Quleaf 已提交
504 505 506 507 508 509
      "iter: 20 loss: [-1.1363345]\n",
      "iter: 40 loss: [-1.1367742]\n",
      "iter: 60 loss: [-1.137219]\n",
      "iter: 80 loss: [-1.1372814]\n",
      "iter: 100 loss: [-1.1372831]\n",
      "iter: 120 loss: [-1.1372838]\n",
Q
Quleaf 已提交
510 511 512 513 514
      "     accpet the new circuit!\n",
      "     start deleting gates\n",
      "         Deletion: reject deletion\n",
      "         Deletion: accept deletion with acceptable loss\n",
      "         Deletion: reject deletion\n",
Q
Quleaf 已提交
515 516 517 518
      "         Deletion: accept deletion with acceptable loss\n",
      "         Deletion: accept deletion with acceptable loss\n",
      "         Deletion: accept deletion with acceptable loss\n",
      "         Deletion: accept deletion with acceptable loss\n",
Q
Quleaf 已提交
519 520
      "         Deletion: reject deletion\n",
      "         Deletion: accept deletion with acceptable loss\n",
Q
Quleaf 已提交
521
      "         Deletion: accept deletion with acceptable loss\n",
Q
Quleaf 已提交
522 523
      "         Deletion: accept deletion with acceptable loss\n",
      "         Deletion: accept deletion with acceptable loss\n",
Q
Quleaf 已提交
524
      "         Deletion: reject deletion\n",
Q
Quleaf 已提交
525 526 527
      "         Deletion: accept deletion with acceptable loss\n",
      "      10  gates are deleted!\n",
      " Current loss: -1.126142144203186\n",
Q
Quleaf 已提交
528
      " Current cir:\n",
Q
Quleaf 已提交
529 530 531 532 533 534 535 536
      "--Rx(3.141)----*------------------------------------*---------------------*----x--\n",
      "               |                                    |                     |    |  \n",
      "---------------x----*----Rx(0.226)----*----*--------x--------Rz(-0.81)----x----|--\n",
      "                    |                 |    |                                   |  \n",
      "--------------------|-----------------|----x----Rx(3.141)----------------------|--\n",
      "                    |                 |                                        |  \n",
      "--------------------x-----------------x----------------------------------------*--\n",
      "                                                                                   \n",
Q
Quleaf 已提交
537 538
      "\n",
      "Out iteration 3 for structure optimization:\n",
Q
Quleaf 已提交
539 540 541 542 543 544
      "iter: 20 loss: [-1.1365268]\n",
      "iter: 40 loss: [-1.1370414]\n",
      "iter: 60 loss: [-1.1372557]\n",
      "iter: 80 loss: [-1.1372817]\n",
      "iter: 100 loss: [-1.1372832]\n",
      "iter: 120 loss: [-1.1372838]\n",
Q
Quleaf 已提交
545 546 547 548 549 550 551
      "     accpet the new circuit!\n",
      "     start deleting gates\n",
      "         Deletion: reject deletion\n",
      "         Deletion: reject deletion\n",
      "         Deletion: accept deletion with acceptable loss\n",
      "         Deletion: accept deletion with acceptable loss\n",
      "         Deletion: accept deletion with acceptable loss\n",
Q
Quleaf 已提交
552
      "         Deletion: accept deletion with acceptable loss\n",
Q
Quleaf 已提交
553 554 555 556 557 558
      "         Deletion: accept deletion with acceptable loss\n",
      "         Deletion: accept deletion with acceptable loss\n",
      "         Deletion: reject deletion\n",
      "         Deletion: reject deletion\n",
      "      6  gates are deleted!\n",
      " Current loss: -1.1340010166168213\n",
Q
Quleaf 已提交
559
      " Current cir:\n",
Q
Quleaf 已提交
560 561 562 563 564 565 566 567
      "--Rx(3.141)----*------------------------------------*---------------------*----x--\n",
      "               |                                    |                     |    |  \n",
      "---------------x----*----Rx(0.225)----*----*--------x--------Rz(-1.16)----x----|--\n",
      "                    |                 |    |                                   |  \n",
      "--------------------|-----------------|----x----Rx(3.141)----------------------|--\n",
      "                    |                 |                                        |  \n",
      "--------------------x-----------------x----------------------------------------*--\n",
      "                                                                                   \n",
Q
Quleaf 已提交
568 569
      "\n",
      "Out iteration 4 for structure optimization:\n",
Q
Quleaf 已提交
570 571 572 573 574 575
      "iter: 20 loss: [-1.1371578]\n",
      "iter: 40 loss: [-1.1371865]\n",
      "iter: 60 loss: [-1.1372653]\n",
      "iter: 80 loss: [-1.1372821]\n",
      "iter: 100 loss: [-1.1372833]\n",
      "iter: 120 loss: [-1.137284]\n",
Q
Quleaf 已提交
576 577 578 579 580 581
      "     accpet the new circuit!\n",
      "     start deleting gates\n",
      "         Deletion: reject deletion\n",
      "         Deletion: reject deletion\n",
      "         Deletion: reject deletion\n",
      "         Deletion: reject deletion\n",
Q
Quleaf 已提交
582 583 584
      "         Deletion: accept deletion with acceptable loss\n",
      "         Deletion: accept deletion with acceptable loss\n",
      "         Deletion: accept deletion with acceptable loss\n",
Q
Quleaf 已提交
585 586
      "      3  gates are deleted!\n",
      " Current loss: -1.135810136795044\n",
Q
Quleaf 已提交
587
      " Current cir:\n",
Q
Quleaf 已提交
588 589 590 591 592 593 594 595
      "--Rx(3.141)----*------------------------------------*---------------------*----x--\n",
      "               |                                    |                     |    |  \n",
      "---------------x----*----Rx(0.225)----*----*--------x--------Rz(-1.30)----x----|--\n",
      "                    |                 |    |                                   |  \n",
      "--------------------|-----------------|----x----Rx(3.141)----------------------|--\n",
      "                    |                 |                                        |  \n",
      "--------------------x-----------------x----------------------------------------*--\n",
      "                                                                                   \n",
Q
Quleaf 已提交
596 597
      "\n",
      "Out iteration 5 for structure optimization:\n",
Q
Quleaf 已提交
598 599 600 601 602 603
      "iter: 20 loss: [-1.1363769]\n",
      "iter: 40 loss: [-1.1369352]\n",
      "iter: 60 loss: [-1.1372398]\n",
      "iter: 80 loss: [-1.137279]\n",
      "iter: 100 loss: [-1.1372832]\n",
      "iter: 120 loss: [-1.1372834]\n",
Q
Quleaf 已提交
604 605 606
      "     accpet the new circuit!\n",
      "     start deleting gates\n",
      "         Deletion: reject deletion\n",
Q
Quleaf 已提交
607 608 609 610 611 612
      "         Deletion: accept deletion with acceptable loss\n",
      "         Deletion: accept deletion with acceptable loss\n",
      "         Deletion: accept deletion with acceptable loss\n",
      "         Deletion: accept deletion with acceptable loss\n",
      "         Deletion: accept deletion with acceptable loss\n",
      "         Deletion: reject deletion\n",
Q
Quleaf 已提交
613 614 615 616
      "         Deletion: reject deletion\n",
      "         Deletion: reject deletion\n",
      "         Deletion: accept deletion with acceptable loss\n",
      "         Deletion: accept deletion with acceptable loss\n",
Q
Quleaf 已提交
617 618 619
      "         Deletion: accept deletion with acceptable loss\n",
      "      8  gates are deleted!\n",
      " Current loss: -1.135881781578064\n",
Q
Quleaf 已提交
620
      " Current cir:\n",
Q
Quleaf 已提交
621 622 623 624 625 626 627 628
      "--Rx(3.141)----*------------------------------------*---------------------*----x--\n",
      "               |                                    |                     |    |  \n",
      "---------------x----*----Rx(0.226)----*----*--------x--------Rz(-1.30)----x----|--\n",
      "                    |                 |    |                                   |  \n",
      "--------------------|-----------------|----x----Rx(3.141)----------------------|--\n",
      "                    |                 |                                        |  \n",
      "--------------------x-----------------x----------------------------------------*--\n",
      "                                                                                   \n",
Q
Quleaf 已提交
629 630 631
      "\n",
      "\n",
      "\n",
Q
Quleaf 已提交
632
      "The final loss: -1.135881781578064\n",
Q
Quleaf 已提交
633
      "The final circuit:\n",
Q
Quleaf 已提交
634 635 636 637 638 639 640 641
      "--Rx(3.141)----*------------------------------------*---------------------*----x--\n",
      "               |                                    |                     |    |  \n",
      "---------------x----*----Rx(0.226)----*----*--------x--------Rz(-1.30)----x----|--\n",
      "                    |                 |    |                                   |  \n",
      "--------------------|-----------------|----x----Rx(3.141)----------------------|--\n",
      "                    |                 |                                        |  \n",
      "--------------------x-----------------x----------------------------------------*--\n",
      "                                                                                  \n"
Q
Quleaf 已提交
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
     ]
    }
   ],
   "source": [
    "# optimization process all at once\n",
    "vans.train()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The final circuit we got from VAns is"
   ]
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
659
   "execution_count": 11,
Q
Quleaf 已提交
660 661 662 663 664 665 666
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Final circuit:\n",
Q
Quleaf 已提交
667 668 669 670 671 672 673 674
      "--Rx(3.141)----*------------------------------------*---------------------*----x--\n",
      "               |                                    |                     |    |  \n",
      "---------------x----*----Rx(0.226)----*----*--------x--------Rz(-1.30)----x----|--\n",
      "                    |                 |    |                                   |  \n",
      "--------------------|-----------------|----x----Rx(3.141)----------------------|--\n",
      "                    |                 |                                        |  \n",
      "--------------------x-----------------x----------------------------------------*--\n",
      "                                                                                  \n",
Q
Quleaf 已提交
675
      "Final loss:\n",
Q
Quleaf 已提交
676
      "-1.135881781578064\n"
Q
Quleaf 已提交
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 705 706 707 708 709 710 711 712
     ]
    }
   ],
   "source": [
    "print(\"Final circuit:\\n\" + str(vans.cir))\n",
    "print(\"Final loss:\\n\" + str(vans.loss))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with original VQE"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The circuit we got using VAns consists of only 5 parameters and the depth of the circuit is 9. The minimized loss value is $-1.13728392$ Ha. Comparing to the fixed ansatz used in the original VQE tutorial, where the circuit consists of 12 parameters and with depth 11, VAns reduces the number of parameters needed while keeps the circuit shallower. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "_______\n",
    "\n",
    "## References\n",
    "\n",
    "[1] Bilkis, M., et al. \"A semi-agnostic ansatz with variable structure for quantum machine learning.\" [arXiv preprint arXiv:2103.06712 (2021).](https://arxiv.org/abs/2103.06712)"
   ]
  }
 ],
 "metadata": {
  "interpreter": {
Q
Quleaf 已提交
713
   "hash": "2ab84abaf8d5bbc8765aba8eb82d11e7069f2ff20e8f79b8a9cdeccefd2ac4da"
Q
Quleaf 已提交
714 715
  },
  "kernelspec": {
Q
Quleaf 已提交
716
   "display_name": "Python 3.8.13 ('pq_new')",
Q
Quleaf 已提交
717 718 719 720 721 722 723 724 725 726 727 728 729
   "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 已提交
730
   "version": "3.8.13"
Q
Quleaf 已提交
731 732 733 734 735
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}