{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Introduction to Object-Oriented Programming"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Prerequisites"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* Collections\n",
    "* `numpy` arrays\n",
    "* Functions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Object-Oriented Programming"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now that we are comfortable with basic types, collections, `numpy` arrays, and functions it is time to have a look at object-oriented programming. In programming jargon, an _object_ is an ensemble of data and functionality that make sense together."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In Python, _everything_ is an object and therefore the concepts of object-oriented programming are in extensive use in every Python code. So, why are objects so widespread? Because they are very useful to write re-usable code and hide away a lot of complexity."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Molecule"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's suppose, for example, that we want to represent a molecule in a Python program. At the very least, we will need to store some data representing the molecule. In order to represent a particular configuration of acetylene, we could store the element number and the atomic coordinates of the atoms in the molecule:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "elements = np.array([1, 6, 6, 1])\n",
    "coordinates = np.array([\n",
    "    [-1.06, 0.00, 0.00], # H1\n",
    "    [ 0.00, 0.00, 0.00], # C1\n",
    "    [ 1.20, 0.00, 0.00], # C2\n",
    "    [ 2.26, 0.00, 0.00], # H2\n",
    "])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Coordinates are stored in a $3 \\times N$ array ($N$ being the number of atoms) and each row is assumed to be ordered in the same way as elements are."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<center>\n",
    "<img src=\"../images/acetylene.png\" alt=\"acetylene\" width=\"50%\"/>\n",
    "</center>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is all good, but we'll need to keep track of the fact that the `elements` and `coordinates` vectors represent the same molecule and therefore should be, in most cases, processed together. And what if we want to represent another molecule? To represent a dihydrogen molecule in the same program we will need to do something like the following:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "elements_H2 = np.array([1, 1])\n",
    "coordinates_H2 = np.array([\n",
    "    [0.00, 0.00, 0.00], # H1\n",
    "    [1.00, 0.00, 0.00], # H1\n",
    "])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This works, but it's ugly. It is also error-prone and probably will not scale well to many molecules."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> Can you think of a way of tying together `elements` and `coordinates` within a single variable with what you learned already?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Using a dictionary to represent acetylene could be a good solution:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "acetylene = {\n",
    "    \"elements\": np.array([1, 6, 6, 1]),\n",
    "    \"coordinates\": np.array([\n",
    "        [-1.06, 0.00, 0.00], # H1\n",
    "        [ 0.00, 0.00, 0.00], # C1\n",
    "        [ 1.20, 0.00, 0.00], # C2\n",
    "        [ 2.26, 0.00, 0.00], # H2\n",
    "    ])\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We now have a single variable representing the acetylene molecule. All the information is stored within that variable and it can be easily and unequivocally accessed. If we want to see the elements (atomic numbers) of the  atoms in acetylene, we can simply print them out:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 6 6 1]\n"
     ]
    }
   ],
   "source": [
    "print(acetylene[\"elements\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Do you see where we are heading? Objects allow us to tie together data (as we just did with a dictionary) and functionality together. By defining and using objects we can create a super slick representation of a molecule, with all the data and all the functionality we need."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the following sections we will have a first look at the simple concepts of object-oriented programming (OOP) to get an idea of this powerful paradigm. We'll learn a lot more about OOP in the advanced sections."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Molecule Class"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A _class_ is the definition of an object. We can think of a class as an architectural plan and an object (usually called an _instance_ of the class in this context) as an house built following said plan. With the same plan, you can build multiple houses (create multiple instances), each housing different people (different data). For our example above, a yet to be defined `Molecule` class would represent a generic molecule (by defining the data and the functionality associated to a molecule) while `acetylene` would be an object (instance) of said class, containing the actual data defining `acetylene`. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Creating a new class in Python has a similar syntax to a function definition, with the `class` keyword instead of `def` and without `()` (`()` is optional for a class definition):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "class EmptyClass:\n",
    "    \"\"\"\n",
    "    Empty class that does nothing.\n",
    "\n",
    "    Note:\n",
    "        The `pass` statement in Python does nothing.\n",
    "    \"\"\"\n",
    "    pass"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "_Note #1_: the `pass` statement in Python does nothing and it is therefore useful when a statement is required but no code needs to be written."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "_Note #2_: docstrings are used to document classes as well."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Once our class is defined, we can create (_instantiate_) an object of said class:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "ec = EmptyClass()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can check that the content of the variable `ec` is indeed an instance of  the class `EmptyClass` using the `isinstance` function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "isinstance(ec, EmptyClass)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When we create an object from a class definition, we usually need to initialise some data. Let's now see how to do it."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Class Methods and Attributes"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A _method_ is a function associated to a class. Methods are defined in the same way one would define a standard Python function and follow the same rules. However, there are a few names for methods that have special meaning. One of such methods is the `__init__` function, which is called to create a new object from a class."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "class SimpleMolecule:\n",
    "    \"\"\"\n",
    "    Rempresentation of a simple molecular conformation.\n",
    "\n",
    "    Args:\n",
    "        els (numpy.ndarray): array of elements\n",
    "        coords (numpy.dnarray): array of coordinates\n",
    "\n",
    "    Attributes:\n",
    "        elements (numpy.ndarray): array of elements\n",
    "        coordinates (numpy.dnarray): array of coordinates\n",
    "\n",
    "    Note:\n",
    "        The `self` argument is omitted from the documentation.\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(self, els, coords):\n",
    "        self.elements = els\n",
    "        self.coordinates = coords"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "_Note #3_: The `__init__` method can be documented either at the class level or the `__init__` function level. Either form is acceptable, but one needs to be consistent across the code."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here is a schematic representation of the class `SimpleMolecule`:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<center>\n",
    "<img src=\"../images/SimpleMolecule.png\" alt=\"SimpleMolecule\" width=\"50%\"/>\n",
    "</center>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`SimpleMolecule` is now a class representing a molecule which can be initialised with elements and coordinates. In order to create an `acetylene` instance of the `SimpleMolecule` class we can do the following:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "acetylene = SimpleMolecule(\n",
    "    els=np.array([1, 6, 6, 1]),\n",
    "    coords=np.array([\n",
    "        [-1.06, 0.00, 0.00], # H1\n",
    "        [ 0.00, 0.00, 0.00], # C1\n",
    "        [ 1.20, 0.00, 0.00], # C2\n",
    "        [ 2.26, 0.00, 0.00], # H2\n",
    "    ])\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There are three important things to notice here. First, the `__init__` method takes `self` as the first of its three arguments. Second, the `__init__` function is not called explicitly but it's called implicitly as `SimpleMolecule(els, coords)`; this is why this method is \"special\" (some Pythonistas would call it _magic_!). Third, a `SimpleMolecule` object is created by passing two arguments and not three. The reason behind the latter behavior is that Python always passes, automatically, the object itself (which is an instance of the class `SimpleMolecule`) as first argument of a method. Therefore, when we initialise `SimpleMolecule` we only need to define the `els` and `coords` arguments, while the `self` argument is taken care of automatically by Python."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `self` argument, which represents the particular instance of the class we are working with, can be used to store data related to that particular instance. The variables stored within a class are called _attributes_. In the case of `SimpleMolecule` the attributes are `self.elements` and `self.coordinates`. They can be easily accessed with the `.` operator:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 6 6 1]\n"
     ]
    }
   ],
   "source": [
    "print(acetylene.elements)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "_Note #4_: The `acetylene` instance of the `SimpleMolecule` class is very similar to the dictionary we used before. With the dictionary we used `print(acetylene[\"elements\"])`, while now we use `print(acetylene.elements)`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Recapitulation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In just a few paragraphs we have been through a lot of new and complicated concepts, so let's try to recapitulate the example above. `SimpleMolecule` is a _class_ which defines how a simple molecule is represented in our Python program. The object `acetylene` is a particular _instance_ of the `SimpleMolecule` class, intialised using the `__init__` _method_. `acetylene` stores the atomic numbers and atomic coordinates in the _attributes_ `self.elements` and `self.coordinates`; the values of the attributes are specific to the `acetylene` instance and they will have different values for different instances. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To verify the latter statement we can create another instance of `SimpleMolecule`, this time representing dihydrogen:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "H2 = SimpleMolecule(\n",
    "    np.array([1, 1]),\n",
    "    np.array([[0.00, 0.00, 0.00], [1.00, 0.00, 0.00]])\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If we print out the elements and coordinates associated to `H2` we see that they are different from the ones associated to `acetylene`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 1]\n"
     ]
    }
   ],
   "source": [
    "print(H2.elements)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 6 6 1]\n"
     ]
    }
   ],
   "source": [
    "print(acetylene.elements)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `SimpleMolecule` class specifies the general structure of a simple molecule (as represented in our program), while its instances `H2` and `acetylene` represent actual molecules with the associated data. This example helps clarify the meaning of `self`: for `H2` the attribute `self.elements` actually means `H2.elements` while for `acetylene` the attribute `self.elements` actually means `acetylene.elements`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Adding Functionality to the Molecule Class"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As outlined in _Note #4_, the `SimpleMolecule` class does not differ a lot from the original `acetylene` dictionary we defined above: it contains the same data which are accessed using `acetylene.elements` (class) instead of `acetylene[\"elements\"]` (dictionary). Why we introduced a lot of complicated concepts to accomplish something we can achieve simply with a dictionary? The reason is that with classes we can do much more!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A simple extension of the `SimpleMolecule` class is to add some functionality. For example, we might want to be able to remove hydrogen atoms. We can add functionality to do that, by defining a method for that purpose:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Molecule:\n",
    "    \"\"\"\n",
    "    Rempresentation of a simple molecular conformation.\n",
    "\n",
    "    Args:\n",
    "        els (numpy.ndarray): array of elements\n",
    "        coords (numpy.dnarray): array of coordinates\n",
    "\n",
    "    Attributes:\n",
    "        elements (numpy.ndarray): array of elements\n",
    "        coordinates (numpy.dnarray): array of coordinates\n",
    "\n",
    "    Note:\n",
    "        The `self` argument is omitted from the documentation.\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(self, els, coords):\n",
    "        self.elements = els\n",
    "        self.coordinates = coords\n",
    "\n",
    "    def removeHs(self):\n",
    "        \"\"\"\n",
    "        Remove hydrogen atoms from the molecule.\n",
    "\n",
    "        Note:\n",
    "            Information about hydrogen atoms is lots forever when\n",
    "            this function is called: attributes `elements` and \n",
    "            `coordinates` are modified in-place.\n",
    "        \"\"\"\n",
    "        # Mask for hydrogen atoms\n",
    "        # The mask array is True where there are no hydrogen atoms\n",
    "        # The mask array is False where there are hydrogen atoms\n",
    "        mask = self.elements != 1\n",
    "\n",
    "        # Select only elements where the mask is True\n",
    "        self.elements = self.elements[mask]\n",
    "\n",
    "        # Select only coordinates where the mask is True\n",
    "        self.coordinates = self.coordinates[mask, :]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here is a schematic representation of the class `Molecule`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<center>\n",
    "<img src=\"../images/Molecule.png\" alt=\"Molecule\" width=\"50%\"/>\n",
    "</center>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `Molecule` class is now more complex and can't be reproduced simply or cleanly with a dictionary. In addition to the `self.elements` and `self.coordinates` attributes we now have some functionality (the `removeHs` method) associated to the `Molecule` class that allows us to strip all the hydrogens from any molecule with a simple function call. It is important to notice that the method `removeHs` only takes `self` as argument since `self.elements` and `self.coordinates`, which are attributes, are always available within the class. We can define again an `acetylene` molecule, but this time as an instance of the `Molecule` class (and not the `SimpleMolecule` class we used before):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "acetylene = Molecule(\n",
    "    els=np.array([1, 6, 6, 1]),\n",
    "    coords=np.array([\n",
    "        [-1.06, 0.00, 0.00], # H1\n",
    "        [ 0.00, 0.00, 0.00], # C1\n",
    "        [ 1.20, 0.00, 0.00], # C2\n",
    "        [ 2.26, 0.00, 0.00], # H2\n",
    "    ])\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 6 6 1]\n"
     ]
    }
   ],
   "source": [
    "print(acetylene.elements)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The definition of `acetylene` is the same as before (since the `__init__` method did not change), but being an instance of the `Molecule` class, there is now an associated `removeHs` method. The method can be called using the `.` operator and since the `self` argument of `removeH` is passed automatically there is no other argument that needs to be specified:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "acetylene.removeHs()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If we now print the `self.elements` and `self.coordinates` attributes, we can confirm that hydrogen atoms have been removed:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[6 6]\n"
     ]
    }
   ],
   "source": [
    "print(acetylene.elements)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0.  0.  0. ]\n",
      " [1.2 0.  0. ]]\n"
     ]
    }
   ],
   "source": [
    "print(acetylene.coordinates)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As we can see, after calling `removeHs` from the `acetylene` instance of `Molecule` (using the `.` operator), the information about hydrogen atoms has been removed from both the `self.element` and `self.coordinates` attributes, with a simple function call. Achieving this functionality with the simple dictionary defined above would have been more complicated and error prone."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Conclusion"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this section we have introduced a lot \"basic\" principles and definitions of object oriented programming and hopefully you are now convinced of how powerful and clean this programming paradigm is. We made extensive use of the `.` operators, which indicates you are using an object and accessing its data (attributes) or associated functionality (methods). The key points to take away from this lesson are the following:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* In Python, everything is an _object_\n",
    "* Objects tie together related data and functionality\n",
    "* A _class_ is the definition of an object\n",
    "* The `class` keyword allows us to define a class in Python\n",
    "* An _instance_ of a class is an object of said class which exists in your program as a variable \n",
    "* The variables associated to an object are called _attributes_\n",
    "  * We define an attribute by defining a `self.attribute_name` variable within the class\n",
    "* The functions associated to an object are called _methods_\n",
    "  * We define a method as a standard Python function, with `self` as first argument\n",
    "* The `__init__` method of a class defines how an instance is initialised"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Acknowledgments"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The idea of a molecule API is loosely inspired by [Depth-First: A Minimal Molecule API](https://depth-first.com/articles/2020/04/06/a-minimal-molecule-api/) by Richard L. Apodaca"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.7.6 64-bit ('nbnotes': conda)",
   "language": "python",
   "name": "python37664bitnbnotesconda050afe1249694e59be6572ddc57d11a1"
  },
  "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.7.6-final"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
