{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Chemical files and identity\n",
    "\n",
    "SDF, SMILES, CSV and Parquet compared on one library, read safely at scale, and a stable identity (InChIKey) for every molecule so duplicates can be found.\n",
    "\n",
    "The lesson's page: https://monstrous.com.ng/learn/data-engineering/series-1/03-files-and-identity/"
   ]
  },
  {
   "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 openbabel-wheel\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": [
    "Chemical data moves between people and programs as files. A vendor sends its catalogue as an SDF,\n",
    "a colleague exports hits from a spreadsheet as CSV, a pipeline writes Parquet for the next step.\n",
    "Each format keeps some things and loses others, and each fails in its own way: a record that cannot\n",
    "be read, an ID that loses its leading zeros, a price that arrives as text. Once the molecules are in,\n",
    "you need to know which of them you already have, and that needs an identity that does not depend on\n",
    "how the molecule happened to be written, or on which program wrote it.\n",
    "\n",
    "By the end of this module you will be able to:\n",
    "\n",
    "- write one library of molecules as an SDF, a SMILES file, a CSV and a Parquet file (four file\n",
    "  formats, explained in section 1), and say how big each is and what each keeps;\n",
    "- read a large SDF one record at a time, without loading it all, and keep a list of the records\n",
    "  that cannot be read and why;\n",
    "- avoid the usual mistakes when chemical data goes through a CSV, and keep each column's type\n",
    "  (text, decimal number, whole number) by saving the table as Parquet;\n",
    "- find the same molecule listed twice, even when it is written as two different SMILES, by\n",
    "  comparing InChIKeys;\n",
    "- explain why a molecule's identity must not be one program's canonical SMILES;\n",
    "- check that a file arrived unchanged, with a checksum.\n",
    "\n",
    "This module builds on [Module 2](../02-text-patterns-and-numbers/): SMILES and canonical SMILES\n",
    "(section 1 there), the InChIKey (section 3) and the SDF (section 4). It also uses `log` and `print`\n",
    "as in [Module 1](../01-graphs-and-matrices/#why-log-and-not-print).\n",
    "\n",
    "The lesson uses these packages:\n",
    "\n",
    "- **RDKit**, the chemistry toolkit of Modules 1 and 2, to read and write molecules and SDF files;\n",
    "- **pandas**, for tables, and its readers and writers for CSV and Parquet files;\n",
    "- **PyArrow**, to write Parquet files with column types that we choose;\n",
    "- **Open Babel**, a second open-source chemistry toolkit, to compare with RDKit (section 6);\n",
    "- **chemlib**, a small helper file that comes with this course. It makes the teaching library of\n",
    "  molecules used in the lessons, and the damaged copies of it used to practise on;\n",
    "- a few modules that come with Python itself: `csv` (CSV files), `gzip` (compressed files),\n",
    "  `hashlib` (checksums), `io`, `shutil` and `pathlib` (files and folders), `time` (timing) and\n",
    "  `collections` (counting).\n",
    "\n",
    "Everything here runs in a browser notebook or on any laptop. The files the code writes go into a\n",
    "`work/` folder next to the lesson, which the Setup block creates.\n",
    "\n",
    "## Setup\n",
    "\n",
    "Run this block first. It loads the packages and sets the lesson's settings, written in CAPITALS, so\n",
    "they can be changed in one place. A few things in it may be new:\n",
    "\n",
    "- `Path(\"work\")` is a path to a folder, from `pathlib`. Joining paths uses `/`, so\n",
    "  `WORK / \"library.sdf\"` means the file `library.sdf` inside `work`. The last line,\n",
    "  `WORK.mkdir(exist_ok=True)`, makes the folder, and does nothing if it is already there;\n",
    "- `20_000` is the number 20000: Python ignores the underscore, which is there to make it easy to\n",
    "  read;\n",
    "- `1 << 20` is 2 to the power 20, that is 1,048,576 bytes, one mebibyte (MiB)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import csv\n",
    "import gzip\n",
    "import hashlib\n",
    "import io\n",
    "import logging\n",
    "import shutil\n",
    "import time\n",
    "from collections import Counter\n",
    "from collections.abc import Iterator\n",
    "from pathlib import Path\n",
    "\n",
    "import pandas as pd\n",
    "import pyarrow as pa\n",
    "import pyarrow.parquet as pq\n",
    "from openbabel import pybel\n",
    "from rdkit import Chem, RDLogger\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",
    "# where the lesson writes its files (git-ignored)\n",
    "WORK = Path(\"work\")\n",
    "# the teaching library of sections 1 to 6: its size and seed (same seed, same molecules)\n",
    "LIBRARY_SIZE = 20_000\n",
    "LIBRARY_SEED = 3\n",
    "# the careless vendor's file (section 3): size, seeds, share of damaged records, bytes cut off\n",
    "VENDOR_SIZE = 2_000\n",
    "VENDOR_SEED = 5\n",
    "VENDOR_DEFECT_RATE = 0.05\n",
    "VENDOR_DEFECT_SEED = 6\n",
    "TRUNCATED_BYTES = 300\n",
    "# rows per Parquet row group when streaming an SDF (section 3); larger uses more memory\n",
    "BATCH_SIZE = 5_000\n",
    "# Parquet compression codec (\"zstd\" is small and fast; \"snappy\" is the common default)\n",
    "PARQUET_COMPRESSION = \"zstd\"\n",
    "# the supplier's shipment with added duplicates (section 5)\n",
    "SHIPMENT_SIZE = 3_000\n",
    "SHIPMENT_SEED = 7\n",
    "SHIPMENT_DEFECT_RATE = 0.06\n",
    "SHIPMENT_DEFECT_SEED = 8\n",
    "# how many molecules to compare between RDKit and Open Babel (section 6)\n",
    "TOOLKIT_SAMPLE = 1_000\n",
    "# bytes read at a time when computing a checksum (section 7): 1 MiB\n",
    "CHECKSUM_CHUNK = 1 << 20\n",
    "\n",
    "WORK.mkdir(exist_ok=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. One library, five files\n",
    "\n",
    "We use a teaching library made in code by `chemlib`, the same on every computer: 20,000 molecules,\n",
    "each with an ID, a SMILES and the catalogue data a vendor file carries (vendor, price, stock). The\n",
    "molecules are made the way real screening libraries are: by joining small building blocks onto a\n",
    "few core structures (scaffolds). The `seed` makes the random choices repeatable, as in Module 2:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "         id                                 smiles   vendor  price_usd  stock_mg\n",
      "ML-00000065         c1cc(F)ccc1C(=O)NCc2ccc(CC)cc2 Vendor C     357.35       360\n",
      "ML-00000098     c1cc(OC)ccc1C(=O)NCc2ccc(C(C)C)cc2 Vendor C      84.62       430\n",
      "ML-00000129 c1cc(OCC)ccc1C(=O)NCc2ccc(C(F)(F)F)cc2 Vendor A     134.51       420\n"
     ]
    }
   ],
   "source": [
    "library = chemlib.library(LIBRARY_SIZE, seed=LIBRARY_SEED)\n",
    "print(library.head(3).to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We write it in the four formats of this module, plus the gzipped SDF that vendors usually send.\n",
    "\n",
    "- **SDF** gives each molecule a connection table (atoms with 2D coordinates, then bonds) followed by\n",
    "  its data fields, as in Module 2.\n",
    "- A **SMILES file** (`.smi`) holds one SMILES and one name per line, nothing else.\n",
    "- **CSV** (comma-separated values) is a plain-text table: one row per line, the values separated by\n",
    "  commas. Spreadsheets open and save it.\n",
    "- **Parquet** is a table stored in binary (as raw bytes, not as text you can read) and column by\n",
    "  column. It holds a **schema**, which records each column's name and type; we give the schema\n",
    "  ourselves rather than let a tool guess it.\n",
    "- **gzip** compresses a file (makes it smaller without losing anything), like a zip file; a gzipped\n",
    "  file gets `.gz` added to its name.\n",
    "\n",
    "A few Python features appear in the code for the first time:\n",
    "\n",
    "- `with ... as writer:` opens something (a file, a writer) for the indented lines below it, and\n",
    "  closes it properly when they finish, even if an error stops them;\n",
    "- `df.itertuples(index=False)` goes through a table one row at a time, and `row.smiles` is that\n",
    "  row's value in the `smiles` column;\n",
    "- `mol.SetProp(name, text)` stores a data field on a molecule; the field `_Name` is the record's\n",
    "  first line, its title;\n",
    "- `f\"{row.price_usd:.2f}\"` writes the price with two decimals, and `{size / 1e6:6.2f}` the size in\n",
    "  megabytes (`1e6` is a million) in a space 6 characters wide;\n",
    "- in the schema, `pa.string()` is text, `pa.float64()` a decimal number and `pa.int64()` a whole\n",
    "  number."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "SDF          48.78 MB    2439 bytes per molecule\n",
      "SMILES        1.22 MB      61 bytes per molecule\n",
      "CSV           1.61 MB      80 bytes per molecule\n",
      "Parquet       0.42 MB      21 bytes per molecule\n",
      "SDF (gzip)    1.69 MB      85 bytes per molecule\n"
     ]
    }
   ],
   "source": [
    "def write_sdf(df: pd.DataFrame, path: Path) -> None:\n",
    "    \"\"\"Write a library as SDF: a connection table per molecule, the other columns as data fields.\"\"\"\n",
    "    # RDKit writes into a file we open, with one line ending on every computer\n",
    "    with path.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as handle, Chem.SDWriter(handle) as writer:\n",
    "        for row in df.itertuples(index=False):\n",
    "            mol = Chem.MolFromSmiles(row.smiles)\n",
    "            mol.SetProp(\"_Name\", row.id)  # the first line of the record\n",
    "            mol.SetProp(\"vendor\", row.vendor)\n",
    "            mol.SetProp(\"price_usd\", f\"{row.price_usd:.2f}\")\n",
    "            mol.SetProp(\"stock_mg\", str(row.stock_mg))\n",
    "            writer.write(mol)\n",
    "\n",
    "\n",
    "def write_smi(df: pd.DataFrame, path: Path) -> None:\n",
    "    \"\"\"Write a SMILES file: one SMILES and one name per line.\"\"\"\n",
    "    with path.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as handle:\n",
    "        for row in df.itertuples(index=False):\n",
    "            handle.write(f\"{row.smiles} {row.id}\\n\")\n",
    "\n",
    "\n",
    "def gzip_copy(path: Path) -> Path:\n",
    "    \"\"\"A gzipped copy of a file, as path + '.gz' (mtime=0: the same input gives the same bytes).\"\"\"\n",
    "    target = path.with_name(path.name + \".gz\")\n",
    "    with path.open(\"rb\") as source, gzip.GzipFile(target, \"wb\", mtime=0) as packed:\n",
    "        shutil.copyfileobj(source, packed)\n",
    "    return target\n",
    "\n",
    "\n",
    "SCHEMA = pa.schema(\n",
    "    [\n",
    "        (\"id\", pa.string()),\n",
    "        (\"smiles\", pa.string()),\n",
    "        (\"vendor\", pa.string()),\n",
    "        (\"price_usd\", pa.float64()),\n",
    "        (\"stock_mg\", pa.int64()),\n",
    "    ]\n",
    ")\n",
    "\n",
    "files = {\n",
    "    \"SDF\": WORK / \"library.sdf\",\n",
    "    \"SMILES\": WORK / \"library.smi\",\n",
    "    \"CSV\": WORK / \"library.csv\",\n",
    "    \"Parquet\": WORK / \"library.parquet\",\n",
    "}\n",
    "write_sdf(library, files[\"SDF\"])\n",
    "files[\"SDF (gzip)\"] = gzip_copy(files[\"SDF\"])\n",
    "write_smi(library, files[\"SMILES\"])\n",
    "library.to_csv(files[\"CSV\"], index=False, lineterminator=\"\\n\")  # one line ending on every computer\n",
    "table = pa.Table.from_pandas(library, schema=SCHEMA, preserve_index=False)\n",
    "pq.write_table(table, files[\"Parquet\"], compression=PARQUET_COMPRESSION)\n",
    "\n",
    "for name, path in files.items():\n",
    "    size = path.stat().st_size\n",
    "    print(f\"{name:11} {size / 1e6:6.2f} MB  {size / len(library):6.0f} bytes per molecule\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![Bar chart of the size on disk of the same 20,000 molecules in each format: SDF is far the largest, Parquet the smallest](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/03-files-and-identity/figures/file-sizes.svg)\n",
    "\n",
    "The SDF is more than 40 times the size of the SMILES file, because every atom and bond is a line\n",
    "of text with coordinates, written out in full. Gzip shrinks it almost 30 times, to about the size\n",
    "of the CSV, because those lines repeat so much; this is why vendors send `.sdf.gz`. The CSV is the\n",
    "SMILES file plus the catalogue columns. Parquet is the smallest: it stores each column\n",
    "together, so similar values sit side by side and compress well, and its numbers are stored as\n",
    "binary numbers rather than as text. File sizes are the same every time for the same library and\n",
    "the same versions of RDKit and PyArrow; other versions may differ by a few bytes.\n",
    "\n",
    "Reading each file back into a table takes very different times. The code keeps one reading function\n",
    "per format in a dictionary, times each with `time.perf_counter()` (a stopwatch: the time read before\n",
    "and after), and prints the row count with `{...:,}`, which adds commas to large numbers. Three more\n",
    "features:\n",
    "\n",
    "- `lambda path: ...` is a one-line function without a name, used here to read the SMILES file as a\n",
    "  table whose values are separated by spaces;\n",
    "- `**mol.GetPropsAsDict()` copies all of a molecule's data fields (name and value) into the\n",
    "  dictionary being built;\n",
    "- `opener = gzip.open if ... else open` picks the gzip reader when the file name ends in `.gz`, and\n",
    "  the ordinary one otherwise."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "SDF         11.803 s  20,000 rows\n",
      "SMILES       0.052 s  20,000 rows\n",
      "CSV          0.053 s  20,000 rows\n",
      "Parquet      0.094 s  20,000 rows\n"
     ]
    }
   ],
   "source": [
    "def read_sdf_table(path: Path) -> pd.DataFrame:\n",
    "    \"\"\"Read every record of an SDF (plain or gzipped) into a table of its name and data fields.\"\"\"\n",
    "    opener = gzip.open if path.suffix == \".gz\" else open\n",
    "    rows = []\n",
    "    with opener(path, \"rb\") as handle:\n",
    "        for mol in Chem.ForwardSDMolSupplier(handle):\n",
    "            rows.append({\"id\": mol.GetProp(\"_Name\"), **mol.GetPropsAsDict()})\n",
    "    return pd.DataFrame(rows)\n",
    "\n",
    "\n",
    "readers = {\n",
    "    \"SDF\": read_sdf_table,\n",
    "    \"SMILES\": lambda path: pd.read_csv(path, sep=\" \", names=[\"smiles\", \"id\"]),\n",
    "    \"CSV\": pd.read_csv,\n",
    "    \"Parquet\": pd.read_parquet,\n",
    "}\n",
    "tables = {}\n",
    "for name, reader in readers.items():\n",
    "    start = time.perf_counter()\n",
    "    tables[name] = reader(files[name])\n",
    "    seconds = time.perf_counter() - start\n",
    "    print(f\"{name:11} {seconds:6.3f} s  {len(tables[name]):,} rows\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Reading the SDF is about a hundred times slower, or more, because every record has to be parsed\n",
    "into a molecule (atoms, bonds, valences, aromaticity) before its data fields can be read.\n",
    "The text and Parquet tables are read as plain columns; the molecules in them are only built when\n",
    "something needs them.\n",
    "\n",
    "## 2. What each format keeps and loses\n",
    "\n",
    "Write a table and read it back, and check what survived (a *round trip*). Parquet gives back exactly\n",
    "what went in, column types included, because the types are written in the file. Below, `.equals`\n",
    "checks that two tables are identical, and `dtypes` lists each column's type (`double` and `float64`\n",
    "are both decimal numbers, `int64` a whole number, `str` and `string` text):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "id: string\n",
      "smiles: string\n",
      "vendor: string\n",
      "price_usd: double\n",
      "stock_mg: int64\n",
      "Parquet round trip equal: True\n",
      "CSV round trip equal:     True\n",
      "SMILES file columns:      ['smiles', 'id']\n",
      "SDF columns and types:    {'id': 'str', 'vendor': 'str', 'price_usd': 'float64', 'stock_mg': 'int64'}\n"
     ]
    }
   ],
   "source": [
    "print(pq.read_schema(files[\"Parquet\"]).remove_metadata())\n",
    "print(\"Parquet round trip equal:\", tables[\"Parquet\"].equals(library))\n",
    "print(\"CSV round trip equal:    \", tables[\"CSV\"].equals(library))\n",
    "print(\"SMILES file columns:     \", list(tables[\"SMILES\"].columns))\n",
    "print(\"SDF columns and types:   \", tables[\"SDF\"].dtypes.astype(str).to_dict())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The CSV comes back equal too, but only because this table is easy: plain IDs, plain numbers, no\n",
    "commas in the text. Section 4 shows what happens with real catalogue data. The SMILES file has lost\n",
    "every column but the molecule and its name.\n",
    "\n",
    "The SDF's data fields come back with types, but nobody wrote those types down: an SDF stores every\n",
    "field as text, and RDKit's `GetPropsAsDict` *guessed* them from how the text looks. The guess is\n",
    "right here. It goes wrong as soon as a field looks like a number but is not one, such as a\n",
    "catalogue number with leading zeros:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "{'catalogue_no': 417}\n"
     ]
    }
   ],
   "source": [
    "mol = Chem.MolFromSmiles(\"CCO\")\n",
    "mol.SetProp(\"catalogue_no\", \"00417\")\n",
    "print(mol.GetPropsAsDict())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Text also cuts the other way. Give RDKit a number to write, and it writes every digit it has.\n",
    "`SetDoubleProp` stores the price as a number rather than as text, and `io.StringIO()` is a text\n",
    "\"file\" kept in memory, so we can see what the writer writes without making a real file:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "\n",
      ">  <catalogue_no>  (1) \n",
      "00417\n",
      "\n",
      ">  <price_usd>  (1) \n",
      "57.659999999999997\n",
      "\n",
      "$$$$\n",
      "\n"
     ]
    }
   ],
   "source": [
    "mol.SetDoubleProp(\"price_usd\", 57.66)\n",
    "buffer = io.StringIO()\n",
    "with Chem.SDWriter(buffer) as writer:\n",
    "    writer.write(mol)\n",
    "print(buffer.getvalue().split(\"M  END\")[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Computers store decimal numbers in binary, usually as a **double** (a 64-bit floating-point number).\n",
    "57.66 has no exact binary form, and the file shows the nearest double, to 17 digits. That is why\n",
    "`write_sdf` above formats prices as text with two decimals itself. In short:\n",
    "\n",
    "| Format | Keeps | Loses | Use it for |\n",
    "|---|---|---|---|\n",
    "| SDF | The connection table with coordinates (2D or 3D); any data fields | Field types (all text); size; reading speed | Receiving and sending libraries; 3D structures for docking |\n",
    "| SMILES file | The molecule and one name | Coordinates; every other column | Lists of molecules for tools; quick exchange |\n",
    "| CSV | Any columns; opens anywhere | Column types; one agreed way to quote and encode | Small tables that people read and edit |\n",
    "| Parquet | Columns with their types (a schema); compression; fast reads of chosen columns | Human readability (it is binary); coordinates, unless you add a column for them | Tables inside pipelines and databases |\n",
    "\n",
    "## 3. Reading an SDF the way industry does\n",
    "\n",
    "`read_sdf_table` above read every record into one list before making a table. That is fine for\n",
    "20,000 molecules, but vendor catalogues run to millions of records and tens of gigabytes, and a\n",
    "list of millions of molecules will not fit in memory. Two habits make SDF reading safe at any size:\n",
    "\n",
    "- **Stream.** Reading a file in small pieces, one after another, instead of all at once, is called\n",
    "  *streaming*. `ForwardSDMolSupplier` reads one record at a time from any open file, including a\n",
    "  gzipped one, so nothing is unpacked to disk and only one molecule is in memory at once. Wrap it\n",
    "  in a generator (explained below), and the rest of the code sees records one by one.\n",
    "- **Expect failures, and record them.** Some records will not *parse* (be read into a molecule): a\n",
    "  valence no atom can have, a record cut short. The reader returns `None` (Python's \"nothing\") for\n",
    "  those. Count them and keep their record number and the reason, so someone can go back to the\n",
    "  file and the supplier.\n",
    "\n",
    "When RDKit reads a molecule it also **sanitises** it: it checks the valences, perceives aromaticity\n",
    "and tidies up the structure. A molecule that fails these checks is not returned.\n",
    "\n",
    "To see failures, we make a file like a careless vendor would. `chemlib.add_defects` damages 5% of a\n",
    "2,000-molecule library in the ways real files are damaged, and adds a `defect` column naming the\n",
    "damage: a salt or solvent mixed in, an impossible valence, an unexpected element, a SMILES that\n",
    "cannot be read (`invalid`), or a molecule listed twice. Undamaged rows have an empty `defect`, so\n",
    "they are the first, unnamed line of the count printed below. The writer then skips the valence\n",
    "check, so impossible molecules get written. (The flags `SANITIZE_ALL ^ SANITIZE_PROPERTIES` mean\n",
    "\"every check except the valence check\".) Records whose SMILES cannot be read at all never make it\n",
    "into the file; the writer logs how many it wrote and how many it skipped, as a job would. Finally,\n",
    "`read_bytes()[:-TRUNCATED_BYTES]` keeps every byte of the file except the last 300, as an\n",
    "interrupted download would. The sizes, seeds and rate are set in the Setup block, and\n",
    "`RDLogger.DisableLog` turns off RDKit's own error messages, because we record the failures\n",
    "ourselves:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "defect\n",
      "             1916\n",
      "salt           17\n",
      "invalid        17\n",
      "valence        17\n",
      "solvent        17\n",
      "element        16\n",
      "duplicate      16\n",
      "INFO wrote 1999 records to vendor.sdf; skipped 17 unreadable SMILES\n"
     ]
    }
   ],
   "source": [
    "RDLogger.DisableLog(\"rdApp.*\")  # we record every failure ourselves, below\n",
    "\n",
    "\n",
    "def write_unchecked_sdf(df: pd.DataFrame, path: Path) -> None:\n",
    "    \"\"\"Write an SDF without checking valences, as some tools do; skip SMILES that cannot be read.\"\"\"\n",
    "    no_valence_check = Chem.SanitizeFlags.SANITIZE_ALL ^ Chem.SanitizeFlags.SANITIZE_PROPERTIES\n",
    "    written = skipped = 0\n",
    "    with path.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as handle, Chem.SDWriter(handle) as writer:\n",
    "        for row in df.itertuples(index=False):\n",
    "            mol = Chem.MolFromSmiles(row.smiles, sanitize=False)\n",
    "            if mol is None:\n",
    "                skipped += 1\n",
    "                continue\n",
    "            Chem.SanitizeMol(mol, no_valence_check)\n",
    "            mol.SetProp(\"_Name\", row.id)\n",
    "            mol.SetProp(\"vendor\", row.vendor)\n",
    "            mol.SetProp(\"price_usd\", f\"{row.price_usd:.2f}\")\n",
    "            mol.SetProp(\"stock_mg\", str(row.stock_mg))\n",
    "            writer.write(mol)\n",
    "            written += 1\n",
    "    log.info(\"wrote %d records to %s; skipped %d unreadable SMILES\", written, path.name, skipped)\n",
    "\n",
    "\n",
    "vendor_library = chemlib.library(VENDOR_SIZE, seed=VENDOR_SEED)\n",
    "received = chemlib.add_defects(vendor_library, rate=VENDOR_DEFECT_RATE, seed=VENDOR_DEFECT_SEED)\n",
    "print(received[\"defect\"].value_counts().to_string())\n",
    "vendor_file = WORK / \"vendor.sdf\"\n",
    "write_unchecked_sdf(received, vendor_file)\n",
    "vendor_file.write_bytes(vendor_file.read_bytes()[:-TRUNCATED_BYTES])  # the download stopped early"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The reader is a **generator**: a function that uses `yield` instead of `return`. Each time the loop\n",
    "that uses it asks for the next item, the function runs until the next `yield`, hands back that one\n",
    "item, and waits. So the records come out one at a time, and the file is never read all at once. The\n",
    "type hint `Iterator[tuple[int, Chem.Mol | None, str]]` says what it hands back: a record number, a\n",
    "molecule or `None` (the `|` means \"or\"), and a reason. `enumerate` numbers the records from 0.\n",
    "\n",
    "It reads without sanitising, then sanitises each molecule itself, so it can keep RDKit's reason for\n",
    "every failure. When something goes wrong, Python *raises an error* (an exception), which normally\n",
    "stops the program. `try:` runs some lines, and `except SomeError as error:` runs instead if that\n",
    "error is raised, with the error's message in `error`. RDKit raises a `MolSanitizeException` (or a\n",
    "more specific kind of it, such as `AtomValenceException`) when a molecule cannot be sanitised, and\n",
    "that is the only error we catch: anything else is a bug and should stop the run.\n",
    "\n",
    "The loop below logs a warning for each failed record, with its number and reason. `Counter`,\n",
    "imported in the Setup block, counts the reasons: `reasons[reason] += 1` adds one to that reason's\n",
    "count, `.total()` adds up all the counts, and `.most_common()` lists the reasons, most common first:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "WARNING record 153 failed: Explicit valence for atom # 0 C, 5, is greater than permitted\n",
      "WARNING record 297 failed: Explicit valence for atom # 0 C, 5, is greater than permitted\n",
      "WARNING record 392 failed: Explicit valence for atom # 0 C, 5, is greater than permitted\n",
      "WARNING record 414 failed: Explicit valence for atom # 0 C, 5, is greater than permitted\n",
      "WARNING record 449 failed: Explicit valence for atom # 0 C, 5, is greater than permitted\n",
      "WARNING record 565 failed: Explicit valence for atom # 0 C, 5, is greater than permitted\n",
      "WARNING record 615 failed: Explicit valence for atom # 0 C, 5, is greater than permitted\n",
      "WARNING record 646 failed: Explicit valence for atom # 0 C, 5, is greater than permitted\n",
      "WARNING record 1204 failed: Explicit valence for atom # 0 C, 5, is greater than permitted\n",
      "WARNING record 1229 failed: Explicit valence for atom # 0 C, 5, is greater than permitted\n",
      "WARNING record 1359 failed: Explicit valence for atom # 0 C, 5, is greater than permitted\n",
      "WARNING record 1384 failed: Explicit valence for atom # 0 C, 5, is greater than permitted\n",
      "WARNING record 1550 failed: Explicit valence for atom # 0 C, 5, is greater than permitted\n",
      "WARNING record 1632 failed: Explicit valence for atom # 0 C, 5, is greater than permitted\n",
      "WARNING record 1721 failed: Explicit valence for atom # 0 C, 5, is greater than permitted\n",
      "WARNING record 1923 failed: Explicit valence for atom # 0 C, 5, is greater than permitted\n",
      "WARNING record 1975 failed: Explicit valence for atom # 0 C, 5, is greater than permitted\n",
      "WARNING record 1998 failed: the record could not be parsed\n",
      "INFO 1981 molecules read; 18 records failed\n",
      " 17  Explicit valence for atom # 0 C, 5, is greater than permitted\n",
      "  1  the record could not be parsed\n"
     ]
    }
   ],
   "source": [
    "def records(path: Path) -> Iterator[tuple[int, Chem.Mol | None, str]]:\n",
    "    \"\"\"Yield (record number, molecule or None, reason it failed) for each record of an SDF.\"\"\"\n",
    "    opener = gzip.open if path.suffix == \".gz\" else open\n",
    "    with opener(path, \"rb\") as handle:\n",
    "        for number, mol in enumerate(Chem.ForwardSDMolSupplier(handle, sanitize=False)):\n",
    "            if mol is None:\n",
    "                yield number, None, \"the record could not be parsed\"\n",
    "                continue\n",
    "            try:\n",
    "                Chem.SanitizeMol(mol)\n",
    "            except Chem.MolSanitizeException as error:  # keep RDKit's message\n",
    "                yield number, None, str(error).splitlines()[0]\n",
    "                continue\n",
    "            yield number, mol, \"\"\n",
    "\n",
    "\n",
    "read, reasons = 0, Counter()\n",
    "for number, mol, reason in records(vendor_file):\n",
    "    if mol is None:\n",
    "        log.warning(\"record %d failed: %s\", number, reason)\n",
    "        reasons[reason] += 1\n",
    "    else:\n",
    "        read += 1\n",
    "log.info(\"%d molecules read; %d records failed\", read, reasons.total())\n",
    "for reason, count in reasons.most_common():\n",
    "    print(f\"{count:3}  {reason}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The 17 records with a pentavalent carbon fail with RDKit's valence message, and the last record,\n",
    "cut short, could not be parsed. Every other record, including the salts, solvents and the selenium\n",
    "compound, is read: those are valid molecules that are wrong *for a screening library*, and finding\n",
    "them is the job of validation (Module 6). The whole file was never in memory, and none of the\n",
    "failures stopped the reading.\n",
    "\n",
    "### Properties as typed columns\n",
    "\n",
    "Section 2 showed that SDF data fields are text and that guessing their types goes wrong. So we\n",
    "convert each field ourselves, to the type we chose, and write the rows to Parquet a batch at a time\n",
    "with a fixed schema. Memory stays flat however long the file is, and the same code turns a\n",
    "ten-million-record catalogue into Parquet. Each row also gets the molecule's InChIKey (section 5).\n",
    "\n",
    "The code is longer than before, but it does four simple things:\n",
    "\n",
    "1. `ROW_SCHEMA` lists the columns of the output table and their types;\n",
    "2. `typed_row` turns one molecule into one row (a dictionary of column name to value), converting\n",
    "   each field with `float(...)` or `int(...)` ourselves;\n",
    "3. `sdf_to_parquet` goes through the records with `records`, collects rows in a list called\n",
    "   `batch`, and every `BATCH_SIZE` rows writes the batch to the file and empties the list. Rows left\n",
    "   over at the end are written last. Failed records are logged and kept in `failures`;\n",
    "4. `pq.ParquetWriter` writes the file a batch at a time. Each batch becomes one **row group**, the\n",
    "   block of rows Parquet stores together, and `pa.Table.from_pylist` turns a list of dictionaries\n",
    "   into a table with our schema."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO wrote 20000 rows to library-keys.parquet; 0 records failed\n",
      "row groups (one per batch): 4\n",
      "         id                    inchikey  price_usd  stock_mg\n",
      "ML-00000065 CIIMLXOJFPMAPG-UHFFFAOYSA-N     357.35       360\n",
      "ML-00000098 LXXHHYGMWMRNRZ-UHFFFAOYSA-N      84.62       430\n",
      "ML-00000129 BCBSZRQYWOQCCI-UHFFFAOYSA-N     134.51       420\n"
     ]
    }
   ],
   "source": [
    "ROW_SCHEMA = pa.schema(\n",
    "    [\n",
    "        (\"record\", pa.int64()),\n",
    "        (\"id\", pa.string()),\n",
    "        (\"smiles\", pa.string()),\n",
    "        (\"inchikey\", pa.string()),\n",
    "        (\"vendor\", pa.string()),\n",
    "        (\"price_usd\", pa.float64()),\n",
    "        (\"stock_mg\", pa.int64()),\n",
    "    ]\n",
    ")\n",
    "\n",
    "\n",
    "def typed_row(number: int, mol: Chem.Mol) -> dict:\n",
    "    \"\"\"One SDF record as a row of values with the types we chose, not the types a guesser picked.\"\"\"\n",
    "    return {\n",
    "        \"record\": number,\n",
    "        \"id\": mol.GetProp(\"_Name\"),\n",
    "        \"smiles\": Chem.MolToSmiles(mol),\n",
    "        \"inchikey\": Chem.MolToInchiKey(mol),\n",
    "        \"vendor\": mol.GetProp(\"vendor\"),\n",
    "        \"price_usd\": float(mol.GetProp(\"price_usd\")),\n",
    "        \"stock_mg\": int(mol.GetProp(\"stock_mg\")),\n",
    "    }\n",
    "\n",
    "\n",
    "def sdf_to_parquet(\n",
    "    source: Path, target: Path, batch_size: int = BATCH_SIZE\n",
    ") -> list[tuple[int, str]]:\n",
    "    \"\"\"Stream an SDF into Parquet one batch at a time; return the records that failed.\"\"\"\n",
    "    failures, batch, rows = [], [], 0\n",
    "    with pq.ParquetWriter(target, ROW_SCHEMA, compression=PARQUET_COMPRESSION) as writer:\n",
    "        for number, mol, reason in records(source):\n",
    "            if mol is None:\n",
    "                log.warning(\"record %d failed: %s\", number, reason)\n",
    "                failures.append((number, reason))\n",
    "                continue\n",
    "            batch.append(typed_row(number, mol))\n",
    "            if len(batch) == batch_size:\n",
    "                writer.write_table(pa.Table.from_pylist(batch, schema=ROW_SCHEMA))\n",
    "                rows += len(batch)\n",
    "                batch = []\n",
    "        if batch:\n",
    "            writer.write_table(pa.Table.from_pylist(batch, schema=ROW_SCHEMA))\n",
    "            rows += len(batch)\n",
    "    log.info(\"wrote %d rows to %s; %d records failed\", rows, target.name, len(failures))\n",
    "    return failures\n",
    "\n",
    "\n",
    "keys_file = WORK / \"library-keys.parquet\"\n",
    "sdf_to_parquet(files[\"SDF (gzip)\"], keys_file)\n",
    "print(\"row groups (one per batch):\", pq.ParquetFile(keys_file).metadata.num_row_groups)\n",
    "compounds = pd.read_parquet(keys_file)\n",
    "print(compounds[[\"id\", \"inchikey\", \"price_usd\", \"stock_mg\"]].head(3).to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Module 8 takes this further, for libraries far larger than memory.\n",
    "\n",
    "## 4. CSV and chemistry\n",
    "\n",
    "CSV looks simple: values separated by commas. Chemistry breaks it in several ways at once. Here is\n",
    "a small catalogue of the kind that arrives by email, with catalogue numbers that start with zeros,\n",
    "names that contain commas and apostrophes, a SMILES with a `#` (a triple bond), prices written as\n",
    "text and storage temperatures with a degree sign. `csv.DictWriter` writes a list of dictionaries\n",
    "as a CSV, one row each, with a header line of column names:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "catalogue_no,name,smiles,price,storage\n",
      "00417,\"2,4-dichlorophenol\",Oc1ccc(Cl)cc1Cl,$12.50,2–8 °C\n",
      "01203,acetonitrile,CC#N,$8.00,15–25 °C\n",
      "00090,4'-hydroxyacetophenone,CC(=O)c1ccc(O)cc1,\"$1,250.00\",15–25 °C\n",
      "\n"
     ]
    }
   ],
   "source": [
    "catalogue = [\n",
    "    {\"catalogue_no\": \"00417\", \"name\": \"2,4-dichlorophenol\", \"smiles\": \"Oc1ccc(Cl)cc1Cl\",\n",
    "     \"price\": \"$12.50\", \"storage\": \"2–8 °C\"},\n",
    "    {\"catalogue_no\": \"01203\", \"name\": \"acetonitrile\", \"smiles\": \"CC#N\",\n",
    "     \"price\": \"$8.00\", \"storage\": \"15–25 °C\"},\n",
    "    {\"catalogue_no\": \"00090\", \"name\": \"4'-hydroxyacetophenone\", \"smiles\": \"CC(=O)c1ccc(O)cc1\",\n",
    "     \"price\": \"$1,250.00\", \"storage\": \"15–25 °C\"},\n",
    "]\n",
    "csv_file = WORK / \"catalogue.csv\"\n",
    "with open(csv_file, \"w\", encoding=\"utf-8\", newline=\"\") as handle:\n",
    "    writer = csv.DictWriter(handle, fieldnames=list(catalogue[0]))\n",
    "    writer.writeheader()\n",
    "    writer.writerows(catalogue)\n",
    "print(csv_file.read_text(encoding=\"utf-8\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python's `csv` module did the right thing: it put quotes around the values that contain commas.\n",
    "Code that splits lines on commas by hand ignores the quotes, and the columns no longer line up.\n",
    "(In the first line of the code, `header, *lines = ...` puts the first line in `header` and all the\n",
    "others in the list `lines`.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "5 columns in the header\n",
      "6 fields: ['00417', '\"2', '4-dichlorophenol\"']\n",
      "5 fields: ['01203', 'acetonitrile', 'CC#N']\n",
      "6 fields: ['00090', \"4'-hydroxyacetophenone\", 'CC(=O)c1ccc(O)cc1']\n"
     ]
    }
   ],
   "source": [
    "header, *lines = csv_file.read_text(encoding=\"utf-8\").splitlines()\n",
    "print(len(header.split(\",\")), \"columns in the header\")\n",
    "for line in lines:\n",
    "    print(len(line.split(\",\")), \"fields:\", line.split(\",\")[:3])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A CSV reader that understands quotes, like pandas, gets the columns right. It then guesses each\n",
    "column's type from what the values look like, and the guesses are wrong for chemistry. The\n",
    "catalogue numbers become integers and lose their leading zeros, so `00417` no longer matches the\n",
    "supplier's records. The prices stay text, so they cannot be summed or compared:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "{'catalogue_no': 'int64', 'name': 'str', 'smiles': 'str', 'price': 'str', 'storage': 'str'}\n",
      "catalogue numbers: [417, 1203, 90]\n",
      "prices: ['$12.50', '$8.00', '$1,250.00']\n"
     ]
    }
   ],
   "source": [
    "guessed = pd.read_csv(csv_file)\n",
    "print(guessed.dtypes.astype(str).to_dict())\n",
    "print(\"catalogue numbers:\", guessed[\"catalogue_no\"].tolist())\n",
    "print(\"prices:\", guessed[\"price\"].tolist())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Options meant for other kinds of file do damage too. `comment=\"#\"` is a common way to skip comment\n",
    "lines, and it also cuts every SMILES at its first triple bond, without an error:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "['Oc1ccc(Cl)cc1Cl', 'CC', 'CC(=O)c1ccc(O)cc1']\n"
     ]
    }
   ],
   "source": [
    "print(pd.read_csv(csv_file, comment=\"#\")[\"smiles\"].tolist())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then there is the **encoding**: the rule that turns characters into bytes in the file. **UTF-8** is\n",
    "today's standard and covers every character in every language. A CSV file does not say which\n",
    "encoding it uses. The same table saved by an older Windows program is often in Windows-1252 (also\n",
    "called `cp1252`), an older encoding for Western European text, and the degree sign and the en dash\n",
    "become different bytes. pandas expects UTF-8 and stops with an error; told the right encoding, it\n",
    "reads the file:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "UnicodeDecodeError: invalid start byte\n",
      "['2–8 °C', '15–25 °C', '15–25 °C']\n"
     ]
    }
   ],
   "source": [
    "old_file = WORK / \"catalogue-cp1252.csv\"\n",
    "old_file.write_bytes(csv_file.read_text(encoding=\"utf-8\").encode(\"cp1252\"))\n",
    "try:\n",
    "    pd.read_csv(old_file)\n",
    "except UnicodeDecodeError as error:\n",
    "    print(\"UnicodeDecodeError:\", error.reason)\n",
    "print(pd.read_csv(old_file, encoding=\"cp1252\")[\"storage\"].tolist())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The fix is to stop guessing. Read the CSV once, carefully, saying what each column is, turn the\n",
    "prices into numbers, and store the result as Parquet with a schema. From then on, every program\n",
    "that reads the file gets the same columns with the same types, and the text is always UTF-8.\n",
    "\n",
    "In the code, `dtype={\"catalogue_no\": str}` tells pandas to keep the catalogue numbers as text.\n",
    "`clean.pop(\"price\")` takes the price column out of the table. `.str.replace(\"[$,]\", \"\", regex=True)`\n",
    "removes characters from it: `[$,]` is a **regular expression**, a small pattern language for text,\n",
    "and in it square brackets mean \"any one of these characters\", here a dollar sign or a comma.\n",
    "`.astype(float)` then turns the text into numbers:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "catalogue_no                   name            smiles  storage  price_usd\n",
      "       00417     2,4-dichlorophenol   Oc1ccc(Cl)cc1Cl   2–8 °C       12.5\n",
      "       01203           acetonitrile              CC#N 15–25 °C        8.0\n",
      "       00090 4'-hydroxyacetophenone CC(=O)c1ccc(O)cc1 15–25 °C     1250.0\n",
      "total price: 1270.5\n"
     ]
    }
   ],
   "source": [
    "clean = pd.read_csv(csv_file, dtype={\"catalogue_no\": str}, encoding=\"utf-8\")\n",
    "clean[\"price_usd\"] = clean.pop(\"price\").str.replace(\"[$,]\", \"\", regex=True).astype(float)\n",
    "CATALOGUE_SCHEMA = pa.schema(\n",
    "    [\n",
    "        (\"catalogue_no\", pa.string()),\n",
    "        (\"name\", pa.string()),\n",
    "        (\"smiles\", pa.string()),\n",
    "        (\"storage\", pa.string()),\n",
    "        (\"price_usd\", pa.float64()),\n",
    "    ]\n",
    ")\n",
    "catalogue_file = WORK / \"catalogue.parquet\"\n",
    "clean_table = pa.Table.from_pandas(clean, schema=CATALOGUE_SCHEMA, preserve_index=False)\n",
    "pq.write_table(clean_table, catalogue_file)\n",
    "print(pd.read_parquet(catalogue_file).to_string(index=False))\n",
    "print(\"total price:\", pd.read_parquet(catalogue_file)[\"price_usd\"].sum())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If a CSV must be sent on, write it with the `csv` module or pandas (never by joining strings with\n",
    "commas), in UTF-8, and send its column types alongside it. Module 12 checks such tables\n",
    "automatically.\n",
    "\n",
    "## 5. Identity and duplicates\n",
    "\n",
    "A library should hold each molecule once. Comparing SMILES strings does not find repeats, because\n",
    "one molecule has many SMILES (Module 2). Canonical SMILES and InChIKeys both give one string per\n",
    "molecule. Count the distinct values in our 20,000-molecule library each way. `compounds` is the\n",
    "table we wrote to Parquet in section 3, with RDKit's canonical SMILES and the InChIKey of each\n",
    "molecule. `nunique()` counts the different values in a column, and `groupby(\"inchikey\").size()`\n",
    "counts how many rows share each InChIKey:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "distinct SMILES as written: 20000\n",
      "distinct canonical SMILES:  19891\n",
      "distinct InChIKeys:         19891\n",
      "molecules listed twice: 109\n",
      "molecules listed more than twice: 0\n"
     ]
    }
   ],
   "source": [
    "print(\"distinct SMILES as written:\", library[\"smiles\"].nunique())\n",
    "print(\"distinct canonical SMILES: \", compounds[\"smiles\"].nunique())\n",
    "print(\"distinct InChIKeys:        \", compounds[\"inchikey\"].nunique())\n",
    "sizes = compounds.groupby(\"inchikey\").size()\n",
    "print(\"molecules listed twice:\", int((sizes == 2).sum()))\n",
    "print(\"molecules listed more than twice:\", int((sizes > 2).sum()))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As written, every SMILES is different. Canonical SMILES and InChIKeys agree that 109 molecules\n",
    "are listed twice, each under two IDs: about 0.5% of the library.\n",
    "These are real duplicates of the kind every enumerated library (one made by combining building\n",
    "blocks in every allowed way) has: two building blocks on symmetric positions of a scaffold,\n",
    "swapped, give the same molecule. The code picks the first InChIKey listed twice, and `merge` adds\n",
    "the SMILES as written, matching rows on their `id`. One pair:\n",
    "\n",
    "![Two library entries with different IDs and different SMILES that are the same molecule, with their shared InChIKey](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/03-files-and-identity/figures/duplicate-group.svg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "         id                    inchikey                                                   smiles\n",
      "ML-00868944 ADFIRXKXLAICQM-UHFFFAOYSA-N c1c(CO)cc(cc1C(=O)OC)C(=O)NC(CC8CCNCC8)C(=O)Nc8ccc(F)cc8\n",
      "ML-00869234 ADFIRXKXLAICQM-UHFFFAOYSA-N c1c(C(=O)OC)cc(cc1CO)C(=O)NC(CC8CCNCC8)C(=O)Nc8ccc(F)cc8\n"
     ]
    }
   ],
   "source": [
    "first_key = sizes[sizes == 2].index[0]\n",
    "pair = compounds.loc[compounds[\"inchikey\"] == first_key, [\"id\", \"inchikey\"]]\n",
    "pair = pair.merge(library[[\"id\", \"smiles\"]], on=\"id\")\n",
    "print(pair.to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The two substituents sit on a 1,3,5-substituted benzene ring, so swapping them gives the same\n",
    "molecule written from the other side.\n",
    "\n",
    "The same works for duplicates that a supplier adds by mistake. `add_defects` adds some molecules a\n",
    "second time, written as a different, randomly ordered SMILES, with `-dup` on the ID. Compare the\n",
    "strings and you find none of them; compare InChIKeys and you find them all.\n",
    "\n",
    "The code works on whole columns at once, each giving one `True` or `False` per row:\n",
    "\n",
    "- `.map(inchikey)` runs the function `inchikey` on every SMILES in the column;\n",
    "- `duplicated(keep=False)` is `True` for every row whose value appears in another row too;\n",
    "- `notna()` is `True` where there is a value (the key is missing for SMILES RDKit cannot read), and\n",
    "  `&` means \"and\";\n",
    "- `isin(added_keys)` is `True` where the value is one of those keys;\n",
    "- `.sum()` on such a column counts the `True`s, and `[added]` keeps only the rows where `added` is\n",
    "  `True`.\n",
    "\n",
    "The last three lines find one added duplicate, remove `-dup` from its ID with `removesuffix`, and\n",
    "print every row whose ID starts with what is left:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "duplicates added: 30\n",
      "rows sharing a SMILES string with another row: 0\n",
      "rows sharing an InChIKey with another row:     68\n",
      "every added duplicate found: True\n",
      "rows that are an added duplicate or its original: 60\n",
      "             id                                                   smiles                    inchikey\n",
      "ML-00911844-dup C(c1cc(C(F)(F)F)cc(c1)C(NC(C(=O)NC1CCNCC1)Cc1ccncc1)=O)O JQHQCTSCMYNCGE-UHFFFAOYSA-N\n",
      "    ML-00911844   c1c(CO)cc(cc1C(F)(F)F)C(=O)NC(Cc8ccncc8)C(=O)NC8CCNCC8 JQHQCTSCMYNCGE-UHFFFAOYSA-N\n"
     ]
    }
   ],
   "source": [
    "def inchikey(smiles: str) -> str | None:\n",
    "    \"\"\"The InChIKey of a SMILES, or None if RDKit cannot read it.\"\"\"\n",
    "    mol = Chem.MolFromSmiles(smiles)\n",
    "    return Chem.MolToInchiKey(mol) if mol is not None else None\n",
    "\n",
    "\n",
    "shipment_library = chemlib.library(SHIPMENT_SIZE, seed=SHIPMENT_SEED)\n",
    "shipment = chemlib.add_defects(\n",
    "    shipment_library, rate=SHIPMENT_DEFECT_RATE, seed=SHIPMENT_DEFECT_SEED\n",
    ")\n",
    "shipment[\"inchikey\"] = shipment[\"smiles\"].map(inchikey)\n",
    "added = shipment[\"defect\"] == \"duplicate\"\n",
    "same_string = shipment[\"smiles\"].duplicated(keep=False)\n",
    "same_key = shipment[\"inchikey\"].notna() & shipment[\"inchikey\"].duplicated(keep=False)\n",
    "print(\"duplicates added:\", int(added.sum()))\n",
    "print(\"rows sharing a SMILES string with another row:\", int(same_string.sum()))\n",
    "print(\"rows sharing an InChIKey with another row:    \", int(same_key.sum()))\n",
    "print(\"every added duplicate found:\", bool(same_key[added].all()))\n",
    "added_keys = set(shipment.loc[added, \"inchikey\"])\n",
    "from_added = same_key & shipment[\"inchikey\"].isin(added_keys)\n",
    "print(\"rows that are an added duplicate or its original:\", int(from_added.sum()))\n",
    "example = shipment.loc[added, \"id\"].iloc[0].removesuffix(\"-dup\")\n",
    "copies = shipment[shipment[\"id\"].str.startswith(example)]\n",
    "print(copies[[\"id\", \"smiles\", \"inchikey\"]].to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Two SMILES that look nothing alike give one key. Of the 68 rows that share a key, 60 are the 30\n",
    "added duplicates and their originals; the other 8 are symmetric pairs like the one above, which\n",
    "were in the library before any defects were added. Which copy to keep (the\n",
    "cheaper, the one in stock, the first received) is a business rule, written down and applied the same\n",
    "way every time; Module 7 makes it part of standardisation.\n",
    "\n",
    "## 6. Toolkits disagree\n",
    "\n",
    "Canonical SMILES found the same duplicates as InChIKeys above. So why not use them as the identity?\n",
    "Because \"canonical\" means canonical for one program. Open Babel, the other widely used open-source\n",
    "toolkit, has its own canonical SMILES. Read the first 1,000 molecules of the library with both.\n",
    "\n",
    "`pybel` is Open Babel's Python interface: `pybel.readstring(\"smi\", smiles)` reads a SMILES and\n",
    "`.write(\"can\")` writes Open Babel's canonical SMILES. For each molecule the code records four\n",
    "`True`/`False` answers, and adding up a column of them counts the `True`s. The last two lines print\n",
    "the two SMILES of the last molecule in the loop:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "same canonical SMILES               0\n",
      "RDKit agrees with itself         1000\n",
      "Open Babel agrees with itself    1000\n",
      "same InChIKey                    1000\n",
      "RDKit:      COc1ccc(-c2nc(-c3ccc(F)cc3)c(CO)o2)cc1\n",
      "Open Babel: OCc1oc(nc1c1ccc(cc1)F)c1ccc(cc1)OC\n"
     ]
    }
   ],
   "source": [
    "pybel.ob.obErrorLog.SetOutputLevel(0)  # quiet: we compare the results ourselves\n",
    "\n",
    "\n",
    "def rdkit_canonical(smiles: str) -> str:\n",
    "    \"\"\"RDKit's canonical SMILES.\"\"\"\n",
    "    return Chem.MolToSmiles(Chem.MolFromSmiles(smiles))\n",
    "\n",
    "\n",
    "def openbabel_canonical(smiles: str) -> str:\n",
    "    \"\"\"Open Babel's canonical SMILES (its output is the SMILES, a tab, then a title).\"\"\"\n",
    "    return pybel.readstring(\"smi\", smiles).write(\"can\").split(\"\\t\")[0].strip()\n",
    "\n",
    "\n",
    "rows = []\n",
    "for smiles in library[\"smiles\"].head(TOOLKIT_SAMPLE):\n",
    "    rd, ob = rdkit_canonical(smiles), openbabel_canonical(smiles)\n",
    "    rows.append(\n",
    "        {\n",
    "            \"same canonical SMILES\": rd == ob,\n",
    "            \"RDKit agrees with itself\": rdkit_canonical(ob) == rd,\n",
    "            \"Open Babel agrees with itself\": openbabel_canonical(rd) == ob,\n",
    "            \"same InChIKey\": inchikey(rd) == inchikey(ob),\n",
    "        }\n",
    "    )\n",
    "print(pd.DataFrame(rows).sum().to_string())\n",
    "print(\"RDKit:     \", rd)\n",
    "print(\"Open Babel:\", ob)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![One oxazole drawn by RDKit, with RDKit's canonical SMILES and Open Babel's, which differ, and the single InChIKey both give](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/03-files-and-identity/figures/toolkits-one-key.svg)\n",
    "\n",
    "Each toolkit is consistent with itself: given the other's SMILES, it produces its own canonical\n",
    "form again. But the two forms are different for every one of these molecules, so a database keyed on\n",
    "RDKit's canonical SMILES would not recognise a single molecule sent in by an Open Babel pipeline.\n",
    "The canonical SMILES can also change between versions of one toolkit, when its algorithm is\n",
    "improved. The InChIKeys are the same whichever SMILES they are made from.\n",
    "\n",
    "InChI avoids the problem by design: there is one InChI algorithm, maintained by IUPAC and the InChI\n",
    "Trust, and toolkits call the same InChI library rather than writing their own. Open Babel can write\n",
    "InChIs and InChIKeys too, when it is built with that library. You can check with\n",
    "`\"inchikey\" in pybel.outformats`, which gives `True` or `False`. The package installed with `pip`\n",
    "(Python's package installer) includes it on Linux, and so in Colab; the one for Windows, at the time\n",
    "of writing, does not. Store the toolkit's canonical SMILES to rebuild the molecule, and the InChIKey\n",
    "to identify it.\n",
    "\n",
    "## 7. Did the file arrive unchanged?\n",
    "\n",
    "Files are copied, downloaded, uploaded and synchronised, and somewhere along the way one can be cut\n",
    "short or changed. A truncated SDF still opens (section 3 lost only one record), and a single changed\n",
    "byte can turn chlorine into bromine. A **checksum** catches both. **SHA-256** is a standard\n",
    "recipe (a hash, like the InChIKey in Module 2) that turns a file's bytes into a 64-character code\n",
    "of digits and the letters a to f. Change any byte and the code changes completely. Whoever sends a\n",
    "file publishes its checksum, and whoever receives it computes the checksum again and compares.\n",
    "\n",
    "The code has three functions:\n",
    "\n",
    "- `sha256` reads the file a chunk at a time and feeds each chunk to `hashlib`. The line\n",
    "  `while chunk := handle.read(chunk_size):` reads the next chunk into `chunk` and keeps going as\n",
    "  long as it is not empty; the `:=` gives a name to a value in the middle of a line;\n",
    "- `write_checksums` writes a **manifest**: a small text file listing each file's checksum, two\n",
    "  spaces, and its name;\n",
    "- `verify` reads the manifest back, computes each file's checksum again, and returns the names of\n",
    "  the files that no longer match:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO wrote the checksums of 2 files to SHA256SUMS\n",
      "d694974ab38e5b235f1e5b9f4b8fef717b0f79e618220df5b862255f630569d5  library.smi\n",
      "aed1fa33d0dcc7729d1b0527d4e73713b617d7de70d2d57aacbe73190da18f6c  library.parquet\n",
      "changed files: []\n"
     ]
    }
   ],
   "source": [
    "def sha256(path: Path, chunk_size: int = CHECKSUM_CHUNK) -> str:\n",
    "    \"\"\"The SHA-256 checksum of a file, read a chunk at a time so any size of file fits.\"\"\"\n",
    "    digest = hashlib.sha256()\n",
    "    with path.open(\"rb\") as handle:\n",
    "        while chunk := handle.read(chunk_size):\n",
    "            digest.update(chunk)\n",
    "    return digest.hexdigest()\n",
    "\n",
    "\n",
    "def write_checksums(paths: list[Path], manifest: Path) -> None:\n",
    "    \"\"\"Write a manifest: one line per file, its checksum then its name (as sha256sum writes).\"\"\"\n",
    "    lines = [f\"{sha256(path)}  {path.name}\\n\" for path in paths]\n",
    "    manifest.write_text(\"\".join(lines), encoding=\"utf-8\")\n",
    "    log.info(\"wrote the checksums of %d files to %s\", len(lines), manifest.name)\n",
    "\n",
    "\n",
    "def verify(manifest: Path) -> list[str]:\n",
    "    \"\"\"Check every file listed in a manifest; return the names whose checksum no longer matches.\"\"\"\n",
    "    changed = []\n",
    "    for line in manifest.read_text(encoding=\"utf-8\").splitlines():\n",
    "        expected, name = line.split(\"  \", 1)\n",
    "        if sha256(manifest.parent / name) != expected:\n",
    "            log.warning(\"%s: checksum does not match the manifest\", name)\n",
    "            changed.append(name)\n",
    "    return changed\n",
    "\n",
    "\n",
    "manifest = WORK / \"SHA256SUMS\"\n",
    "write_checksums([files[\"SMILES\"], files[\"Parquet\"]], manifest)\n",
    "print(manifest.read_text(encoding=\"utf-8\"), end=\"\")\n",
    "print(\"changed files:\", verify(manifest))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now change one character in the SMILES file, a chlorine into a bromine, the kind of change no one\n",
    "would spot by eye in a 20,000-line file:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "same size: True\n",
      "WARNING library.smi: checksum does not match the manifest\n",
      "changed files: ['library.smi']\n"
     ]
    }
   ],
   "source": [
    "text = files[\"SMILES\"].read_text(encoding=\"utf-8\")\n",
    "files[\"SMILES\"].write_text(text.replace(\"Cl\", \"Br\", 1), encoding=\"utf-8\", newline=\"\\n\")\n",
    "print(\"same size:\", files[\"SMILES\"].stat().st_size == len(text.encode(\"utf-8\")))\n",
    "print(\"changed files:\", verify(manifest))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The file is the same size and still a valid SMILES file, so only the checksum notices. The\n",
    "manifest format is the one the `sha256sum` command reads, so the receiver does not need Python to\n",
    "check it. You do not need this for the lesson, but if you want to try it: `sha256sum` is a terminal\n",
    "command on Linux. In Colab, run it in a new code cell, where a line starting with `!` is sent to\n",
    "the terminal instead of to Python:\n",
    "\n",
    "```bash\n",
    "!cd work && sha256sum -c SHA256SUMS\n",
    "```\n",
    "\n",
    "It prints each file's name followed by `OK` or `FAILED` (here `library.smi: FAILED`, because we just\n",
    "changed it) and a warning line counting the failures. On macOS, type\n",
    "`shasum -a 256 -c SHA256SUMS` in Terminal, in the `work` folder, without the `!`. Windows\n",
    "PowerShell has no `sha256sum`.\n",
    "\n",
    "When you download data from a data repository (a website that keeps published datasets, such as\n",
    "Zenodo) that publishes checksums, compare them before you use the files; Module 13 builds manifests\n",
    "like this one into versioning.\n",
    "\n",
    "## 8. Choosing a format\n",
    "\n",
    "- **Receiving** data, you take what you are given, often SDF or CSV. Stream it, record what fails\n",
    "  and why, convert the types yourself, and check its checksum if one was published.\n",
    "- **Inside** a pipeline, store tables as Parquet with a schema: small, fast, typed, and the same in\n",
    "  every program. Keep a SMILES column to rebuild molecules and an InChIKey column to identify them.\n",
    "- **Sending** data, write the format the receiver asks for, with the `csv` module or RDKit's\n",
    "  writers rather than by joining strings, and publish its checksum beside it.\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",
    "- Dalby, A., Nourse, J. G., Hounshell, W. D., Gushurst, A. K. I., Grier, D. L., Leland, B. A. &\n",
    "  Laufer, J. (1992). Description of several chemical structure file formats used by computer\n",
    "  programs developed at Molecular Design Limited. *Journal of Chemical Information and Computer\n",
    "  Sciences*, 32(3), 244–255. <https://doi.org/10.1021/ci00007a012>\n",
    "- Heller, S. R., McNaught, A., Pletnev, I., Stein, S. & Tchekhovskoi, D. (2015). InChI, the IUPAC\n",
    "  International Chemical Identifier. *Journal of Cheminformatics*, 7(1), 23.\n",
    "  <https://doi.org/10.1186/s13321-015-0068-4>\n",
    "- O'Boyle, N. M., Banck, M., James, C. A., Morley, C., Vandermeersch, T. & Hutchison, G. R. (2011).\n",
    "  Open Babel: An open chemical toolbox. *Journal of Cheminformatics*, 3(1), 33.\n",
    "  <https://doi.org/10.1186/1758-2946-3-33>\n",
    "- Shafranovich, Y. (2005). *Common Format and MIME Type for Comma-Separated Values (CSV) Files*.\n",
    "  RFC 4180. <https://www.rfc-editor.org/rfc/rfc4180>\n",
    "- The Apache Parquet documentation. <https://parquet.apache.org/docs/>\n",
    "- The RDKit documentation. *Getting Started with the RDKit in Python*.\n",
    "  <https://www.rdkit.org/docs/GettingStartedInPython.html>\n",
    "- The Open Babel documentation. <https://open-babel.readthedocs.io/en/latest/>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
