{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Molecules as text, patterns and numbers\n",
    "\n",
    "SMILES, InChI, molfiles, conformers, SMARTS, fingerprints and descriptors: what each keeps and loses, and which to store for which job.\n",
    "\n",
    "The lesson's page: https://monstrous.com.ng/learn/data-engineering/series-1/02-text-patterns-and-numbers/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Install what this lesson needs (in Colab, or any fresh environment)\n",
    "%pip install -q rdkit pandas"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[Module 1](../01-graphs-and-matrices/) treated a molecule as a graph. Most chemical data does not\n",
    "arrive as graphs, though. It arrives as text: SMILES strings, InChIs, SDF files. It is searched with\n",
    "patterns, and it is compared and modelled as numbers. Each of these ways of writing a molecule down\n",
    "(we call them **representations**) keeps some things and loses others. Before we choose what to\n",
    "store, we have to know which.\n",
    "\n",
    "By the end of this module you will be able to:\n",
    "\n",
    "- explain why one molecule can be written as many different SMILES strings, and how RDKit picks one\n",
    "  standard string for it (the **canonical** SMILES);\n",
    "- tell what each representation keeps and what it loses, such as stereochemistry (which mirror image\n",
    "  a molecule is), aromaticity and tautomers (forms that differ only in where a hydrogen sits);\n",
    "- use an **InChIKey**, a short code calculated from the structure, as a molecule's identity, and a\n",
    "  **SMARTS** pattern to search for a group such as a carboxylic acid;\n",
    "- turn molecules into **fingerprints** (long strings of 0s and 1s) and **descriptors** (calculated\n",
    "  numbers such as molecular weight), to compare them and to use them in models;\n",
    "- choose which of these to store, for which job.\n",
    "\n",
    "From Module 1 we use RDKit's `Chem.MolFromSmiles`, which reads a SMILES string into a molecule, and\n",
    "the habit of reporting with `log` and showing values with `print`.\n",
    "\n",
    "The lesson uses two Python packages:\n",
    "\n",
    "- **RDKit**, the chemistry toolkit from Module 1. We load five of its parts: `Chem` (reading and\n",
    "  writing molecules), `AllChem` (3D shapes), `rdFingerprintGenerator` (making fingerprints),\n",
    "  `DataStructs` (comparing fingerprints) and `Descriptors` (calculated properties);\n",
    "- **pandas**, for tables with named columns (used at the end to build a small compound table).\n",
    "\n",
    "Everything here runs in a browser notebook or on any laptop.\n",
    "\n",
    "## Setup\n",
    "\n",
    "Run this block first. It loads the packages and sets the lesson's settings, written in CAPITALS, so\n",
    "they can be changed in one place. As in Module 1, `log` reports what a job did and `print` shows you\n",
    "values; [Module 1](../01-graphs-and-matrices/#why-log-and-not-print) explains why."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import logging\n",
    "\n",
    "import pandas as pd\n",
    "from rdkit import Chem, DataStructs\n",
    "from rdkit.Chem import AllChem, Descriptors, rdFingerprintGenerator\n",
    "\n",
    "# log lines: level and message only, so the lesson's outputs are the same on every run\n",
    "# (a real job would add \"%(asctime)s\" to the format)\n",
    "logging.basicConfig(level=logging.INFO, format=\"%(levelname)s %(message)s\", force=True)\n",
    "log = logging.getLogger(__name__)\n",
    "\n",
    "# conformers (section 5): how many to generate, and the random seed that makes them repeatable\n",
    "N_CONFORMERS = 5\n",
    "CONFORMER_SEED = 42\n",
    "# Morgan fingerprints (section 7): radius 2 is ECFP4-like; 2048 bits is a common length\n",
    "MORGAN_RADIUS = 2\n",
    "MORGAN_BITS = 2048"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We start from aspirin again:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "aspirin = Chem.MolFromSmiles(\"CC(=O)Oc1ccccc1C(=O)O\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. SMILES: one molecule, many strings\n",
    "\n",
    "**SMILES** (Simplified Molecular Input Line Entry System) writes the graph of Module 1 as a line of\n",
    "text, by walking from atom to atom and writing down what it meets. The main rules:\n",
    "\n",
    "- an atom is its element symbol: `C`, `N`, `O`, `Cl`. Hydrogens are left out and filled in by the\n",
    "  usual valences, so `CCO` is ethanol, CH3-CH2-OH;\n",
    "- lower-case letters (`c`, `n`, `o`) are aromatic atoms, so `c1ccccc1` is benzene;\n",
    "- atoms written next to each other are joined by a single bond; `=` is a double bond and `#` a\n",
    "  triple bond;\n",
    "- brackets `( )` hold a branch: in `CC(=O)O` (acetic acid) the `=O` hangs off the second carbon and\n",
    "  the walk then carries on to the last `O`;\n",
    "- a matching pair of digits closes a ring: the two atoms marked `1` in `c1ccccc1` are bonded to\n",
    "  each other;\n",
    "- square brackets hold an atom written in full, with its hydrogens, charge or stereochemistry:\n",
    "  `[CH3]`, `[O-]`, `[nH]`, `[C@H]`.\n",
    "\n",
    "You can start the walk at any atom and take the branches in any order, so one molecule has many\n",
    "valid SMILES. RDKit's **canonical SMILES** always picks the same one for a given molecule, which\n",
    "makes it usable for comparing molecules. In the code, `{smiles:16}` inside the f-string pads the\n",
    "text to 16 characters, so that the arrows line up:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "OCC              -> CCO\n",
      "CCO              -> CCO\n",
      "C(O)C            -> CCO\n",
      "[CH3][CH2][OH]   -> CCO\n"
     ]
    }
   ],
   "source": [
    "for smiles in [\"OCC\", \"CCO\", \"C(O)C\", \"[CH3][CH2][OH]\"]:\n",
    "    canonical = Chem.MolToSmiles(Chem.MolFromSmiles(smiles))\n",
    "    print(f\"{smiles:16} -> {canonical}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Canonical means canonical *for one toolkit and version*. (A **toolkit** is a chemistry program or\n",
    "package such as RDKit.) Another program, or another RDKit release, may choose a different canonical\n",
    "form. That is why a database needs an identity that does not depend on the toolkit (section 3).\n",
    "\n",
    "**Aromaticity** is a choice too. Benzene can be written with alternating single and double bonds\n",
    "(the Kekulé form, `C1=CC=CC=C1`) or with aromatic lower-case atoms (`c1ccccc1`). When RDKit reads a\n",
    "molecule it decides which rings are aromatic (it *perceives* aromaticity), and writes them in lower\n",
    "case. `Chem.Kekulize` turns the aromatic form back into alternating bonds:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "as read:    c1ccccc1\n",
      "kekulised:  C1=CC=CC=C1\n"
     ]
    }
   ],
   "source": [
    "benzene = Chem.MolFromSmiles(\"C1=CC=CC=C1\")\n",
    "print(\"as read:   \", Chem.MolToSmiles(benzene))\n",
    "Chem.Kekulize(benzene, clearAromaticFlags=True)\n",
    "print(\"kekulised: \", Chem.MolToSmiles(benzene))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Different toolkits perceive aromaticity by different rules, so the same file can give different\n",
    "aromatic forms in different programs. That is one more reason to **standardise** before storing,\n",
    "that is, to put every molecule into one agreed form (Module 7).\n",
    "\n",
    "## 2. What a representation can lose: stereochemistry\n",
    "\n",
    "Ibuprofen has one stereocentre: a carbon with four different groups on it. The two mirror images\n",
    "(enantiomers, R and S) are different molecules with different biology. **Isomeric SMILES**, SMILES\n",
    "that include stereochemistry, keeps them apart with `@` and `@@` inside the square brackets: they\n",
    "say whether, looking from the first neighbour written towards the stereocentre, the other three\n",
    "neighbours, in the order they are written, go round anticlockwise (`@`) or clockwise (`@@`). `Chem.FindMolChiralCenters` lists each stereocentre as its atom number and\n",
    "its R or S label:\n",
    "\n",
    "![The two enantiomers of ibuprofen, labelled R and S](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/02-text-patterns-and-numbers/figures/ibuprofen-enantiomers.svg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "S: [(10, 'S')] CC(C)Cc1ccc([C@H](C)C(=O)O)cc1\n",
      "R: [(10, 'R')] CC(C)Cc1ccc([C@@H](C)C(=O)O)cc1\n"
     ]
    }
   ],
   "source": [
    "s_ibuprofen = Chem.MolFromSmiles(\"CC(C)Cc1ccc(cc1)[C@H](C)C(=O)O\")\n",
    "r_ibuprofen = Chem.MolFromSmiles(\"CC(C)Cc1ccc(cc1)[C@@H](C)C(=O)O\")\n",
    "print(\"S:\", Chem.FindMolChiralCenters(s_ibuprofen), Chem.MolToSmiles(s_ibuprofen))\n",
    "print(\"R:\", Chem.FindMolChiralCenters(r_ibuprofen), Chem.MolToSmiles(r_ibuprofen))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Ask for SMILES without stereochemistry, and the two collapse into one. The small function below\n",
    "does that. In its first line, `mol: Chem.Mol` and `-> str` are **type hints**: notes that say the\n",
    "function takes an RDKit molecule and returns a string (text). Python does not check them; they are\n",
    "there for the reader:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "isomeric SMILES equal: False\n",
      "flat SMILES equal:     True\n",
      "flat: CC(C)Cc1ccc(C(C)C(=O)O)cc1\n"
     ]
    }
   ],
   "source": [
    "def flat(mol: Chem.Mol) -> str:\n",
    "    \"\"\"Canonical SMILES with the stereochemistry left out.\"\"\"\n",
    "    return Chem.MolToSmiles(mol, isomericSmiles=False)\n",
    "\n",
    "\n",
    "print(\"isomeric SMILES equal:\", Chem.MolToSmiles(s_ibuprofen) == Chem.MolToSmiles(r_ibuprofen))\n",
    "print(\"flat SMILES equal:    \", flat(s_ibuprofen) == flat(r_ibuprofen))\n",
    "print(\"flat:\", flat(s_ibuprofen))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Store the flat form and your database silently merges two different drugs. Sometimes that is what\n",
    "you want (grouping a racemate, the 50:50 mixture, with its two enantiomers), but it must be a\n",
    "decision, never an accident.\n",
    "\n",
    "## 3. InChI and InChIKey: an identity for every molecule\n",
    "\n",
    "The **InChI** (IUPAC International Chemical Identifier) is a standard, open description of a\n",
    "molecule. It is written in layers separated by `/`: the formula, then the connections between atoms\n",
    "(`c...`), then the hydrogens (`h...`), and further layers for charge and stereochemistry when there\n",
    "are any. Every program that uses the official InChI software produces the same InChI for the same\n",
    "molecule.\n",
    "\n",
    "The **InChIKey** is a **hash** of the InChI: a code of fixed length (27 characters) calculated from\n",
    "it. The same InChI always gives the same key, but the key cannot be turned back into the InChI. It is\n",
    "short enough to use as a label in a database: to look a molecule up quickly, and to match rows of two\n",
    "tables that share it (a *join*)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "InChI=1S/C9H8O4/c1-6(10)13-8-5-3-2-4-7(8)9(11)12/h2-5H,1H3,(H,11,12)\n",
      "BSYNRYMUTXBXSQ-UHFFFAOYSA-N\n"
     ]
    }
   ],
   "source": [
    "print(Chem.MolToInchi(aspirin))\n",
    "print(Chem.MolToInchiKey(aspirin))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The key has three blocks. The first 14 letters encode the connectivity (the skeleton). The next\n",
    "block has 8 letters for stereochemistry and the other layers, then `S` (a standard InChI) and `A`\n",
    "(version 1). The last letter records protonation (`N` for neutral). So the two ibuprofen\n",
    "enantiomers share the first block and differ in the second. `key[:14]` takes the first 14\n",
    "characters of the key:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "S HEFNNWSXXWATRW-JTQLQIEISA-N   skeleton: HEFNNWSXXWATRW\n",
      "R HEFNNWSXXWATRW-SNVBAGLBSA-N   skeleton: HEFNNWSXXWATRW\n"
     ]
    }
   ],
   "source": [
    "for name, mol in [(\"S\", s_ibuprofen), (\"R\", r_ibuprofen)]:\n",
    "    key = Chem.MolToInchiKey(mol)\n",
    "    print(name, key, \"  skeleton:\", key[:14])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Grouping on the first 14 letters finds every stereoisomer of a structure; joining on the whole key\n",
    "keeps them apart.\n",
    "\n",
    "**Tautomers** are forms of one compound that differ only in where a hydrogen sits (and so which\n",
    "bonds are double), and that turn into each other easily: 2-pyridone and 2-hydroxypyridine are one\n",
    "example. Standard InChI treats some of these mobile hydrogens as one, so certain tautomers share a\n",
    "key, which is usually what a database wants. (In the SMILES below, `[nH]` is an aromatic nitrogen\n",
    "that carries a hydrogen.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "SMILES equal:   False\n",
      "InChIKey equal: True\n"
     ]
    }
   ],
   "source": [
    "pyridone = Chem.MolFromSmiles(\"O=c1cccc[nH]1\")\n",
    "hydroxypyridine = Chem.MolFromSmiles(\"Oc1ccccn1\")\n",
    "print(\"SMILES equal:  \", Chem.MolToSmiles(pyridone) == Chem.MolToSmiles(hydroxypyridine))\n",
    "print(\"InChIKey equal:\", Chem.MolToInchiKey(pyridone) == Chem.MolToInchiKey(hydroxypyridine))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "InChIKeys are hashes, so two different molecules could in principle share one (a *collision*). In\n",
    "practice collisions are extremely rare, but a careful pipeline keeps the full InChI or SMILES beside\n",
    "the key.\n",
    "\n",
    "## 4. Molfiles and SDF: the connection table\n",
    "\n",
    "Before SMILES there were **connection tables**: a list of atoms (with coordinates) and a list of\n",
    "bonds between them. The **molfile**, from the company MDL, is the classic format. An **SDF**\n",
    "(structure-data file, ending `.sdf`) is many molfiles one after another, each followed by optional\n",
    "data fields such as a name, a price or a measured value. Most compound libraries and vendor\n",
    "catalogues arrive as SDF. `Chem.MolToMolBlock` gives a molecule as molfile text:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "\n",
      "     RDKit          2D\n",
      "\n",
      "  3  2  0  0  0  0  0  0  0  0999 V2000\n",
      "    0.0000    0.0000    0.0000 C   0  0  0  0  0  0  0  0  0  0  0  0\n",
      "    1.2990    0.7500    0.0000 C   0  0  0  0  0  0  0  0  0  0  0  0\n",
      "    2.5981   -0.0000    0.0000 O   0  0  0  0  0  0  0  0  0  0  0  0\n",
      "  1  2  1  0\n",
      "  2  3  1  0\n",
      "M  END\n",
      "\n"
     ]
    }
   ],
   "source": [
    "ethanol = Chem.MolFromSmiles(\"CCO\")\n",
    "print(Chem.MolToMolBlock(ethanol))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Read it as a table: the counts line (3 atoms, 2 bonds), three atom lines (x, y, z, element) and two\n",
    "bond lines (atom, atom, bond order). Unlike SMILES, a molfile carries coordinates, which also means\n",
    "it is much larger: Module 3 measures what each format costs.\n",
    "\n",
    "## 5. Three dimensions: conformers\n",
    "\n",
    "Real molecules are three-dimensional and flexible. RDKit can generate 3D shapes, called\n",
    "**conformers**, but one molecule has many, and which you get depends on the method and the random\n",
    "seed. (The method starts from random numbers; a **seed** is the number the random numbers start\n",
    "from, so the same seed gives the same conformers on every run. Both are set in the Setup block.)\n",
    "`AllChem` holds RDKit's 3D tools. The code first adds the hydrogens with `Chem.AddHs`, because a 3D\n",
    "shape needs them, then generates the conformers and compares the x coordinate of atom 0 in the first\n",
    "two:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "5 conformers of 21 atoms (hydrogens included)\n",
      "same atoms, different coordinates: True\n"
     ]
    }
   ],
   "source": [
    "with_h = Chem.AddHs(aspirin)\n",
    "ids = AllChem.EmbedMultipleConfs(with_h, numConfs=N_CONFORMERS, randomSeed=CONFORMER_SEED)\n",
    "print(len(ids), \"conformers of\", with_h.GetNumAtoms(), \"atoms (hydrogens included)\")\n",
    "print(\n",
    "    \"same atoms, different coordinates:\",\n",
    "    with_h.GetConformer(0).GetAtomPosition(0).x != with_h.GetConformer(1).GetAtomPosition(0).x,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So 3D coordinates are not an identity: store them, when a job needs them (docking, which predicts\n",
    "how a molecule fits into a protein, or shape searches), as data *about* a molecule, never as the\n",
    "molecule's key.\n",
    "\n",
    "## 6. SMARTS: patterns, not molecules\n",
    "\n",
    "**SMARTS** describes a pattern to search for, not a molecule. It looks like SMILES, but each atom in\n",
    "square brackets can carry conditions. A common mistake is to search with a molecule written as\n",
    "SMILES. `C(=O)O` read as a molecule matches any carbon double-bonded to one oxygen and\n",
    "single-bonded to another: carboxylic acids, but also esters. The SMARTS `[CX3](=O)[OX2H1]` adds\n",
    "conditions. `[CX3]` is a carbon with three neighbours, and `[OX2H1]` is an oxygen with two\n",
    "neighbours, one of which is a hydrogen. So it finds acids only.\n",
    "\n",
    "The code keeps the four molecules in a dictionary called `library` (each name points to its\n",
    "molecule), and `.items()` goes through the name and molecule pairs. `HasSubstructMatch` says whether\n",
    "the pattern occurs anywhere in a molecule. In the printout, `!s:5` turns `True` or `False` into\n",
    "text and pads it to 5 characters, so that the columns line up:\n",
    "\n",
    "![Four molecules with the carboxylic acid group highlighted where the SMARTS pattern matches](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/02-text-patterns-and-numbers/figures/smarts-acid.svg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "aspirin            C(=O)O as a molecule: True   acid SMARTS: True\n",
      "salicylic acid     C(=O)O as a molecule: True   acid SMARTS: True\n",
      "methyl salicylate  C(=O)O as a molecule: True   acid SMARTS: False\n",
      "ibuprofen          C(=O)O as a molecule: True   acid SMARTS: True\n"
     ]
    }
   ],
   "source": [
    "library = {\n",
    "    \"aspirin\": aspirin,\n",
    "    \"salicylic acid\": Chem.MolFromSmiles(\"O=C(O)c1ccccc1O\"),\n",
    "    \"methyl salicylate\": Chem.MolFromSmiles(\"COC(=O)c1ccccc1O\"),\n",
    "    \"ibuprofen\": s_ibuprofen,\n",
    "}\n",
    "as_molecule = Chem.MolFromSmiles(\"C(=O)O\")\n",
    "acid = Chem.MolFromSmarts(\"[CX3](=O)[OX2H1]\")\n",
    "for name, mol in library.items():\n",
    "    print(\n",
    "        f\"{name:18} C(=O)O as a molecule: {mol.HasSubstructMatch(as_molecule)!s:5}  \"\n",
    "        f\"acid SMARTS: {mol.HasSubstructMatch(acid)}\"\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Methyl salicylate is an ester, not an acid: only the SMARTS gets it right. [Module 4](../04-databases-and-schemas/) runs the same\n",
    "searches inside the database.\n",
    "\n",
    "## 7. Fingerprints: molecules as bits\n",
    "\n",
    "To compare thousands of molecules quickly, we turn each into a **fingerprint**, a fixed-length\n",
    "string of bits (each bit is a 0 or a 1). A **Morgan** fingerprint looks at every atom's\n",
    "surroundings out to a radius (radius 2 means the atom, its neighbours, and their neighbours), and\n",
    "sets a bit to 1 for each environment it finds. It is also called a circular fingerprint, and it is\n",
    "close to the published ECFP (extended-connectivity fingerprint); ECFP4 has radius 2. The radius and\n",
    "length are set in the Setup block. Similar molecules share many bits.\n",
    "\n",
    "The code makes a fingerprint *generator* (an object that makes fingerprints with fixed settings),\n",
    "uses it on every molecule in `library`, then compares aspirin with the others. `{similarity:.2f}`\n",
    "prints the number to two decimal places:\n",
    "\n",
    "![Morgan fingerprint bits of aspirin and salicylic acid, with the bits they share marked](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/02-text-patterns-and-numbers/figures/fingerprint-bits.svg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "bits set in aspirin: 24 of 2048\n",
      "Tanimoto similarity, aspirin and salicylic acid: 0.45\n",
      "Tanimoto similarity, aspirin and methyl salicylate: 0.35\n",
      "Tanimoto similarity, aspirin and ibuprofen: 0.20\n"
     ]
    }
   ],
   "source": [
    "morgan = rdFingerprintGenerator.GetMorganGenerator(radius=MORGAN_RADIUS, fpSize=MORGAN_BITS)\n",
    "fingerprints = {name: morgan.GetFingerprint(mol) for name, mol in library.items()}\n",
    "print(\"bits set in aspirin:\", fingerprints[\"aspirin\"].GetNumOnBits(), \"of\", MORGAN_BITS)\n",
    "for name in [\"salicylic acid\", \"methyl salicylate\", \"ibuprofen\"]:\n",
    "    similarity = DataStructs.TanimotoSimilarity(fingerprints[\"aspirin\"], fingerprints[name])\n",
    "    print(f\"Tanimoto similarity, aspirin and {name}: {similarity:.2f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The **Tanimoto similarity** is the number of bits set in both fingerprints divided by the number set\n",
    "in either. It runs from 0 (no bits in common) to 1 (the same bits). A fingerprint cannot be turned\n",
    "back into a molecule, and two different molecules can share one: it is for comparing and searching,\n",
    "not for identity.\n",
    "\n",
    "## 8. Descriptors: molecules as numbers\n",
    "\n",
    "**Descriptors** are numbers calculated from a molecule. Four common ones:\n",
    "\n",
    "- **MW**, the molecular weight;\n",
    "- **logP**, a predicted octanol-water partition coefficient (on a log scale): higher means more\n",
    "  greasy;\n",
    "- **TPSA**, the topological polar surface area, in Å², an estimate of the surface taken by polar\n",
    "  atoms (N, O and their hydrogens);\n",
    "- **HBD**, the number of hydrogen-bond donors.\n",
    "\n",
    "They are what most machine-learning models and most filters (rules such as \"molecular weight under\n",
    "500\") work with. RDKit's `Descriptors` module calculates them. The f-string codes line the table up:\n",
    "`>8` puts text on the right of an 8-character space, `8.1f` writes a number 8 characters wide with\n",
    "one decimal, and `5d` a whole number 5 characters wide:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "molecule                MW   logP   TPSA  HBD\n",
      "aspirin              180.2   1.31   63.6    1\n",
      "salicylic acid       138.1   1.09   57.5    2\n",
      "methyl salicylate    152.1   1.18   46.5    1\n",
      "ibuprofen            206.3   3.07   37.3    1\n"
     ]
    }
   ],
   "source": [
    "print(f\"{'molecule':18}{'MW':>8}{'logP':>7}{'TPSA':>7}{'HBD':>5}\")\n",
    "for name, mol in library.items():\n",
    "    print(\n",
    "        f\"{name:18}{Descriptors.MolWt(mol):8.1f}{Descriptors.MolLogP(mol):7.2f}\"\n",
    "        f\"{Descriptors.TPSA(mol):7.1f}{Descriptors.NumHDonors(mol):5d}\"\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Descriptors are calculated, so they depend on the toolkit and its version: store the version beside\n",
    "them (Module 13 returns to this).\n",
    "\n",
    "## 9. What to store, for which job\n",
    "\n",
    "The table brings the module together, with the graph and matrices of Module 1. Two terms in it:\n",
    "graph neural networks are machine-learning models that read a molecule as a graph (Module 1), and\n",
    "clustering means sorting molecules into groups of similar ones.\n",
    "\n",
    "| Representation | Keeps | Loses | Use it for |\n",
    "|---|---|---|---|\n",
    "| Canonical isomeric SMILES | Connectivity, stereochemistry, charges | Coordinates; toolkit-specific | Readable storage, exchange, rebuilding the molecule |\n",
    "| InChI / InChIKey | A standard identity, the same in every program | Readability (the key); some tautomer detail | Keys, joins, finding duplicates |\n",
    "| Molfile / SDF | Coordinates, data fields | Compactness | Receiving and sending libraries; 3D work |\n",
    "| Molecular graph | Atoms, bonds, structure | Nothing of the 2D structure; no coordinates | Graph algorithms, graph databases |\n",
    "| Adjacency, distance and feature matrices | The graph and chosen atom properties, as numbers | Compactness (they grow with atoms squared) | Algorithms, graph neural networks; build them when needed |\n",
    "| 3D conformers | Shape | Uniqueness | Docking, shape searches (as data, never as a key) |\n",
    "| SMARTS | A pattern | It is not a molecule | Searching and filtering |\n",
    "| Fingerprints | Local environments, as bits | Can't be reversed; not unique | Similarity search, clustering, machine learning |\n",
    "| Descriptors | Chosen properties, as numbers | Structure | Filters, analysis, machine learning |\n",
    "\n",
    "A sensible first table for a compound library, which the next modules build on. The code makes one\n",
    "dictionary per molecule (column name to value), collects them in a list, and lets pandas turn the\n",
    "list into a table; `to_string(index=False)` prints it without row numbers:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "             name                    inchikey                         smiles     mw\n",
      "          aspirin BSYNRYMUTXBXSQ-UHFFFAOYSA-N          CC(=O)Oc1ccccc1C(=O)O 180.16\n",
      "   salicylic acid YGSDEFSMJLZEOE-UHFFFAOYSA-N                O=C(O)c1ccccc1O 138.12\n",
      "methyl salicylate OSWPMRLSEDHDFF-UHFFFAOYSA-N               COC(=O)c1ccccc1O 152.15\n",
      "        ibuprofen HEFNNWSXXWATRW-JTQLQIEISA-N CC(C)Cc1ccc([C@H](C)C(=O)O)cc1 206.28\n"
     ]
    }
   ],
   "source": [
    "rows = []\n",
    "for name, mol in library.items():\n",
    "    rows.append(\n",
    "        {\n",
    "            \"name\": name,\n",
    "            \"inchikey\": Chem.MolToInchiKey(mol),\n",
    "            \"smiles\": Chem.MolToSmiles(mol),\n",
    "            \"mw\": round(Descriptors.MolWt(mol), 2),\n",
    "        }\n",
    "    )\n",
    "compounds = pd.DataFrame(rows)\n",
    "print(compounds.to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The InChIKey is the identity, the canonical isomeric SMILES rebuilds the molecule, and everything\n",
    "else (fingerprints, descriptors, conformers) can be recalculated from it, as long as we record how.\n",
    "\n",
    "## Try it yourself\n",
    "\n",
    "The homework is a few questions, answered by running code like the code above: in a new cell at\n",
    "the end of the notebook, or in a script. It is at the end of the lesson's page, and in\n",
    "`homework.md` in the module's folder. The answers are published after the cohort's deadline.\n",
    "\n",
    "## Further reading\n",
    "\n",
    "- Weininger, D. (1988). SMILES, a chemical language and information system. 1. Introduction to\n",
    "  methodology and encoding rules. *Journal of Chemical Information and Computer Sciences*, 28(1),\n",
    "  31–36. <https://doi.org/10.1021/ci00057a005>\n",
    "- Heller, S., McNaught, A., Pletnev, I., Stein, S. & Tchekhovskoi, D. (2015). InChI, the IUPAC\n",
    "  International Chemical Identifier. *Journal of Cheminformatics*, 7, 23.\n",
    "  <https://doi.org/10.1186/s13321-015-0068-4>\n",
    "- Dalby, A. et al. (1992). Description of several chemical structure file formats used by computer\n",
    "  programs developed at Molecular Design Limited. *Journal of Chemical Information and Computer\n",
    "  Sciences*, 32(3), 244–255. <https://doi.org/10.1021/ci00007a012>\n",
    "- Rogers, D. & Hahn, M. (2010). Extended-connectivity fingerprints. *Journal of Chemical\n",
    "  Information and Modeling*, 50(5), 742–754. <https://doi.org/10.1021/ci100050t>\n",
    "- David, L., Thakkar, A., Mercado, R. & Engkvist, O. (2020). Molecular representations in AI-driven\n",
    "  drug discovery: a review and practical guide. *Journal of Cheminformatics*, 12, 56.\n",
    "  <https://doi.org/10.1186/s13321-020-00460-5>\n",
    "- Daylight Chemical Information Systems. *Daylight Theory Manual*, chapters on SMILES and SMARTS.\n",
    "  <https://www.daylight.com/dayhtml/doc/theory/>\n",
    "- The RDKit documentation. *Getting Started with the RDKit in Python*.\n",
    "  <https://www.rdkit.org/docs/GettingStartedInPython.html>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
