{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Validating molecules\n",
    "\n",
    "A validation gate that reads every record, checks it, and accepts it or quarantines it with recorded reasons, so no broken structure spreads and no record disappears silently.\n",
    "\n",
    "The lesson's page: https://monstrous.com.ng/learn/data-engineering/series-1/06-validating-molecules/"
   ]
  },
  {
   "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": [
    "Every chemical data set has broken records in it. A vendor file holds a SMILES whose ring is never\n",
    "closed, a carbon with five bonds, a hydrochloride salt written into the structure, a compound with\n",
    "an element the library should never contain. If these records reach the database, they spread:\n",
    "a fingerprint is computed from a salt, a model is trained on a mixture, a search misses a compound\n",
    "because it is stored with its counter-ion. Fourches, Muratov and Tropsha (2010) set out the steps\n",
    "of chemical curation (removing inorganic compounds, salts and mixtures, validating structures,\n",
    "deleting duplicates) and described case studies where curating the raw data significantly improved\n",
    "a model's predictions. Public databases now do this in code: ChEMBL, for example, checks its\n",
    "structures with an open-source pipeline built on RDKit (section 7).\n",
    "\n",
    "A **record** here is one row of a data file: one compound, with its ID and its SMILES. A data\n",
    "engineer turns that curation into a **gate**: every record is read and checked before it is\n",
    "stored, and it leaves the gate in one of two ways. It is accepted, or it is put in **quarantine**\n",
    "(a separate table of records held back) with the reasons written down. Nothing is dropped without\n",
    "a trace.\n",
    "\n",
    "By the end of this module you will be able to:\n",
    "\n",
    "- explain why a SMILES that RDKit cannot read must be kept with a written reason, and never simply\n",
    "  left out;\n",
    "- catch RDKit's own error messages for each record;\n",
    "- write checks that say what is wrong (a short code, a message and what to do), not just True or\n",
    "  False;\n",
    "- check a molecule's elements, its separate pieces (salts, solvents), its charge, its\n",
    "  stereochemistry and its size;\n",
    "- run the gate over a whole library and make a table of the quarantined records and a count of\n",
    "  records for each reason;\n",
    "- test the gate against a library whose faults are known: what it caught, what it missed and where\n",
    "  it raised a false alarm.\n",
    "\n",
    "From earlier modules we use SMILES, stereochemistry and the InChIKey\n",
    "([Module 2](../02-text-patterns-and-numbers/)), the teaching library `chemlib`, Parquet files and\n",
    "the InChIKey as a molecule's identity ([Module 3](../03-files-and-identity/)), and the habit of\n",
    "reporting with `log` and showing values with `print` ([Module 1](../01-graphs-and-matrices/)).\n",
    "\n",
    "The lesson uses these packages:\n",
    "\n",
    "- **RDKit**, the chemistry toolkit: it reads the SMILES and checks the chemistry;\n",
    "- **pandas**, for tables (a table in pandas is called a **DataFrame**);\n",
    "- **pyarrow**, which pandas uses to write Parquet files; you never call it yourself;\n",
    "- **chemlib**, the course's own small package that makes a teaching library of molecules and can\n",
    "  damage it on purpose.\n",
    "\n",
    "Everything here runs in a browser notebook (Google Colab) or 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",
    "That includes the library's policy (the elements it allows, the salts and solvents it knows, its\n",
    "size limits), which section 3 explains check by check: a policy kept in one place can be read,\n",
    "reviewed and changed without hunting through the code. Pipeline steps report with `log`; `print`\n",
    "is kept for showing you results; Module 1 explains why.\n",
    "\n",
    "Besides the packages above, the block imports a few tools that come with Python itself (its\n",
    "**standard library**); each is explained where it is first used:\n",
    "\n",
    "- `re`, for **regular expressions**, patterns that match pieces of text (section 2);\n",
    "- `Counter`, a dictionary that counts things (section 4);\n",
    "- `Callable` and `NamedTuple`, used in **type hints**, the notes after a colon or `->` that say what\n",
    "  kind of value a function takes or returns (section 2);\n",
    "- `Path`, for file and folder names that work on Windows, macOS and Linux.\n",
    "\n",
    "A few Python details in the settings: `10_000` is ten thousand (the underscore only makes it easier\n",
    "to read); curly brackets such as `{\"H\", \"B\", ...}` make a **set**, a collection with no order and no\n",
    "repeats, which is quick to check membership in; `{\"Cl\": \"hydrogen chloride\", ...}` is a\n",
    "**dictionary**, which looks up a value (the name) from a key (the SMILES); and `(6, 50)` is a\n",
    "**tuple**, a fixed pair of values. The comment `# fmt: skip`, here and later, tells the course's\n",
    "code formatter to leave that line's layout alone; you can ignore it. The last line makes the\n",
    "`work` folder, if it is not there already, for the files this lesson writes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import logging\n",
    "import re\n",
    "from collections import Counter\n",
    "from collections.abc import Callable\n",
    "from pathlib import Path\n",
    "from typing import NamedTuple\n",
    "\n",
    "import pandas as pd\n",
    "from rdkit import Chem, RDLogger, rdBase\n",
    "from rdkit.Chem import Descriptors\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",
    "# the teaching library and the damage done to it: change the size or seeds for another sample\n",
    "LIBRARY_SIZE = 10_000  # molecules made by chemlib\n",
    "LIBRARY_SEED = 6\n",
    "DEFECT_RATE = 0.05  # fraction of molecules given a fault by add_defects\n",
    "DEFECT_SEED = 7\n",
    "WORK = Path(\"work\")  # where the accepted records and the quarantine are written\n",
    "\n",
    "# the library's policy (section 3): edit these lists and limits to suit another collection\n",
    "ALLOWED_ELEMENTS = {\"H\", \"B\", \"C\", \"N\", \"O\", \"F\", \"P\", \"S\", \"Cl\", \"Br\", \"I\"}\n",
    "SALTS = {\"Cl\": \"hydrogen chloride\", \"[Cl-]\": \"chloride\", \"Br\": \"hydrogen bromide\",\n",
    "         \"[Na+]\": \"sodium\", \"[K+]\": \"potassium\", \"O=C(O)C(F)(F)F\": \"trifluoroacetic acid\"}\n",
    "SOLVENTS = {\"O\": \"water\", \"CCO\": \"ethanol\", \"CO\": \"methanol\", \"CS(C)=O\": \"DMSO\",\n",
    "            \"ClCCl\": \"dichloromethane\"}  # fmt: skip\n",
    "HEAVY_ATOMS = (6, 50)  # smallest and largest number of heavy atoms in the largest piece\n",
    "MAX_WEIGHT = 700.0  # largest molecular weight of the largest piece, in g/mol\n",
    "\n",
    "WORK.mkdir(exist_ok=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. What goes wrong without a gate\n",
    "\n",
    "We start from a teaching library made by `chemlib` (the course's library generator, as in Module 3)\n",
    "and damage it on purpose with `add_defects`. The damage is on record: the `defect` column says\n",
    "which fault each row was given, so we can check our validator against the truth at the end. (A\n",
    "**validator** is the code that does the checking.)\n",
    "\n",
    "The second `print` counts the rows of each kind of fault: `.replace(\"\", \"(none)\")` gives the\n",
    "undamaged rows, whose `defect` is empty, a readable name, `value_counts()` counts each value, and\n",
    "`sort_index()` puts the names in alphabetical order."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "10083 records\n",
      "defect\n",
      "(none)       9583\n",
      "duplicate      83\n",
      "element        83\n",
      "invalid        83\n",
      "salt           84\n",
      "solvent        84\n",
      "valence        83\n"
     ]
    }
   ],
   "source": [
    "library = chemlib.library(LIBRARY_SIZE, seed=LIBRARY_SEED)\n",
    "dirty = chemlib.add_defects(library, rate=DEFECT_RATE, seed=DEFECT_SEED)\n",
    "print(len(dirty), \"records\")\n",
    "print(dirty[\"defect\"].replace(\"\", \"(none)\").value_counts().sort_index().to_string())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A rate of 0.05 damaged 500 of the 10,000 molecules, split as evenly as possible across six kinds\n",
    "of fault: 417 rows were changed in place, and the 83 duplicates were added as new rows. Here is\n",
    "one example of each, as the file holds it. `groupby(\"defect\").head(1)` keeps the first row of each\n",
    "kind of fault, `iterrows()` goes through those rows one at a time, and `{row['defect']:10}` in the\n",
    "f-string pads the name to 10 characters so the SMILES line up:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "valence    C(C)(C)(C)(C)c1cc(Cl)c(nc1)Nc2nc(N8CCOCC8)c(c8cn[nH]c8)c(Br)n2\n",
      "duplicate  S(=O)(c1cccc(c1)C(NC(C(NC)=O)CN1CCOCC1)=O)(=O)C\n",
      "solvent    c1cc(c8cn[nH]c8)c(nc1)Nc2nc(c8ccc(F)cc8)c(C(=O)N)c(N(C)C)n2.CCO\n",
      "element    c1c(c8ccc(F)cc8)cc(cc1c8ccco8)[Se](=O)NC(CC)C(=O)NO\n",
      "salt       c1cc(c8ccco8)c(nc1)Nc2nc(C(=O)C)c(O)c(CN)n2.Cl\n",
      "invalid    ccc(N8CCCC8)c(nc1)Nc2nc(C(=O)C)c(C(C)C)c(C8CC8)n2\n"
     ]
    }
   ],
   "source": [
    "for kind, row in dirty[dirty[\"defect\"] != \"\"].groupby(\"defect\").head(1).iterrows():\n",
    "    print(f\"{row['defect']:10} {row['smiles']}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A **valence** fault is an atom with more bonds than it can have (here a carbon with five), and an\n",
    "**invalid** SMILES is one RDKit cannot read at all (here the ring-closing `1` at the start has been\n",
    "cut off).\n",
    "\n",
    "The usual first script reads every SMILES with RDKit, silences RDKit's warnings because they clutter\n",
    "the screen, and keeps what worked. It is written with **list comprehensions**, the short form\n",
    "`[f(x) for x in items]` that makes a list by doing one thing to each item, with an optional\n",
    "`if` to keep only some. `sum(test for m in kept)` counts the molecules for which the test is\n",
    "True, because Python counts True as 1 and False as 0. `Chem.GetMolFrags(m)` returns the separate\n",
    "pieces of a molecule, as Module 1 found them from its graph:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "166 records vanished, with no reason recorded\n",
      "168 kept records are in more than one piece\n",
      "83 kept records contain selenium\n"
     ]
    }
   ],
   "source": [
    "RDLogger.DisableLog(\"rdApp.*\")  # silence RDKit, as many scripts do\n",
    "mols = [Chem.MolFromSmiles(s) for s in dirty[\"smiles\"]]\n",
    "RDLogger.EnableLog(\"rdApp.*\")\n",
    "kept = [m for m in mols if m is not None]\n",
    "print(len(dirty) - len(kept), \"records vanished, with no reason recorded\")\n",
    "in_pieces = sum(len(Chem.GetMolFrags(m)) > 1 for m in kept)\n",
    "with_selenium = sum(any(a.GetSymbol() == \"Se\" for a in m.GetAtoms()) for m in kept)\n",
    "print(in_pieces, \"kept records are in more than one piece\")\n",
    "print(with_selenium, \"kept records contain selenium\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Two failures at once. 166 records disappeared, and nobody can say which or why: a chemist who asks\n",
    "\"where is compound ML-00123456?\" gets no answer. And 251 broken records went through untouched,\n",
    "because RDKit reads a salt or a selenium compound without complaint: they are valid molecules,\n",
    "just not ones this library should store. A gate fixes both: it keeps every record, and it checks\n",
    "more than \"can RDKit read it?\".\n",
    "\n",
    "## 2. Reading a record without losing the reason\n",
    "\n",
    "### Reasons, not True or False\n",
    "\n",
    "A check that answers only True or False tells you *that* a record failed, not *why*, and a\n",
    "quarantine full of \"False\" cannot be acted on. Each of our checks returns a list of **issues**\n",
    "instead: a short, stable **code** that programs can count and filter on, a **message** a chemist\n",
    "can read, and the **action** the gate should take.\n",
    "\n",
    "We describe an issue with a **named tuple**: a small record with named fields, made by writing a\n",
    "`class` based on `NamedTuple`. Each line inside gives a field's name and, after the colon, its\n",
    "type (`str` means text). Once it is defined, `Issue(\"VALENCE\", \"a carbon with five bonds\",\n",
    "\"reject\")` makes one issue, and `issue.code` reads its code back. The text in triple quotes is a\n",
    "**docstring**, a short description of what the code is for."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Issue(NamedTuple):\n",
    "    \"\"\"One problem found in a record: what it is, in words, and what to do about it.\"\"\"\n",
    "\n",
    "    code: str  # a short, stable reason code, e.g. \"VALENCE\"\n",
    "    message: str  # what a person needs to know to act on it\n",
    "    action: str  # \"reject\" (cannot be repaired), \"fix\" (Module 7 repairs it) or \"warn\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The three actions are a policy, and writing them down makes the policy visible. **Reject** means\n",
    "the record cannot be repaired automatically: someone has to go back to the source. **Fix** means\n",
    "a standard repair exists (stripping a salt, neutralising a charge), which Module 7 applies; until\n",
    "then the record waits in quarantine. **Warn** means the record is stored, with the issue recorded\n",
    "beside it.\n",
    "\n",
    "### Capturing RDKit's messages\n",
    "\n",
    "When RDKit cannot read a SMILES it returns `None` (Python's word for \"nothing\") and writes its\n",
    "reason to a log, a stream of messages that normally appears on the screen. We send that log\n",
    "to Python's `logging` module, the same system our own `log` uses, and collect the messages, so each\n",
    "record keeps its own.\n",
    "\n",
    "This is the hardest code in the module, so here is the idea first. Every message goes to a\n",
    "**logger**, and every logger can have its own **handlers**, which decide where its messages go.\n",
    "`logging.basicConfig` in the Setup block gave the **root logger** (the one every other logger\n",
    "passes its messages on to) one handler, which writes our pipeline's lines to the screen.\n",
    "RDKit's messages go to a logger named `\"rdkit\"`, and we give it a different handler: one that\n",
    "keeps each message in a list until the gate reads it. Setting `propagate = False` stops the same\n",
    "messages also reaching the root logger's screen handler, so a reason is recorded with its record\n",
    "instead of scrolling past.\n",
    "\n",
    "Our handler, `Collector`, is a class built on `logging.Handler`, so it can do everything a handler\n",
    "does; we only change two things. `__init__` runs once when the collector is made and gives it an\n",
    "empty list, `messages` (`super().__init__()` first lets `logging.Handler` set itself up).\n",
    "`emit` runs for every message and adds it to that list. RDKit starts each message with the time,\n",
    "such as `[14:02:57] `, which would make the lesson's output change on every run, so `re.sub`\n",
    "removes it: the regular expression `^\\[\\d\\d:\\d\\d:\\d\\d\\] ` means \"at the start (`^`), a square\n",
    "bracket, two digits (`\\d\\d`), a colon, two digits, a colon, two digits, a closing bracket and a\n",
    "space\". The `r` before the quotes keeps Python from reading the backslashes itself:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Collector(logging.Handler):\n",
    "    \"\"\"Keeps RDKit's log messages, without their timestamps, until they are read.\"\"\"\n",
    "\n",
    "    def __init__(self) -> None:\n",
    "        \"\"\"Start with no messages.\"\"\"\n",
    "        super().__init__()\n",
    "        self.messages: list[str] = []\n",
    "\n",
    "    def emit(self, record: logging.LogRecord) -> None:\n",
    "        \"\"\"Keep one message, with RDKit's \"[hh:mm:ss] \" prefix removed.\"\"\"\n",
    "        text = re.sub(r\"^\\[\\d\\d:\\d\\d:\\d\\d\\] \", \"\", record.getMessage()).strip()\n",
    "        self.messages.append(text)\n",
    "\n",
    "\n",
    "rdBase.LogToPythonLogger()\n",
    "collector = Collector()\n",
    "rdkit_log = logging.getLogger(\"rdkit\")\n",
    "rdkit_log.handlers = [collector]  # replace RDKit's own handler, which prints to the screen\n",
    "rdkit_log.propagate = False  # keep RDKit's messages away from our screen handler"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Reading happens in two steps. `Chem.MolFromSmiles(s, sanitize=False)` only checks the syntax: a\n",
    "ring that is never closed, or a stray bracket, fails here. **Sanitisation** then checks the\n",
    "chemistry: valences, aromaticity, ring perception (the RDKit Book lists every step).\n",
    "`Chem.DetectChemistryProblems` runs those checks and returns every problem it finds, each with a\n",
    "type and a message, instead of stopping at the first (`Chem.SanitizeMol(mol, catchErrors=True)`\n",
    "is the other way to do it, but reports only the first failure). An **aromaticity** problem\n",
    "(code `AROMATICITY`) means RDKit cannot draw the ring with alternating single and double bonds,\n",
    "which RDKit calls **kekulizing** it: a five-carbon ring written in lower case is one example.\n",
    "\n",
    "`PROBLEM_CODES` is a dictionary from RDKit's name for a problem to our short code, and\n",
    "`PROBLEM_CODES.get(name, \"SANITISATION\")` uses `\"SANITISATION\"` for any problem not in it. In\n",
    "`parse`, the type hint `tuple[Chem.Mol | None, list[Issue]]` says that it returns two things: a\n",
    "molecule or `None`, and a list of issues. `\"; \".join(...)` joins RDKit's messages into one line,\n",
    "and `or` gives a plain message when RDKit wrote none."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "ethanol: read\n",
      "unclosed ring: not read\n",
      "    PARSE: SMILES Parse Error: unclosed ring for input: 'c1ccccc'\n",
      "five-bond carbon: not read\n",
      "    VALENCE: Explicit valence for atom # 0 C, 5, is greater than permitted\n",
      "five-atom aromatic ring: not read\n",
      "    AROMATICITY: Can't kekulize mol.  Unkekulized atoms: 0 1 2 3 4\n"
     ]
    }
   ],
   "source": [
    "PROBLEM_CODES = {\n",
    "    \"AtomValenceException\": \"VALENCE\",\n",
    "    \"AtomKekulizeException\": \"AROMATICITY\",\n",
    "    \"KekulizeException\": \"AROMATICITY\",\n",
    "}\n",
    "\n",
    "\n",
    "def parse(smiles: str) -> tuple[Chem.Mol | None, list[Issue]]:\n",
    "    \"\"\"Read a SMILES and sanitise it, keeping RDKit's reasons when either step fails.\n",
    "\n",
    "    Returns the sanitised molecule (or None) and a list of issues.\n",
    "    \"\"\"\n",
    "    collector.messages.clear()\n",
    "    mol = Chem.MolFromSmiles(smiles, sanitize=False)\n",
    "    if mol is None:\n",
    "        message = \"; \".join(collector.messages) or \"the SMILES could not be read\"\n",
    "        return None, [Issue(\"PARSE\", message, \"reject\")]\n",
    "    problems = Chem.DetectChemistryProblems(mol)\n",
    "    if problems:\n",
    "        issues = [\n",
    "            Issue(PROBLEM_CODES.get(p.GetType(), \"SANITISATION\"), p.Message(), \"reject\")\n",
    "            for p in problems\n",
    "        ]\n",
    "        return None, issues\n",
    "    Chem.SanitizeMol(mol)\n",
    "    return mol, []\n",
    "\n",
    "\n",
    "examples = {\n",
    "    \"ethanol\": \"CCO\",\n",
    "    \"unclosed ring\": \"c1ccccc\",\n",
    "    \"five-bond carbon\": \"C(C)(C)(C)(C)C\",\n",
    "    \"five-atom aromatic ring\": \"c1cccc1\",\n",
    "}\n",
    "for name, smiles in examples.items():\n",
    "    mol, issues = parse(smiles)\n",
    "    print(f\"{name}: {'read' if mol else 'not read'}\")\n",
    "    for issue in issues:\n",
    "        print(f\"    {issue.code}: {issue.message}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every failure now carries RDKit's own words, which point to the atom at fault.\n",
    "\n",
    "### Turning RDKit's messages down, or off\n",
    "\n",
    "*This part is optional: it is reference material for when RDKit's messages get in your way. Skip\n",
    "to [section 3](#3-checks-on-a-molecule-that-can-be-read) on a first reading: nothing later in the\n",
    "course depends on it beyond `RDLogger.DisableLog`, which section 1 already showed.*\n",
    "\n",
    "Silencing RDKit was the first script's mistake, but some messages really are noise: a pipeline\n",
    "that has recorded a parse failure as an issue does not need it on the screen as well, and a\n",
    "standardiser (the tool of Module 7, which redraws molecules in one standard way) can write several\n",
    "lines of chatter per molecule. RDKit gives you five controls, from the bluntest to the most\n",
    "precise. To see what each one lets through, `heard` runs some code and returns what reached our\n",
    "collector. It takes a function as its input (the hint `Callable[[], object]` means \"a function\n",
    "called with no inputs\"), and `two_problems` is the function we give it. In the `print`, the `*`\n",
    "in front of `heard(...)` passes each message as a separate value, and `sep=\"\\n    \"` puts each one\n",
    "on its own indented line:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "everything on:\n",
      "    SMILES Parse Error: unclosed ring for input: 'c1ccccc'\n",
      "    WARNING: not removing hydrogen atom without neighbors\n"
     ]
    }
   ],
   "source": [
    "def heard(action: Callable[[], object]) -> list[str]:\n",
    "    \"\"\"Run some RDKit code and return the messages that reached the collector.\"\"\"\n",
    "    collector.messages.clear()\n",
    "    action()\n",
    "    return collector.messages.copy()\n",
    "\n",
    "\n",
    "def two_problems() -> None:\n",
    "    \"\"\"Read one SMILES that fails (an error) and one with a lone hydrogen (a warning).\"\"\"\n",
    "    Chem.MolFromSmiles(\"c1ccccc\")\n",
    "    Chem.MolFromSmiles(\"C.[H]\")\n",
    "\n",
    "\n",
    "print(\"everything on:\", *heard(two_problems), sep=\"\\n    \")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "RDKit sorts its messages into four channels, `rdApp.debug`, `rdApp.info`, `rdApp.warning` and\n",
    "`rdApp.error`, and `LogToPythonLogger` delivers them to the `\"rdkit\"` logger at the matching\n",
    "`logging` level. The first two controls work in RDKit itself, before a message is made, so they\n",
    "apply to every handler at once. The second uses a `with` block: the setting applies to the\n",
    "indented lines under `with` and is undone automatically when they finish, even if they fail:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "warnings off:\n",
      "    SMILES Parse Error: unclosed ring for input: 'c1ccccc'\n",
      "inside BlockLogs: []\n",
      "after BlockLogs: 2 messages\n"
     ]
    }
   ],
   "source": [
    "# 1. one channel off, here the warnings, then on again\n",
    "RDLogger.DisableLog(\"rdApp.warning\")\n",
    "print(\"warnings off:\", *heard(two_problems), sep=\"\\n    \")\n",
    "RDLogger.EnableLog(\"rdApp.warning\")\n",
    "\n",
    "# 2. everything off, but only inside the with block: the rest of the program is untouched\n",
    "with rdBase.BlockLogs():\n",
    "    print(\"inside BlockLogs:\", heard(two_problems))\n",
    "print(\"after BlockLogs:\", len(heard(two_problems)), \"messages\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The next two work in Python's `logging`, after the message is made, so different destinations can\n",
    "get different amounts: here the collector keeps every message and a file only the errors. A\n",
    "`FileHandler` is a handler that writes messages to a file, here `work/rdkit.log`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "logger at ERROR:\n",
      "    SMILES Parse Error: unclosed ring for input: 'c1ccccc'\n",
      "collector: 2 messages\n",
      "rdkit.log: SMILES Parse Error: unclosed ring for input: 'c1ccccc'\n"
     ]
    }
   ],
   "source": [
    "# 3. a level on RDKit's logger: here only errors and worse pass\n",
    "rdkit_log.setLevel(logging.ERROR)\n",
    "print(\"logger at ERROR:\", *heard(two_problems), sep=\"\\n    \")\n",
    "rdkit_log.setLevel(logging.WARNING)  # back to RDKit's default: warnings and errors\n",
    "\n",
    "# 4. a level on one handler: the collector keeps everything, a file handler only errors\n",
    "to_file = logging.FileHandler(WORK / \"rdkit.log\", mode=\"w\", encoding=\"utf-8\")\n",
    "to_file.setLevel(logging.ERROR)\n",
    "rdkit_log.addHandler(to_file)\n",
    "print(\"collector:\", len(heard(two_problems)), \"messages\")\n",
    "rdkit_log.removeHandler(to_file)\n",
    "to_file.close()\n",
    "logged = (WORK / \"rdkit.log\").read_text(encoding=\"utf-8\").strip()\n",
    "print(\"rdkit.log:\", re.sub(r\"^\\[\\d\\d:\\d\\d:\\d\\d\\] \", \"\", logged))  # without the time"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The fifth is the one most scripts use, and the one section 1 showed going wrong:\n",
    "`RDLogger.DisableLog(\"rdApp.*\")` switches every channel off for the whole program, until something\n",
    "switches them on again. Use it only where the reason for every failure is recorded some other way,\n",
    "as the later modules of this course do once they keep issues like ours. Two more things to know:\n",
    "the settings belong to one process, so worker processes (Module 9) need them set in each worker;\n",
    "and RDKit's logger starts at `WARNING`, which is why the info channel's chatter (a standardiser\n",
    "reporting each step) is not seen until you lower the level to `INFO`.\n",
    "\n",
    "## 3. Checks on a molecule that can be read\n",
    "\n",
    "A molecule that RDKit reads may still be wrong for the library. Each check below looks at one\n",
    "property, returns a list of issues (empty when all is well), and is short enough to read in full.\n",
    "\n",
    "### Elements\n",
    "\n",
    "A drug-like screening library contains a handful of elements. An **allow-list** names them\n",
    "(`ALLOWED_ELEMENTS`, set in the Setup block); anything else is either a mistake or a compound the\n",
    "library should not hold. An allow-list is safer than a list of forbidden elements, because it\n",
    "rejects what nobody thought of. The check makes a set of the molecule's element symbols and\n",
    "subtracts the allowed set with `-`, which leaves only the elements that are not allowed:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "[]\n",
      "[Issue(code='ELEMENT', message='element not allowed: Se', action='reject')]\n"
     ]
    }
   ],
   "source": [
    "def check_elements(mol: Chem.Mol) -> list[Issue]:\n",
    "    \"\"\"Elements outside the allow-list.\"\"\"\n",
    "    found = sorted({atom.GetSymbol() for atom in mol.GetAtoms()} - ALLOWED_ELEMENTS)\n",
    "    if not found:\n",
    "        return []\n",
    "    return [Issue(\"ELEMENT\", f\"element not allowed: {', '.join(found)}\", \"reject\")]\n",
    "\n",
    "\n",
    "print(check_elements(Chem.MolFromSmiles(\"CC(=O)Oc1ccccc1C(=O)O\")))\n",
    "print(check_elements(Chem.MolFromSmiles(\"C[Se]c1ccccc1\")))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Fragments: salts, solvents and mixtures\n",
    "\n",
    "A record in more than one piece holds more than one molecule; in SMILES the pieces are separated by\n",
    "a full stop, as in `CC(=O)[O-].[Na+]`. Module 1 found the pieces of sodium\n",
    "acetate from the graph Laplacian; RDKit's `GetMolFrags` gives the same answer directly. What to do\n",
    "depends on what the extra pieces are. A counter-ion or a solvent can be stripped to leave one\n",
    "parent compound (Module 7 does it), so those are fixable. Two drug-sized pieces are a **mixture**:\n",
    "no rule can say which one was tested, so the record is rejected. Real pipelines keep lists of\n",
    "known salts and solvents for this; ours, `SALTS` and `SOLVENTS` in the Setup block, are short\n",
    "(six counter-ions and five solvents, each with its name).\n",
    "\n",
    "The check writes each piece as a canonical SMILES (Module 2), so a piece can be looked up in\n",
    "`SALTS` and `SOLVENTS` however the record wrote it. To find the largest piece it uses\n",
    "`max(pieces, key=...)`, which picks the item with the highest value of the `key`. The key is a\n",
    "**lambda**, a one-line function without a name: `lambda s: ...GetNumHeavyAtoms()` takes a SMILES\n",
    "`s` and returns its number of heavy atoms. In the `print`, `{name:22}` pads the name to 22\n",
    "characters:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "sodium acetate         SALT: counter-ion [Na+] (sodium) -> fix\n",
      "phenol hydrate         SOLVENT: solvent O (water) -> fix\n",
      "triethylamine HCl      SALT: counter-ion Cl (hydrogen chloride) -> fix\n",
      "aspirin + paracetamol  MIXTURE: a second compound: CC(=O)Nc1ccc(O)cc1 -> reject\n",
      "benzene + ethanol      SOLVENT: solvent CCO (ethanol) -> fix\n"
     ]
    }
   ],
   "source": [
    "def check_fragments(mol: Chem.Mol) -> list[Issue]:\n",
    "    \"\"\"More than one molecule in the record: salts and solvents (fixable) or a mixture.\"\"\"\n",
    "    pieces = sorted(Chem.MolToSmiles(f) for f in Chem.GetMolFrags(mol, asMols=True))\n",
    "    if len(pieces) == 1:\n",
    "        return []\n",
    "    largest = max(pieces, key=lambda s: Chem.MolFromSmiles(s).GetNumHeavyAtoms())\n",
    "    issues = []\n",
    "    for piece in pieces:\n",
    "        if piece == largest:\n",
    "            continue\n",
    "        if piece in SALTS:\n",
    "            issues.append(Issue(\"SALT\", f\"counter-ion {piece} ({SALTS[piece]})\", \"fix\"))\n",
    "        elif piece in SOLVENTS:\n",
    "            issues.append(Issue(\"SOLVENT\", f\"solvent {piece} ({SOLVENTS[piece]})\", \"fix\"))\n",
    "        else:\n",
    "            issues.append(Issue(\"MIXTURE\", f\"a second compound: {piece}\", \"reject\"))\n",
    "    return issues\n",
    "\n",
    "\n",
    "records = {\n",
    "    \"sodium acetate\": \"CC(=O)[O-].[Na+]\",\n",
    "    \"phenol hydrate\": \"c1ccccc1O.O\",\n",
    "    \"triethylamine HCl\": \"CCN(CC)CC.Cl\",\n",
    "    \"aspirin + paracetamol\": \"CC(=O)Oc1ccccc1C(=O)O.CC(=O)Nc1ccc(O)cc1\",\n",
    "    \"benzene + ethanol\": \"c1ccccc1.CCO\",\n",
    "}\n",
    "for name, smiles in records.items():\n",
    "    for issue in check_fragments(Chem.MolFromSmiles(smiles)):\n",
    "        print(f\"{name:22} {issue.code}: {issue.message} -> {issue.action}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The last record shows the limit of a list. Ethanol is on the solvent list and benzene is the larger\n",
    "piece, so the record is read as benzene with ethanol as its solvent. For a solvate that would be\n",
    "right; for a bottle of a benzene and ethanol mixture it is wrong, and no rule can tell the two\n",
    "apart from the structure alone. Lists like these need a person to own them.\n",
    "\n",
    "### Charges\n",
    "\n",
    "A record with a net charge is either half of a salt (the other half is missing) or a charged form\n",
    "of a neutral compound, such as a protonated amine. Both can usually be neutralised (Module 7).\n",
    "Charges that cancel inside the molecule are different: a nitro group is written with a `+` and a\n",
    "`-` in RDKit, and a zwitterionic amino acid has both. We flag only a net charge, the sum of the\n",
    "formal charges on all atoms. In the message, `{net:+d}` writes the whole number with its sign\n",
    "(`+1`, `-1`):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "C[N+](=O)[O-]      []\n",
      "[NH3+]CC(=O)[O-]   []\n",
      "CC[NH3+]           [Issue(code='CHARGE', message='net charge +1', action='fix')]\n",
      "CC(=O)[O-]         [Issue(code='CHARGE', message='net charge -1', action='fix')]\n"
     ]
    }
   ],
   "source": [
    "def check_charge(mol: Chem.Mol) -> list[Issue]:\n",
    "    \"\"\"A net formal charge on the record (charges that cancel, as in nitro groups, are fine).\"\"\"\n",
    "    net = Chem.GetFormalCharge(mol)\n",
    "    if net == 0:\n",
    "        return []\n",
    "    return [Issue(\"CHARGE\", f\"net charge {net:+d}\", \"fix\")]\n",
    "\n",
    "\n",
    "for smiles in [\"C[N+](=O)[O-]\", \"[NH3+]CC(=O)[O-]\", \"CC[NH3+]\", \"CC(=O)[O-]\"]:\n",
    "    print(f\"{smiles:18} {check_charge(Chem.MolFromSmiles(smiles))}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Stereochemistry\n",
    "\n",
    "Module 2 showed that the two enantiomers of ibuprofen are different molecules. A record that has a\n",
    "stereocentre but does not say which way round it is (a racemate, or simply missing information)\n",
    "cannot be told apart from either enantiomer. `Chem.FindPotentialStereo` lists every atom and double\n",
    "bond that could carry stereochemistry and whether the record specifies it. The list comprehension\n",
    "keeps only the entries whose `specified` is `Unspecified`; the rest of the check counts how many of\n",
    "those are stereocentres (tetrahedral atoms) and how many are double bonds:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "CC(C)Cc1ccc(cc1)[C@H](C)C(=O)O   []\n",
      "CC(C)Cc1ccc(cc1)C(C)C(=O)O       [Issue(code='STEREO', message='unassigned: 1 stereocentre(s), 0 double bond(s)', action='warn')]\n",
      "CC=CC                            [Issue(code='STEREO', message='unassigned: 0 stereocentre(s), 1 double bond(s)', action='warn')]\n"
     ]
    }
   ],
   "source": [
    "def check_stereo(mol: Chem.Mol) -> list[Issue]:\n",
    "    \"\"\"Stereocentres and double bonds whose configuration the record does not give.\"\"\"\n",
    "    missing = [\n",
    "        info\n",
    "        for info in Chem.FindPotentialStereo(mol)\n",
    "        if info.specified == Chem.StereoSpecified.Unspecified\n",
    "    ]\n",
    "    if not missing:\n",
    "        return []\n",
    "    centres = sum(info.type == Chem.StereoType.Atom_Tetrahedral for info in missing)\n",
    "    bonds = len(missing) - centres\n",
    "    return [Issue(\"STEREO\", f\"unassigned: {centres} stereocentre(s), {bonds} double bond(s)\",\n",
    "                  \"warn\")]  # fmt: skip\n",
    "\n",
    "\n",
    "for smiles in [\"CC(C)Cc1ccc(cc1)[C@H](C)C(=O)O\", \"CC(C)Cc1ccc(cc1)C(C)C(=O)O\", \"CC=CC\"]:\n",
    "    print(f\"{smiles:32} {check_stereo(Chem.MolFromSmiles(smiles))}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Whether this is a warning or a rejection is a policy decision. A screening library made by\n",
    "combining building blocks is often sold as racemates, so rejecting every unassigned centre would\n",
    "reject much of it; a registration system for a single, purified clinical compound would reject it.\n",
    "Here we warn, and the warning is stored with the record.\n",
    "\n",
    "### Size\n",
    "\n",
    "Size limits catch records that cannot be what the library holds: a lone solvent molecule that lost\n",
    "its compound, a fragment cut off by a broken export, a polymer or peptide in a small-molecule\n",
    "collection. We measure the largest piece, because a counter-ion says nothing about the compound,\n",
    "against the limits `HEAVY_ATOMS` and `MAX_WEIGHT` set in the Setup block. `HEAVY_ATOMS[0]` and\n",
    "`HEAVY_ATOMS[1]` are the two numbers of the tuple (Python counts from 0), and `{weight:.0f}`\n",
    "writes the weight with no decimal places. In the examples, `\"C\" * 60` is sixty carbons in a chain,\n",
    "and `smiles[:24]` shows only its first 24 characters:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "CCO                        [Issue(code='SIZE', message='3 heavy atoms (allowed (6, 50))', action='reject')]\n",
      "CC(=O)Oc1ccccc1C(=O)O      []\n",
      "CCCCCCCCCCCCCCCCCCCCCCCC   [Issue(code='SIZE', message='60 heavy atoms (allowed (6, 50))', action='reject'), Issue(code='WEIGHT', message='molecular weight 844 (max 700)', action='reject')]\n",
      "heavy atoms in the clean library: 14 to 39\n"
     ]
    }
   ],
   "source": [
    "def check_size(mol: Chem.Mol) -> list[Issue]:\n",
    "    \"\"\"The largest piece must be between the heavy-atom limits and below the weight limit.\"\"\"\n",
    "    piece = max(Chem.GetMolFrags(mol, asMols=True), key=lambda f: f.GetNumHeavyAtoms())\n",
    "    heavy = piece.GetNumHeavyAtoms()\n",
    "    weight = Descriptors.MolWt(piece)\n",
    "    issues = []\n",
    "    if not HEAVY_ATOMS[0] <= heavy <= HEAVY_ATOMS[1]:\n",
    "        issues.append(Issue(\"SIZE\", f\"{heavy} heavy atoms (allowed {HEAVY_ATOMS})\", \"reject\"))\n",
    "    if weight > MAX_WEIGHT:\n",
    "        issues.append(Issue(\"WEIGHT\", f\"molecular weight {weight:.0f} (max {MAX_WEIGHT:.0f})\",\n",
    "                            \"reject\"))  # fmt: skip\n",
    "    return issues\n",
    "\n",
    "\n",
    "for smiles in [\"CCO\", \"CC(=O)Oc1ccccc1C(=O)O\", \"C\" * 60]:\n",
    "    print(f\"{smiles[:24]:26} {check_size(Chem.MolFromSmiles(smiles))}\")\n",
    "heavy = [Chem.MolFromSmiles(s).GetNumHeavyAtoms() for s in library[\"smiles\"]]\n",
    "print(\"heavy atoms in the clean library:\", min(heavy), \"to\", max(heavy))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The limits are a property of the library, not of chemistry: ours allow every molecule in the clean\n",
    "library, with room to spare. Choose them from the data you expect, and write them down.\n",
    "\n",
    "## 4. The gate\n",
    "\n",
    "The gate runs the parse step and, if the molecule can be read, every check. A record is accepted\n",
    "when it has no issues or only warnings, and quarantined otherwise. The rule fits in two functions.\n",
    "`CHECKS` is a list of the five check functions themselves (written without brackets, so they are\n",
    "not run yet), and `validate` runs each of them in turn on the molecule:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "CC(=O)Oc1ccccc1C(=O)O          accept     []\n",
      "CC(C)Cc1ccc(cc1)C(C)C(=O)O     accept     ['STEREO']\n",
      "CC[NH3+].[Cl-]                 quarantine ['SALT', 'SIZE']\n"
     ]
    }
   ],
   "source": [
    "CHECKS = [check_elements, check_fragments, check_charge, check_stereo, check_size]\n",
    "\n",
    "\n",
    "def validate(smiles: str) -> list[Issue]:\n",
    "    \"\"\"Every issue found in one record: from parsing, or from every check if it can be read.\"\"\"\n",
    "    mol, issues = parse(smiles)\n",
    "    if mol is None:\n",
    "        return issues\n",
    "    for check in CHECKS:\n",
    "        issues = issues + check(mol)\n",
    "    return issues\n",
    "\n",
    "\n",
    "def verdict(issues: list[Issue]) -> str:\n",
    "    \"\"\"Accept a record with no issues or only warnings; quarantine everything else.\"\"\"\n",
    "    blocking = [i for i in issues if i.action != \"warn\"]\n",
    "    return \"quarantine\" if blocking else \"accept\"\n",
    "\n",
    "\n",
    "for smiles in [\"CC(=O)Oc1ccccc1C(=O)O\", \"CC(C)Cc1ccc(cc1)C(C)C(=O)O\", \"CC[NH3+].[Cl-]\"]:\n",
    "    issues = validate(smiles)\n",
    "    print(f\"{smiles:30} {verdict(issues):10} {[i.code for i in issues]}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The ethylammonium chloride record shows why every issue is kept rather than only the first: it is a\n",
    "salt, and also too small for this library. A chemist fixing the record at its source needs both.\n",
    "\n",
    "![The validation gate. Every record is read and sanitised; records that cannot be read are quarantined with RDKit's reason. Readable records go through five checks, each adding issues with a code, a message and an action. Records with no issues, or only warnings, are accepted; the rest are quarantined, and those whose issues are all fixable go on to standardisation in Module 7](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/06-validating-molecules/figures/validation-gate.svg)\n",
    "\n",
    "Now the whole library. Each record gets its issues, its codes and its verdict, in new columns\n",
    "beside the original data, so nothing about the record is lost. This is the step a nightly job\n",
    "would run unattended, so it reports with `log`, and the quarantine count is a warning: it is the\n",
    "number someone should look at in the morning. The `assert` line stops the program with an error if\n",
    "its condition is False; here it guards against the gate ever losing a record:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO validated 10083 records: 9666 accepted\n",
      "WARNING quarantined 417 records\n"
     ]
    }
   ],
   "source": [
    "results = dirty.copy()\n",
    "results[\"issues\"] = [validate(s) for s in results[\"smiles\"]]\n",
    "results[\"codes\"] = [\";\".join(i.code for i in issues) for issues in results[\"issues\"]]\n",
    "results[\"verdict\"] = [verdict(issues) for issues in results[\"issues\"]]\n",
    "assert len(results) == len(dirty), \"every record leaves the gate\"\n",
    "n_quarantined = int((results[\"verdict\"] == \"quarantine\").sum())\n",
    "log.info(\"validated %d records: %d accepted\", len(results), len(results) - n_quarantined)\n",
    "log.warning(\"quarantined %d records\", n_quarantined)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The assertion is the point of the whole module: every one of the 10,083 records came out, either\n",
    "accepted or quarantined. The **quarantine table** has one row per issue, so it can be filtered,\n",
    "counted and handed to whoever fixes the source. The code is one chain of pandas steps, read from\n",
    "top to bottom: keep the quarantined rows; `explode` turns a row with two issues into two rows with\n",
    "one issue each; `assign` adds columns for the code, message and action of each issue (each\n",
    "`lambda t:` receives the table so far); then the wanted columns are kept, the rows are sorted and\n",
    "renumbered:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "541 issues on 417 quarantined records\n",
      "         id    code                                                      message\n",
      "ML-00006917 VALENCE Explicit valence for atom # 0 C, 5, is greater than permi...\n",
      "ML-00007690   PARSE SMILES Parse Error: unclosed ring for input: 'ccc(O)c(cc1...\n",
      "ML-00009561 VALENCE Explicit valence for atom # 0 C, 5, is greater than permi...\n",
      "ML-00015388   PARSE SMILES Parse Error: unclosed ring for input: 'ccc(c8cn[nH...\n",
      "ML-00021654 SOLVENT                                        solvent CCO (ethanol)\n",
      "ML-00027465    SALT                           counter-ion Cl (hydrogen chloride)\n"
     ]
    }
   ],
   "source": [
    "quarantine = (\n",
    "    results[results[\"verdict\"] == \"quarantine\"]\n",
    "    .explode(\"issues\")\n",
    "    .assign(\n",
    "        code=lambda t: [i.code for i in t[\"issues\"]],\n",
    "        message=lambda t: [i.message for i in t[\"issues\"]],\n",
    "        action=lambda t: [i.action for i in t[\"issues\"]],\n",
    "    )[[\"id\", \"smiles\", \"code\", \"message\", \"action\"]]\n",
    "    .sort_values([\"id\", \"code\"])\n",
    "    .reset_index(drop=True)\n",
    ")\n",
    "print(len(quarantine), \"issues on\", quarantine[\"id\"].nunique(), \"quarantined records\")\n",
    "print(quarantine[[\"id\", \"code\", \"message\"]].head(6).to_string(index=False, max_colwidth=60))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The **summary by reason** is what a team reviews each day: which faults arrive, how often, and\n",
    "which can be repaired. It counts records, not issues, over the whole library, so warnings on\n",
    "accepted records appear too. A `Counter` (from the standard library's `collections`, imported in\n",
    "the Setup block) is made for this: it is a dictionary that starts every count at zero, so each\n",
    "record simply adds one to each of its reasons. Taking the reasons of a record as a set first means\n",
    "a record with two issues of one kind is counted once:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "   code action  records\n",
      " STEREO   warn     4805\n",
      "   SALT    fix       84\n",
      "SOLVENT    fix       84\n",
      "ELEMENT reject       83\n",
      "  PARSE reject       83\n",
      "VALENCE reject       83\n"
     ]
    }
   ],
   "source": [
    "records_per_reason = Counter()\n",
    "for issues in results[\"issues\"]:\n",
    "    records_per_reason.update({(i.code, i.action) for i in issues})\n",
    "summary = pd.DataFrame(\n",
    "    [(code, action, n) for (code, action), n in records_per_reason.items()],\n",
    "    columns=[\"code\", \"action\", \"records\"],\n",
    ").sort_values([\"records\", \"code\"], ascending=[False, True])\n",
    "print(summary.to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![Records per reason code in the dirty library, coloured by the action each reason calls for. Unassigned stereochemistry, a warning, is by far the most common; the five blocking reasons each affect 83 or 84 records](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/06-validating-molecules/figures/reasons.svg)\n",
    "\n",
    "Two things stand out. Nearly half the records (4,805 of 10,083) have at least one unassigned\n",
    "stereocentre or double bond: `chemlib` writes no stereochemistry, like many enumerated libraries,\n",
    "so this is a fact about the source rather than a fault in individual records, and it is exactly\n",
    "why it is a warning. And no record was flagged for a net charge, a mixture or its size: the\n",
    "damaged library contains none (every salt `add_defects` wrote with this seed is a hydrochloride,\n",
    "`.Cl`, which is neutral). Those checks are still worth running: the next vendor's file may be\n",
    "full of them, and section 3 showed each one working.\n",
    "\n",
    "Accepted records and the quarantine are written out side by side, as Parquet files (Module 3) in\n",
    "the `work` folder. The issues are stored as their codes and messages, plain text that any tool can\n",
    "read:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO wrote 9666 accepted records to work/accepted.parquet\n",
      "INFO wrote 541 issues on 417 quarantined records to work/quarantine.parquet\n"
     ]
    }
   ],
   "source": [
    "accepted = results[results[\"verdict\"] == \"accept\"].drop(columns=[\"issues\"])\n",
    "accepted_path = WORK / \"accepted.parquet\"\n",
    "quarantine_path = WORK / \"quarantine.parquet\"\n",
    "accepted.to_parquet(accepted_path, index=False)\n",
    "quarantine.to_parquet(quarantine_path, index=False)\n",
    "n_quarantined = quarantine[\"id\"].nunique()\n",
    "assert len(accepted) + n_quarantined == len(dirty), \"every record is in one file or the other\"\n",
    "log.info(\"wrote %d accepted records to %s\", len(accepted), accepted_path.as_posix())\n",
    "log.info(\"wrote %d issues on %d quarantined records to %s\", len(quarantine), n_quarantined,\n",
    "         quarantine_path.as_posix())  # fmt: skip"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Checks across records: duplicates\n",
    "\n",
    "Every check so far looks at one record at a time. A duplicate is different: it is a perfectly good\n",
    "record whose molecule is already in the table, so no record-level check can see it. It takes a\n",
    "check across records, on identity. As in Module 3, the InChIKey is the identity: two records with\n",
    "the same key are the same molecule, however their SMILES are written. We keep the first record (by\n",
    "id) and flag the rest, with a pointer to the record they repeat. After sorting by id,\n",
    "`groupby(\"inchikey\")[\"id\"].transform(\"first\")` gives every row the id of the first record with\n",
    "the same InChIKey; a row whose own id is different is a repeat:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "109 accepted records repeat an earlier one\n",
      "             id     repeats    defect\n",
      "ML-00057592-dup ML-00057592 duplicate\n",
      "ML-00073568-dup ML-00073568 duplicate\n",
      "ML-00075590-dup ML-00075590 duplicate\n"
     ]
    }
   ],
   "source": [
    "readable = results[results[\"verdict\"] == \"accept\"].copy()\n",
    "readable[\"inchikey\"] = [Chem.MolToInchiKey(Chem.MolFromSmiles(s)) for s in readable[\"smiles\"]]\n",
    "readable = readable.sort_values(\"id\")\n",
    "first_id = readable.groupby(\"inchikey\")[\"id\"].transform(\"first\")\n",
    "repeats = readable[readable[\"id\"] != first_id]\n",
    "print(len(repeats), \"accepted records repeat an earlier one\")\n",
    "print(repeats.assign(repeats=first_id)[[\"id\", \"repeats\", \"defect\"]].head(3).to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There were 83 duplicates on record, so where do the other 26 come from? They are in the library\n",
    "itself. As the `chemlib` documentation says, a few combinations of scaffold and substituents give\n",
    "the same molecule by symmetry (a 3,5-disubstituted benzene with the two groups swapped is the same\n",
    "compound), just as in real enumerated libraries. The validator found real duplicates that the\n",
    "record of defects never listed.\n",
    "\n",
    "Flagging, not deleting, is deliberate: two records of one molecule may carry different prices or\n",
    "assay results, and merging them is a decision for the next stage. Duplicates also hide behind\n",
    "salts and charges (the hydrochloride and the free base have different InChIKeys); Module 7 finds\n",
    "those after standardisation.\n",
    "\n",
    "## 6. Checking the validator against the truth\n",
    "\n",
    "A validator is software, and software is tested. Because `chemlib` recorded every fault it made,\n",
    "we can compare the validator's verdicts with the truth. A **confusion table** puts the true fault in\n",
    "the rows and the verdict in the columns, and counts the records in each cell; pandas makes one with\n",
    "`pd.crosstab`. First we add an outcome column that marks the duplicates found in section 5:\n",
    "`isin` tests whether each id is in the list of repeats, and `.where(~flag, \"accept, duplicate\")`\n",
    "keeps the verdict where the flag is False (`~` means \"not\") and writes the new label where it is\n",
    "True:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "outcome    accept  accept, duplicate  quarantine\n",
      "defect                                          \n",
      "(none)       9557                 26           0\n",
      "duplicate       0                 83           0\n",
      "element         0                  0          83\n",
      "invalid         0                  0          83\n",
      "salt            0                  0          84\n",
      "solvent         0                  0          84\n",
      "valence         0                  0          83\n"
     ]
    }
   ],
   "source": [
    "results[\"duplicate flag\"] = results[\"id\"].isin(repeats[\"id\"])\n",
    "results[\"outcome\"] = results[\"verdict\"].where(~results[\"duplicate flag\"], \"accept, duplicate\")\n",
    "truth = results[\"defect\"].replace(\"\", \"(none)\")\n",
    "print(pd.crosstab(truth, results[\"outcome\"]).to_string())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Read it row by row. Every invalid, valence, element, salt and solvent record was quarantined\n",
    "(caught: 417 of 417), and no clean record was quarantined (no false alarms). Every duplicate on\n",
    "record was flagged (83 of 83), and nothing was missed. The 26 clean records flagged as duplicates\n",
    "look like false alarms in this table, but section 5 showed they are real: the record of truth is\n",
    "incomplete, not the validator. That is the usual situation with real data, and the reason a\n",
    "disagreement between a validator and a \"truth\" is investigated, never just counted.\n",
    "\n",
    "A perfect score on faults we planted ourselves proves less than it seems. The validator was written\n",
    "knowing what `add_defects` does; a new source will bring faults nobody planned for. The table is a\n",
    "**regression test**, a test that checks a change to the code has not broken something that used to\n",
    "work: it must stay perfect when the code changes.\n",
    "\n",
    "Which reason codes did each kind of fault produce? This is where a validator's behaviour is\n",
    "understood, not just scored. The `codes` column holds the codes of a record joined by `;`, so we\n",
    "split them and `explode` them into one row per code, then line each code up with its record's\n",
    "fault:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "codes    ELEMENT  PARSE  SALT  SOLVENT  STEREO  VALENCE\n",
      "defect                                                 \n",
      "element       83      0     0        0      47        0\n",
      "invalid        0     83     0        0       0        0\n",
      "salt           0      0    84        0      36        0\n",
      "solvent        0      0     0       84      40        0\n",
      "valence        0      0     0        0       0       84\n"
     ]
    }
   ],
   "source": [
    "quarantined = results[results[\"verdict\"] == \"quarantine\"]\n",
    "codes = quarantined[\"codes\"].str.split(\";\").explode()\n",
    "print(pd.crosstab(quarantined[\"defect\"].reindex(codes.index), codes).to_string())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Each fault produced the reason it should, and only that blocking reason. The table counts issues,\n",
    "so two details need explaining. The valence row shows 84 issues for 83 records: one record had its\n",
    "five-bond carbon written in front of a carbonyl oxygen (`C(C)(C)(C)(C)O=C(...`), which gave that\n",
    "oxygen three bonds as well, and `DetectChemistryProblems` reported both atoms. And the stereo\n",
    "warnings on element, salt and solvent records are real too: those molecules have unassigned\n",
    "stereocentres like half the library. The records that failed to parse or sanitise carry no stereo\n",
    "warning, because no further checks can run on a molecule that cannot be read.\n",
    "\n",
    "## 7. From a lesson to a pipeline\n",
    "\n",
    "The gate here checks 10,083 records in about a quarter of a minute on a laptop, one record at a\n",
    "time. The same two functions scale to millions: run them on **batches** (a few thousand records at a\n",
    "time) from `chemlib.stream` (or chunks of a file), write each batch's accepted records and\n",
    "quarantine to Parquet, and spread batches over several processes, which lets a computer use all\n",
    "its processor cores at once (Module 9). Keep the reason codes stable, because dashboards and\n",
    "alerts count them (Module 14), and record the validator's version with its output, so a record\n",
    "quarantined last month can be explained today (Module 13).\n",
    "\n",
    "The ChEMBL database has curated its structures with an open-source pipeline built on RDKit since\n",
    "release 26, the ChEMBL Structure Pipeline (Bento et al., 2020). Its checker returns for each issue a description and\n",
    "a penalty score from 0 to 9 that reflects how serious it is, the same idea as our code, message and\n",
    "action. Module 12 returns to validation for whole records and tables, with Pydantic and Pandera,\n",
    "two Python packages for checking data.\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",
    "- Fourches, D., Muratov, E. & Tropsha, A. (2010). Trust, But Verify: On the Importance of Chemical\n",
    "  Structure Curation in Cheminformatics and QSAR Modeling Research. *Journal of Chemical\n",
    "  Information and Modeling*, 50(7), 1189–1204. <https://doi.org/10.1021/ci100176x>\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",
    "- The ChEMBL Structure Pipeline (source code and documentation, including its checker).\n",
    "  <https://github.com/chembl/ChEMBL_Structure_Pipeline>\n",
    "- The RDKit documentation. *The RDKit Book*, section \"Molecular Sanitization\".\n",
    "  <https://www.rdkit.org/docs/RDKit_Book.html#molecular-sanitization>\n",
    "- Daylight Chemical Information Systems. *Daylight Theory Manual*, chapter on SMILES (valences and\n",
    "  the rules for writing a valid SMILES). <https://www.daylight.com/dayhtml/doc/theory/>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
