BuildingMolecule_EN.ipynb 12.2 KB
Newer Older
Q
Quleaf 已提交
1 2 3 4
{
 "cells": [
  {
   "cell_type": "markdown",
Q
Quleaf 已提交
5
   "metadata": {},
Q
Quleaf 已提交
6 7 8
   "source": [
    "# Building Molecular Hamiltonian\n",
    "*Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved.*"
Q
Quleaf 已提交
9
   ]
Q
Quleaf 已提交
10 11
  },
  {
Q
Quleaf 已提交
12
   "attachments": {},
Q
Quleaf 已提交
13
   "cell_type": "markdown",
Q
Quleaf 已提交
14
   "metadata": {},
Q
Quleaf 已提交
15 16 17
   "source": [
    "## Overview\n",
    "\n",
Q
Quleaf 已提交
18
    "In this tutorial, we will demonstrate how to use Paddle Quantum's *qchem* module to build valid Hamiltonian for simulating chemical molecules on a quantum computer. We will go step by step how to build the second quantized Hamiltonian from a molecular structure and how to transform it to a set of Pauli matrices. \n",
Q
Quleaf 已提交
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
    "\n",
    "Hamiltonian is a physical quantity related to the total energy of a physical system. In general, it can be represented as \n",
    "\n",
    "$$\n",
    "\\hat{H}=\\hat{T}+\\hat{V},\\tag{1}\n",
    "$$\n",
    "\n",
    "where $\\hat{T}$ is the kinetic energy and $\\hat{V}$ is the potential energy. Hamiltonian is useful for various quantum algorithms, such as [variational quantum eigensolver](./VQE_EN.ipynb) and [Hamiltonian Simulation with Product Formula](./HamiltonianSimulation_EN.ipynb).\n",
    "\n",
    "When trying to solve a chemistry problem with quantum mechanics, we also need to write down a Hamiltonian that describes the chemical system involved in the problem. Starting from this Hamiltonian, we can, in principle, calculate the ground state and excited states, and use the information to further explore all the physical properties of the quantum system. The dominant Hamiltonian of electronic problems has the form\n",
    "\n",
    "$$\n",
    "\\hat{H}=\\sum_{i=1}^N\\left(-\\frac{1}{2}\\nabla_{x_i}^2\\right)+\\sum_{i=1}^N\\sum_{j< i}\\frac{1}{|x_i-x_j|}-\\sum_{i=1}^N\\sum_{I=1}^M\\frac{Z_I}{|x_i-R_I|},\\tag{2}\n",
    "$$\n",
    "\n",
    "when we use [atomic units](https://en.wikipedia.org/wiki/Hartree_atomic_units). Our electronic problem contains $N$ electrons and $M$ nucleus. We use $x_i$ to denote position of the $i$-th electron, and use $R_I$ to denote position of the $I$-th nuclei. \n",
    "\n",
Q
Quleaf 已提交
36
    "This tutorial will have the following parts. Let's first talk about how to construct a molecule in *qchem*. After that, we will briefly describe how to calculate [Hartree Fock](https://en.wikipedia.org/wiki/Hartree%E2%80%93Fock_method) single particle orbitals by calling external quantum chemistry within Paddle Quantum. Next, we show how we can obtain molecular Hamiltonian using *qchem*'s `Molecule` class."
Q
Quleaf 已提交
37
   ]
Q
Quleaf 已提交
38 39 40
  },
  {
   "cell_type": "markdown",
Q
Quleaf 已提交
41
   "metadata": {},
Q
Quleaf 已提交
42 43 44 45 46 47 48 49 50
   "source": [
    "## Defining the molecular structure\n",
    "In this example, we show how to construct water molecule from its chemical formula and coordinates of atoms. \n",
    "\n",
    "![h2o.png](figures/buildingmolecule-fig-h2o.png)\n",
    "\n",
    "Within Paddle Quantum, we specify the atom as a list whose first element is the atomic symbol and the second element is another list that contains its Cartesian coordinate. The molecule is thus a bigger list composed of atoms' list.\n",
    "\n",
    "**Note: As to the environment setting, please refer to [README.md](https://github.com/PaddlePaddle/Quantum/blob/master/README.md).**"
Q
Quleaf 已提交
51
   ]
Q
Quleaf 已提交
52 53 54 55
  },
  {
   "cell_type": "code",
   "execution_count": 1,
Q
Quleaf 已提交
56 57
   "metadata": {},
   "outputs": [],
Q
Quleaf 已提交
58 59 60
   "source": [
    "# Eliminate noisy python warnings\n",
    "import warnings\n",
Q
Quleaf 已提交
61 62 63
    "warnings.filterwarnings(\"ignore\")\n",
    "import logging\n",
    "logging.basicConfig(level=logging.INFO)"
Q
Quleaf 已提交
64
   ]
Q
Quleaf 已提交
65 66 67 68
  },
  {
   "cell_type": "code",
   "execution_count": 2,
Q
Quleaf 已提交
69 70
   "metadata": {},
   "outputs": [],
Q
Quleaf 已提交
71 72
   "source": [
    "# in Angstrom\n",
Q
Quleaf 已提交
73 74 75
    "h2o_coords = [(\"H\", [-0.02111417,0.8350417,1.47688078]),  # H stands for hydrogen element in water\n",
    "                        (\"O\", [0.0, 0.0, 0.0]),                     # O stands for oxygen element in water\n",
    "                        (\"H\", [-0.00201087,0.45191737,-0.27300254])]"
Q
Quleaf 已提交
76
   ]
Q
Quleaf 已提交
77 78
  },
  {
Q
Quleaf 已提交
79
   "attachments": {},
Q
Quleaf 已提交
80
   "cell_type": "markdown",
Q
Quleaf 已提交
81
   "metadata": {},
Q
Quleaf 已提交
82 83 84 85
   "source": [
    "## Calculate Hartree Fock orbitals\n",
    "Hartree Fock method uses the [Slater determinant](https://en.wikipedia.org/wiki/Slater_determinant) to represent the $N$-electron wavefunction. It could provide us with a set of single particle orbitals which are often taken as input to more advanced quantum chemistry methods. \n",
    "\n",
Q
Quleaf 已提交
86
    "Currently, Paddle Quantum uses PySCF [1] as its quantum chemistry engine, we will support more quantum chemistry toolkits, such as psi4, in the future (NOTE: PySCF currently only support Mac and Linux platform). We could use the `PySCFDriver` provided in `qchem` module to manage the quantum chemistry calculation and get the necessary information about the molecule. It takes molecular structure, total molecular charge, and spin multiplicity as its major inputs. We can also control the precision of Hartree Fock calculation by setting different [basis set](https://en.wikipedia.org/wiki/Basis_set_(chemistry)) for `basis` keyword. "
Q
Quleaf 已提交
87
   ]
Q
Quleaf 已提交
88 89 90
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
91
   "execution_count": 4,
Q
Quleaf 已提交
92
   "metadata": {},
Q
Quleaf 已提交
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:root:\n",
      "#######################################\n",
      "SCF Calculation (Classical)\n",
      "#######################################\n",
      "INFO:root:Basis: sto-3g\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "converged SCF energy = -73.9677038774737\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:root:SCF energy: -73.96770.\n"
     ]
    }
   ],
Q
Quleaf 已提交
120
   "source": [
Q
Quleaf 已提交
121 122 123 124 125 126 127 128 129
    "from paddle_quantum.qchem import PySCFDriver\n",
    "\n",
    "driver = PySCFDriver()\n",
    "driver.load_molecule(\n",
    "    atom=h2o_coords,         # Geometry of H2O molecule\n",
    "    basis=\"sto-3g\",          # Basis set for quantum chemistry calculation\n",
    "    multiplicity=1,          # Spin multiplicity for molecule, since the total spin of H2O is S=0,its spin multiplicity is 2S+1=1\n",
    "    charge=0,                 # Total charge of molecule, since H2O is charge neutral, its charge=0\n",
    "    unit=\"Angstrom\"\n",
Q
Quleaf 已提交
130
    ")\n",
Q
Quleaf 已提交
131
    "driver.run_scf()             # Perform Hartree Fock calculation"
Q
Quleaf 已提交
132
   ]
Q
Quleaf 已提交
133 134
  },
  {
Q
Quleaf 已提交
135
   "attachments": {},
Q
Quleaf 已提交
136
   "cell_type": "markdown",
Q
Quleaf 已提交
137
   "metadata": {},
Q
Quleaf 已提交
138 139 140 141 142 143 144
   "source": [
    "## Molecular Hamiltonian in second quantization form\n",
    "When we study many electron quantum systems, it's often convenient to write Hamiltonian at the beginning of this tutorial in [second quantization](https://en.wikipedia.org/wiki/Second_quantization) representation \n",
    "\n",
    "$$\n",
    "\\hat{H}=\\sum_{p,q}h_{pq}\\hat{c}^{\\dagger}_p\\hat{c}_q+\\frac{1}{2}\\sum_{p,q,r,s}v_{pqrs}\\hat{c}^{\\dagger}_p\\hat{c}^{\\dagger}_q\\hat{c}_r\\hat{c}_s,\\tag{3}$$\n",
    "\n",
Q
Quleaf 已提交
145
    "where $p$, $q$, $r$ and $s$ are Hartree Fock orbitals computed in the previous section. $\\hat{c}^{\\dagger}_p$ and $\\hat{c}_q$ are creation and annihilation operations, respectively. The two coefficients $h_{pq}$ and $v_{pqrs}$ are called molecular integrals, and can be obtained from `PySCFDriver` in the following way."
Q
Quleaf 已提交
146
   ]
Q
Quleaf 已提交
147 148 149
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
150
   "execution_count": 5,
Q
Quleaf 已提交
151 152 153 154 155 156
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
Q
Quleaf 已提交
157 158 159 160 161 162 163
      "[[-3.2911e+01  5.5623e-01  2.8755e-01 -5.1653e-15 -7.4568e-02 -9.4552e-02 -2.8670e-01]\n",
      " [ 5.5623e-01 -8.0729e+00 -4.0904e-02  1.5532e-15  1.7890e-01  3.5048e-01  1.3460e+00]\n",
      " [ 2.8755e-01 -4.0904e-02 -7.3355e+00  6.8611e-16  4.1911e-01  5.2109e-01 -7.0928e-01]\n",
      " [-5.1650e-15  1.5617e-15  6.7472e-16 -7.5108e+00  5.4096e-16  1.7947e-15  4.5448e-16]\n",
      " [-7.4568e-02  1.7890e-01  4.1911e-01  5.3561e-16 -5.7849e+00  2.0887e+00 -1.2427e-01]\n",
      " [-9.4552e-02  3.5048e-01  5.2109e-01  1.8235e-15  2.0887e+00 -5.0803e+00 -1.3967e-02]\n",
      " [-2.8670e-01  1.3460e+00 -7.0928e-01  4.8475e-16 -1.2427e-01 -1.3967e-02 -5.0218e+00]]\n"
Q
Quleaf 已提交
164 165 166
     ]
    }
   ],
Q
Quleaf 已提交
167 168 169 170
   "source": [
    "import numpy as np \n",
    "np.set_printoptions(precision=4, linewidth=150)\n",
    "\n",
Q
Quleaf 已提交
171 172 173
    "hpq = driver.get_onebody_tensor(\"int1e_kin\") + driver.get_onebody_tensor(\"int1e_nuc\")\n",
    "vpqrs = driver.get_twobody_tensor()\n",
    "assert np.shape(hpq)==(7, 7)             # H2O has 7 orbitals when using STO-3G basis.\n",
Q
Quleaf 已提交
174 175 176
    "assert np.shape(vpqrs)==(7, 7, 7, 7)\n",
    "\n",
    "print(hpq)\n",
Q
Quleaf 已提交
177
    "# print(vpqrs)  # vpqrs is a large tensor,for brevity, we comment this line by default, interested users can uncomment this line to see it."
Q
Quleaf 已提交
178
   ]
Q
Quleaf 已提交
179 180
  },
  {
Q
Quleaf 已提交
181
   "attachments": {},
Q
Quleaf 已提交
182
   "cell_type": "markdown",
Q
Quleaf 已提交
183
   "metadata": {},
Q
Quleaf 已提交
184
   "source": [
Q
Quleaf 已提交
185
    "Most of the time, we don't need to extract those integrals and assemble the Hamiltonian manually, *qchem* has already ecapsulated this procedure in `Molecule` class, we can get the Hamiltonian of water molecule from it."
Q
Quleaf 已提交
186
   ]
Q
Quleaf 已提交
187 188 189
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
190
   "execution_count": 6,
Q
Quleaf 已提交
191 192
   "metadata": {},
   "outputs": [
Q
Quleaf 已提交
193 194 195 196 197 198 199 200 201 202 203
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:root:\n",
      "#######################################\n",
      "SCF Calculation (Classical)\n",
      "#######################################\n",
      "INFO:root:Basis: sto-3g\n"
     ]
    },
Q
Quleaf 已提交
204 205 206 207
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
Q
Quleaf 已提交
208 209 210 211 212 213 214 215
      "converged SCF energy = -73.9677038774737\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:root:SCF energy: -73.96770.\n"
Q
Quleaf 已提交
216 217 218
     ]
    }
   ],
Q
Quleaf 已提交
219
   "source": [
Q
Quleaf 已提交
220 221
    "# Build `Molecule` for water molecule.\n",
    "from paddle_quantum.qchem import Molecule\n",
Q
Quleaf 已提交
222
    "\n",
Q
Quleaf 已提交
223 224 225 226
    "mol = Molecule(\n",
    "    geometry=h2o_coords,\n",
    "    basis=\"sto-3g\",\n",
    "    driver=PySCFDriver()\n",
Q
Quleaf 已提交
227 228
    ")\n",
    "\n",
Q
Quleaf 已提交
229 230
    "\n",
    "H_of_water = mol.get_molecular_hamiltonian()"
Q
Quleaf 已提交
231
   ]
Q
Quleaf 已提交
232 233
  },
  {
Q
Quleaf 已提交
234
   "attachments": {},
Q
Quleaf 已提交
235
   "cell_type": "markdown",
Q
Quleaf 已提交
236
   "metadata": {},
Q
Quleaf 已提交
237
   "source": [
Q
Quleaf 已提交
238
    "Since quantum computing only allows operation based on Pauli operators $\\hat{\\sigma}_x$, $\\hat{\\sigma}_y$, $\\hat{\\sigma}_z$, we have to transform Hamiltonian in above expression to a form represented by Pauli operators. This can be achieved via [Jordan-Wigner 变换](https://en.wikipedia.org/wiki/Jordan%E2%80%93Wigner_transformation) and we have already integrated it in `get_molecular_hamiltonian` method."
Q
Quleaf 已提交
239
   ]
Q
Quleaf 已提交
240 241 242
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
243
   "execution_count": 7,
Q
Quleaf 已提交
244 245 246 247 248 249
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
Q
Quleaf 已提交
250
      "There are 2110 terms in H2O Hamiltonian in total.\n",
Q
Quleaf 已提交
251
      "The first 10 terms are \n",
Q
Quleaf 已提交
252 253 254 255 256 257 258 259 260 261
      " -44.808115297466266 I\n",
      "12.537584025014317 Z0\n",
      "12.537584025014313 Z1\n",
      "1.8115178684479893 Z2\n",
      "1.8115178684479893 Z3\n",
      "1.4546840922727915 Z4\n",
      "1.4546840922727915 Z5\n",
      "1.4299903414012243 Z6\n",
      "1.429990341401224 Z7\n",
      "1.0849294605602529 Z8\n"
Q
Quleaf 已提交
262 263 264
     ]
    }
   ],
Q
Quleaf 已提交
265
   "source": [
Q
Quleaf 已提交
266 267
    "print('There are', H_of_water.n_terms, 'terms in H2O Hamiltonian in total.')\n",
    "print('The first 10 terms are \\n', H_of_water[:10])"
Q
Quleaf 已提交
268
   ]
Q
Quleaf 已提交
269 270 271
  },
  {
   "cell_type": "markdown",
Q
Quleaf 已提交
272
   "metadata": {},
Q
Quleaf 已提交
273 274
   "source": [
    "Great! Now you know how to build a proper Hamiltonian from a given molecular structure, let's move further and see how to use [variational quantum eigensolver](./VQE_EN.ipynb) (VQE) to determine the ground state of hydrogen molecule.\n"
Q
Quleaf 已提交
275
   ]
Q
Quleaf 已提交
276 277
  },
  {
Q
Quleaf 已提交
278
   "attachments": {},
Q
Quleaf 已提交
279
   "cell_type": "markdown",
Q
Quleaf 已提交
280
   "metadata": {},
Q
Quleaf 已提交
281 282 283 284
   "source": [
    "---\n",
    "## References\n",
    "\n",
Q
Quleaf 已提交
285
    "[1] [PySCF: Python-based Simulations of Chemistry Framework](https://pyscf.org/)"
Q
Quleaf 已提交
286
   ]
Q
Quleaf 已提交
287 288 289 290
  }
 ],
 "metadata": {
  "kernelspec": {
Q
Quleaf 已提交
291
   "display_name": "modellib",
Q
Quleaf 已提交
292 293 294 295 296 297 298 299 300 301 302 303 304
   "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 已提交
305 306 307 308 309 310
   "version": "3.7.15"
  },
  "vscode": {
   "interpreter": {
    "hash": "8f24120f890011f53feb4ed62c47961d8565ec1de8b7cb23548c15bd6da8f2d2"
   }
Q
Quleaf 已提交
311 312 313 314
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
Q
Quleaf 已提交
315
}