{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Standardisation as a tested transformation\n",
    "\n",
    "One canonical form per compound, made by one pure, versioned function (clean up, choose the parent, neutralise, optionally choose one tautomer) and tested like any other software.\n",
    "\n",
    "The lesson's page: https://monstrous.com.ng/learn/data-engineering/series-1/07-standardisation/"
   ]
  },
  {
   "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 pyarrow\n",
    "\n",
    "import pathlib\n",
    "import urllib.request\n",
    "if not pathlib.Path(\"chemlib.py\").exists():\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/shared/chemlib.py\", \"chemlib.py\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A compound reaches a database in many forms. One vendor sells it as the free base, another as the\n",
    "hydrochloride salt, a third writes the salt with the charges drawn in, and an assay file records\n",
    "it with a molecule of solvent. Chemically these are one compound under test; as records they have\n",
    "different SMILES and different InChIKeys, so a database that stores them as they come holds four\n",
    "compounds, splits their assay results four ways, and never notices.\n",
    "\n",
    "**Standardisation** turns every record into one canonical form (one agreed way of writing the\n",
    "compound) before its identity is computed and before it is stored. It is a transformation of the\n",
    "data, so it needs the same care as any code that changes data: it must be a single function that\n",
    "always gives the same answer for the same input, its rules must carry a version number that is\n",
    "stored with every output, and it must be tested.\n",
    "\n",
    "By the end of this module you will be able to:\n",
    "\n",
    "- explain the four usual steps (clean up how groups are drawn, keep the main compound and drop salts\n",
    "  and solvents, remove charges, and optionally pick one tautomer) and what each one changes;\n",
    "- run them with RDKit's `rdMolStandardize` module;\n",
    "- write standardisation as one function whose settings are written down, given a version and a\n",
    "  short fingerprint;\n",
    "- test that running it twice changes nothing, that two ways of writing a molecule give one answer,\n",
    "  and that agreed examples come out as agreed;\n",
    "- run it on a library, store beside each record where it came from and which rules made it, and\n",
    "  find the duplicates it reveals;\n",
    "- judge when picking one tautomer is worth the time it takes.\n",
    "\n",
    "From earlier modules we use canonical SMILES, the InChIKey and SMARTS patterns\n",
    "([Module 2](../02-text-patterns-and-numbers/)), the teaching library `chemlib`, Parquet files and\n",
    "finding duplicates by InChIKey ([Module 3](../03-files-and-identity/)), and the validation gate\n",
    "and its idea of fixable faults ([Module 6](../06-validating-molecules/)).\n",
    "\n",
    "The lesson uses RDKit for the chemistry, pandas for tables (a table in pandas is a **DataFrame**),\n",
    "pyarrow, which pandas uses to write Parquet files, and `chemlib`, the course's own package that\n",
    "makes and damages a teaching library. Everything here runs in a browser notebook (Google Colab) or\n",
    "on any laptop.\n",
    "\n",
    "## Setup\n",
    "\n",
    "Everything this lesson needs is imported and set here, so the settings can be changed in one place.\n",
    "Pipeline steps report with `log`; `print` is kept for showing you results; Module 1 explains why.\n",
    "\n",
    "Besides the packages above, the block imports tools that come with Python itself (its **standard\n",
    "library**), each explained where it is first used: `hashlib` and `json` make the short fingerprint\n",
    "of section 3, `time` measures how long code takes (section 6), `Path` handles file and folder\n",
    "names, and `Callable` and `NamedTuple` are used to describe and build small records (section 3).\n",
    "As in Module 6, `4_000` is four thousand (the underscore is only for reading), curly brackets with\n",
    "plain values make a **set** (a collection with no order and no repeats), and the comment\n",
    "`# fmt: skip`, used later, only tells the course's code formatter to leave a line alone."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import hashlib\n",
    "import json\n",
    "import logging\n",
    "import time\n",
    "from collections.abc import Callable\n",
    "from pathlib import Path\n",
    "from typing import NamedTuple\n",
    "\n",
    "import pandas as pd\n",
    "import rdkit\n",
    "from rdkit import Chem, RDLogger\n",
    "from rdkit.Chem.MolStandardize import rdMolStandardize\n",
    "\n",
    "import chemlib\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",
    "# tests of the standardiser (section 4): a sample of the library, and random SMILES of each\n",
    "TEST_SAMPLE_SIZE = 500  # molecules checked for idempotency and invariance\n",
    "TEST_SAMPLE_SEED = 31\n",
    "RANDOM_SMILES = 3  # randomly written SMILES per molecule in the invariance test\n",
    "RANDOM_SMILES_SEED = 7\n",
    "\n",
    "# the dirty library of section 5: change the size or seeds for another sample\n",
    "LIBRARY_SIZE = 4_000  # molecules made by chemlib for vendor A\n",
    "LIBRARY_SEED = 21\n",
    "DEFECT_RATE = 0.05  # fraction of molecules given a fault by add_defects\n",
    "DEFECT_SEED = 22\n",
    "VENDOR_B_SIZE = 200  # vendor A compounds that vendor B also sells, as salts\n",
    "VENDOR_B_SEED = 5\n",
    "\n",
    "# the short validation gate of section 5 (Module 6 has the full one)\n",
    "ALLOWED_ELEMENTS = {\"H\", \"B\", \"C\", \"N\", \"O\", \"F\", \"P\", \"S\", \"Cl\", \"Br\", \"I\"}\n",
    "SALTS_AND_SOLVENTS = {\"Cl\", \"[Cl-]\", \"Br\", \"[Na+]\", \"[K+]\", \"O=C(O)C(F)(F)F\", \"O\", \"CCO\", \"CO\"}\n",
    "\n",
    "TAUTOMER_SAMPLE_SIZE = 200  # molecules timed with and without the tautomer step (section 6)\n",
    "WORK = Path(\"work\")  # where the standardised table is written\n",
    "\n",
    "WORK.mkdir(exist_ok=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. One compound, many records\n",
    "\n",
    "Take one molecule from the course's teaching library (`chemlib`, as in Module 6), a benzamide with a\n",
    "basic piperidine, and write it the ways real files do. In SMILES a full stop separates two pieces\n",
    "in one record, so `.Cl` is hydrogen chloride beside the compound and `.O` a molecule of water;\n",
    "`{name:22}` in the f-string pads each name to 22 characters so the keys line up:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "free base              YJQXKEWIRCHOIN-UHFFFAOYSA-N\n",
      "hydrochloride, as HCl  FLVGHKUJGSVPDG-UHFFFAOYSA-N\n",
      "hydrochloride, ionic   FLVGHKUJGSVPDG-UHFFFAOYSA-N\n",
      "hydrate                QWZLHQPGDUXVNO-UHFFFAOYSA-N\n"
     ]
    }
   ],
   "source": [
    "records = {\n",
    "    \"free base\": \"O=C(NCc1ccc(F)cc1)c1ccc(C2CCNCC2)cc1\",\n",
    "    \"hydrochloride, as HCl\": \"O=C(NCc1ccc(F)cc1)c1ccc(C2CCNCC2)cc1.Cl\",\n",
    "    \"hydrochloride, ionic\": \"O=C(NCc1ccc(F)cc1)c1ccc(C2CC[NH2+]CC2)cc1.[Cl-]\",\n",
    "    \"hydrate\": \"O=C(NCc1ccc(F)cc1)c1ccc(C2CCNCC2)cc1.O\",\n",
    "}\n",
    "for name, smiles in records.items():\n",
    "    print(f\"{name:22} {Chem.MolToInchiKey(Chem.MolFromSmiles(smiles))}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Four records, three identities. The standard InChI already treats the two ways of writing the\n",
    "hydrochloride as one, but the free base, the salt and the hydrate are three different keys. The\n",
    "InChIKey is doing its job, which is to describe exactly what the record contains; it is the records\n",
    "that differ. Standardisation decides, by rule, what the\n",
    "compound is, and only then is the identity computed.\n",
    "\n",
    "## 2. The steps\n",
    "\n",
    "RDKit's `rdMolStandardize` module provides each step. (It began as a copy, rewritten inside RDKit,\n",
    "of MolVS, a Python package that has had no release since version 0.1.1 in 2018; use\n",
    "`rdMolStandardize`, which is maintained inside RDKit itself.)\n",
    "\n",
    "![The standardisation steps in order: clean-up applies normalisation rules, the parent step keeps the largest organic fragment, the uncharger neutralises charges by adding or removing hydrogens, and the optional tautomer step picks one canonical tautomer. A record goes in at the left and its canonical SMILES and InChIKey come out at the right, with the rules version and configuration hash recorded beside them](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/07-standardisation/figures/standardisation-steps.svg)\n",
    "\n",
    "### Clean-up: one way to draw each group\n",
    "\n",
    "Some groups can be drawn in more than one way: a sulfoxide as `S=O` or with separated charges as\n",
    "`[S+][O-]`. RDKit's sanitisation already redraws a few (a nitro group written `N(=O)=O` becomes\n",
    "`[N+](=O)[O-]` as it is read; **sanitisation** is RDKit's check of valences and aromaticity, as in\n",
    "Module 6), and `rdMolStandardize.Cleanup` applies a longer list of **normalisation rules**, each\n",
    "of which redraws one kind of group in RDKit's preferred way:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "CN(=O)=O       read as C[N+](=O)[O-]    cleaned: C[N+](=O)[O-]\n",
      "CS(C)=O        read as CS(C)=O          cleaned: C[S+](C)[O-]\n",
      "C[S+](C)[O-]   read as C[S+](C)[O-]     cleaned: C[S+](C)[O-]\n"
     ]
    }
   ],
   "source": [
    "for smiles in [\"CN(=O)=O\", \"CS(C)=O\", \"C[S+](C)[O-]\"]:\n",
    "    mol = Chem.MolFromSmiles(smiles)\n",
    "    cleaned = rdMolStandardize.Cleanup(mol)\n",
    "    print(f\"{smiles:14} read as {Chem.MolToSmiles(mol):16} cleaned: {Chem.MolToSmiles(cleaned)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "RDKit's rules draw sulfoxides with separated charges. Another tool's rules may choose `S=O`;\n",
    "which convention wins matters much less than applying one convention to every record.\n",
    "\n",
    "### The parent: strip salts and solvents\n",
    "\n",
    "The **parent** is the compound without its counter-ions and solvents. The simplest rule, and the\n",
    "usual one, keeps the largest organic fragment (a **fragment** is one of the separate pieces of a\n",
    "record). In RDKit this is an object, a `LargestFragmentChooser`, that is made once with its\n",
    "settings and then used with `chooser.choose(mol)`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "hydrochloride, as HCl  -> O=C(NCc1ccc(F)cc1)c1ccc(C2CCNCC2)cc1\n",
      "hydrate                -> O=C(NCc1ccc(F)cc1)c1ccc(C2CCNCC2)cc1\n"
     ]
    }
   ],
   "source": [
    "chooser = rdMolStandardize.LargestFragmentChooser(preferOrganic=True)\n",
    "for name in [\"hydrochloride, as HCl\", \"hydrate\"]:\n",
    "    parent = chooser.choose(Chem.MolFromSmiles(records[name]))\n",
    "    print(f\"{name:22} -> {Chem.MolToSmiles(parent)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\"Largest\" fails for mixtures of two drug-sized compounds, which is why Module 6 rejects mixtures\n",
    "before they reach this step.\n",
    "\n",
    "### Neutralise\n",
    "\n",
    "After the counter-ion has gone, a protonated amine is left with a charge. The **uncharger** adds or\n",
    "removes hydrogens to neutralise charges where it can, leaving charges it cannot remove (a quaternary\n",
    "ammonium has no hydrogen to lose):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "CC[NH3+]           -> CCN\n",
      "CC(=O)[O-]         -> CC(=O)O\n",
      "[NH3+]CC(=O)[O-]   -> NCC(=O)O\n",
      "C[N+](C)(C)C       -> C[N+](C)(C)C\n"
     ]
    }
   ],
   "source": [
    "uncharger = rdMolStandardize.Uncharger()\n",
    "for smiles in [\"CC[NH3+]\", \"CC(=O)[O-]\", \"[NH3+]CC(=O)[O-]\", \"C[N+](C)(C)C\"]:\n",
    "    neutral = uncharger.uncharge(Chem.MolFromSmiles(smiles))\n",
    "    print(f\"{smiles:18} -> {Chem.MolToSmiles(neutral)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The neutral form is a convention for identity, not a claim about the compound in water: glycine is\n",
    "a zwitterion at pH 7. Store the neutral parent for identity and searching; compute charge states at\n",
    "a given pH separately when a model needs them.\n",
    "\n",
    "### Canonical tautomer\n",
    "\n",
    "Tautomers differ only by where a hydrogen sits (2-hydroxypyridine and 2-pyridone). The\n",
    "`TautomerEnumerator` lists a molecule's tautomers, scores them by fixed rules and returns the best,\n",
    "so every tautomer of a compound gives the same output:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Oc1ccccn1      -> O=c1cccc[nH]1\n",
      "O=c1cccc[nH]1  -> O=c1cccc[nH]1\n",
      "O=C1C=CCC=C1   -> Oc1ccccc1\n"
     ]
    }
   ],
   "source": [
    "enumerator = rdMolStandardize.TautomerEnumerator()\n",
    "for smiles in [\"Oc1ccccn1\", \"O=c1cccc[nH]1\", \"O=C1C=CCC=C1\"]:\n",
    "    canonical = enumerator.Canonicalize(Chem.MolFromSmiles(smiles))\n",
    "    print(f\"{smiles:14} -> {Chem.MolToSmiles(canonical)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The first two records are one compound and now give one output. The third shows that the step can\n",
    "change aromaticity: a non-aromatic cyclohexadienone becomes phenol, its aromatic tautomer. It is\n",
    "the most expensive step and the one that changes the most; section 6 measures what it costs and\n",
    "shows when to skip it.\n",
    "\n",
    "## 3. One pure function, with versioned rules\n",
    "\n",
    "Each step is a choice (which fragment, which charges, which tautomer, how many tautomers to try),\n",
    "and a change to any of them changes the output for some molecules. So the whole of standardisation\n",
    "is written as **one pure function**: the same input and the same options always give the same\n",
    "output, and it reads and changes nothing else (no settings hidden elsewhere, no files, no clock).\n",
    "Its options are an **immutable** object, one that cannot be changed after it is made, and the rules\n",
    "carry a **version** and a short **hash** of the full configuration, recorded with every output.\n",
    "\n",
    "A hash is a fingerprint of a piece of text: a short string of letters and digits computed from it,\n",
    "which changes completely if any character of the text changes. So two outputs with the same hash\n",
    "were made with exactly the same settings. The code below works in four small steps:\n",
    "\n",
    "- `Options` is a named tuple (Module 6), a small record with named fields, here each with a\n",
    "  default value after the `=`; `Options(tautomer=True)` makes one with only that field changed;\n",
    "- `options._asdict()` turns it into a dictionary, and `**` copies that dictionary's entries into\n",
    "  the new dictionary `config`, beside the rules version and the RDKit version;\n",
    "- `json.dumps(config, sort_keys=True)` writes the dictionary as one line of text, with its keys\n",
    "  always in the same order, so the same settings always give the same text;\n",
    "- `hashlib.sha256(...)` computes the hash of that text (as bytes, hence `.encode(\"utf-8\")`), and\n",
    "  `.hexdigest()[:12]` keeps its first 12 characters, which is plenty to tell configurations apart:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "default:        f9351755c44a\n",
      "with tautomers: ef5ea73b092f\n"
     ]
    }
   ],
   "source": [
    "RULES_VERSION = \"1.0.0\"  # change it whenever a step or a default changes\n",
    "\n",
    "\n",
    "class Options(NamedTuple):\n",
    "    \"\"\"Which standardisation steps to run, and their settings. Immutable, so it can be hashed.\"\"\"\n",
    "\n",
    "    cleanup: bool = True\n",
    "    parent: bool = True\n",
    "    uncharge: bool = True\n",
    "    tautomer: bool = False\n",
    "    max_tautomers: int = 1000\n",
    "\n",
    "\n",
    "def config_hash(options: Options) -> str:\n",
    "    \"\"\"A short fingerprint of everything that decides the output: the rules, options and RDKit.\"\"\"\n",
    "    config = {\"rules\": RULES_VERSION, \"rdkit\": rdkit.__version__, **options._asdict()}\n",
    "    text = json.dumps(config, sort_keys=True)\n",
    "    return hashlib.sha256(text.encode(\"utf-8\")).hexdigest()[:12]\n",
    "\n",
    "\n",
    "DEFAULT = Options()\n",
    "WITH_TAUTOMERS = Options(tautomer=True)\n",
    "print(\"default:       \", config_hash(DEFAULT))\n",
    "print(\"with tautomers:\", config_hash(WITH_TAUTOMERS))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The RDKit version is part of the hash because a new release can change a rule or a canonical\n",
    "SMILES; the same options under another RDKit are another configuration.\n",
    "\n",
    "The function itself runs the steps that are switched on, in a fixed order, and notes which ones\n",
    "changed the molecule. It is built from two parts:\n",
    "\n",
    "- `steps_for` makes the list of steps for a set of options. Each step is a pair: its name and the\n",
    "  function that does it (written without brackets, so it is stored, not run). The type hint\n",
    "  `Callable[[Chem.Mol], Chem.Mol]` says each such function takes a molecule and returns one.\n",
    "- `standardise` reads the SMILES, then runs each step in turn, comparing the SMILES before and\n",
    "  after to see whether the step changed anything. `{smiles!r}` in the error message shows the\n",
    "  SMILES in quotes, and `raise ValueError(...)` stops with that message, because an unreadable\n",
    "  SMILES should never reach this function. The result is another named tuple, `Standardised`;\n",
    "  `tuple[str, ...]` means a tuple of any number of strings."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "free base              O=C(NCc1ccc(F)cc1)c1ccc(C2CCNCC2)cc1  changed by: -\n",
      "hydrochloride, as HCl  O=C(NCc1ccc(F)cc1)c1ccc(C2CCNCC2)cc1  changed by: parent\n",
      "hydrochloride, ionic   O=C(NCc1ccc(F)cc1)c1ccc(C2CCNCC2)cc1  changed by: parent, uncharge\n",
      "hydrate                O=C(NCc1ccc(F)cc1)c1ccc(C2CCNCC2)cc1  changed by: parent\n"
     ]
    }
   ],
   "source": [
    "class Standardised(NamedTuple):\n",
    "    \"\"\"The canonical SMILES of a record and the steps that changed it.\"\"\"\n",
    "\n",
    "    smiles: str\n",
    "    changed_by: tuple[str, ...]\n",
    "\n",
    "\n",
    "def steps_for(options: Options) -> list[tuple[str, Callable[[Chem.Mol], Chem.Mol]]]:\n",
    "    \"\"\"The standardisation steps switched on in `options`, in the order they run.\"\"\"\n",
    "    steps = []\n",
    "    if options.cleanup:\n",
    "        steps.append((\"cleanup\", rdMolStandardize.Cleanup))\n",
    "    if options.parent:\n",
    "        chooser = rdMolStandardize.LargestFragmentChooser(preferOrganic=True)\n",
    "        steps.append((\"parent\", chooser.choose))\n",
    "    if options.uncharge:\n",
    "        steps.append((\"uncharge\", rdMolStandardize.Uncharger().uncharge))\n",
    "    if options.tautomer:\n",
    "        params = rdMolStandardize.CleanupParameters()\n",
    "        params.maxTautomers = options.max_tautomers\n",
    "        enumerator = rdMolStandardize.TautomerEnumerator(params)\n",
    "        steps.append((\"tautomer\", enumerator.Canonicalize))\n",
    "    return steps\n",
    "\n",
    "\n",
    "def standardise(smiles: str, options: Options = DEFAULT) -> Standardised:\n",
    "    \"\"\"The canonical form of one record under `options`. Pure: nothing else is read or changed.\n",
    "\n",
    "    Raises ValueError for SMILES that cannot be read: validate first (Module 6).\n",
    "    \"\"\"\n",
    "    mol = Chem.MolFromSmiles(smiles)\n",
    "    if mol is None:\n",
    "        raise ValueError(f\"cannot read {smiles!r}: validate it first\")\n",
    "    changed_by = []\n",
    "    for name, step in steps_for(options):\n",
    "        before = Chem.MolToSmiles(mol)\n",
    "        mol = step(mol)\n",
    "        if Chem.MolToSmiles(mol) != before:\n",
    "            changed_by.append(name)\n",
    "    return Standardised(Chem.MolToSmiles(mol), tuple(changed_by))\n",
    "\n",
    "\n",
    "for name, smiles in records.items():\n",
    "    result = standardise(smiles)\n",
    "    print(f\"{name:22} {result.smiles}  changed by: {', '.join(result.changed_by) or '-'}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The four records of section 1 are now one compound. A batch job, a web form and a notebook that\n",
    "all call `standardise` get the same answer, because nothing else is involved.\n",
    "\n",
    "## 4. Testing it like software\n",
    "\n",
    "A standardiser touches every structure in the database, so a bug in it is a bug everywhere. Three\n",
    "kinds of test catch most of them. Each test is a function full of `assert` lines; `assert` stops the\n",
    "program with an error if what follows it is False, so a test that runs to the end has passed.\n",
    "\n",
    "**Known cases** pin down behaviour that chemists have agreed on. If a rule changes and one of these\n",
    "breaks, the change was not harmless:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO known cases pass\n"
     ]
    }
   ],
   "source": [
    "def test_known_cases() -> None:\n",
    "    \"\"\"Records whose standard form is agreed in advance.\"\"\"\n",
    "    assert standardise(\"CC(=O)[O-].[Na+]\").smiles == \"CC(=O)O\"  # sodium acetate -> acetic acid\n",
    "    assert standardise(\"[NH3+]CC(=O)[O-]\").smiles == \"NCC(=O)O\"  # zwitterion -> neutral glycine\n",
    "    assert standardise(\"CCN(CC)CC.Cl\").smiles == \"CCN(CC)CC\"  # salt stripped\n",
    "    pyridone = standardise(\"O=c1cccc[nH]1\", WITH_TAUTOMERS).smiles\n",
    "    assert standardise(\"Oc1ccccn1\", WITH_TAUTOMERS).smiles == pyridone  # a tautomer pair\n",
    "    assert standardise(\"Oc1ccccn1\").smiles != pyridone  # ... and without the tautomer step\n",
    "\n",
    "\n",
    "test_known_cases()\n",
    "log.info(\"known cases pass\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Idempotency** (from Latin for \"the same power\"): standardising a standard form changes nothing,\n",
    "`standardise(standardise(x)) == standardise(x)`. If it fails, a record's identity depends on how\n",
    "many times it went through the pipeline. **Invariance**: different SMILES of the same molecule give\n",
    "the same output. If it fails, the identity depends on how the vendor happened to write the record.\n",
    "Both are properties that must hold for every molecule, so we test them on many.\n",
    "\n",
    "For the invariance test, `Chem.MolToRandomSmilesVect(mol, n, randomSeed=...)` writes `n` different,\n",
    "randomly ordered but valid SMILES of the same molecule (the seed makes the random choice the same\n",
    "on every run). `[smiles, *variants]` is a list of the original SMILES followed by all the variants,\n",
    "and the curly brackets around the comprehension make a set of the outputs: if the set holds one\n",
    "SMILES, every variant gave the same answer:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO idempotent: 500 of 500\n",
      "INFO invariant: 500 of 500\n"
     ]
    }
   ],
   "source": [
    "def is_idempotent(smiles: str, options: Options = DEFAULT) -> bool:\n",
    "    \"\"\"Standardising the output again gives the output.\"\"\"\n",
    "    once = standardise(smiles, options).smiles\n",
    "    return standardise(once, options).smiles == once\n",
    "\n",
    "\n",
    "def is_invariant(smiles: str, options: Options = DEFAULT, n: int = RANDOM_SMILES) -> bool:\n",
    "    \"\"\"n randomly written SMILES of the same molecule all give one output.\"\"\"\n",
    "    mol = Chem.MolFromSmiles(smiles)\n",
    "    variants = Chem.MolToRandomSmilesVect(mol, n, randomSeed=RANDOM_SMILES_SEED)\n",
    "    return len({standardise(s, options).smiles for s in [smiles, *variants]}) == 1\n",
    "\n",
    "\n",
    "sample = chemlib.library(TEST_SAMPLE_SIZE, seed=TEST_SAMPLE_SEED)[\"smiles\"]\n",
    "log.info(\"idempotent: %d of %d\", sum(is_idempotent(s) for s in sample), len(sample))\n",
    "log.info(\"invariant: %d of %d\", sum(is_invariant(s) for s in sample), len(sample))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "All 500 molecules pass both tests. In a project these functions live in a test file\n",
    "(`test_standardise.py`) and are run by **pytest**, a Python package for running tests, which finds\n",
    "every function whose name starts with `test_` and reports each failure with the values involved.\n",
    "**Continuous integration**, a service that runs the tests automatically every time the code is\n",
    "changed, runs them on every change (Module 13). The plain `assert`s here are exactly what pytest\n",
    "runs. You do not need pytest for this lesson: in the notebook we call the test functions\n",
    "ourselves.\n",
    "\n",
    "## 5. Standardising a dirty library\n",
    "\n",
    "### Validate first\n",
    "\n",
    "Standardisation assumes a molecule that can be read and is worth keeping, so it runs after the\n",
    "validation gate. Here is a short version of Module 6's gate: records that cannot be read, or that\n",
    "contain an element outside the allow-list (`ALLOWED_ELEMENTS`, set in the Setup block) or a fragment\n",
    "that is neither a known salt nor a known solvent (`SALTS_AND_SOLVENTS`), are rejected; everything\n",
    "else goes on. Unlike Module 6, this short gate keeps no reasons, only the verdict, so it switches\n",
    "RDKit's messages off with `RDLogger.DisableLog`. As in Module 6, the largest piece is found with\n",
    "`max(..., key=lambda s: ...)`: a **lambda** is a one-line function without a name, here giving the\n",
    "number of heavy atoms of a SMILES `s`, and `max` keeps the piece for which it is highest:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "verdict    pass  reject\n",
      "defect                 \n",
      "(none)     3833       0\n",
      "duplicate    33       0\n",
      "element       0      33\n",
      "invalid       0      33\n",
      "salt         34       0\n",
      "solvent      34       0\n",
      "valence       0      33\n"
     ]
    }
   ],
   "source": [
    "RDLogger.DisableLog(\"rdApp.*\")  # the reasons are Module 6's subject; here we only need verdicts\n",
    "\n",
    "\n",
    "def gate(smiles: str) -> str:\n",
    "    \"\"\"'reject' for unreadable records, foreign elements or unknown fragments; else 'pass'.\"\"\"\n",
    "    mol = Chem.MolFromSmiles(smiles)\n",
    "    if mol is None:\n",
    "        return \"reject\"\n",
    "    if {atom.GetSymbol() for atom in mol.GetAtoms()} - ALLOWED_ELEMENTS:\n",
    "        return \"reject\"\n",
    "    pieces = sorted(Chem.MolToSmiles(f) for f in Chem.GetMolFrags(mol, asMols=True))\n",
    "    largest = max(pieces, key=lambda s: Chem.MolFromSmiles(s).GetNumHeavyAtoms())\n",
    "    if any(p not in SALTS_AND_SOLVENTS for p in pieces if p != largest):\n",
    "        return \"reject\"\n",
    "    return \"pass\"\n",
    "\n",
    "\n",
    "library = chemlib.library(LIBRARY_SIZE, seed=LIBRARY_SEED)\n",
    "vendor_a = chemlib.add_defects(library, rate=DEFECT_RATE, seed=DEFECT_SEED)\n",
    "vendor_a[\"verdict\"] = [gate(s) for s in vendor_a[\"smiles\"]]\n",
    "print(pd.crosstab(vendor_a[\"defect\"].replace(\"\", \"(none)\"), vendor_a[\"verdict\"]).to_string())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As in Module 6, records that cannot be read and selenium records are rejected. Salts and solvates\n",
    "pass this time, because standardisation can repair them, and the duplicates pass, as they should:\n",
    "they are good records, and standardisation is where they are found.\n",
    "\n",
    "### A second supplier\n",
    "\n",
    "Duplicates hidden by salts appear when sources are merged. A second supplier, vendor B, sells some\n",
    "of vendor A's compounds that have a basic amine, as hydrochloride salts written with the charges\n",
    "drawn in, or as trifluoroacetate (TFA) salts, the usual form after purification by HPLC. We make\n",
    "its catalogue from vendor A's records.\n",
    "\n",
    "This step only builds test data, so you can read it lightly. It finds a basic amine with a SMARTS\n",
    "pattern (Module 2), `BASIC_AMINE`: a nitrogen with one or two hydrogens that is not part of an\n",
    "amide, not attached to an aromatic ring and not bonded to another S, N or O. `as_hydrochloride`\n",
    "then puts a hydrogen and a `+` charge on the first such nitrogen and adds a chloride ion. It uses\n",
    "`Chem.RWMol`, an editable copy of a molecule (RDKit's ordinary molecules cannot be changed atom\n",
    "by atom). The table of vendor B is made with a comprehension that alternates between the two\n",
    "kinds of salt: `k % 2 == 0` is True for even row numbers, which become hydrochlorides, and the odd\n",
    "ones get a TFA salt. The ids are written with `{k:05d}`, a whole number padded with zeros to five\n",
    "digits:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "906 of vendor A's clean records have a basic amine; vendor B sells 200\n",
      "      id                                                              smiles\n",
      "VB-00000              CCOc1ccccc1Oc1ccc(C(=O)N(C(C)C)C2CC[NH2+]CC2)cc1.[Cl-]\n",
      "VB-00001 c1cc(C8CCNCC8)c(cc1)Oc2ccc(cc2)C(=O)N(C(C)C)C(F)(F)F.O=C(O)C(F)(F)F\n"
     ]
    }
   ],
   "source": [
    "BASIC_AMINE = Chem.MolFromSmarts(\"[NX3;H2,H1;!$(N-C=[O,N,S]);!$(N-a);!$(N-[S,N,O])]\")\n",
    "\n",
    "\n",
    "def as_hydrochloride(smiles: str) -> str:\n",
    "    \"\"\"The compound with its first basic amine protonated, and a chloride ion beside it.\"\"\"\n",
    "    mol = Chem.RWMol(Chem.MolFromSmiles(smiles))\n",
    "    atom = mol.GetAtomWithIdx(mol.GetSubstructMatch(BASIC_AMINE)[0])\n",
    "    atom.SetFormalCharge(1)\n",
    "    atom.SetNumExplicitHs(atom.GetTotalNumHs() + 1)\n",
    "    Chem.SanitizeMol(mol)\n",
    "    return Chem.MolToSmiles(mol) + \".[Cl-]\"\n",
    "\n",
    "\n",
    "passed = vendor_a[(vendor_a[\"verdict\"] == \"pass\") & (vendor_a[\"defect\"] == \"\")]\n",
    "basic = passed[[Chem.MolFromSmiles(s).HasSubstructMatch(BASIC_AMINE) for s in passed[\"smiles\"]]]\n",
    "picked = basic.sample(VENDOR_B_SIZE, random_state=VENDOR_B_SEED).sort_values(\"id\")\n",
    "vendor_b = pd.DataFrame(\n",
    "    {\n",
    "        \"id\": [f\"VB-{k:05d}\" for k in range(len(picked))],\n",
    "        \"smiles\": [\n",
    "            as_hydrochloride(s) if k % 2 == 0 else s + \".O=C(O)C(F)(F)F\"\n",
    "            for k, s in enumerate(picked[\"smiles\"])\n",
    "        ],\n",
    "    }\n",
    ")\n",
    "print(len(basic), \"of vendor A's clean records have a basic amine; vendor B sells\", len(vendor_b))\n",
    "print(vendor_b.head(2).to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Run it, with provenance\n",
    "\n",
    "**Provenance** is the record of where a piece of data came from and what was done to it. Every\n",
    "record that passed the gate, from both suppliers, goes through `standardise`, after `pd.concat`\n",
    "has joined the two suppliers' tables into one (`ignore_index=True` numbers the rows afresh). The\n",
    "output\n",
    "keeps the input SMILES beside the standard one, with the steps that changed it, the rules version\n",
    "and the configuration hash. Anyone can later see where a structure came from and which rules made\n",
    "it, and records made under old rules can be found and re-run when the rules change:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO standardised 4134 records; 268 changed\n",
      "changed_by\n",
      "parent             168\n",
      "parent,uncharge    100\n"
     ]
    }
   ],
   "source": [
    "merged = pd.concat(\n",
    "    [vendor_a.loc[vendor_a[\"verdict\"] == \"pass\", [\"id\", \"smiles\"]], vendor_b],\n",
    "    ignore_index=True,\n",
    ")\n",
    "results = [standardise(s) for s in merged[\"smiles\"]]\n",
    "standard = pd.DataFrame(\n",
    "    {\n",
    "        \"id\": merged[\"id\"],\n",
    "        \"input_smiles\": merged[\"smiles\"],\n",
    "        \"smiles\": [r.smiles for r in results],\n",
    "        \"changed_by\": [\",\".join(r.changed_by) for r in results],\n",
    "        \"rules_version\": RULES_VERSION,\n",
    "        \"config_hash\": config_hash(DEFAULT),\n",
    "    }\n",
    ")\n",
    "changed = standard[standard[\"changed_by\"] != \"\"]\n",
    "log.info(\"standardised %d records; %d changed\", len(standard), len(changed))\n",
    "print(changed[\"changed_by\"].value_counts().sort_index().to_string())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every change is the parent step or the parent step followed by neutralisation: vendor A's 34\n",
    "salts and 34 solvates and vendor B's 100 TFA salts lost a fragment, and vendor B's 100 ionic\n",
    "hydrochlorides lost a fragment and a charge. One example of each, before and after:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "         id                                           input_smiles                                          smiles\n",
      "ML-00847014     c1c(CO)cc(cc1C(C)C)C(=O)NC(CF)C(=O)Nc8ccc(F)cc8.Cl CC(C)c1cc(CO)cc(C(=O)NC(CF)C(=O)Nc2ccc(F)cc2)c1\n",
      "   VB-00000 CCOc1ccccc1Oc1ccc(C(=O)N(C(C)C)C2CC[NH2+]CC2)cc1.[Cl-]     CCOc1ccccc1Oc1ccc(C(=O)N(C(C)C)C2CCNCC2)cc1\n"
     ]
    }
   ],
   "source": [
    "examples = changed.groupby(\"changed_by\").head(1)\n",
    "print(examples[[\"id\", \"input_smiles\", \"smiles\"]].to_string(index=False, max_colwidth=58))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![Records before and after standardisation, in pairs: on the left as received, on the right the standard form. Counter-ions and solvents are removed and charges neutralised](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/07-standardisation/figures/before-after.svg)\n",
    "\n",
    "### Duplicates that only standardisation reveals\n",
    "\n",
    "Now compare identities. The InChIKey of each record as received, and of its standard form. A\n",
    "**duplicate group** is an InChIKey held by more than one record; `value_counts` counts the records\n",
    "for each key, and the groups are the keys counted more than once:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "duplicate groups before standardisation: 37\n",
      "duplicate groups after standardisation:  236\n",
      "distinct compounds: 4097 -> 3897\n"
     ]
    }
   ],
   "source": [
    "def inchikey(smiles: str) -> str:\n",
    "    \"\"\"The InChIKey of a SMILES.\"\"\"\n",
    "    return Chem.MolToInchiKey(Chem.MolFromSmiles(smiles))\n",
    "\n",
    "\n",
    "standard[\"inchikey_in\"] = [inchikey(s) for s in standard[\"input_smiles\"]]\n",
    "standard[\"inchikey\"] = [inchikey(s) for s in standard[\"smiles\"]]\n",
    "\n",
    "\n",
    "def duplicate_groups(keys: pd.Series) -> int:\n",
    "    \"\"\"How many identities are held by more than one record.\"\"\"\n",
    "    sizes = keys.value_counts()\n",
    "    return int((sizes > 1).sum())\n",
    "\n",
    "\n",
    "before = duplicate_groups(standard[\"inchikey_in\"])\n",
    "after = duplicate_groups(standard[\"inchikey\"])\n",
    "print(\"duplicate groups before standardisation:\", before)\n",
    "print(\"duplicate groups after standardisation: \", after)\n",
    "distinct_in, distinct_out = standard[\"inchikey_in\"].nunique(), standard[\"inchikey\"].nunique()\n",
    "print(\"distinct compounds:\", distinct_in, \"->\", distinct_out)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Standardisation turned 37 duplicate groups into 236, and the number of distinct compounds fell by\n",
    "200. Which records did it join? Those whose identities differed before and agree after. The code\n",
    "groups the records by their new InChIKey: `agg(sorted)` collects the sorted ids in each group, and a\n",
    "group joins records that differed before if it holds more than one old InChIKey (`nunique() > 1`\n",
    "counts the distinct old keys). `i.startswith(\"VB-\")` picks out vendor B's records by their id:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "200 groups join records whose InChIKeys differed before; the first three:\n",
      "  ACIFUBKVQIZHAZ-UHFFFAOYSA-N: ML-01112212, VB-00113\n",
      "  ACQBWWYNHXOFBE-UHFFFAOYSA-N: ML-00838364, VB-00079\n",
      "  ADGTYJCSQSHQNF-UHFFFAOYSA-N: ML-00614039, VB-00061\n",
      "200 of them include a vendor B record; 1 already held a duplicate before\n"
     ]
    }
   ],
   "source": [
    "group_ids = standard.groupby(\"inchikey\")[\"id\"].agg(sorted)\n",
    "joined = group_ids[standard.groupby(\"inchikey\")[\"inchikey_in\"].nunique() > 1]\n",
    "print(len(joined), \"groups join records whose InChIKeys differed before; the first three:\")\n",
    "for key, ids in joined.head(3).items():\n",
    "    print(f\"  {key}: {', '.join(ids)}\")\n",
    "with_vendor_b = sum(any(i.startswith(\"VB-\") for i in ids) for ids in joined)\n",
    "grown = sum(standard.loc[standard[\"inchikey\"] == key, \"inchikey_in\"].duplicated().any()\n",
    "            for key in joined.index)  # fmt: skip\n",
    "print(with_vendor_b, \"of them include a vendor B record;\", grown, \"already held a duplicate before\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every one of vendor B's 200 salts has found the vendor A record it came from: 199 new duplicate\n",
    "groups, and one vendor B record that joined a pair already there (a vendor A record and its planted\n",
    "duplicate), which is why the count grew by 199, not 200. Vendor A's own 68 salts and solvates were\n",
    "repaired but matched nothing else, which is what we expect: `add_defects` damaged different\n",
    "molecules from the ones it duplicated. In a real merge, these joins are where assay results from\n",
    "two suppliers meet for the first time.\n",
    "\n",
    "Finally the table is written out as a Parquet file (Module 3), with its provenance columns, ready\n",
    "for loading into a database ([Module 4](../04-databases-and-schemas/)):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO wrote 4134 records to work/standardised.parquet\n",
      "['id', 'input_smiles', 'smiles', 'changed_by', 'rules_version', 'config_hash', 'inchikey_in', 'inchikey']\n"
     ]
    }
   ],
   "source": [
    "standard_path = WORK / \"standardised.parquet\"\n",
    "standard.to_parquet(standard_path, index=False)\n",
    "log.info(\"wrote %d records to %s\", len(standard), standard_path.as_posix())\n",
    "print(standard.columns.tolist())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. Tautomers: what they cost and when to skip them\n",
    "\n",
    "The default configuration above leaves tautomers alone. Here is why. First, the cost, on 200\n",
    "molecules from the library (timings differ from computer to computer, so yours will not match).\n",
    "`time.perf_counter()` reads a clock, so the difference between two readings is the time the code\n",
    "between them took, in seconds; we multiply by 1000 for milliseconds and divide by the number of\n",
    "molecules. In the `log` lines, `%.1f` is filled in with the number, to one decimal place:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO without tautomers: 3.5 ms per molecule\n",
      "INFO with tautomers:    12.3 ms per molecule\n"
     ]
    }
   ],
   "source": [
    "tautomer_sample = library[\"smiles\"].head(TAUTOMER_SAMPLE_SIZE).tolist()\n",
    "start = time.perf_counter()\n",
    "plain = [standardise(s) for s in tautomer_sample]\n",
    "middle = time.perf_counter()\n",
    "with_tautomers = [standardise(s, WITH_TAUTOMERS) for s in tautomer_sample]\n",
    "end = time.perf_counter()\n",
    "log.info(\"without tautomers: %.1f ms per molecule\",\n",
    "         1000 * (middle - start) / len(tautomer_sample))  # fmt: skip\n",
    "log.info(\"with tautomers:    %.1f ms per molecule\",\n",
    "         1000 * (end - middle) / len(tautomer_sample))  # fmt: skip"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here the tautomer step more than doubled the time per molecule. Then, what it changed, and how many\n",
    "tautomers it had to consider. `zip(plain, with_tautomers)` walks through the two lists side by side,\n",
    "giving each molecule's result without and with the tautomer step together, and\n",
    "`enumerator.Enumerate` lists all the tautomers RDKit finds for a molecule:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "3 of 200 changed by the tautomer step; 3 of those keep their InChIKey\n",
      "for example: CN(C)c1ccc2nc(-c3ccc(-c4ccccc4)cc3)[nH]c2c1 -> CN(C)c1ccc2[nH]c(-c3ccc(-c4ccccc4)cc3)nc2c1\n",
      "tautomers per molecule: median 2  most 46\n"
     ]
    }
   ],
   "source": [
    "moved = [(p.smiles, t.smiles) for p, t in zip(plain, with_tautomers) if p.smiles != t.smiles]\n",
    "same_key = sum(\n",
    "    Chem.MolToInchiKey(Chem.MolFromSmiles(a)) == Chem.MolToInchiKey(Chem.MolFromSmiles(b))\n",
    "    for a, b in moved\n",
    ")\n",
    "print(len(moved), \"of\", len(tautomer_sample), \"changed by the tautomer step;\", same_key,\n",
    "      \"of those keep their InChIKey\")\n",
    "print(\"for example:\", moved[0][0], \"->\", moved[0][1])\n",
    "counts = [len(enumerator.Enumerate(Chem.MolFromSmiles(s))) for s in tautomer_sample]\n",
    "print(\"tautomers per molecule: median\", sorted(counts)[len(counts) // 2], \" most\", max(counts))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Only 3 of the 200 molecules changed, and every one kept its InChIKey: here a benzimidazole had its\n",
    "NH moved from one ring nitrogen to the other, and the standard InChI already treats those two forms\n",
    "as one. The step's cost grows with the number of tautomers to enumerate and score: a median of two\n",
    "per molecule here, but 46 for one of them; molecules with many mobile hydrogens can reach the\n",
    "enumerator's limit (`max_tautomers` in our options), and then the answer depends on that limit too.\n",
    "\n",
    "Some changes look odd to a chemist. A hydroxamic acid, a common metal-binding group in drugs, is\n",
    "turned into its rarely drawn hydroximic acid form:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "CC(O)=NO\n"
     ]
    }
   ],
   "source": [
    "print(standardise(\"CC(=O)NO\", WITH_TAUTOMERS).smiles)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The tautomer step can also remove stereochemistry. An atom that loses its hydrogen in some\n",
    "tautomer (next to a carbonyl, for example) could invert through that tautomer, so RDKit's default\n",
    "removes its stereo label. An (S)-alanine amide is a chiral drug fragment, and it loses its\n",
    "stereocentre:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "default:        CNC(=O)[C@H](C)N\n",
      "with tautomers: CNC(=O)C(C)N\n"
     ]
    }
   ],
   "source": [
    "alanine_amide = \"C[C@H](N)C(=O)NC\"\n",
    "print(\"default:       \", standardise(alanine_amide).smiles)\n",
    "print(\"with tautomers:\", standardise(alanine_amide, WITH_TAUTOMERS).smiles)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So, when to use it, and when to skip it:\n",
    "\n",
    "- **Identity by InChIKey.** The standard InChI already treats many tautomers (those that move a\n",
    "  hydrogen between heteroatoms) as one, so most tautomer duplicates are caught without this step:\n",
    "  all three changes above kept their InChIKey.\n",
    "- **Identity by canonical SMILES** (a SMILES-based database key, or a machine-learning set where two\n",
    "  tautomers of one compound could end up one in the training set and one in the test set, so the\n",
    "  model is tested on a compound it has already seen): use it, so that tautomers of one compound are\n",
    "  one record.\n",
    "- **Stereochemistry matters** (single enantiomers): skip it, or set\n",
    "  `CleanupParameters().tautomerRemoveSp3Stereo = False` and record that choice in the options.\n",
    "- **Display.** The canonical tautomer is a rule's choice, not the form that predominates in\n",
    "  solution, as the hydroximic acid shows. Keep the input structure for drawing.\n",
    "- **Large libraries.** At ten milliseconds or more per molecule, a million molecules take hours of\n",
    "  processor time; spread it over processes (Module 9), or skip it.\n",
    "\n",
    "Whatever is chosen goes into `Options`, and so into the configuration hash stored with every\n",
    "record.\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",
    "- Bento, A. P., Hersey, A., Félix, E., Landrum, G., Gaulton, A., Atkinson, F., Bellis, L. J.,\n",
    "  De Veij, M. & Leach, A. R. (2020). An open source chemical structure curation pipeline using\n",
    "  RDKit. *Journal of Cheminformatics*, 12, 51. <https://doi.org/10.1186/s13321-020-00456-1>\n",
    "- Sitzmann, M., Ihlenfeldt, W.-D. & Nicklaus, M. C. (2010). Tautomerism in large databases.\n",
    "  *Journal of Computer-Aided Molecular Design*, 24(6–7), 521–551.\n",
    "  <https://doi.org/10.1007/s10822-010-9346-4>\n",
    "- The RDKit documentation. *rdkit.Chem.MolStandardize.rdMolStandardize module*.\n",
    "  <https://www.rdkit.org/docs/source/rdkit.Chem.MolStandardize.rdMolStandardize.html>\n",
    "- The ChEMBL Structure Pipeline (source code and documentation of its standardiser and parent\n",
    "  steps). <https://github.com/chembl/ChEMBL_Structure_Pipeline>\n",
    "- The pytest documentation. <https://docs.pytest.org/en/stable/>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
