{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Validating data: records with Pydantic, tables with Pandera\n",
    "\n",
    "Write down what a table of activity data must contain, check single records at the edges with Pydantic and whole batches with Pandera, and quarantine what fails with the reason why.\n",
    "\n",
    "The lesson's page: https://monstrous.com.ng/learn/data-engineering/series-1/12-validating-data/"
   ]
  },
  {
   "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 pydantic pandera pandas numpy duckdb pint\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": [
    "[Module 6](../06-validating-molecules/) checked molecules. This module checks everything that\n",
    "travels with them. A table of bioactivity measurements (an IC50 here, a Ki there) is where most of\n",
    "the value in medicinal chemistry data sits, and it breaks in ordinary ways: a unit column left\n",
    "empty, a micromolar value typed as `uM` by one lab and `µM` by another, a minus sign from a\n",
    "spreadsheet formula, the same measurement loaded twice, an InChIKey (the fixed-length code worked\n",
    "out from a structure, [Module 3](../03-files-and-identity/)) pasted from the wrong row. None of\n",
    "these stops a pipeline.\n",
    "Each one quietly moves a mean pIC50, doubles the weight of one compound in a model or joins a\n",
    "result to the wrong structure. Public data has these problems too: when Kramer and co-workers\n",
    "set out to measure how well independent Ki values in ChEMBL agree, they first had to filter out\n",
    "unit-transcription errors, stereoisomers that were not told apart, and single measurements cited\n",
    "again and again by later papers.\n",
    "\n",
    "Data engineers deal with this by writing down, once, what a table must contain (a **data\n",
    "contract**) and checking it with code at every boundary the data crosses: every point where data\n",
    "passes from one person, program or step to the next. This module builds that contract for\n",
    "activity data and checks it two ways: one record (one row) at a time with Pydantic, and a whole\n",
    "table at once with Pandera.\n",
    "\n",
    "By the end of this module you will be able to:\n",
    "\n",
    "- write down, with a version number, what a table of bioactivity measurements must contain (its\n",
    "  data contract);\n",
    "- check one record at a time with Pydantic, including rules that link several fields, and read\n",
    "  its error messages;\n",
    "- convert activities to one unit (nM) and work out pIC50, and test that conversion;\n",
    "- check a whole table at once with Pandera, see every failure in one report, and move the rows\n",
    "  that fail into a separate table (a quarantine) while keeping the rest;\n",
    "- decide whether to stop a batch (one delivery of rows) or let it through, and record why;\n",
    "- time the two ways of checking, and say when to use which.\n",
    "\n",
    "From earlier modules we use the quarantine and the idea of checking against data with known\n",
    "faults ([Module 6](../06-validating-molecules/)), standardisation rules and tests run by pytest\n",
    "([Module 7](../07-standardisation/)), Pydantic models for settings\n",
    "([Module 10](../10-pipelines-that-survive-failure/)), records from a web API\n",
    "([Module 11](../11-incremental-ingestion/)), and DuckDB, the database in one file, from [Module 4](../04-databases-and-schemas/).\n",
    "\n",
    "The lesson uses these packages:\n",
    "\n",
    "- **RDKit**, the chemistry toolkit: it reads SMILES and works out InChIKeys;\n",
    "- **Pydantic**, which checks one record (a Python dictionary) against a description of its fields;\n",
    "- **Pandera**, which checks a whole pandas table (a **DataFrame**) against a description of its\n",
    "  columns;\n",
    "- **pandas**, for tables, and **NumPy**, for arrays of numbers and random numbers;\n",
    "- **DuckDB**, a database kept in one file, which we load the checked rows into;\n",
    "- **chemlib**, the course's own small package that makes a teaching library of molecules.\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\n",
    "place. Pipeline steps report with `log`; `print` is kept for showing you results;\n",
    "[Module 1](../01-graphs-and-matrices/) explains why.\n",
    "\n",
    "Besides the packages above, the block imports a few tools that come with Python itself: `json`,\n",
    "for writing dictionaries to text files; `math`, for logarithms; `time`, for the stopwatch of\n",
    "section 5; `dataclass` and `Enum`, two ways of making small classes (explained in sections 2\n",
    "and 4); `Path`, for file names; and `Self`, used in a **type hint** (the notes after a colon or\n",
    "`->` that say what kind of value a function takes or returns). A **seed** fixes the random numbers\n",
    "a program draws, so that everyone who runs the lesson gets the same test data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "import logging\n",
    "import math\n",
    "import time\n",
    "from dataclasses import dataclass\n",
    "from enum import Enum\n",
    "from pathlib import Path\n",
    "from typing import Self\n",
    "\n",
    "import duckdb\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import pandera.pandas as pa\n",
    "import pint\n",
    "from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator, model_validator\n",
    "from rdkit import Chem, RDLogger\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",
    "# where the lesson writes its files (git-ignored); change it to write somewhere else\n",
    "WORK = Path(\"work\")\n",
    "# the database the checked measurements and the quarantine are loaded into\n",
    "DB_PATH = WORK / \"activity.duckdb\"\n",
    "# the test data: how many compounds and measurements, and the seeds that make them\n",
    "N_COMPOUNDS = 2_000\n",
    "COMPOUND_SEED = 12\n",
    "N_MEASUREMENTS = 5_000\n",
    "MEASUREMENT_SEED = 13\n",
    "FAULT_SEED = 14\n",
    "# the name of the batch we check (a real job takes it from the file or the run)\n",
    "BATCH_ID = \"batch-0001\"\n",
    "# the targets we screen: the only target_id values the contract allows\n",
    "TARGETS = [\"ABL1\", \"BRAF\", \"CDK2\", \"EGFR\", \"JAK2\"]\n",
    "# how far a stored pChEMBL may be from 9 - log10(value in nM) and still be accepted\n",
    "PCHEMBL_TOLERANCE = 0.01\n",
    "# the largest share of failing rows a batch may have and still be loaded (0.05 is 5%)\n",
    "MAX_FAILED_SHARE = 0.05\n",
    "# the timing comparison repeats the batch this many times (40 gives about 200,000 rows)\n",
    "BENCHMARK_COPIES = 40\n",
    "\n",
    "WORK.mkdir(exist_ok=True)\n",
    "RDLogger.DisableLog(\"rdApp.*\")  # RDKit's own warnings would repeat what our errors say"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. A data contract\n",
    "\n",
    "A data contract is a short, versioned document that says what a table holds: its columns, their\n",
    "types, which may be empty, which values are allowed, and which rules link columns together. The\n",
    "team that produces the table and every team that reads it agree on it. Code then checks it,\n",
    "because a contract that is only written down is broken within a week.\n",
    "\n",
    "Ours describes one row per measurement. The rules are the ones a medicinal chemist would state\n",
    "out loud; the contract just makes them exact. We write it as a Python dictionary and save it as a\n",
    "**JSON** file, a plain-text format for dictionaries and lists that almost every program can read.\n",
    "\"14-10-1 capital letters\" is the shape of an InChIKey, and pChEMBL is the activity on a log scale\n",
    "(section 2 explains it):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO wrote contract-measurements-1.0.0.json with 9 columns\n"
     ]
    }
   ],
   "source": [
    "CONTRACT = {\n",
    "    \"name\": \"measurements\",\n",
    "    \"version\": \"1.0.0\",\n",
    "    \"columns\": {\n",
    "        \"measurement_id\": \"text, required, unique, M- and six digits\",\n",
    "        \"compound_id\": \"text, required, ML- and eight digits, must exist in the compounds table\",\n",
    "        \"smiles\": \"text, required, readable by RDKit\",\n",
    "        \"inchikey\": \"text, required, 14-10-1 capital letters, must match the SMILES\",\n",
    "        \"target_id\": \"text, required, one of the targets we screen\",\n",
    "        \"activity_type\": \"text, required, one of IC50, Ki, Kd, EC50\",\n",
    "        \"value\": \"number, required, greater than 0\",\n",
    "        \"units\": \"text, required, one of nM, µM, mM\",\n",
    "        \"pchembl\": \"number, optional, 0 to 14, equal to 9 - log10(value in nM) \"\n",
    "                   f\"within {PCHEMBL_TOLERANCE}\",\n",
    "    },\n",
    "    \"rows\": \"no two rows with the same compound, target, activity type, value and units\",\n",
    "}\n",
    "\n",
    "contract_file = WORK / f\"contract-{CONTRACT['name']}-{CONTRACT['version']}.json\"\n",
    "contract_file.write_text(json.dumps(CONTRACT, indent=2, ensure_ascii=False), encoding=\"utf-8\")\n",
    "log.info(\"wrote %s with %d columns\", contract_file.name, len(CONTRACT[\"columns\"]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The file name carries the version, `1.0.0`. The version follows the usual convention for\n",
    "software, three numbers that mean major.minor.patch: a change that cannot break a reader (a new\n",
    "optional column) raises the middle number; a change that can (a column renamed, a unit removed, a\n",
    "rule tightened) raises the first; the last is for small fixes that change no rule. A reader can\n",
    "then refuse a table whose contract version it does not know, instead of misreading it.\n",
    "[Module 13](../13-versioning-everything/) versions the code that checks it in the same way.\n",
    "\n",
    "The contract is checked at two kinds of place. At the **edges**, data arrives one record at a\n",
    "time: an API response (an answer from a web service such as ChEMBL's, Module 11), a row typed into\n",
    "a form, a message from an instrument. There\n",
    "we check each record as it arrives and turn it into a typed Python object, with Pydantic. In the\n",
    "**middle** of a pipeline, data moves in tables of thousands or millions of rows, between steps\n",
    "and into the database. There we check whole tables at once, with Pandera.\n",
    "\n",
    "![Where each tool sits: records from an API, a form and an instrument are checked one by one with Pydantic at the edge; batches are then checked as tables with Pandera between pipeline steps, with failing rows sent to a quarantine table and the rest loaded](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/12-validating-data/figures/pipeline-checks.svg)\n",
    "\n",
    "## 2. Records at the edges, with Pydantic\n",
    "\n",
    "### A model for one measurement\n",
    "\n",
    "A **class** is a template for making objects of one kind, each holding named values (its\n",
    "**fields**). A Pydantic model is a class whose fields have types and constraints. Pydantic checks\n",
    "every value when the object is made and refuses to make it if any check fails. You met Pydantic\n",
    "models for a run's settings in Module 10 and for API records in Module 11; here the record is one\n",
    "measurement. Fixed lists of allowed values are written as **enumerations** (`Enum`): a class whose\n",
    "only possible values are the ones listed in it, so a typo cannot slip through as a new category.\n",
    "\n",
    "We build the model in two parts: `Activity` holds the measured value and its context, and\n",
    "`Measurement` adds the compound. The numbers and units are checked by field constraints; the\n",
    "SMILES by a **field validator** that asks RDKit to read it; and the agreement between `pchembl`,\n",
    "`value` and `units`, which involves three fields at once, by a **model validator** that runs after\n",
    "every field has passed.\n",
    "\n",
    "The code uses a few pieces of Python that may be new:\n",
    "\n",
    "- `class Activity(BaseModel):` makes a new class built on Pydantic's `BaseModel`, so it gets all of\n",
    "  Pydantic's checking. `class Measurement(Activity):` builds on `Activity` in the same way: it has\n",
    "  all of `Activity`'s fields and checks, plus its own.\n",
    "- A line such as `value: float = Field(gt=0)` declares one field: its name, its type after the\n",
    "  colon (a number with a decimal point), and its rules in `Field(...)` (`gt=0` is \"greater than\n",
    "  0\", `ge` and `le` are \"greater than or equal\" and \"less than or equal\"). `float | None` means a\n",
    "  number or nothing, and `default=None` makes the field optional.\n",
    "- `pattern=` takes a **regular expression**, a pattern that a piece of text must match:\n",
    "  `^M-\\d{6}$` reads \"start (`^`), the letters `M-`, six digits (`\\d{6}`), end (`$`)\". The `r`\n",
    "  before the quotes stops Python from treating the backslash as special.\n",
    "- A line starting with `@` just above a function is a **decorator**: it hands the function to\n",
    "  something else. `@model_validator` and `@field_validator` tell Pydantic to run the function as a\n",
    "  check; `@property` lets us write `m.value_nm` without brackets, like a field, although it is\n",
    "  worked out each time; `@classmethod` is required by Pydantic for field validators, and can be\n",
    "  copied as it is.\n",
    "- `raise ValueError(\"...\")` stops the check with that message, which Pydantic then reports. The\n",
    "  validator ends with `return self` (the object that passed), which is why its type hint is\n",
    "  `Self`.\n",
    "- `f\"{expected:.2f}\"` writes a number with two decimal places."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "MEASUREMENT_ID = r\"^M-\\d{6}$\"  # the identifier formats the contract gives\n",
    "COMPOUND_ID = r\"^ML-\\d{8}$\"\n",
    "\n",
    "\n",
    "class ActivityType(str, Enum):\n",
    "    \"\"\"The kinds of activity this table accepts.\"\"\"\n",
    "\n",
    "    IC50 = \"IC50\"\n",
    "    KI = \"Ki\"\n",
    "    KD = \"Kd\"\n",
    "    EC50 = \"EC50\"\n",
    "\n",
    "\n",
    "class Unit(str, Enum):\n",
    "    \"\"\"Concentration units, written exactly as the contract says (with the micro sign µ).\"\"\"\n",
    "\n",
    "    NM = \"nM\"\n",
    "    UM = \"µM\"\n",
    "    MM = \"mM\"\n",
    "\n",
    "\n",
    "NM_PER_UNIT = {Unit.NM: 1.0, Unit.UM: 1_000.0, Unit.MM: 1_000_000.0}\n",
    "\n",
    "\n",
    "class Activity(BaseModel):\n",
    "    \"\"\"One measured activity: what was measured, against what, and its value.\"\"\"\n",
    "\n",
    "    model_config = ConfigDict(extra=\"forbid\", frozen=True)\n",
    "\n",
    "    target_id: str = Field(pattern=r\"^[A-Z0-9]{2,10}$\")\n",
    "    activity_type: ActivityType\n",
    "    value: float = Field(gt=0)\n",
    "    units: Unit\n",
    "    pchembl: float | None = Field(default=None, ge=0, le=14)\n",
    "\n",
    "    @property\n",
    "    def value_nm(self) -> float:\n",
    "        \"\"\"The value in nanomolar.\"\"\"\n",
    "        return self.value * NM_PER_UNIT[self.units]\n",
    "\n",
    "    @model_validator(mode=\"after\")\n",
    "    def pchembl_matches_value(self) -> Self:\n",
    "        \"\"\"pChEMBL is -log10 of the molar value, so it must agree with value and units.\"\"\"\n",
    "        if self.pchembl is not None:\n",
    "            expected = 9 - math.log10(self.value_nm)\n",
    "            if abs(self.pchembl - expected) > PCHEMBL_TOLERANCE:\n",
    "                raise ValueError(\n",
    "                    f\"pchembl {self.pchembl} does not match {self.value} {self.units.value} \"\n",
    "                    f\"(expected {expected:.2f})\"\n",
    "                )\n",
    "        return self\n",
    "\n",
    "\n",
    "class Measurement(Activity):\n",
    "    \"\"\"An activity together with the compound it was measured for.\"\"\"\n",
    "\n",
    "    measurement_id: str = Field(pattern=MEASUREMENT_ID)\n",
    "    compound_id: str = Field(pattern=COMPOUND_ID)\n",
    "    smiles: str\n",
    "\n",
    "    @field_validator(\"smiles\")\n",
    "    @classmethod\n",
    "    def readable_by_rdkit(cls, smiles: str) -> str:\n",
    "        \"\"\"Refuse a SMILES that RDKit cannot read.\"\"\"\n",
    "        if Chem.MolFromSmiles(smiles) is None:\n",
    "            raise ValueError(\"RDKit cannot read this SMILES\")\n",
    "        return smiles"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`extra=\"forbid\"` refuses fields the model does not know, so a renamed column in an API fails\n",
    "loudly instead of being dropped. `frozen=True` makes the object read-only once checked, so nothing\n",
    "later can make it invalid again.\n",
    "\n",
    "### Good records and bad records\n",
    "\n",
    "A good record becomes an object with real types: the units are a `Unit`, not a string (a piece of\n",
    "text) that might be spelled several ways. `Measurement.model_validate(good)` checks a dictionary\n",
    "and makes the object from it. An `Activity` on its own works too, for a source that reports\n",
    "activities without structures; here we make one by giving the fields by name, and the optional\n",
    "`pchembl` is then `None`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "ActivityType.IC50 Unit.UM 250.0 nM\n",
      "target_id='JAK2' activity_type=<ActivityType.KI: 'Ki'> value=4.2 units=<Unit.NM: 'nM'> pchembl=None\n"
     ]
    }
   ],
   "source": [
    "good = {\n",
    "    \"measurement_id\": \"M-000001\",\n",
    "    \"compound_id\": \"ML-00012345\",\n",
    "    \"smiles\": \"CC(=O)Oc1ccccc1C(=O)O\",\n",
    "    \"target_id\": \"EGFR\",\n",
    "    \"activity_type\": \"IC50\",\n",
    "    \"value\": 0.25,\n",
    "    \"units\": \"µM\",\n",
    "    \"pchembl\": 6.6,\n",
    "}\n",
    "m = Measurement.model_validate(good)\n",
    "print(m.activity_type, m.units, m.value_nm, \"nM\")\n",
    "a = Activity(target_id=\"JAK2\", activity_type=\"Ki\", value=4.2, units=\"nM\")\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A bad record raises a `ValidationError` that lists every problem, each with where it is and what\n",
    "is wrong. A small helper prints them one per line. It uses `try:` and `except ValidationError`:\n",
    "Python runs the `try` part, and if that raises a `ValidationError` it runs the `except` part\n",
    "instead of stopping. To make bad records we change a copy of `good`: `{**good, \"units\": \"uM\"}` is\n",
    "a copy of `good` with `units` replaced, and `{k: v for k, v in good.items() if k != \"units\"}` is a\n",
    "copy without `units` at all (a **dictionary comprehension**, a loop written inside the brackets);\n",
    "`|` then adds a new SMILES to that copy."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "micromolar typed as uM, and a negative value:\n",
      "  value: Input should be greater than 0\n",
      "  units: Input should be 'nM', 'µM' or 'mM'\n",
      "units missing, and a SMILES with a ring that never closes:\n",
      "  units: Field required\n",
      "  smiles: Value error, RDKit cannot read this SMILES\n",
      "pchembl worked out as if the value were in nM:\n",
      "  record: Value error, pchembl 9.6 does not match 0.25 µM (expected 6.60)\n",
      "an extra column:\n",
      "  assay_ref: Extra inputs are not permitted\n"
     ]
    }
   ],
   "source": [
    "def show_errors(record: dict) -> None:\n",
    "    \"\"\"Validate a record and print 'valid' or one line per problem.\"\"\"\n",
    "    try:\n",
    "        Measurement.model_validate(record)\n",
    "        print(\"valid\")\n",
    "    except ValidationError as error:\n",
    "        for problem in error.errors():\n",
    "            where = \".\".join(str(part) for part in problem[\"loc\"]) or \"record\"\n",
    "            print(f\"  {where}: {problem['msg']}\")\n",
    "\n",
    "\n",
    "print(\"micromolar typed as uM, and a negative value:\")\n",
    "show_errors({**good, \"units\": \"uM\", \"value\": -0.25})\n",
    "print(\"units missing, and a SMILES with a ring that never closes:\")\n",
    "show_errors({k: v for k, v in good.items() if k != \"units\"} | {\"smiles\": \"c1ccccc\"})\n",
    "print(\"pchembl worked out as if the value were in nM:\")\n",
    "show_errors({**good, \"pchembl\": 9.6})\n",
    "print(\"an extra column:\")\n",
    "show_errors({**good, \"assay_ref\": \"lab book 7\"})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The pchembl check reports `record`, not a field: it is a rule about the record as a whole, and it\n",
    "runs only once every field has passed on its own, so the first two records never reach it.\n",
    "\n",
    "What to do with `uM` is a decision, not a validation. The contract says `µM`, and the model\n",
    "refuses anything else. If a supplier always writes `uM`, the right fix is a written, versioned\n",
    "list of known spellings applied *before* validation (a standardisation rule, Module 7), so that\n",
    "the change is on record. Silently accepting every spelling inside the model would hide where the\n",
    "data came from. The same goes for the Greek letter mu (μ, U+03BC), which looks identical to the\n",
    "micro sign (µ, U+00B5) on screen but is a different character. (U+03BC is the character's number\n",
    "in Unicode, the list of every character a computer can write.) To show which is which, the code\n",
    "prints each spelling with `encode('unicode_escape')`, which writes any character outside plain\n",
    "English letters as its code; `:>10` lines the spellings up on the right, ten characters wide:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Greek mu and micro sign are the same character: False\n",
      "        uM -> µM\n",
      "   \\u03bcM -> µM\n",
      "     \\xb5M -> µM\n",
      "        nM -> nM\n",
      "        pM -> pM\n"
     ]
    }
   ],
   "source": [
    "UNIT_SPELLINGS = {\"uM\": \"µM\", \"μM\": \"µM\", \"nm\": \"nM\", \"um\": \"µM\", \"mm\": \"mM\"}\n",
    "\n",
    "\n",
    "def normalise_units(units: str | None) -> str | None:\n",
    "    \"\"\"Map a known alternative spelling of a unit to the contract's spelling; leave others.\"\"\"\n",
    "    if units is None:\n",
    "        return None\n",
    "    return UNIT_SPELLINGS.get(units, units)\n",
    "\n",
    "\n",
    "print(\"Greek mu and micro sign are the same character:\", \"μM\" == \"µM\")\n",
    "for spelling in [\"uM\", \"μM\", \"µM\", \"nM\", \"pM\"]:\n",
    "    print(f\"{spelling.encode('unicode_escape').decode():>10} -> {normalise_units(spelling)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`pM` is left alone: it is a real unit that the contract does not allow, so the model should\n",
    "refuse it and a person should decide whether to add it.\n",
    "\n",
    "### One unit, one scale: nanomolar and pIC50\n",
    "\n",
    "Activities arrive in nM, µM and mM. Before they can be compared, averaged or modelled they go on\n",
    "one scale. We convert every value to nanomolar and then to the negative log of the molar\n",
    "concentration, which is what ChEMBL calls pChEMBL (pIC50 for an IC50):\n",
    "\n",
    "pIC50 = −log10(IC50 in M) = 9 − log10(IC50 in nM)\n",
    "\n",
    "so 1 nM is 9, 1 µM is 6 and 1 mM is 3, and every factor of ten in potency is one unit. Conversion\n",
    "code is the kind of code that is wrong by exactly a factor of 1,000 and still looks plausible, so\n",
    "it gets a test: a function that runs the code on values whose answers we know. Each `assert` line\n",
    "stops with an error if what follows it is not true, so if the test runs to the end, every answer\n",
    "was right:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO conversion tests passed\n"
     ]
    }
   ],
   "source": [
    "def to_nm(value: float, units: str) -> float:\n",
    "    \"\"\"A concentration in nanomolar.\"\"\"\n",
    "    return value * NM_PER_UNIT[Unit(units)]\n",
    "\n",
    "\n",
    "def p_activity(value_nm: float) -> float:\n",
    "    \"\"\"-log10 of the molar concentration, from a value in nanomolar.\"\"\"\n",
    "    return 9 - math.log10(value_nm)\n",
    "\n",
    "\n",
    "def test_conversion() -> None:\n",
    "    \"\"\"Known values: 50 nM written three ways, and the anchor points of the log scale.\"\"\"\n",
    "    assert math.isclose(to_nm(50, \"nM\"), 50)\n",
    "    assert math.isclose(to_nm(0.05, \"µM\"), 50)\n",
    "    assert math.isclose(to_nm(0.00005, \"mM\"), 50)\n",
    "    assert math.isclose(p_activity(to_nm(1, \"nM\")), 9)\n",
    "    assert math.isclose(p_activity(to_nm(1, \"µM\")), 6)\n",
    "    assert math.isclose(p_activity(to_nm(1, \"mM\")), 3)\n",
    "    assert math.isclose(p_activity(to_nm(250, \"nM\")), 6.60, abs_tol=0.01)\n",
    "\n",
    "\n",
    "test_conversion()\n",
    "log.info(\"conversion tests passed\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In a project this test lives in a test file and runs with pytest (a program that finds and runs\n",
    "every test) on every change, as in Module 7. `math.isclose` is used because `0.05 * 1000` is not\n",
    "exactly `50` in floating point, the way computers store decimal numbers, which rounds them very\n",
    "slightly.\n",
    "\n",
    "### Letting a library check the units\n",
    "\n",
    "*This part is optional. The rest of the module keeps the table of spellings and `NM_PER_UNIT`\n",
    "above; here we see what a units library adds, and what it cannot do for us.*\n",
    "\n",
    "Our table knows three units, and every line of it can be read and checked. A **units library**\n",
    "knows thousands, and something more useful: what each unit *measures*. That is its\n",
    "**dimension**. A nanomolar is an amount of substance per volume, a microgram per millilitre is a\n",
    "mass per volume, and a nanometre is a length. Values can only be converted between units of the\n",
    "same dimension. The best-known library for Python is **pint**. `ureg` (short for unit registry)\n",
    "holds every unit pint knows, and `ureg.Unit(\"uM\")` reads a spelling. Here pint reads the spellings\n",
    "from earlier, plus two more:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "        nM -> nanomolar              measures [substance] / [length] ** 3\n",
      "        uM -> micromolar             measures [substance] / [length] ** 3\n",
      "     \\xb5M -> micromolar             measures [substance] / [length] ** 3\n",
      "   \\u03bcM -> micromolar             measures [substance] / [length] ** 3\n",
      "        pM -> picomolar              measures [substance] / [length] ** 3\n",
      "        nm -> nanometer              measures [length]\n",
      "     ug/mL -> microgram / milliliter measures [mass] / [length] ** 3\n"
     ]
    }
   ],
   "source": [
    "ureg = pint.UnitRegistry()\n",
    "for spelling in [\"nM\", \"uM\", \"µM\", \"μM\", \"pM\", \"nm\", \"ug/mL\"]:\n",
    "    unit = ureg.Unit(spelling)\n",
    "    code = spelling.encode(\"unicode_escape\").decode()\n",
    "    print(f\"{code:>10} -> {unit!s:22} measures {unit.dimensionality}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "pint reads `uM`, the micro sign and the Greek mu all as micromolar, which saves us part of the\n",
    "table. `[length] ** 3` is a volume, so `[substance] / [length] ** 3` is amount per volume: a molar\n",
    "concentration. But look at `nm`: pint reads it as a **nanometre**, a length, because that is what\n",
    "the letters mean. Our table maps `nm` to `nM` because *we decided* that a supplier who writes `nm`\n",
    "in a concentration column means nanomolar. A library reads exactly what is written; deciding what\n",
    "a supplier meant stays a written, versioned decision of ours.\n",
    "\n",
    "What the library adds is a check that cannot be fooled by spelling: converting between units of\n",
    "different dimensions is refused, with an error that says why. A **quantity** is a number with its\n",
    "unit, made with `ureg.Quantity(value, unit)`, and `.to(...)` converts it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "4200.0 nanomolar\n",
      "refused: Cannot convert from 'microgram / milliliter' ([mass] / [length] ** 3) to 'nanomolar' ([substance] / [length] ** 3)\n"
     ]
    }
   ],
   "source": [
    "print(ureg.Quantity(4.2, \"uM\").to(\"nM\"))\n",
    "try:\n",
    "    ureg.Quantity(5, \"ug/mL\").to(\"nM\")\n",
    "except pint.DimensionalityError as error:\n",
    "    print(\"refused:\", error)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Some assays do report potency as a mass per volume, such as µg/mL. Turning grams into moles needs\n",
    "the **molecular weight** (grams per mole), and that comes from the structure, which RDKit gives us\n",
    "(`Descriptors.MolWt`). pint has a built-in **context** called `\"chemistry\"` that does the\n",
    "conversion once it is given the molecular weight as `mw`. In the formats, `.2f` means two decimal\n",
    "places and `~P` writes the unit's short symbol:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "aspirin, 180.16 g/mol: 5 µg/ml is 27753.3 nM, pIC50 4.56\n"
     ]
    }
   ],
   "source": [
    "aspirin = Chem.MolFromSmiles(\"CC(=O)Oc1ccccc1C(=O)O\")\n",
    "mw = ureg.Quantity(Descriptors.MolWt(aspirin), \"g/mol\")\n",
    "dose = ureg.Quantity(5, \"ug/mL\")\n",
    "in_nm = dose.to(\"nM\", \"chemistry\", mw=mw)\n",
    "print(f\"aspirin, {mw:.2f~P}: {dose:~P} is {in_nm:.1f~P}, pIC50 {p_activity(in_nm.magnitude):.2f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is also the kind of conversion that goes wrong silently by hand: forget the factor of 1,000\n",
    "between millilitres and litres and the answer is still a plausible-looking number. pint keeps\n",
    "track of every factor. Even so, the molecular weight must be the right one: that of the compound\n",
    "as tested (a salt such as a hydrochloride weighs more than the parent), which is one more reason\n",
    "to standardise structures (Module 7) before converting.\n",
    "\n",
    "Finally, the dimension gives a check that a column holds concentrations at all, whatever the\n",
    "spelling. A spelling pint does not know raises an error, and so does a value with a number in it,\n",
    "so the function treats both as \"no\":"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "     'µM' -> True\n",
      " 'umol/L' -> True\n",
      "     'nm' -> False\n",
      "  'ug/mL' -> False\n",
      "      '%' -> False\n",
      "    'n/a' -> False\n",
      "  '10 nM' -> False\n",
      "       '' -> False\n"
     ]
    }
   ],
   "source": [
    "MOLAR = ureg.Unit(\"M\").dimensionality\n",
    "\n",
    "\n",
    "def is_concentration(units: str) -> bool:\n",
    "    \"\"\"Whether pint reads a spelling as an amount per volume (a molar concentration).\"\"\"\n",
    "    try:\n",
    "        return ureg.Unit(units).dimensionality == MOLAR\n",
    "    except (pint.PintError, ValueError, TypeError):\n",
    "        return False\n",
    "\n",
    "\n",
    "for spelling in [\"µM\", \"umol/L\", \"nm\", \"ug/mL\", \"%\", \"n/a\", \"10 nM\", \"\"]:\n",
    "    print(f\"{spelling!r:>9} -> {is_concentration(spelling)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`umol/L` is a concentration (it is the same as µM) even though our contract does not list it: a\n",
    "library check answers \"is this a concentration?\", and the contract answers \"is this one of the\n",
    "units we agreed?\". A pipeline can use both. In section 4's Pandera schema this function could be a\n",
    "check on the `units` column, `pa.Check(is_concentration, element_wise=True)`, to report rows whose\n",
    "unit is not a concentration at all, before the stricter list of allowed units is applied.\n",
    "\n",
    "**Which to use?** For a few units that never change, a short table with a test, as above, is\n",
    "simple, has no extra package, and is easy to read. When data arrive in many units, in mixed\n",
    "dimensions (molar and mass per volume, or temperatures and volumes from lab instruments), a\n",
    "library such as pint is safer, because every conversion is checked. Other Python units libraries\n",
    "include `astropy.units` and `unyt` (both fast on large NumPy arrays); clinical and laboratory\n",
    "systems often write units in **UCUM**, a standard set of unit codes (`umol/L`, `mg/dL`).\n",
    "\n",
    "The same approach works for any quantity, not only concentrations. Reaction times and\n",
    "temperatures typed by hand (`1 min`, `1mins`, `90 s`, `rt`, `o/n` for overnight) are the classic\n",
    "case: a library reads most of them, a written list of local shorthand covers the rest, and the\n",
    "dimension check catches a slip such as `1m` (a metre, not a minute). Reading lab conditions\n",
    "safely into tables is part of Series 3, *Data Pipelines for Digital and Autonomous Chemistry*\n",
    "(Module 3, \"Reaction and synthesis metadata\"; planned). Homework question 7 is a first taste.\n",
    "\n",
    "## 3. Test data with known faults\n",
    "\n",
    "To see whether checks work, we need data whose faults we know. As in Module 6 we take molecules\n",
    "from `chemlib` and add the measurements ourselves, with fixed seeds so everyone gets the same\n",
    "table. First the compounds table, with an InChIKey for each structure (the square brackets around\n",
    "the `for` loop make a list, one key per SMILES: a **list comprehension**):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO made 2000 compounds\n",
      "compound_id                                          smiles                    inchikey\n",
      "ML-00000267        c1cc(c8ccc(F)cc8)ccc1C(=O)NCc2ccc(OC)cc2 OVAABZUXCGPVDU-UHFFFAOYSA-N\n",
      "ML-00002909 c1nc(C8CCNCC8)cc(n1)N2CCN(CC2)C(=O)c3ccc(Cl)cc3 LLUXFYAMPKXHKJ-UHFFFAOYSA-N\n",
      "ML-00004719            c1cc(OCC)c(cc1)Oc2ccc(cc2)C(=O)N(Br) ADTGZEKAFDLMAF-UHFFFAOYSA-N\n"
     ]
    }
   ],
   "source": [
    "compounds = chemlib.library(N_COMPOUNDS, seed=COMPOUND_SEED)[[\"id\", \"smiles\"]]\n",
    "compounds = compounds.rename(columns={\"id\": \"compound_id\"})\n",
    "compounds[\"inchikey\"] = [Chem.MolToInchiKey(Chem.MolFromSmiles(s)) for s in compounds[\"smiles\"]]\n",
    "log.info(\"made %d compounds\", len(compounds))\n",
    "print(compounds.head(3).to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then 5,000 measurements against five kinase targets. Each potency is drawn on the log scale (as\n",
    "real potencies spread), turned into a value in nM or µM the way a lab would report it, and rounded\n",
    "to three significant figures; the pChEMBL value is worked out from the rounded value, and about\n",
    "one in ten is left empty, as ChEMBL does for values it cannot put on that scale (a value given\n",
    "only as \"> 10 µM\", for example). In the code, `rng` is NumPy's random number generator, started\n",
    "from the seed; `np.where(condition, a, b)` takes `a` where the condition is true and `b` where it\n",
    "is not; `f\"{v:.3g}\"` writes a number to three significant figures; and `f\"M-{i:06d}\"` writes `i`\n",
    "as six digits with leading zeros, so `1` becomes `M-000001`. The empty pChEMBL values are `NaN`\n",
    "(\"not a number\"), which is how pandas and NumPy mark an empty cell in a column of numbers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "measurement_id compound_id target_id activity_type  value units  pchembl\n",
      "      M-000001 ML-01564933      BRAF          EC50 451.00    nM     6.35\n",
      "      M-000002 ML-01522653      CDK2          EC50   2.94    µM     5.53\n",
      "      M-000003 ML-01441112      CDK2          IC50   6.78    µM     5.17\n",
      "      M-000004 ML-01506847      ABL1            Ki   4.20    µM     5.38\n",
      "{'nM': 2694, 'µM': 2306}\n"
     ]
    }
   ],
   "source": [
    "def make_measurements(compounds: pd.DataFrame, n: int, seed: int) -> pd.DataFrame:\n",
    "    \"\"\"n synthetic measurements for random compounds, with consistent values, units and pChEMBL.\"\"\"\n",
    "    rng = np.random.default_rng(seed)\n",
    "    rows = compounds.iloc[rng.integers(0, len(compounds), n)].reset_index(drop=True)\n",
    "    potency = rng.normal(6.5, 1.2, n).clip(3.5, 10.5)  # on the pIC50 scale\n",
    "    value_nm = 10 ** (9 - potency)\n",
    "    micromolar = (value_nm >= 1_000) | (rng.random(n) < 0.2)\n",
    "    units = np.where(micromolar, \"µM\", \"nM\")\n",
    "    value = np.where(micromolar, value_nm / 1_000, value_nm)\n",
    "    value = np.array([float(f\"{v:.3g}\") for v in value])  # three significant figures\n",
    "    pchembl = np.round(9 - np.log10(np.where(micromolar, value * 1_000, value)), 2)\n",
    "    pchembl[rng.random(n) < 0.1] = np.nan\n",
    "    return pd.DataFrame(\n",
    "        {\n",
    "            \"measurement_id\": [f\"M-{i:06d}\" for i in range(1, n + 1)],\n",
    "            \"compound_id\": rows[\"compound_id\"],\n",
    "            \"smiles\": rows[\"smiles\"],\n",
    "            \"inchikey\": rows[\"inchikey\"],\n",
    "            \"target_id\": rng.choice(TARGETS, n),\n",
    "            \"activity_type\": rng.choice([t.value for t in ActivityType], n,\n",
    "                                        p=[0.6, 0.2, 0.1, 0.1]),\n",
    "            \"value\": value,\n",
    "            \"units\": units,\n",
    "            \"pchembl\": pchembl,\n",
    "        }\n",
    "    )\n",
    "\n",
    "\n",
    "clean = make_measurements(compounds, N_MEASUREMENTS, seed=MEASUREMENT_SEED)\n",
    "print(clean[[\"measurement_id\", \"compound_id\", \"target_id\", \"activity_type\", \"value\", \"units\",\n",
    "             \"pchembl\"]].head(4).to_string(index=False))\n",
    "print(clean[\"units\"].value_counts().to_dict())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now the faults. Each kind goes into a few rows, more for the common faults than for the rare\n",
    "ones, chosen with a fixed seed; a separate `fault` series (a pandas `Series`, a single column with\n",
    "the same row labels as the table) records which row got which, so we can\n",
    "check the checks afterwards. These are the faults real activity files have: units missing or\n",
    "misspelled, a sign error, a row loaded twice, a broken or misplaced InChIKey, a pChEMBL worked out\n",
    "in the wrong units, and a compound the compounds table does not know.\n",
    "\n",
    "The function is longer than most in the course, but each `for` loop does one thing: it picks rows\n",
    "for one kind of fault and spoils them. You do not need to follow every line. What matters is what\n",
    "comes out: the damaged table, `batch`, and the series `truth`, which says which row got which fault\n",
    "(`\"\"` for none). Inside it, `pick` is a small function defined within the function; `used` is a\n",
    "**set** (a collection with no repeats), so no row gets two faults; and `tuple[pd.DataFrame,\n",
    "pd.Series]` in the first line is a type hint saying the function returns two things, a table and a\n",
    "series, which `batch, truth = ...` then receives."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "5020 rows, 100 with a fault\n",
      "InChIKey of another compound     8\n",
      "duplicate measurement           20\n",
      "malformed InChIKey               4\n",
      "negative value                   5\n",
      "pchembl in wrong units          12\n",
      "units missing                   15\n",
      "unknown compound                 6\n",
      "µM written as uM                30\n"
     ]
    }
   ],
   "source": [
    "FAULTS = {\n",
    "    \"µM written as uM\": 30,\n",
    "    \"duplicate measurement\": 20,\n",
    "    \"units missing\": 15,\n",
    "    \"pchembl in wrong units\": 12,\n",
    "    \"InChIKey of another compound\": 8,\n",
    "    \"unknown compound\": 6,\n",
    "    \"negative value\": 5,\n",
    "    \"malformed InChIKey\": 4,\n",
    "}\n",
    "\n",
    "\n",
    "def inject_faults(df: pd.DataFrame, seed: int) -> tuple[pd.DataFrame, pd.Series]:\n",
    "    \"\"\"A copy of df with FAULTS added, and a series saying which row has which (\"\" if none).\"\"\"\n",
    "    rng = np.random.default_rng(seed)\n",
    "    out = df.copy()\n",
    "    fault = pd.Series(\"\", index=out.index)\n",
    "    micromolar = out.index[out[\"units\"] == \"µM\"]\n",
    "    with_pchembl = out.index[out[\"pchembl\"].notna() & (out[\"units\"] == \"µM\")]\n",
    "    used: set[int] = set()\n",
    "\n",
    "    def pick(kind: str, pool: pd.Index) -> list[int]:\n",
    "        \"\"\"FAULTS[kind] rows from pool that have no fault yet.\"\"\"\n",
    "        free = [i for i in pool if i not in used]\n",
    "        chosen = [int(i) for i in rng.choice(free, FAULTS[kind], replace=False)]\n",
    "        used.update(chosen)\n",
    "        if kind != \"duplicate measurement\":  # duplicates are new rows, added below\n",
    "            fault[chosen] = kind\n",
    "        return chosen\n",
    "\n",
    "    for i in pick(\"units missing\", out.index):\n",
    "        out.loc[i, \"units\"] = None\n",
    "    for i in pick(\"µM written as uM\", micromolar):\n",
    "        out.loc[i, \"units\"] = \"uM\"\n",
    "    for i in pick(\"negative value\", out.index):\n",
    "        out.loc[i, \"value\"] = -out.loc[i, \"value\"]\n",
    "    for i in pick(\"malformed InChIKey\", out.index):\n",
    "        out.loc[i, \"inchikey\"] = out.loc[i, \"inchikey\"][:-2]  # the final \"-N\" cut off\n",
    "    for i in pick(\"InChIKey of another compound\", out.index):\n",
    "        others = compounds.loc[compounds[\"inchikey\"] != out.loc[i, \"inchikey\"], \"inchikey\"]\n",
    "        out.loc[i, \"inchikey\"] = others.iloc[int(rng.integers(len(others)))]\n",
    "    for i in pick(\"pchembl in wrong units\", with_pchembl):\n",
    "        out.loc[i, \"pchembl\"] = round(9 - math.log10(out.loc[i, \"value\"]), 2)  # as if in nM\n",
    "    for i in pick(\"unknown compound\", out.index):\n",
    "        out.loc[i, \"compound_id\"] = f\"ML-9{i:07d}\"\n",
    "    copies = out.loc[pick(\"duplicate measurement\", out.index)].copy()  # loaded a second time\n",
    "    copies[\"measurement_id\"] = [f\"M-{len(out) + k:06d}\" for k in range(1, len(copies) + 1)]\n",
    "    out = pd.concat([out, copies], ignore_index=True)\n",
    "    fault = pd.concat([fault, pd.Series(\"duplicate measurement\", index=range(len(df), len(out)))])\n",
    "    return out, fault\n",
    "\n",
    "\n",
    "batch, truth = inject_faults(clean, seed=FAULT_SEED)\n",
    "print(len(batch), \"rows,\", int((truth != \"\").sum()), \"with a fault\")\n",
    "print(truth[truth != \"\"].value_counts().sort_index().to_string())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Tables with Pandera\n",
    "\n",
    "### A schema for the whole table\n",
    "\n",
    "A **schema** is the description of a table: its columns, their types and the rules the data must\n",
    "follow. A Pandera schema is the contract written as code for a pandas DataFrame: one entry per\n",
    "column with its type, whether it may be empty, whether it must be unique, and its checks; then\n",
    "checks that involve several columns or the whole table. The built-in checks are `isin` (the value\n",
    "is one of a list), `gt` (greater than), `in_range` (between two numbers) and `str_matches` (the\n",
    "text matches a regular expression). They are **vectorised**: each runs once over a whole column,\n",
    "in fast compiled code, not once per row in a Python loop.\n",
    "\n",
    "Two rules need our own code. The pChEMBL rule compares three columns, so it is a table-level\n",
    "check that returns `True` or `False` for every row. The InChIKey rule needs RDKit, so it works out\n",
    "the key once for each different SMILES (there are fewer SMILES than rows) and compares. Rows that\n",
    "fail a simpler rule (a negative value, a missing unit) pass these two, so that each fault is\n",
    "reported once, by the check that names it.\n",
    "\n",
    "In these two functions, `~` means \"not\" and `|` means \"or\" for a whole column of `True` and\n",
    "`False` values at once; `.map(...)` looks up each value of a column in a dictionary; and\n",
    "`.where(checkable, 1.0)` keeps a value where `checkable` is true and puts 1.0 elsewhere, so that\n",
    "the logarithm is never taken of a missing or negative value."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "schema columns match the contract: True\n",
      "INFO the clean table passes: 5000 rows\n"
     ]
    }
   ],
   "source": [
    "INCHIKEY = r\"^[A-Z]{14}-[A-Z]{10}-[A-Z]$\"\n",
    "\n",
    "\n",
    "def pchembl_matches_value(df: pd.DataFrame) -> pd.Series:\n",
    "    \"\"\"True where pchembl is empty, cannot be checked yet, or equals 9 - log10(value in nM).\"\"\"\n",
    "    factor = df[\"units\"].map({u.value: f for u, f in NM_PER_UNIT.items()})\n",
    "    checkable = df[\"pchembl\"].notna() & factor.notna() & (df[\"value\"] > 0)\n",
    "    value_nm = (df[\"value\"] * factor).where(checkable, 1.0)\n",
    "    expected = 9 - np.log10(value_nm.astype(float))\n",
    "    return ~checkable | ((df[\"pchembl\"] - expected).abs() <= PCHEMBL_TOLERANCE)\n",
    "\n",
    "\n",
    "def inchikey_matches_smiles(df: pd.DataFrame) -> pd.Series:\n",
    "    \"\"\"True where the InChIKey is malformed (another check reports it) or matches the SMILES.\"\"\"\n",
    "    keys = {s: Chem.MolToInchiKey(Chem.MolFromSmiles(s)) for s in df[\"smiles\"].unique()}\n",
    "    well_formed = df[\"inchikey\"].str.match(INCHIKEY)\n",
    "    return ~well_formed | (df[\"smiles\"].map(keys) == df[\"inchikey\"])\n",
    "\n",
    "\n",
    "def measurement_schema(known_compounds: pd.Series) -> pa.DataFrameSchema:\n",
    "    \"\"\"The measurements contract, version 1.0.0, as a Pandera schema.\"\"\"\n",
    "    return pa.DataFrameSchema(\n",
    "        {\n",
    "            \"measurement_id\": pa.Column(str, pa.Check.str_matches(MEASUREMENT_ID), unique=True),\n",
    "            \"compound_id\": pa.Column(str, [pa.Check.str_matches(COMPOUND_ID),\n",
    "                                           pa.Check.isin(known_compounds.tolist())]),\n",
    "            \"smiles\": pa.Column(str),\n",
    "            \"inchikey\": pa.Column(str, pa.Check.str_matches(INCHIKEY)),\n",
    "            \"target_id\": pa.Column(str, pa.Check.isin(TARGETS)),\n",
    "            \"activity_type\": pa.Column(str, pa.Check.isin([t.value for t in ActivityType])),\n",
    "            \"value\": pa.Column(float, pa.Check.gt(0)),\n",
    "            \"units\": pa.Column(str, pa.Check.isin([u.value for u in Unit])),\n",
    "            \"pchembl\": pa.Column(float, pa.Check.in_range(0, 14), nullable=True),\n",
    "        },\n",
    "        checks=[\n",
    "            pa.Check(pchembl_matches_value, name=\"pchembl_matches_value\"),\n",
    "            pa.Check(inchikey_matches_smiles, name=\"inchikey_matches_smiles\"),\n",
    "        ],\n",
    "        unique=[\"compound_id\", \"target_id\", \"activity_type\", \"value\", \"units\"],\n",
    "        report_duplicates=\"exclude_first\",\n",
    "        strict=True,\n",
    "        name=f\"measurements {CONTRACT['version']}\",\n",
    "    )\n",
    "\n",
    "\n",
    "schema = measurement_schema(compounds[\"compound_id\"])\n",
    "print(\"schema columns match the contract:\", list(schema.columns) == list(CONTRACT[\"columns\"]))\n",
    "log.info(\"the clean table passes: %d rows\", len(schema.validate(clean)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`strict=True` refuses a table with columns the contract does not name, the table-level twin of\n",
    "Pydantic's `extra=\"forbid\"`. The first line checks that the schema and the written contract name\n",
    "the same columns, so the two cannot drift apart unnoticed. The check that every `compound_id`\n",
    "exists in the compounds table is a link between tables, the job a **foreign key** does in a\n",
    "database (a column whose values must exist in another table, Module 4); checking it here catches\n",
    "the problem before the load, with the row that caused it. `unique=[...]` says that no two rows may\n",
    "have the same values in all five of those columns, and `report_duplicates=\"exclude_first\"` reports\n",
    "the second copy of a duplicated measurement and keeps the first.\n",
    "\n",
    "Pandera can also write a schema as a class (`pa.DataFrameModel`), in the same style as a\n",
    "Pydantic model; the checks are the same, and a function that returns a `DataFrameSchema` is\n",
    "easier when part of the schema (here the list of known compounds) is only known at run time.\n",
    "\n",
    "### Lazy validation: every failure at once\n",
    "\n",
    "By default Pandera stops at the first failure, like Python stops at the first error. For a\n",
    "batch that is not useful: fixing one problem, rerunning and finding the next wastes a day. With\n",
    "`lazy=True` it runs every check and raises one `SchemaErrors` whose `failure_cases` table lists\n",
    "every failure: which column, which check, the value that failed and the row's index (its row\n",
    "label: row 5000 is the 5,001st row, since counting starts at 0)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "339 failure cases\n",
      "     column                      check failure_case  index\n",
      "compound_id multiple_fields_uniqueness  ML-00345391   5000\n",
      "compound_id multiple_fields_uniqueness  ML-00214734   5001\n",
      "compound_id multiple_fields_uniqueness  ML-01539024   5002\n",
      "compound_id multiple_fields_uniqueness  ML-01601965   5003\n",
      "compound_id multiple_fields_uniqueness  ML-01557373   5004\n",
      "compound_id multiple_fields_uniqueness  ML-00398134   5005\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    schema.validate(batch, lazy=True)\n",
    "except pa.errors.SchemaErrors as error:\n",
    "    failures = error.failure_cases\n",
    "print(len(failures), \"failure cases\")\n",
    "print(failures[[\"column\", \"check\", \"failure_case\", \"index\"]].head(6).to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A check that involves several columns (uniqueness over five columns, our two table-level checks)\n",
    "lists one failure case per column for each failing row, so failure cases are not rows. Counting\n",
    "the different rows each check fails gives the report we want, with a short label for each check.\n",
    "`failures.apply(label, axis=1)` runs `label` on every row of the failures table; `drop_duplicates`\n",
    "then keeps one line per check and row, and `groupby(\"label\").size()` counts the rows for each\n",
    "check:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "label\n",
      "units: isin                   30\n",
      "multiple_fields_uniqueness    20\n",
      "units: not_nullable           15\n",
      "pchembl_matches_value         12\n",
      "inchikey_matches_smiles        8\n",
      "compound_id: isin              6\n",
      "value: greater_than            5\n",
      "inchikey: str_matches          4\n"
     ]
    }
   ],
   "source": [
    "def label(row: pd.Series) -> str:\n",
    "    \"\"\"A short name for a failed check: the column (for column checks) and the check's name.\"\"\"\n",
    "    check = str(row[\"check\"]).split(\"(\")[0]\n",
    "    if row[\"schema_context\"] == \"Column\":\n",
    "        return f\"{row['column']}: {check}\"\n",
    "    return check\n",
    "\n",
    "\n",
    "failures[\"label\"] = failures.apply(label, axis=1)\n",
    "failed_rows = failures.dropna(subset=[\"index\"]).drop_duplicates([\"label\", \"index\"])\n",
    "by_check = failed_rows.groupby(\"label\").size().sort_values(ascending=False)\n",
    "print(by_check.to_string())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![Validation failures by check, one bar per check, counting the rows each check failed](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/12-validating-data/figures/failures-by-check.svg)\n",
    "\n",
    "The malformed InChIKeys are counted once, by the format check, because the matching check skips\n",
    "keys it cannot read. Every kind of fault we injected is caught by the check that names it. Is that\n",
    "all of them, and did any clean row fail? The `fault` series, which we called `truth`, lets us\n",
    "check the checks. With two sets of row numbers, `&` gives the rows in both and `-` the rows in the\n",
    "first but not the second:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "injected faults caught: 100 of 100\n",
      "clean rows flagged: 0\n"
     ]
    }
   ],
   "source": [
    "caught = set(failed_rows[\"index\"].astype(int))\n",
    "injected = set(truth.index[truth != \"\"])\n",
    "print(\"injected faults caught:\", len(injected & caught), \"of\", len(injected))\n",
    "print(\"clean rows flagged:\", len(caught - injected))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Quarantine the failing rows, keep the rest\n",
    "\n",
    "A failing row is not deleted. It goes to a **quarantine** table with the reasons it failed, so\n",
    "someone can fix it at the source, and the batch carries on without it. The rest is validated\n",
    "again: what goes into the database must pass the whole contract. A row that fails several checks\n",
    "gets all their names, joined by `; `. The `lambda s: ...` in the first line is a **lambda**, a\n",
    "one-line function without a name, written where it is used."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO kept 4920 rows, quarantined 100\n",
      "measurement_id units   value                  reason\n",
      "      M-000089    µM   9.000   pchembl_matches_value\n",
      "      M-000153    uM   5.600             units: isin\n",
      "      M-000176    uM   0.446             units: isin\n",
      "      M-000235    nM 806.000 inchikey_matches_smiles\n"
     ]
    }
   ],
   "source": [
    "reasons = failed_rows.groupby(\"index\")[\"label\"].apply(lambda s: \"; \".join(sorted(s)))\n",
    "reasons.index = reasons.index.astype(int)\n",
    "quarantine = batch.loc[reasons.index].assign(reason=reasons)\n",
    "kept = batch.drop(index=reasons.index)\n",
    "schema.validate(kept, lazy=True)  # raises if anything that fails is still there\n",
    "log.info(\"kept %d rows, quarantined %d\", len(kept), len(quarantine))\n",
    "print(quarantine[[\"measurement_id\", \"units\", \"value\", \"reason\"]].head(4).to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The quarantine is a table like any other, so it belongs in the database next to the data, with\n",
    "the batch it came from. Here it goes into DuckDB, a database in one file (Module 4); the same SQL\n",
    "works in PostgreSQL, the database server of Module 4. **SQL** is the language databases are asked questions in, and a question\n",
    "written in it is a **query**. Then a question such as \"what goes wrong most often, and from which\n",
    "batch?\" is one query.\n",
    "\n",
    "`with duckdb.connect(...) as db:` opens the database file and closes it again when the indented\n",
    "block ends, even if something in it fails (a `with` block). Inside, `CREATE TABLE ... AS SELECT *\n",
    "FROM kept` copies the pandas table `kept` into the database; DuckDB finds it by its Python name.\n",
    "The `?` is filled in with `BATCH_ID`, and `GROUP BY ALL` counts the rows for each batch and\n",
    "reason:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "('batch-0001', 'units: isin', 30)\n",
      "('batch-0001', 'multiple_fields_uniqueness', 20)\n",
      "('batch-0001', 'units: not_nullable', 15)\n",
      "('batch-0001', 'pchembl_matches_value', 12)\n",
      "('batch-0001', 'inchikey_matches_smiles', 8)\n",
      "('batch-0001', 'compound_id: isin', 6)\n",
      "('batch-0001', 'value: greater_than', 5)\n",
      "('batch-0001', 'inchikey: str_matches', 4)\n"
     ]
    }
   ],
   "source": [
    "DB_PATH.unlink(missing_ok=True)\n",
    "with duckdb.connect(str(DB_PATH)) as db:\n",
    "    db.execute(\"CREATE TABLE measurements AS SELECT * FROM kept\")\n",
    "    db.execute(\"CREATE TABLE quarantine AS SELECT ? AS batch_id, * FROM quarantine\", [BATCH_ID])\n",
    "    for row in db.sql(\n",
    "        \"SELECT batch_id, reason, count(*) AS n_rows FROM quarantine \"\n",
    "        \"GROUP BY ALL ORDER BY n_rows DESC, reason\"\n",
    "    ).fetchall():\n",
    "        print(row)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Stop the batch, or let it through?\n",
    "\n",
    "Quarantining a few rows is right when the batch is mostly good. When many rows fail, the problem\n",
    "is usually the whole batch (a supplier changed a column's units, an export was cut short), and\n",
    "loading the good part would give a table that looks complete but is not. A pipeline therefore\n",
    "decides per batch, with a threshold written down in advance, and records the decision.\n",
    "\n",
    "Two more checks belong here, and neither looks at single rows. A missing column fails the whole\n",
    "table at once: there is nothing to quarantine. And the counts must agree with the source: if the\n",
    "supplier's **manifest** (a short list sent with the file, saying what is in it) says 5,020 rows,\n",
    "the rows we kept and quarantined must add up to 5,020, or rows have been lost or added on the way.\n",
    "\n",
    "The decision is a small record of its own, so it is written as a frozen dataclass (met in\n",
    "[Module 8](../08-larger-than-memory/)): a class that only holds named fields, cannot be changed\n",
    "once made, and prints itself readably (`slots=True` stops a misspelt field being added by\n",
    "accident). The `@dataclass(...)` line above it is a decorator, as in section 2: it writes the\n",
    "class's plumbing for us.\n",
    "\n",
    "In the `log.info` line, each `%d` is filled with a whole number, `%s` with text and `%.2f` with a\n",
    "number to two decimal places, in order; `%%` prints a plain `%`. The last part of the code checks\n",
    "the same batch with its `units` column removed, and `.query(...)` picks out the failure for the\n",
    "missing column."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "rows agree with the manifest: True\n",
      "INFO batch-0001: 100 of 5020 rows failed (1.99%), load\n",
      "BatchDecision(batch_id='batch-0001', n_rows=5020, n_failed=100, action='load')\n",
      "ERROR batch stopped, column missing: ['units']\n"
     ]
    }
   ],
   "source": [
    "@dataclass(frozen=True, slots=True)\n",
    "class BatchDecision:\n",
    "    \"\"\"What was decided about one batch, and the numbers it was decided on.\"\"\"\n",
    "\n",
    "    batch_id: str\n",
    "    n_rows: int\n",
    "    n_failed: int\n",
    "    action: str  # \"load\" or \"stop\"\n",
    "\n",
    "\n",
    "def decide(batch_id: str, n_rows: int, n_failed: int,\n",
    "           max_failed_share: float = MAX_FAILED_SHARE) -> BatchDecision:\n",
    "    \"\"\"Load the batch if its share of failing rows is within the threshold, otherwise stop it.\"\"\"\n",
    "    action = \"load\" if n_failed / n_rows <= max_failed_share else \"stop\"\n",
    "    return BatchDecision(batch_id, n_rows, n_failed, action)\n",
    "\n",
    "\n",
    "supplier_manifest = {\"file\": f\"{BATCH_ID}.csv\", \"rows\": 5_020}\n",
    "print(\"rows agree with the manifest:\",\n",
    "      len(kept) + len(quarantine) == len(batch) == supplier_manifest[\"rows\"])\n",
    "decision = decide(BATCH_ID, len(batch), len(quarantine))\n",
    "log.info(\"%s: %d of %d rows failed (%.2f%%), %s\", decision.batch_id, decision.n_failed,\n",
    "         decision.n_rows, 100 * decision.n_failed / decision.n_rows, decision.action)\n",
    "print(decision)\n",
    "\n",
    "try:\n",
    "    schema.validate(batch.drop(columns=\"units\"), lazy=True)\n",
    "except pa.errors.SchemaErrors as error:\n",
    "    missing = error.failure_cases.query(\"check == 'column_in_dataframe'\")\n",
    "    log.error(\"batch stopped, column missing: %s\", missing[\"failure_case\"].tolist())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With 1.99% of rows failing against a threshold of 5%, this batch is loaded and its 100\n",
    "failing rows wait in quarantine. The same batch without its `units` column is stopped outright.\n",
    "The decision and its reason are themselves data: a run that stopped a batch should say which\n",
    "batch, which checks failed and how often, and Module 14 turns exactly these counts into alerts.\n",
    "\n",
    "## 5. Records or tables? Measuring the difference\n",
    "\n",
    "*The timing in this section is optional: it measures why we use two tools. If you are short of\n",
    "time, read the list at the end of the section and move on; nothing later in the course depends on\n",
    "the timing code.*\n",
    "\n",
    "Pydantic could check the whole table too: turn each row into a dictionary and validate it. The\n",
    "answer would be the same, but the cost is not, because the work is done once per row in Python\n",
    "instead of once per column in compiled code. To compare fairly, both check the same rules: the\n",
    "activity part of the contract, without RDKit (which costs the same in both). We use about 200,000\n",
    "rows, the batch repeated forty times, and time the two parts of the Pydantic route separately:\n",
    "turning rows into dictionaries, and validating them. `time.perf_counter()` reads a stopwatch, so\n",
    "the time a step took is the reading after it minus the reading before; `enumerate(records)` gives\n",
    "each record together with its position."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ACTIVITY_COLUMNS = [\"target_id\", \"activity_type\", \"value\", \"units\", \"pchembl\"]\n",
    "activity_schema = pa.DataFrameSchema(\n",
    "    {name: schema.columns[name] for name in ACTIVITY_COLUMNS},\n",
    "    checks=[pa.Check(pchembl_matches_value, name=\"pchembl_matches_value\")],\n",
    ")\n",
    "big = pd.concat([batch[ACTIVITY_COLUMNS]] * BENCHMARK_COPIES, ignore_index=True)\n",
    "\n",
    "\n",
    "def as_records(df: pd.DataFrame) -> list[dict]:\n",
    "    \"\"\"One dictionary per row, with empty cells as None (what Pydantic expects).\"\"\"\n",
    "    return df.astype(object).where(df.notna(), None).to_dict(\"records\")\n",
    "\n",
    "\n",
    "def failing_records(records: list[dict]) -> set[int]:\n",
    "    \"\"\"Validate every record as an Activity; the positions of the records that fail.\"\"\"\n",
    "    failed: set[int] = set()\n",
    "    for i, record in enumerate(records):\n",
    "        try:\n",
    "            Activity.model_validate(record)\n",
    "        except ValidationError:\n",
    "            failed.add(i)\n",
    "    return failed\n",
    "\n",
    "\n",
    "def failing_rows(df: pd.DataFrame) -> set[int]:\n",
    "    \"\"\"Validate the table in one lazy pass; the positions of the rows that fail.\"\"\"\n",
    "    try:\n",
    "        activity_schema.validate(df, lazy=True)\n",
    "    except pa.errors.SchemaErrors as error:\n",
    "        return set(error.failure_cases[\"index\"].dropna().astype(int))\n",
    "    return set()\n",
    "\n",
    "\n",
    "start = time.perf_counter()\n",
    "records = as_records(big)\n",
    "to_records_s = time.perf_counter() - start\n",
    "start = time.perf_counter()\n",
    "by_record = failing_records(records)\n",
    "pydantic_s = time.perf_counter() - start\n",
    "start = time.perf_counter()\n",
    "by_table = failing_rows(big)\n",
    "pandera_s = time.perf_counter() - start"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Both find exactly the same rows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "200800 rows; 2480 fail; same rows: True\n"
     ]
    }
   ],
   "source": [
    "print(len(big), \"rows;\", len(by_record), \"fail;\", \"same rows:\", by_record == by_table)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "and the times, with what they mean for a million rows. Your times will differ from these, since\n",
    "they depend on the computer (the box is labelled **Example output** on the lesson's page):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "rows to dictionaries:          1.01 s\n",
      "Pydantic, one record at a time: 1.06 s (5.3 microseconds per record)\n",
      "Pandera, one pass over the table: 0.13 s\n",
      "for a million rows: about 10.3 s one record at a time, 0.6 s as a table (16 times faster)\n"
     ]
    }
   ],
   "source": [
    "per_million = 1_000_000 / len(big)\n",
    "record_route = to_records_s + pydantic_s\n",
    "print(f\"rows to dictionaries:          {to_records_s:.2f} s\")\n",
    "print(f\"Pydantic, one record at a time: {pydantic_s:.2f} s \"\n",
    "      f\"({pydantic_s / len(big) * 1e6:.1f} microseconds per record)\")\n",
    "print(f\"Pandera, one pass over the table: {pandera_s:.2f} s\")\n",
    "print(f\"for a million rows: about {record_route * per_million:.1f} s one record at a time, \"\n",
    "      f\"{pandera_s * per_million:.1f} s as a table ({record_route / pandera_s:.0f} times faster)\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Pydantic's core is written in Rust, a language that is compiled to fast machine code, and is\n",
    "fast for what it does: a few microseconds per record\n",
    "is nothing when records arrive one at a time from an API. The cost of the record route is\n",
    "everything around it: every row becomes a Python dictionary first (often as long as the validation\n",
    "itself) and every record a Python object, and a pipeline that checks a million rows at several\n",
    "steps pays that every time. Vectorised checks pay once per column, and the gap widens as tables\n",
    "grow, because Pandera's fixed cost per check is spread over more rows. Speed is not the only\n",
    "difference: the table route also gives one report of every failure, ready to quarantine.\n",
    "\n",
    "So the rule of thumb is:\n",
    "\n",
    "- **Pydantic at the edges**: one record, one message, one API response, one settings file. You\n",
    "  want a typed object to work with, and an error that says exactly which field of which record is\n",
    "  wrong, at the moment it arrives.\n",
    "- **Pandera in the middle**: tables between steps and before a load. You want every failure in\n",
    "  one report, a quarantine and a count, at the speed of the table.\n",
    "\n",
    "Both check the same contract, so a rule should not live in only one of them. Pandera also checks\n",
    "Polars, Dask and PySpark tables (the table packages for data larger than memory and for many\n",
    "computers, Modules 8 and 9), so the same schema follows a pipeline as it grows. Teams that check\n",
    "data inside a **data warehouse** (a large database built for analysis) use tools such as dbt\n",
    "tests, Great Expectations or Soda for the same job; dbt, which Series 2 introduces, has tests for\n",
    "it too.\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",
    "- The Pydantic documentation, in particular *Validators*.\n",
    "  <https://docs.pydantic.dev/latest/concepts/validators/>\n",
    "- The Pandera documentation, in particular *Lazy Validation*.\n",
    "  <https://pandera.readthedocs.io/en/stable/lazy_validation.html>\n",
    "- Bantilan, N. (2020). pandera: Statistical Data Validation of Pandas Dataframes. *Proceedings of\n",
    "  the 19th Python in Science Conference*, 116–124. <https://doi.org/10.25080/Majora-342d178e-010>\n",
    "- Kramer, C., Kalliokoski, T., Gedeck, P. & Vulpetti, A. (2012). The Experimental Uncertainty of\n",
    "  Heterogeneous Public Ki Data. *Journal of Medicinal Chemistry*, 55(11), 5165–5173.\n",
    "  <https://doi.org/10.1021/jm300131x>\n",
    "- Papadatos, G., Gaulton, A., Hersey, A. & Overington, J. P. (2015). Activity, assay and target\n",
    "  data curation and quality in the ChEMBL database. *Journal of Computer-Aided Molecular Design*,\n",
    "  29(9), 885–896. <https://doi.org/10.1007/s10822-015-9860-5>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
