{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Libraries larger than memory\n",
    "\n",
    "Stream molecules in batches, write a partitioned Parquet dataset and query it with DuckDB, so a library far larger than memory is processed in a fixed amount of memory.\n",
    "\n",
    "The lesson's page: https://monstrous.com.ng/learn/data-engineering/series-1/08-larger-than-memory/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Install what this lesson needs (in Colab, or any fresh environment)\n",
    "%pip install -q pandas pyarrow rdkit numpy psutil duckdb tqdm\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": [
    "Screening libraries are large and getting larger. Make-on-demand catalogues (lists of molecules a\n",
    "supplier has never made but can synthesise to order) already offer tens of billions of molecules\n",
    "(Irwin et al., 2020, in the further reading), and even an in-house collection with fingerprints and\n",
    "descriptors soon outgrows a laptop's **memory**. Memory here means the computer's working memory\n",
    "(RAM): the fast, limited space a program holds its data in while it runs, usually 8 to 32 GB on a\n",
    "laptop. The disk, where files are kept, is far larger but much slower.\n",
    "\n",
    "The first version of most pipelines reads the whole file into a pandas table at once. That works on\n",
    "a small test file and then fails on the real one, often hours in: the computer runs out of memory,\n",
    "starts moving memory to the disk to make room (called **swapping**, which makes everything crawl),\n",
    "and in the end the operating system stops the program. Data engineers avoid this by never holding\n",
    "the whole library at once. They **stream** it: read a **batch** of a few thousand molecules,\n",
    "process it, write the results to a file, forget the batch and read the next. They also keep each\n",
    "column in the smallest form that holds it, store the results in a file format that can be read in\n",
    "pieces, and ask questions of that file with a tool that reads only the parts each question needs.\n",
    "\n",
    "By the end of this module you will be able to:\n",
    "\n",
    "- measure how much memory a library takes as a table, as RDKit molecules and as fingerprints, and\n",
    "  compare it with the size of the file on disk;\n",
    "- find out which line of your code uses the memory, before trying to save any, and choose how to\n",
    "  hold each record (as a dictionary, a named tuple or a dataclass) by what it costs;\n",
    "- process a library in batches, so the memory used stays the same however large the library is;\n",
    "- count and summarise the molecules as they pass, without keeping them;\n",
    "- show how far a long run has got: a progress bar for a person watching, a line in the log every\n",
    "  so often for a job nobody is watching;\n",
    "- make a table smaller by storing each column in a smaller type, checked against the data;\n",
    "- write a library as a folder of Parquet files, split by vendor, and read back only the columns\n",
    "  and rows a question needs;\n",
    "- ask questions of the whole folder with DuckDB, without loading it into memory.\n",
    "\n",
    "This module builds on earlier ones: Parquet files and generators (functions that hand out records\n",
    "one at a time) from [Module 3](../03-files-and-identity/), and the damaged molecules made with\n",
    "`chemlib.add_defects` from [Module 6](../06-validating-molecules/). `chemlib` is the course's own\n",
    "small helper file that makes a made-up but realistic teaching library of molecules, with ids,\n",
    "SMILES, vendors, prices and stock. It can make 1,733,400 molecules. We use a few hundred thousand\n",
    "of them for plain data and a few tens of thousands for RDKit work, so the lesson runs in about a\n",
    "minute, and we say at each step how the same code scales.\n",
    "\n",
    "The lesson uses these packages (each is introduced again where it is first used):\n",
    "\n",
    "- **pandas**, for tables, and **NumPy**, for arrays of numbers, as in the earlier modules;\n",
    "- **PyArrow**, the Python package of **Apache Arrow**, a way of holding tables in memory column by\n",
    "  column; it also reads and writes Parquet files;\n",
    "- **RDKit**, for molecules, as before;\n",
    "- **psutil**, which reports how much memory a running program is using;\n",
    "- **DuckDB**, a small database that runs inside Python and can answer questions about Parquet\n",
    "  files directly;\n",
    "- **tqdm**, which draws progress bars.\n",
    "\n",
    "We also use several parts of Python's **standard library** (the modules that come with Python\n",
    "itself, such as `collections`, `itertools` and `tracemalloc`); each is explained where it is used.\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; Module 1 explains\n",
    "why. The block is long because the lesson covers a lot of ground: you do not need to read every\n",
    "setting now, as each section says which ones it uses.\n",
    "\n",
    "The lesson writes its files into a folder called `work`, next to the notebook (in Colab, in the\n",
    "Files panel on the left). In the numbers, `20_000` is Python's way of writing 20,000: the\n",
    "underscores are ignored and only make the number easier to read."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "the generator can make 1,733,400 molecules; we stream 300,000 in batches of 25,000\n"
     ]
    }
   ],
   "source": [
    "import csv\n",
    "import logging\n",
    "import math\n",
    "import re\n",
    "import shutil\n",
    "import sys\n",
    "import threading\n",
    "import time\n",
    "import tracemalloc\n",
    "from collections import Counter, defaultdict, deque, namedtuple\n",
    "from collections.abc import Callable, Iterable, Iterator\n",
    "from dataclasses import dataclass\n",
    "from itertools import chain, groupby, islice\n",
    "from pathlib import Path\n",
    "\n",
    "import duckdb\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import psutil\n",
    "import pyarrow as pa\n",
    "import pyarrow.compute as pc\n",
    "import pyarrow.dataset as ds\n",
    "import pyarrow.parquet as pq\n",
    "from rdkit import Chem\n",
    "from rdkit.Chem import Descriptors, rdFingerprintGenerator\n",
    "from tqdm import tqdm\n",
    "from tqdm.contrib.logging import logging_redirect_tqdm\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",
    "SAMPLE_CSV = WORK / \"sample.csv\"\n",
    "SAMPLE_PARQUET = WORK / \"sample.parquet\"\n",
    "STREAMED = WORK / \"stream.parquet\"  # the streamed library, made in section 3\n",
    "LOADED = WORK / \"load-everything.parquet\"  # the same, made by loading everything\n",
    "DESCRIPTORS = WORK / \"descriptors.parquet\"\n",
    "DATASET = WORK / \"library\"  # the partitioned dataset of section 5\n",
    "\n",
    "SAMPLE_SIZE = 20_000  # molecules measured in sections 1 and 4; any size up to chemlib.size()\n",
    "SEED = 8  # which sample; change it for different molecules\n",
    "N_RECORDS = 100_000  # records built in section 2 to measure containers\n",
    "N_MOLECULES = 300_000  # molecules streamed into Parquet; chemlib.size() streams them all\n",
    "BATCH = 25_000  # molecules per batch: sets the streaming memory, whatever N_MOLECULES is\n",
    "REBATCH = 12_000  # the batch size a later step wants, in the itertools example\n",
    "DELIVERIES = [(30_000, 0), (20_000, 1_000_000)]  # (molecules, first molecule) of two deliveries\n",
    "FP_RADIUS, FP_BITS = 2, 2048  # Morgan fingerprint settings\n",
    "WATCH_SECONDS = 0.005  # how often the memory watcher looks at the process\n",
    "\n",
    "N_CHECKED = 100_000  # molecules checked for defects while streaming, in batches of CHECK_BATCH\n",
    "CHECK_BATCH = 10_000\n",
    "PROGRESS_EVERY = 4  # an unattended job logs its progress every this many batches\n",
    "DEFECT_RATE = 0.02  # share of damaged records in a normal delivery\n",
    "WORSE_RATE = 0.08  # ... and in the later batches, from a supplier's worse export\n",
    "WORSE_FROM = 6  # the first batch (counting from 0) of the worse export\n",
    "WINDOW = 3  # how many recent batches the rolling defect rate covers\n",
    "ALERT_SHARE = 0.03  # warn when the rolling defect rate is above this\n",
    "\n",
    "RDKIT_N, RDKIT_BATCH, RDKIT_START = 20_000, 5_000, 1_000_000  # the RDKit streaming example\n",
    "ROW_GROUP = 20_000  # rows per Parquet row group in the dataset; 100,000 to 1,000,000 in production\n",
    "DUCKDB_MEMORY = \"200MB\"  # the memory limit DuckDB is held to in section 6\n",
    "\n",
    "WORK.mkdir(exist_ok=True)\n",
    "print(f\"the generator can make {chemlib.size():,} molecules; we stream {N_MOLECULES:,} \"\n",
    "      f\"in batches of {BATCH:,}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The last line uses an f-string **format spec**: in `{N_MOLECULES:,}`, the part after the colon says\n",
    "how to print the value, and `,` means \"with commas between thousands\". We use several of these:\n",
    "`{x:.1f}` prints a number with one decimal place, `{x:6.1f}` does the same in a space six\n",
    "characters wide (so columns line up), `{name:22}` pads text to 22 characters, and `{x:.0%}` prints a\n",
    "fraction as a percentage.\n",
    "\n",
    "## 1. Why loading everything fails\n",
    "\n",
    "### What one molecule costs\n",
    "\n",
    "Memory and file sizes are counted in **bytes** (one byte is enough to store one letter of plain\n",
    "text); a kilobyte (kB) is a thousand bytes, a megabyte (MB) a million and a gigabyte (GB) a billion.\n",
    "Take a sample of 20,000 molecules and measure the same data five ways:\n",
    "\n",
    "- as a **CSV** file, plain text with commas between the values;\n",
    "- as a **Parquet** file (Module 3), compressed with **zstd**, a common compression method like the\n",
    "  one in a zip file;\n",
    "- as an Arrow table in memory;\n",
    "- as a pandas table in memory, with its text stored two ways (explained after the output).\n",
    "\n",
    "pandas reports its own size with `memory_usage(deep=True)` (deep, so the text is counted too);\n",
    "Arrow reports `nbytes`. `pa.Table.from_pandas` turns a pandas table into an Arrow one:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "CSV file                 1.6 MB     81 bytes per molecule\n",
      "Parquet file (zstd)      0.4 MB     21 bytes per molecule\n",
      "Arrow table              2.1 MB    107 bytes per molecule\n",
      "pandas, Arrow text       2.1 MB    107 bytes per molecule\n",
      "pandas, Python text      5.1 MB    254 bytes per molecule\n"
     ]
    }
   ],
   "source": [
    "sample = chemlib.library(SAMPLE_SIZE, seed=SEED)\n",
    "sample.to_csv(SAMPLE_CSV, index=False, lineterminator=\"\\n\")  # one line ending on every computer\n",
    "pq.write_table(pa.Table.from_pandas(sample, preserve_index=False), SAMPLE_PARQUET,\n",
    "               compression=\"zstd\")\n",
    "text_as_objects = sample.astype({\"id\": object, \"smiles\": object, \"vendor\": object})\n",
    "\n",
    "sizes = {\n",
    "    \"CSV file\": SAMPLE_CSV.stat().st_size,\n",
    "    \"Parquet file (zstd)\": SAMPLE_PARQUET.stat().st_size,\n",
    "    \"Arrow table\": pa.Table.from_pandas(sample, preserve_index=False).nbytes,\n",
    "    \"pandas, Arrow text\": sample.memory_usage(deep=True).sum(),\n",
    "    \"pandas, Python text\": text_as_objects.memory_usage(deep=True).sum(),\n",
    "}\n",
    "for name, size in sizes.items():\n",
    "    print(f\"{name:22}{size / 1e6:6.1f} MB {size / len(sample):6.0f} bytes per molecule\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Parquet is the smallest by far: each column is compressed on its own, and a column of similar\n",
    "values compresses well. In memory, the cost depends on how the text is held. Arrow stores all the\n",
    "SMILES of a column one after another in a single buffer, with an offset for each, so its table is\n",
    "close to the size of the raw text; pandas 3 stores text columns this way by default. Older pandas\n",
    "versions, and any column whose **dtype** (the column's data type) is `object`, hold every SMILES and\n",
    "every id as a separate Python object, each with a header of around 50 bytes before its first\n",
    "character and a pointer to it in the column: more than twice the size for the same molecules. The\n",
    "`astype({...: object})` line above made such a copy, so we could measure it.\n",
    "\n",
    "### Molecules and fingerprints cost more\n",
    "\n",
    "Most pipelines do not stop at text: they parse each SMILES into an RDKit molecule and compute a\n",
    "fingerprint. RDKit is written in another language, C++, and keeps its molecules in memory that\n",
    "Python's own tools cannot see. So we ask the operating system instead. A running program is called\n",
    "a **process**, and `psutil` reports how much memory the whole process holds (its *resident set\n",
    "size*, or RSS); we read it before and after parsing the sample. The number depends on the machine\n",
    "and the operating system, so the output below is an example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "20,000 RDKit molecules: about 643 MB, 32,142 bytes each\n"
     ]
    }
   ],
   "source": [
    "process = psutil.Process()\n",
    "before = process.memory_info().rss\n",
    "molecules = [Chem.MolFromSmiles(smiles) for smiles in sample[\"smiles\"]]\n",
    "after = process.memory_info().rss\n",
    "per_molecule = (after - before) / len(molecules)\n",
    "print(f\"{len(molecules):,} RDKit molecules: about {(after - before) / 1e6:.0f} MB, \"\n",
    "      f\"{per_molecule:,.0f} bytes each\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A Morgan fingerprint (Module 2) is a row of 2048 bits, each 0 or 1. Stored as one byte per bit\n",
    "(NumPy's `uint8` type, a whole number from 0 to 255), the way many machine-learning examples do,\n",
    "it is 2048 bytes per molecule whatever the molecule. A byte has room for eight bits, so\n",
    "`np.packbits` packs eight of them into each byte, and the fingerprint takes 256 bytes. The second\n",
    "half of the block scales the sample's sizes up to the whole teaching library:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "one byte per bit: (20000, 2048) 41.0 MB\n",
      "packed bits:      (20000, 256) 5.1 MB\n",
      "all 1,733,400 molecules, pandas, Arrow text: 0.19 GB\n",
      "all 1,733,400 molecules, pandas, Python text: 0.44 GB\n",
      "all 1,733,400 molecules, fingerprints one byte per bit: 3.55 GB\n"
     ]
    }
   ],
   "source": [
    "morgan = rdFingerprintGenerator.GetMorganGenerator(radius=FP_RADIUS, fpSize=FP_BITS)\n",
    "fingerprints = np.array([morgan.GetFingerprintAsNumPy(m) for m in molecules], dtype=np.uint8)\n",
    "packed = np.packbits(fingerprints, axis=1)\n",
    "print(\"one byte per bit:\", fingerprints.shape, f\"{fingerprints.nbytes / 1e6:.1f} MB\")\n",
    "print(\"packed bits:     \", packed.shape, f\"{packed.nbytes / 1e6:.1f} MB\")\n",
    "\n",
    "full = chemlib.size()\n",
    "for name in [\"pandas, Arrow text\", \"pandas, Python text\"]:\n",
    "    print(f\"all {full:,} molecules, {name}: {full * sizes[name] / len(sample) / 1e9:.2f} GB\")\n",
    "print(f\"all {full:,} molecules, fingerprints one byte per bit: {full * FP_BITS / 1e9:.2f} GB\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The catalogue data of the full teaching library fits in memory comfortably; its fingerprints\n",
    "already need gigabytes, and the RDKit molecules, at the tens of kilobytes each measured above,\n",
    "would need tens of gigabytes. A make-on-demand library of billions of molecules is a thousand\n",
    "times larger again, and its catalogue text alone would not fit. No laptop, and no single server,\n",
    "holds that in memory; the answer is to stop trying. The figure shows the two ways of working that\n",
    "the rest of the lesson compares:\n",
    "\n",
    "![Two ways to process a library: loading it all keeps every batch in memory at once, so memory grows with the library; streaming holds one batch at a time, writes it out and moves on, so memory stays flat](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/08-larger-than-memory/figures/stream-vs-load.svg)\n",
    "\n",
    "## 2. Measuring memory, and what Python's containers cost\n",
    "\n",
    "### Measure before optimising\n",
    "\n",
    "The rule data engineers follow is to **measure before optimising**. Guesses about where memory goes\n",
    "are often wrong: the large cost may be a list of dictionaries built on one line, not the table you\n",
    "suspected, and an \"optimisation\" made without a measurement can make the code harder to read and\n",
    "save nothing. There are three tools, for three kinds of memory:\n",
    "\n",
    "- `DataFrame.memory_usage(deep=True)` for a pandas table, column by column (section 1);\n",
    "- the whole process's memory with `psutil`, for memory that Python cannot see, such as RDKit's\n",
    "  molecules and Arrow's buffers (section 1);\n",
    "- Python's built-in **`tracemalloc`**, for the Python objects your own code makes. Once started, it\n",
    "  records every block of memory Python sets aside (**allocates**) and the line of code that asked\n",
    "  for it. It reports the memory **current**ly held and the **peak** (the most held at any moment)\n",
    "  since it started, and a **snapshot** lists the lines that hold the most.\n",
    "\n",
    "`tracemalloc` slows Python down while it runs, so switch it on around the code you are measuring,\n",
    "not for the whole job. Here it watches a common pattern: read 100,000 records as dictionaries, keep\n",
    "the cheap ones, and drop the rest. The records' values are made first, outside the measurement, so\n",
    "what it sees is the cost of the containers. Three pieces of Python in the block may be new:\n",
    "\n",
    "- `zip(*columns)` takes several columns and walks along them together, giving one tuple per row;\n",
    "  the `*` passes each column to `zip` as a separate argument;\n",
    "- `dict(zip(FIELDS, row))` pairs each column name with its value, making one dictionary per record;\n",
    "- `del as_dicts` deletes the name `as_dicts`, so Python can free the list it pointed to."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "6,147 cheap records kept\n",
      "peak 19.3 MB, still held 1.2 MB\n",
      "line 6: 19.2 MB in 200,004 allocations\n",
      "line 7: 0.1 MB in 1 allocations\n"
     ]
    }
   ],
   "source": [
    "source = chemlib.library(N_RECORDS, seed=SEED)\n",
    "FIELDS = list(source.columns)\n",
    "rows = list(zip(*(source[name].tolist() for name in FIELDS)))  # plain tuples of Python values\n",
    "\n",
    "tracemalloc.start()\n",
    "as_dicts = [dict(zip(FIELDS, row)) for row in rows]\n",
    "cheap = [record for record in as_dicts if record[\"price_usd\"] < 50]\n",
    "snapshot = tracemalloc.take_snapshot()\n",
    "del as_dicts\n",
    "current, peak = tracemalloc.get_traced_memory()\n",
    "tracemalloc.stop()\n",
    "\n",
    "print(f\"{len(cheap):,} cheap records kept\")\n",
    "print(f\"peak {peak / 1e6:.1f} MB, still held {current / 1e6:.1f} MB\")\n",
    "for stat in snapshot.statistics(\"lineno\")[:2]:\n",
    "    print(f\"line {stat.traceback[0].lineno}: {stat.size / 1e6:.1f} MB \"\n",
    "          f\"in {stat.count:,} allocations\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The snapshot's line numbers count from the top of the code block, so line 6 is the line that builds\n",
    "`as_dicts`: the dictionaries hold almost all the memory. The peak is what\n",
    "matters for whether a job fits, and here it is set by the moment every record existed at once;\n",
    "once the list of all records is deleted, only the cheap ones stay. Had the records been filtered\n",
    "as they were read, the peak would never have been reached, which is the idea of section 3.\n",
    "`tracemalloc` cannot see memory that libraries allocate for themselves (Arrow's buffers, RDKit's\n",
    "molecules), which is why section 1 measured the whole process instead.\n",
    "\n",
    "### One record, four containers\n",
    "\n",
    "A record (one molecule's id, SMILES, vendor, price and stock) can be held in several ways, and the\n",
    "choice costs memory for every row:\n",
    "\n",
    "- A **dict** (dictionary) stores each record's keys alongside its values, in a lookup table of its\n",
    "  own: `{\"id\": \"ML-00000007\", \"price_usd\": 93.33, ...}`.\n",
    "- A **named tuple** (`collections.namedtuple`) is a tuple whose positions also have names, so you\n",
    "  can write `record.price_usd` instead of `record[3]`. The names are stored once for all records,\n",
    "  so each record holds only its values.\n",
    "- A **dataclass** is a small class whose fields are listed once, with the type each should hold\n",
    "  (`price_usd: float` is a **type hint**: a note for the reader and for checking tools, which Python\n",
    "  itself does not enforce). The line `@dataclass(...)` above the class is a **decorator**: it hands\n",
    "  the class to `dataclass`, which writes the usual code for it (creating, printing, comparing).\n",
    "  With `slots=True` each record has a fixed set of fields and no dictionary of its own, and\n",
    "  `frozen=True` makes records read-only, like a tuple.\n",
    "\n",
    "The same 100,000 records in each. The helper `bytes_per_record` takes a function that builds one\n",
    "record from a row and measures it with `tracemalloc`. The functions are given as **lambdas**:\n",
    "`lambda row: dict(zip(FIELDS, row))` is a one-line function without a name, which takes `row` and\n",
    "returns a dictionary. `MoleculeRecord(*row)` passes the row's values to the class one by one, and\n",
    "`Molecule._make` builds a named tuple from a row. In the type hint, `Callable[[tuple], object]` means\n",
    "\"a function that takes a tuple and returns anything\":"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "dict               192 bytes per record, 1.00 of a dict\n",
      "dataclass          120 bytes per record, 0.63 of a dict\n",
      "named tuple         96 bytes per record, 0.50 of a dict\n",
      "dataclass, slots    80 bytes per record, 0.42 of a dict\n",
      "slots instead of dicts for all 1,733,400 molecules: 194 MB less\n",
      "Molecule(id='ML-00000007', smiles='c1cc(Br)ccc1C(=O)NCc2ccccc2', vendor='Vendor B', price_usd=93.33, stock_mg=40)\n"
     ]
    }
   ],
   "source": [
    "Molecule = namedtuple(\"Molecule\", FIELDS)\n",
    "\n",
    "\n",
    "@dataclass(frozen=True)\n",
    "class MoleculeRecord:\n",
    "    \"\"\"One catalogue record, as an ordinary dataclass.\"\"\"\n",
    "\n",
    "    id: str\n",
    "    smiles: str\n",
    "    vendor: str\n",
    "    price_usd: float\n",
    "    stock_mg: int\n",
    "\n",
    "\n",
    "@dataclass(frozen=True, slots=True)\n",
    "class SlottedRecord:\n",
    "    \"\"\"The same record, with slots: a fixed set of fields and no per-instance dictionary.\"\"\"\n",
    "\n",
    "    id: str\n",
    "    smiles: str\n",
    "    vendor: str\n",
    "    price_usd: float\n",
    "    stock_mg: int\n",
    "\n",
    "\n",
    "def bytes_per_record(build: Callable[[tuple], object]) -> float:\n",
    "    \"\"\"Memory tracemalloc sees while one container is built per row, divided by the rows.\"\"\"\n",
    "    tracemalloc.start()\n",
    "    made = [build(row) for row in rows]\n",
    "    current, _ = tracemalloc.get_traced_memory()\n",
    "    tracemalloc.stop()\n",
    "    return current / len(made)\n",
    "\n",
    "\n",
    "containers = {\n",
    "    \"dict\": lambda row: dict(zip(FIELDS, row)),\n",
    "    \"dataclass\": lambda row: MoleculeRecord(*row),\n",
    "    \"named tuple\": Molecule._make,\n",
    "    \"dataclass, slots\": lambda row: SlottedRecord(*row),\n",
    "}\n",
    "costs = {name: bytes_per_record(build) for name, build in containers.items()}\n",
    "for name, cost in costs.items():\n",
    "    print(f\"{name:17}{cost:5.0f} bytes per record, {cost / costs['dict']:.2f} of a dict\")\n",
    "saved = (costs[\"dict\"] - costs[\"dataclass, slots\"]) * chemlib.size()\n",
    "print(f\"slots instead of dicts for all {chemlib.size():,} molecules: {saved / 1e6:.0f} MB less\")\n",
    "print(Molecule._make(rows[0]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Each figure includes the 8 bytes of the list's **pointer** to the record (the memory address the\n",
    "list keeps for each item), and the values themselves are shared, so this is the cost of the container alone. The numbers are for Python 3.11, which this\n",
    "course uses; other versions differ by a few bytes, but the order is the same. A dataclass with\n",
    "slots takes well under half the memory of a dict and, unlike a dict, rejects a misspelt field name\n",
    "instead of silently adding a new key. A named tuple is almost as small and can be unpacked like any\n",
    "tuple. Keep dicts for records whose fields vary (JSON from a web service, Module 11); for millions\n",
    "of records with the same fields, do not keep Python objects per record at all, but columns, as\n",
    "pandas and Arrow do.\n",
    "\n",
    "![Bytes per record for 100,000 catalogue records held as dicts, ordinary dataclasses, named tuples and dataclasses with slots, measured with tracemalloc on Python 3.11](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/08-larger-than-memory/figures/record-containers.svg)\n",
    "\n",
    "## 3. Streaming in batches\n",
    "\n",
    "### Generators make data only when asked\n",
    "\n",
    "Streaming rests on one Python feature, met in Module 3. A Python **generator** is a function that\n",
    "hands out its results one at a time with `yield` instead of `return`, making each only when the\n",
    "loop asks for it. Work that waits until it is needed like this is called **lazy**.\n",
    "`chemlib.stream(n, batch)` is a generator: it makes the molecules a batch at a time and never holds\n",
    "more than one batch. Creating it does no work at all; `next(batches)` asks it for the next batch,\n",
    "which is what a `for` loop does on every turn:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "generator\n",
      "25000 rows in the first batch; the other batches do not exist yet\n",
      "         id                      smiles   vendor  price_usd  stock_mg\n",
      "ML-00000000     c1ccccc1C(=O)NCc2ccccc2 Vendor A      20.00        10\n",
      "ML-00000001  c1cc(C)ccc1C(=O)NCc2ccccc2 Vendor B      99.19       300\n",
      "ML-00000002 c1cc(CC)ccc1C(=O)NCc2ccccc2 Vendor C     178.38        90\n"
     ]
    }
   ],
   "source": [
    "batches = chemlib.stream(N_MOLECULES, batch=BATCH)\n",
    "print(type(batches).__name__)\n",
    "first = next(batches)\n",
    "print(len(first), \"rows in the first batch; the other batches do not exist yet\")\n",
    "print(first.head(3).to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A file reader can be a generator in the same way: `pyarrow.parquet.ParquetFile.iter_batches`,\n",
    "`pandas.read_csv(..., chunksize=...)` and RDKit's `SDMolSupplier` all hand out records a few at a\n",
    "time instead of reading the whole file first.\n",
    "\n",
    "### A processing step that works on one batch\n",
    "\n",
    "The step we apply is ordinary pandas code that takes one batch and returns it with new columns.\n",
    "For hundreds of thousands of rows, cheap string work is enough to show the idea: the number of\n",
    "heavy atoms and the number of halogen atoms, counted from the SMILES text.\n",
    "\n",
    "The counting uses a **regular expression**: a small pattern that describes the text to look for,\n",
    "which `str.count` then counts in each SMILES. In the pattern `ATOM`, `|` means \"or\", `[BCNOPSFI]`\n",
    "means \"any one of these letters\", and `\\[[^\\]]+\\]` means \"an opening bracket, then anything up to\n",
    "the closing bracket\", so a bracket atom such as `[nH]` counts once. `Br` and `Cl` are listed before\n",
    "the single letters, so they count as one atom each rather than as B and C. The `r` before the quotes\n",
    "tells Python to leave the backslashes alone for the pattern to use.\n",
    "\n",
    "A cheap shortcut like this is only acceptable once it has been checked against the real\n",
    "calculation, so we compare it with RDKit on the 20,000 molecules from section 1. The `int16` type\n",
    "holds whole numbers up to 32,767, plenty for an atom count (section 4 says more about types):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "heavy atoms agree with RDKit for all 20,000: True\n"
     ]
    }
   ],
   "source": [
    "ATOM = r\"\\[[^\\]]+\\]|Br|Cl|[BCNOPSFI]|[bcnops]\"\n",
    "HALOGEN = r\"Br|Cl|F|I\"\n",
    "\n",
    "\n",
    "def add_columns(batch: pd.DataFrame) -> pd.DataFrame:\n",
    "    \"\"\"Add heavy-atom and halogen counts, worked out from each SMILES string.\"\"\"\n",
    "    out = batch.copy()\n",
    "    out[\"heavy_atoms\"] = out[\"smiles\"].str.count(ATOM).astype(\"int16\")\n",
    "    out[\"halogens\"] = out[\"smiles\"].str.count(HALOGEN).astype(\"int16\")\n",
    "    return out\n",
    "\n",
    "\n",
    "checked = add_columns(sample)\n",
    "rdkit_counts = [m.GetNumHeavyAtoms() for m in molecules]\n",
    "print(\"heavy atoms agree with RDKit for all 20,000:\",\n",
    "      bool((checked[\"heavy_atoms\"] == rdkit_counts).all()))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Batches of any size, with itertools\n",
    "\n",
    "The batches a source hands out are not always the ones the next step wants: a supplier sends\n",
    "deliveries of different sizes, and a step that writes to a database may want a fixed number of rows\n",
    "per call. The standard library's `itertools` works on any iterator, a row or a batch at a time,\n",
    "without making a list of everything. An **iterator** is anything a `for` loop can step through one\n",
    "item at a time, such as a generator. Three of its tools do most of the work:\n",
    "\n",
    "- `islice(iterator, n)` takes the next `n` items and stops, so repeating it cuts a stream into\n",
    "  batches. (Python 3.12 added `itertools.batched`, which does this in one call; this course runs on\n",
    "  Python 3.11, so we write the four lines ourselves.)\n",
    "- `chain(a, b, ...)` joins several iterators into one, and `chain.from_iterable` does the same for\n",
    "  an iterator of iterators: several files or deliveries become one stream.\n",
    "- `groupby(iterator, key)` hands out runs of consecutive items with the same key.\n",
    "\n",
    "Here two deliveries are joined into one stream of rows and cut into batches of 12,000; the second\n",
    "delivery starts at molecule 1,000,000, and the third batch spans both. Some notes on the code:\n",
    "\n",
    "- In `batched`, `while batch := list(islice(iterator, size)):` uses `:=`, which gives a value a\n",
    "  name and tests it in one step: take the next `size` items, call them `batch`, and stop when the\n",
    "  list is empty.\n",
    "- `Iterator[list]` is a type hint: the function hands out lists, one at a time.\n",
    "- `(... for n, s in DELIVERIES)`, in round brackets, is a **generator expression**: like a list\n",
    "  comprehension, but lazy, so each delivery starts only when it is reached.\n",
    "- `itertuples(index=False)` walks through a pandas table one row at a time, each row a named tuple."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO batch 0: 12,000 rows, ML-00000000 to ML-00011999\n",
      "INFO batch 1: 12,000 rows, ML-00012000 to ML-00023999\n",
      "INFO batch 2: 12,000 rows, ML-00024000 to ML-01005999\n",
      "INFO batch 3: 12,000 rows, ML-01006000 to ML-01017999\n",
      "INFO batch 4: 2,000 rows, ML-01018000 to ML-01019999\n"
     ]
    }
   ],
   "source": [
    "def batched(items: Iterable, size: int) -> Iterator[list]:\n",
    "    \"\"\"Cut any iterable into lists of `size` items (the last may be shorter), lazily.\"\"\"\n",
    "    iterator = iter(items)\n",
    "    while batch := list(islice(iterator, size)):\n",
    "        yield batch\n",
    "\n",
    "\n",
    "deliveries = (chemlib.stream(n, batch=CHECK_BATCH, start=s) for n, s in DELIVERIES)\n",
    "rows_in_order = chain.from_iterable(b.itertuples(index=False) for b in chain(*deliveries))\n",
    "for k, batch in enumerate(batched(rows_in_order, REBATCH)):\n",
    "    log.info(\"batch %d: %s rows, %s to %s\", k, f\"{len(batch):,}\", batch[0].id, batch[-1].id)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "At no point does more than one delivery batch and one output batch exist. `groupby` needs one\n",
    "thing the others do not: the stream must be **sorted by the key**, because it only groups items\n",
    "that are next to each other. Our sample is in id order, so grouping it by heavy-atom count gives a\n",
    "new group every time the count changes; sorted by heavy atoms first, it gives one group per count,\n",
    "and the loop holds one group at a time. The `key` is given as a lambda that picks each row's\n",
    "heavy-atom count, and `sum(1 for _ in ...)` counts the groups without keeping them (`_` is the\n",
    "usual name for a value we do not use):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "groups in id order: 17,782\n",
      "13 heavy atoms:    1 molecules, cheapest ML-00067710 at $267.90\n",
      "14 heavy atoms:    1 molecules, cheapest ML-00063750 at $287.50\n",
      "15 heavy atoms:    8 molecules, cheapest ML-00950406 at $120.14\n",
      "16 heavy atoms:   25 molecules, cheapest ML-00059495 at $34.05\n"
     ]
    }
   ],
   "source": [
    "by_id = checked.itertuples(index=False)\n",
    "runs = sum(1 for _ in groupby(by_id, key=lambda row: row.heavy_atoms))\n",
    "print(f\"groups in id order: {runs:,}\")\n",
    "\n",
    "by_size = checked.sort_values([\"heavy_atoms\", \"id\"]).itertuples(index=False)\n",
    "for heavy_atoms, group in islice(groupby(by_size, key=lambda row: row.heavy_atoms), 4):\n",
    "    members = list(group)  # this group only, not the whole table\n",
    "    cheapest = min(members, key=lambda row: row.price_usd)\n",
    "    print(f\"{heavy_atoms} heavy atoms: {len(members):>4,} molecules, \"\n",
    "          f\"cheapest {cheapest.id} at ${cheapest.price_usd:.2f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In a real job the sorting is done once, when the file is written (DuckDB, in section 6, sorts more\n",
    "data than fits in memory by spilling to disk), and every later pass can then group the file as it\n",
    "streams: all the conformers of one molecule in an SDF file, or all the records with one InChIKey\n",
    "(both from Module 3).\n",
    "\n",
    "### Writing batch by batch\n",
    "\n",
    "Now stream 300,000 molecules through `add_columns` and write each batch to a Parquet file as soon\n",
    "as it is ready, with `pyarrow.parquet.ParquetWriter`. The writer keeps the file open and appends\n",
    "one **row group** (a block of rows stored column by column) per batch. We give it an explicit\n",
    "**schema**: the column names and types we promise, so a batch that disagrees (a price read as\n",
    "text, an id missing) stops the job instead of silently changing the file.\n",
    "\n",
    "To compare, we also do it the loading-everything way: make all 300,000 rows, then process and\n",
    "write them in one go. `tracemalloc` (section 2) cannot measure this fairly, because it sees only\n",
    "memory allocated through Python, and Arrow (which holds pandas' text) allocates its own.\n",
    "\n",
    "So we need a helper that measures the whole process while a job runs. This is the hardest code in\n",
    "the module, and you do not need to follow every line to use it: `peak_memory(job, ...)` runs the\n",
    "job and returns the most memory the process held above where it started. How it works: a\n",
    "**thread** is a second line of work running inside the same program at the same time. While the\n",
    "job runs in the main thread, a background thread (`watch`) reads the process's memory every few\n",
    "milliseconds and keeps the highest value. Some parts that may be new:\n",
    "\n",
    "- `*args` collects any extra arguments into a tuple, and `job(*args)` passes them on to the job;\n",
    "- `nonlocal peak` lets the inner function `watch` change the `peak` of the function around it;\n",
    "- `threading.Event` is a flag one thread sets and another checks; `done.set()` tells the watcher to\n",
    "  stop;\n",
    "- `try: ... finally: ...` makes sure the `finally` part runs even if the job fails, so the watcher\n",
    "  always stops."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def peak_memory(job: Callable[..., None], *args: object) -> int:\n",
    "    \"\"\"Run job(*args) and return the most memory (bytes) the process held above its start.\"\"\"\n",
    "    start = process.memory_info().rss\n",
    "    peak = start\n",
    "    done = threading.Event()\n",
    "\n",
    "    def watch() -> None:\n",
    "        nonlocal peak\n",
    "        while not done.is_set():\n",
    "            peak = max(peak, process.memory_info().rss)\n",
    "            time.sleep(WATCH_SECONDS)\n",
    "\n",
    "    watcher = threading.Thread(target=watch)\n",
    "    watcher.start()\n",
    "    try:\n",
    "        job(*args)\n",
    "    finally:\n",
    "        done.set()\n",
    "        watcher.join()\n",
    "    return max(peak, process.memory_info().rss) - start"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now the two jobs. Streaming runs first, so any memory it leaves behind with the process counts in\n",
    "favour of loading everything, not against it. In `stream_to_parquet`, `with ... as writer:` opens\n",
    "the writer and closes it (finishing the file) when the indented block ends, even if something goes\n",
    "wrong, the same way `with open(...)` closes a file. `pd.concat` joins a list of tables into one. The\n",
    "measured memory differs from computer to computer, so the output is an example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO stream           peak     8 MB above the start\n",
      "INFO load everything  peak    44 MB above the start\n"
     ]
    }
   ],
   "source": [
    "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",
    "        (\"heavy_atoms\", pa.int16()),\n",
    "        (\"halogens\", pa.int16()),\n",
    "    ]\n",
    ")\n",
    "\n",
    "\n",
    "def load_everything(path: Path, n: int) -> None:\n",
    "    \"\"\"Make every row first, then process and write them all at once.\"\"\"\n",
    "    everything = pd.concat(list(chemlib.stream(n, batch=BATCH)), ignore_index=True)\n",
    "    table = pa.Table.from_pandas(add_columns(everything), schema=SCHEMA, preserve_index=False)\n",
    "    pq.write_table(table, path, compression=\"zstd\")\n",
    "\n",
    "\n",
    "def stream_to_parquet(path: Path, n: int) -> None:\n",
    "    \"\"\"Make, process and write one batch at a time.\"\"\"\n",
    "    with pq.ParquetWriter(path, SCHEMA, compression=\"zstd\") as writer:\n",
    "        for batch in chemlib.stream(n, batch=BATCH):\n",
    "            table = pa.Table.from_pandas(add_columns(batch), schema=SCHEMA, preserve_index=False)\n",
    "            writer.write_table(table)\n",
    "\n",
    "\n",
    "stream_to_parquet(WORK / \"warm-up.parquet\", BATCH)  # one small run, so start-up costs don't count\n",
    "peaks = {\n",
    "    \"stream\": peak_memory(stream_to_parquet, STREAMED, N_MOLECULES),\n",
    "    \"load everything\": peak_memory(load_everything, LOADED, N_MOLECULES),\n",
    "}\n",
    "for name, peak in peaks.items():\n",
    "    log.info(\"%-16s peak %5.0f MB above the start\", name, peak / 1e6)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Both files hold the same rows; only the memory needed to make them differs:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "rows: 300000  row groups: 12\n",
      "same contents: True\n"
     ]
    }
   ],
   "source": [
    "streamed = pq.ParquetFile(STREAMED)\n",
    "loaded = pq.read_table(LOADED)\n",
    "print(\"rows:\", streamed.metadata.num_rows, \" row groups:\", streamed.metadata.num_row_groups)\n",
    "print(\"same contents:\", streamed.read().equals(loaded))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The streaming peak is set by the batch size, not by the number of molecules: stream 1,733,400 or\n",
    "a billion, and it stays at about one batch (plus what the writer buffers). Loading everything\n",
    "grows in step with the library until it no longer fits. Memory measured this way is noisy,\n",
    "because the operating system and Python keep some freed memory back for reuse, so the figure below\n",
    "repeats the measurement in a fresh process (a new run of Python) for each size:\n",
    "\n",
    "![Peak memory against the number of molecules processed, for loading everything and for streaming in batches of 25,000, each measured in a fresh process: one measured run on one laptop, yours will differ](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/08-larger-than-memory/figures/memory-use.svg)\n",
    "\n",
    "### Counting while streaming: Counter, defaultdict and deque\n",
    "\n",
    "A streaming job often needs a summary of everything it has seen: how many records of each defect\n",
    "kind, which elements occur, whether the latest deliveries are worse than the earlier ones. Keeping\n",
    "the batches to work this out afterwards would undo the streaming; instead, the job keeps small\n",
    "running summaries and updates them as each batch passes. Three containers from the standard\n",
    "library's `collections`, imported in the Setup block, are made for this:\n",
    "\n",
    "- **`Counter`** counts things: `update` adds a batch's items to the running counts, and\n",
    "  `most_common()` returns them sorted, largest first, so counting and sorting take one step each.\n",
    "- **`defaultdict(list)`** groups things: looking up a key it has not seen creates an empty list, so\n",
    "  `flagged[kind].append(id)` needs no \"is this key new?\" check.\n",
    "- **`deque(maxlen=n)`** is a queue that keeps only the last `n` items: appending to a full one\n",
    "  drops the oldest, so a rolling window over recent batches never grows.\n",
    "\n",
    "Here 100,000 molecules arrive in batches of 10,000, damaged with `chemlib.add_defects` (as in\n",
    "Module 6): 2% of each batch, until the last four batches, which come from a supplier's worse export\n",
    "at 8%. Elements are counted from the SMILES with a regular expression like `ATOM`'s, one symbol at\n",
    "a time: `re.findall` returns every match in a string as a list. `zip(..., strict=True)` walks two\n",
    "columns together and stops with an error if their lengths differ:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO batch 0:  2.0% defective, last 1 batches  2.0%\n",
      "INFO batch 1:  2.0% defective, last 2 batches  2.0%\n",
      "INFO batch 2:  2.0% defective, last 3 batches  2.0%\n",
      "INFO batch 3:  2.0% defective, last 3 batches  2.0%\n",
      "INFO batch 4:  2.0% defective, last 3 batches  2.0%\n",
      "INFO batch 5:  2.0% defective, last 3 batches  2.0%\n",
      "INFO batch 6:  7.9% defective, last 3 batches  4.0%\n",
      "WARNING rolling defect rate 4.0% is above 3%\n",
      "INFO batch 7:  7.9% defective, last 3 batches  5.9%\n",
      "WARNING rolling defect rate 5.9% is above 3%\n",
      "INFO batch 8:  7.9% defective, last 3 batches  7.9%\n",
      "WARNING rolling defect rate 7.9% is above 3%\n",
      "INFO batch 9:  7.9% defective, last 3 batches  7.9%\n",
      "WARNING rolling defect rate 7.9% is above 3%\n"
     ]
    }
   ],
   "source": [
    "ELEMENT = r\"Br|Cl|Se|[BCNOPSFI]|[bcnops]\"  # aromatic atoms are written in lower case\n",
    "\n",
    "defects = Counter()\n",
    "elements = Counter()\n",
    "flagged = defaultdict(list)  # defect kind -> ids of the records that have it\n",
    "recent = deque(maxlen=WINDOW)  # defect rate of the last WINDOW batches\n",
    "for k, batch in enumerate(chemlib.stream(N_CHECKED, batch=CHECK_BATCH)):\n",
    "    rate = DEFECT_RATE if k < WORSE_FROM else WORSE_RATE\n",
    "    batch = chemlib.add_defects(batch, rate=rate, seed=SEED + k)\n",
    "    bad = batch[batch[\"defect\"] != \"\"]\n",
    "    defects.update(bad[\"defect\"])\n",
    "    for kind, molecule_id in zip(bad[\"defect\"], bad[\"id\"], strict=True):\n",
    "        flagged[kind].append(molecule_id)\n",
    "    for smiles in batch[\"smiles\"]:\n",
    "        elements.update(symbol.capitalize() for symbol in re.findall(ELEMENT, smiles))\n",
    "    recent.append(len(bad) / len(batch))\n",
    "    rolling = sum(recent) / len(recent)\n",
    "    log.info(\"batch %d: %4.1f%% defective, last %d batches %4.1f%%\",\n",
    "             k, 100 * recent[-1], len(recent), 100 * rolling)\n",
    "    if rolling > ALERT_SHARE:\n",
    "        log.warning(\"rolling defect rate %.1f%% is above %.0f%%\", 100 * rolling, 100 * ALERT_SHARE)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The warning starts with the first batch of the worse export, because the window of three batches\n",
    "then includes it; a monitoring system (Module 14) would raise the same alert. When the job ends,\n",
    "the summaries are all that is left, and they are small whatever the size of the library:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "defects: [('salt', 740), ('solvent', 740), ('duplicate', 730), ('element', 730), ('invalid', 730), ('valence', 730)]\n",
      "elements: [('C', 1851475), ('O', 266265), ('N', 230255), ('F', 79097), ('S', 37513), ('Cl', 11078), ('Br', 10341), ('Se', 712)]\n",
      "duplicate  730 records, first ML-00005944-dup\n",
      "element    730 records, first ML-00006079\n",
      "invalid    730 records, first ML-00008671\n",
      "salt       740 records, first ML-00008586\n",
      "solvent    740 records, first ML-00002800\n",
      "valence    730 records, first ML-00003611\n",
      "the rolling window holds 3 rates: ['0.079', '0.079', '0.079']\n"
     ]
    }
   ],
   "source": [
    "print(\"defects:\", defects.most_common())\n",
    "print(\"elements:\", elements.most_common())\n",
    "for kind, ids in sorted(flagged.items()):\n",
    "    print(f\"{kind:9} {len(ids):>4} records, first {ids[0]}\")\n",
    "print(\"the rolling window holds\", len(recent), \"rates:\", [f\"{r:.3f}\" for r in recent])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The element counts are a quick check on what a supplier really sent: selenium appears only because\n",
    "of the element defect, and the chlorine count includes the chloride counter-ions of the salts as\n",
    "well as the chlorine substituents. The defect `Counter` has one entry per kind and the `deque`\n",
    "three numbers. The `defaultdict` grows with the number of damaged records, not with the\n",
    "library; in a real job it would be written out batch by batch, like the data.\n",
    "\n",
    "### The same pattern with RDKit\n",
    "\n",
    "The batch step can be any function, including real chemistry. Here each batch of 5,000 molecules\n",
    "is parsed with RDKit, given a canonical SMILES and two descriptors, and appended to its own\n",
    "Parquet file. RDKit is slower than string work, so we stream 20,000 molecules; the memory used is\n",
    "again one batch, whatever the total. This time we do not write the schema out by hand: the writer\n",
    "is created when the first batch arrives (while `writer` is still `None`), and takes its schema\n",
    "from that batch:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO wrote 20000 rows in 4 row groups to work/descriptors.parquet\n",
      "         id                    canonical_smiles     mw   tpsa\n",
      "ML-01000000     CCc1nc(Nc2ncccc2O)nc(C(C)C)c1CN 287.37  96.95\n",
      "ML-01000001 CCc1nc(Nc2ncccc2N(C)C)nc(C(C)C)c1CN 314.44  79.96\n",
      "ML-01000002   CCc1nc(Nc2ncccc2C#N)nc(C(C)C)c1CN 296.38 100.51\n"
     ]
    }
   ],
   "source": [
    "def describe(batch: pd.DataFrame) -> pd.DataFrame:\n",
    "    \"\"\"Canonical SMILES, molecular weight and polar surface area for one batch.\"\"\"\n",
    "    mols = [Chem.MolFromSmiles(s) for s in batch[\"smiles\"]]\n",
    "    return pd.DataFrame(\n",
    "        {\n",
    "            \"id\": batch[\"id\"].to_numpy(),\n",
    "            \"canonical_smiles\": [Chem.MolToSmiles(m) for m in mols],\n",
    "            \"mw\": [round(Descriptors.MolWt(m), 2) for m in mols],\n",
    "            \"tpsa\": [round(Descriptors.TPSA(m), 2) for m in mols],\n",
    "        }\n",
    "    )\n",
    "\n",
    "\n",
    "writer = None\n",
    "for batch in chemlib.stream(RDKIT_N, batch=RDKIT_BATCH, start=RDKIT_START):\n",
    "    table = pa.Table.from_pandas(describe(batch), preserve_index=False)\n",
    "    if writer is None:\n",
    "        writer = pq.ParquetWriter(DESCRIPTORS, table.schema, compression=\"zstd\")\n",
    "    writer.write_table(table)\n",
    "writer.close()\n",
    "\n",
    "described = pq.read_table(DESCRIPTORS)\n",
    "log.info(\"wrote %d rows in %d row groups to %s\", described.num_rows,\n",
    "         pq.ParquetFile(DESCRIPTORS).num_row_groups, DESCRIPTORS.as_posix())\n",
    "print(described.slice(0, 3).to_pandas().to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Showing progress: a bar for people, log lines for jobs\n",
    "\n",
    "A stream of 300,000 molecules takes seconds; the full library, or the RDKit step on millions,\n",
    "takes hours, and the first question anyone asks of a long run is \"how far has it got?\". There are\n",
    "two answers, for two audiences.\n",
    "\n",
    "**A person watching a terminal or a notebook** wants a progress bar: how much is done, how fast it\n",
    "is going, and how long is left. `tqdm` is the usual library. It wraps any loop, or, as here, is\n",
    "told the total and moved on by each batch's size, so it counts molecules rather than batches:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "total_rows = 0\n",
    "with tqdm(total=N_MOLECULES, unit=\"mol\", unit_scale=True, desc=\"streaming\") as bar:\n",
    "    for batch in chemlib.stream(N_MOLECULES, batch=BATCH):\n",
    "        total_rows += len(add_columns(batch))\n",
    "        bar.update(len(batch))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "While it runs, the bar redraws itself on one line of the screen, with the rate and the time left,\n",
    "and ends as:\n",
    "\n",
    "```text\n",
    "streaming: 100%|██████████| 300k/300k [00:02<00:00, 134kmol/s]\n",
    "```\n",
    "\n",
    "The bar goes to **stderr** (the \"error\" output, a second output channel that programs use for\n",
    "messages, as log lines do) and redraws itself, so the lesson's page cannot show it: run the block\n",
    "yourself to see it move. In a notebook, `from tqdm.auto import tqdm` gives a graphical bar instead.\n",
    "\n",
    "**A job running unattended** (on a server, Module 10, or on a schedule, Module 15) has nobody\n",
    "watching. Its progress belongs in the log, as ordinary lines at a steady pace: every few batches,\n",
    "with the count, the share done and, in a real job, the rate. A progress bar written to a log file is\n",
    "not a bar any more; it is hundreds of half-lines, because the bar redraws itself by jumping back to\n",
    "the start of the line, and a file cannot do that. In the code, `k % PROGRESS_EVERY == 0` is true\n",
    "every fourth batch (`%` gives the remainder after dividing), and `math.ceil` rounds up, so 12.0\n",
    "batches stay 12 and 12.5 would become 13:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO batch 4/12: 100,000 molecules, 33% done\n",
      "INFO batch 8/12: 200,000 molecules, 67% done\n",
      "INFO batch 12/12: 300,000 molecules, 100% done\n"
     ]
    }
   ],
   "source": [
    "n_batches = math.ceil(N_MOLECULES / BATCH)\n",
    "done = 0\n",
    "for k, batch in enumerate(chemlib.stream(N_MOLECULES, batch=BATCH), start=1):\n",
    "    done += len(add_columns(batch))\n",
    "    if k % PROGRESS_EVERY == 0 or k == n_batches:\n",
    "        log.info(\"batch %d/%d: %s molecules, %.0f%% done\", k, n_batches, f\"{done:,}\",\n",
    "                 100 * done / N_MOLECULES)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "One script can serve both. `tqdm(..., disable=None)` shows the bar only when its output is a\n",
    "**terminal** (a window where you type commands), so the same code draws a bar on your screen and\n",
    "nothing in a log file such as `work/run.log`, where the progress lines take over. And when a loop with a bar also logs (a warning about a bad batch, say),\n",
    "the log line would land in the middle of the bar; `logging_redirect_tqdm` sends log lines through\n",
    "tqdm, which prints them above the bar and redraws it underneath:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "WARNING batch 5: supplier sent a different column order\n"
     ]
    }
   ],
   "source": [
    "with logging_redirect_tqdm(), tqdm(total=N_MOLECULES, unit=\"mol\", unit_scale=True,\n",
    "                                   desc=\"checking\") as bar:\n",
    "    for k, batch in enumerate(chemlib.stream(N_MOLECULES, batch=BATCH), start=1):\n",
    "        if k == 5:\n",
    "            log.warning(\"batch %d: supplier sent a different column order\", k)\n",
    "        bar.update(len(batch))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Other libraries do the same job. `rich` draws bars too (`rich.progress`) and also makes log lines\n",
    "easier to read on screen, in colour, with its `RichHandler`; `alive-progress` and `enlighten` are\n",
    "two more bar libraries. Which one you pick matters less than the rule: bars for people, log lines\n",
    "for jobs, and never a bar in a log file.\n",
    "\n",
    "## 4. Compact types\n",
    "\n",
    "Streaming bounds how many rows are in memory; the type of each column sets what each row costs.\n",
    "A number's type says how many bits it is stored in, and so which values it can hold:\n",
    "\n",
    "| Type | Bytes | Holds |\n",
    "|---|---|---|\n",
    "| `uint8` | 1 | whole numbers 0 to 255 |\n",
    "| `int8` | 1 | whole numbers -128 to 127 |\n",
    "| `uint16` | 2 | whole numbers 0 to 65,535 |\n",
    "| `int16` | 2 | whole numbers -32,768 to 32,767 |\n",
    "| `int64` | 8 | whole numbers up to about 9 billion billion, either sign |\n",
    "| `float32` | 4 | decimal numbers, about 7 significant digits |\n",
    "| `float64` | 8 | decimal numbers, about 16 significant digits |\n",
    "\n",
    "(`u` means unsigned: no negative numbers. `uint32` and `int32` take 4 bytes each.) Libraries\n",
    "usually store numbers in the widest types (64-bit integers and floats) and text as text, whatever\n",
    "the values, and narrower types often hold the same data in a fraction of the space. The rule from\n",
    "section 2 applies: measure first, and check that the narrower type really holds every value,\n",
    "because NumPy does not stop you: `np.array([300]).astype(np.uint8)` silently gives 44.\n",
    "\n",
    "### Smaller numbers, checked\n",
    "\n",
    "The damaged sample has prices, stock amounts and the two counts from `add_columns`. A helper picks\n",
    "the smallest integer type that holds a column's minimum and maximum: it tries the types from the\n",
    "smallest up, and `np.iinfo` gives each type's limits (pandas'\n",
    "`pd.to_numeric(..., downcast=\"integer\")` does the same job). Prices have two decimal places and are\n",
    "under 1,000 dollars, so a 32-bit float, which keeps about seven significant digits, holds them; we\n",
    "check that rounding to the cent gives back every price exactly:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "stock_mg      10 to 500: int64 -> uint16\n",
      "heavy_atoms   13 to  42: int16 -> uint8\n",
      "halogens       0 to  10: int16 -> uint8\n",
      "float32 prices give back every price to the cent: True\n"
     ]
    }
   ],
   "source": [
    "def smallest_int(values: pd.Series) -> pd.Series:\n",
    "    \"\"\"The column in the smallest integer type that holds every value (checked, not assumed).\"\"\"\n",
    "    for dtype in (np.uint8, np.int8, np.uint16, np.int16, np.uint32, np.int32):\n",
    "        limits = np.iinfo(dtype)\n",
    "        if limits.min <= values.min() and values.max() <= limits.max:\n",
    "            return values.astype(dtype)\n",
    "    return values\n",
    "\n",
    "\n",
    "damaged = add_columns(chemlib.add_defects(sample, rate=DEFECT_RATE, seed=SEED))\n",
    "compact = damaged.copy()\n",
    "for name in [\"stock_mg\", \"heavy_atoms\", \"halogens\"]:\n",
    "    compact[name] = smallest_int(damaged[name])\n",
    "    print(f\"{name:12} {damaged[name].min():>3} to {damaged[name].max():>3}: \"\n",
    "          f\"{damaged[name].dtype} -> {compact[name].dtype}\")\n",
    "compact[\"price_usd\"] = damaged[\"price_usd\"].astype(np.float32)\n",
    "back = compact[\"price_usd\"].astype(np.float64).round(2)\n",
    "print(\"float32 prices give back every price to the cent:\", bool((back == damaged[\"price_usd\"]).all()))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Categories for repeated text\n",
    "\n",
    "The vendor column holds three different names, and the defect column seven values (six kinds and\n",
    "the empty string of clean rows), repeated over 20,000 rows. A pandas **category** column stores\n",
    "each different value once and, for every row, a small integer code pointing at it. The text of\n",
    "unique values, such as ids and SMILES, gains nothing and stays as it is:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "['', 'duplicate', 'element', 'invalid', 'salt', 'solvent', 'valence'] int8\n",
      "              before  bytes per row     after  bytes per row, after\n",
      "id               str           19.1       str                  19.1\n",
      "smiles           str           56.2       str                  56.2\n",
      "vendor           str           16.1  category                   1.0\n",
      "price_usd    float64            8.0   float32                   4.0\n",
      "stock_mg       int64            8.0    uint16                   2.0\n",
      "defect           str            8.3  category                   1.0\n",
      "heavy_atoms    int16            2.0     uint8                   1.0\n",
      "halogens       int16            2.0     uint8                   1.0\n",
      "whole table: 2.40 MB -> 1.71 MB, 71% of the original\n"
     ]
    }
   ],
   "source": [
    "compact = compact.astype({\"vendor\": \"category\", \"defect\": \"category\"})\n",
    "print(compact[\"defect\"].cat.categories.tolist(), compact[\"defect\"].cat.codes.dtype)\n",
    "\n",
    "memory = pd.DataFrame(\n",
    "    {\n",
    "        \"before\": damaged.dtypes.astype(str),\n",
    "        \"bytes per row\": damaged.memory_usage(deep=True, index=False) / len(damaged),\n",
    "        \"after\": compact.dtypes.astype(str),\n",
    "        \"bytes per row, after\": compact.memory_usage(deep=True, index=False) / len(compact),\n",
    "    }\n",
    ")\n",
    "print(memory.round(1).to_string())\n",
    "total_before = damaged.memory_usage(deep=True).sum()\n",
    "total_after = compact.memory_usage(deep=True).sum()\n",
    "print(f\"whole table: {total_before / 1e6:.2f} MB -> {total_after / 1e6:.2f} MB, \"\n",
    "      f\"{total_after / total_before:.0%} of the original\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The numbers and the repeated text shrink by a factor of 2 to 16; the whole table less, because the\n",
    "SMILES and ids, which nothing here can shrink, are most of it. On a table of descriptors and\n",
    "fingerprint bits, mostly numbers, compact types matter far more. pandas can also read a file\n",
    "straight into compact types, with `pd.read_csv(..., dtype={\"vendor\": \"category\", \"stock_mg\":\n",
    "\"uint16\"})`, so the wide version never exists.\n",
    "\n",
    "### Dictionary encoding in Arrow and Parquet\n",
    "\n",
    "Arrow has the same idea, called a **dictionary** type, and a pandas category column becomes one.\n",
    "Parquet goes further and dictionary-encodes every column by default: each column chunk stores its\n",
    "distinct values once and then small codes, falling back to plain values when there are too many\n",
    "different ones. The column metadata shows which encodings were used, and switching dictionary\n",
    "encoding off (with compression off too, so only the encoding differs) shows what it saves on the\n",
    "vendor column. The sizes are of the column's data in the file, without the file's **footer** (a\n",
    "short summary at the end of every Parquet file: its schema, and where each part of the data is).\n",
    "In the f-string, `!s` turns `True` or `False` into text so `:5` can pad it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "dictionary<values=large_string, indices=int8, ordered=0>\n",
      "use_dictionary=True     5.2 kB, encodings ['PLAIN', 'RLE', 'RLE_DICTIONARY']\n",
      "use_dictionary=False  240.9 kB, encodings ['PLAIN', 'RLE']\n"
     ]
    }
   ],
   "source": [
    "vendor_table = pa.Table.from_pandas(compact[[\"vendor\"]], preserve_index=False)\n",
    "print(vendor_table.schema.field(\"vendor\").type)\n",
    "for use_dictionary in [True, False]:\n",
    "    path = WORK / f\"vendor-dictionary-{use_dictionary}.parquet\"\n",
    "    pq.write_table(vendor_table, path, compression=\"none\", use_dictionary=use_dictionary)\n",
    "    column = pq.ParquetFile(path).metadata.row_group(0).column(0)\n",
    "    print(f\"use_dictionary={use_dictionary!s:5} {column.total_uncompressed_size / 1e3:6.1f} kB, \"\n",
    "          f\"encodings {sorted(column.encodings)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With the dictionary, the file stores the three names once and a few bits per row; without it,\n",
    "every row repeats its vendor's name in full, more than 40 times the space. Parquet does this on its\n",
    "own, so the vendor column costs almost nothing on disk even when it is plain text in pandas. The\n",
    "`RLE` in the list is run-length encoding, which stores a run of repeated codes as one value and a\n",
    "count, and works best when the file is sorted by that column.\n",
    "\n",
    "### One copy of each string: `sys.intern`\n",
    "\n",
    "*This part is optional: nothing later in the course depends on it.*\n",
    "\n",
    "Plain Python has a smaller version of the same trick. Text read with the `csv` module gives a new\n",
    "string object for every field (a piece of text is called a **string** in Python), so the vendor\n",
    "column read that way is 20,000 objects for three names. `sys.intern` returns one shared copy of\n",
    "each distinct string, so equal strings become the same object. `id(v)` gives the identity of the\n",
    "object `v` (in practice, where it is in memory), so counting the different ids counts the objects:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "20,000 vendor names: 20,000 string objects as read, 3 after sys.intern\n"
     ]
    }
   ],
   "source": [
    "with SAMPLE_CSV.open(encoding=\"utf-8\", newline=\"\") as handle:\n",
    "    vendors = [row[\"vendor\"] for row in csv.DictReader(handle)]\n",
    "interned = [sys.intern(vendor) for vendor in vendors]\n",
    "print(f\"{len(vendors):,} vendor names: {len({id(v) for v in vendors}):,} string objects as read, \"\n",
    "      f\"{len({id(v) for v in interned})} after sys.intern\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It helps when a pure-Python job keeps many records with repeated text (vendor names, element\n",
    "symbols, defect kinds) in memory. Once data is in pandas or Arrow, categories and dictionary\n",
    "encoding do the same job for a whole column.\n",
    "\n",
    "## 5. A partitioned Parquet dataset\n",
    "\n",
    "### Why Parquet, and why partitions\n",
    "\n",
    "**Parquet** (Module 3) is the standard file format for data that will be analysed. It stores a\n",
    "table column by column, in row groups, and keeps the minimum and maximum of each column in each\n",
    "row group in the file's footer. A reader can therefore fetch only the columns it needs (**column pruning**) and skip row\n",
    "groups whose minimum and maximum show they cannot match a filter (**predicate pushdown**). Each\n",
    "column is compressed separately, and a column of similar values (vendor names, small integers)\n",
    "compresses well.\n",
    "\n",
    "A **partitioned dataset** goes one step further: a folder of Parquet files split by the value of\n",
    "a column, one sub-folder per value, named `column=value` (the \"Hive\" layout, after the system that\n",
    "introduced it). Each sub-folder is a **partition**. For our library, split by vendor, it looks like\n",
    "this:\n",
    "\n",
    "```text\n",
    "library/\n",
    "  vendor=Vendor A/part-0.parquet\n",
    "  vendor=Vendor B/part-0.parquet\n",
    "  vendor=Vendor C/part-0.parquet\n",
    "```\n",
    " A query that asks for one vendor opens only that vendor's folder. Choose a column\n",
    "that queries often filter on and that has a modest number of values: vendor, library version or\n",
    "scaffold family, not the molecule id.\n",
    "\n",
    "### Writing it with PyArrow\n",
    "\n",
    "`pyarrow.dataset.write_dataset` writes a partitioned dataset from anything that hands out record\n",
    "batches, so we can convert the 300,000-row file without loading it: the source is read and written\n",
    "a row group at a time. We set the compression and the size of each row group (here 20,000 rows; in\n",
    "real jobs, row groups of 100,000 to 1,000,000 rows are common). `shutil.rmtree` first deletes the\n",
    "folder from any earlier run, and `rglob(\"*.parquet\")` then finds every Parquet file in it, however\n",
    "deep:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "library/vendor=Vendor%20A/part-0.parquet 100,000 rows, 5 row groups\n",
      "library/vendor=Vendor%20B/part-0.parquet 100,000 rows, 5 row groups\n",
      "library/vendor=Vendor%20C/part-0.parquet 100,000 rows, 5 row groups\n"
     ]
    }
   ],
   "source": [
    "shutil.rmtree(DATASET, ignore_errors=True)\n",
    "ds.write_dataset(\n",
    "    ds.dataset(STREAMED, format=\"parquet\"),\n",
    "    DATASET,\n",
    "    format=\"parquet\",\n",
    "    partitioning=[\"vendor\"],\n",
    "    partitioning_flavor=\"hive\",\n",
    "    file_options=ds.ParquetFileFormat().make_write_options(compression=\"zstd\"),\n",
    "    max_rows_per_group=ROW_GROUP,\n",
    "    min_rows_per_group=ROW_GROUP,\n",
    "    preserve_order=True,\n",
    ")\n",
    "for path in sorted(DATASET.rglob(\"*.parquet\")):\n",
    "    meta = pq.ParquetFile(path).metadata\n",
    "    print(path.relative_to(WORK).as_posix(), f\"{meta.num_rows:,} rows,\",\n",
    "          meta.num_row_groups, \"row groups\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The space in \"Vendor A\" is written as `%20`, the way spaces are written in web addresses, and\n",
    "turned back into a space when the dataset is read. Keeping partition values short and plain\n",
    "avoids surprises in tools that do not decode them.\n",
    "\n",
    "### Reading back only what you need\n",
    "\n",
    "Open the folder as one dataset. Nothing is read yet except the file list and the schema; the\n",
    "vendor column comes back from the folder names:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "['id', 'smiles', 'price_usd', 'stock_mg', 'heavy_atoms', 'halogens', 'vendor']\n",
      "300,000 rows in 3 files\n"
     ]
    }
   ],
   "source": [
    "library = ds.dataset(DATASET, format=\"parquet\", partitioning=\"hive\")\n",
    "print(library.schema.names)\n",
    "print(f\"{library.count_rows():,} rows in {len(library.files)} files\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now ask a question: small molecules (at most 20 heavy atoms) without halogens from Vendor B, with\n",
    "just the three columns we need. The vendor filter selects one folder; the other two are never\n",
    "opened. The heavy-atom filter is pushed down to the row groups, and only the columns asked for are\n",
    "decoded. The filter is written with `pc.field(\"name\")`, which stands for a column, and `&`, which\n",
    "means \"and\" (each condition needs its own brackets):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "3,575 rows, columns ['id', 'smiles', 'heavy_atoms']\n",
      "         id                          smiles  heavy_atoms\n",
      "ML-00000001      c1cc(C)ccc1C(=O)NCc2ccccc2           17\n",
      "ML-00000010      c1cc(O)ccc1C(=O)NCc2ccccc2           17\n",
      "ML-00000013 c1cc(C(=O)N)ccc1C(=O)NCc2ccccc2           19\n"
     ]
    }
   ],
   "source": [
    "wanted = (\n",
    "    (pc.field(\"vendor\") == \"Vendor B\")\n",
    "    & (pc.field(\"heavy_atoms\") <= 20)\n",
    "    & (pc.field(\"halogens\") == 0)\n",
    ")\n",
    "small = library.to_table(columns=[\"id\", \"smiles\", \"heavy_atoms\"], filter=wanted)\n",
    "print(f\"{small.num_rows:,} rows, columns {small.column_names}\")\n",
    "print(small.slice(0, 3).to_pandas().to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Predicate pushdown is easiest to see with a column whose values are in order, like the id (the\n",
    "library was streamed in id order). The minimum and maximum id in each row group are in the\n",
    "footer, so a filter on an id range can rule out row groups before reading them. PyArrow calls each\n",
    "file of a dataset a **fragment**; the code takes Vendor B's file, prints the id range of each of its\n",
    "row groups, and asks which row groups could hold ids from ML-00100000 to ML-00109999:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "row group 0: id ML-00000001 to ML-00059998\n",
      "row group 1: id ML-00060001 to ML-00119998\n",
      "row group 2: id ML-00120001 to ML-00179998\n",
      "row group 3: id ML-00180001 to ML-00239998\n",
      "row group 4: id ML-00240001 to ML-00299998\n",
      "row groups that could match: 1 of 5\n"
     ]
    }
   ],
   "source": [
    "vendor_b = next(f for f in library.get_fragments() if \"Vendor%20B\" in f.path)\n",
    "groups = vendor_b.metadata\n",
    "for i in range(groups.num_row_groups):\n",
    "    stats = groups.row_group(i).column(0).statistics\n",
    "    print(f\"row group {i}: id {stats.min} to {stats.max}\")\n",
    "one_range = (pc.field(\"id\") >= \"ML-00100000\") & (pc.field(\"id\") < \"ML-00110000\")\n",
    "kept = vendor_b.split_by_row_group(filter=one_range, schema=library.schema)\n",
    "print(f\"row groups that could match: {len(kept)} of {groups.num_row_groups}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The ids are text, so they compare as text; because every id has the same width, text order is\n",
    "number order here. Sorting data by the column you filter on most, before writing, makes row-group\n",
    "statistics far more useful.\n",
    "\n",
    "## 6. Querying the dataset with DuckDB\n",
    "\n",
    "**DuckDB** is a database for analysing data that runs inside your Python process, with nothing to\n",
    "install or start separately ([Module 4](../04-databases-and-schemas/) used it on a single table). It reads Parquet files directly,\n",
    "and a **glob** (a file pattern with wildcards) such as `work/library/**/*.parquet`, meaning \"every\n",
    "file ending in `.parquet`, in any sub-folder of `work/library`\", together with\n",
    "`hive_partitioning = true`, makes the whole folder one table, vendor column included.\n",
    "\n",
    "Questions to DuckDB are written in **SQL**, the language databases understand. If you skipped\n",
    "Module 4, these are the words used below:\n",
    "\n",
    "- `SELECT` lists the columns to return, and can compute new ones: `count(*)` counts rows,\n",
    "  `avg(price_usd)` averages a column, and `AS molecules` names the result;\n",
    "- `FROM` says which table to read;\n",
    "- `WHERE` keeps only the rows that pass a test;\n",
    "- `GROUP BY vendor` makes one result row per vendor;\n",
    "- `ORDER BY` sorts the result, and `LIMIT 5` keeps the first five rows.\n",
    "\n",
    "The SQL is put inside a Python f-string with triple quotes (`f\"\"\"...\"\"\"`), so it can run over\n",
    "several lines and `{LIBRARY}` can be filled in. `con.sql(...)` runs it, and `.df()` returns the\n",
    "answer as a pandas table. A summary per vendor:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "  vendor  molecules  mean_price_usd  min_heavy_atoms  max_heavy_atoms\n",
      "Vendor A     100000          260.51               11               39\n",
      "Vendor B     100000          260.47               12               38\n",
      "Vendor C     100000          260.49               12               38\n"
     ]
    }
   ],
   "source": [
    "con = duckdb.connect()\n",
    "LIBRARY = f\"read_parquet('{DATASET.as_posix()}/**/*.parquet', hive_partitioning = true)\"\n",
    "summary = con.sql(f\"\"\"\n",
    "    SELECT vendor,\n",
    "           count(*) AS molecules,\n",
    "           round(avg(price_usd), 2) AS mean_price_usd,\n",
    "           min(heavy_atoms) AS min_heavy_atoms,\n",
    "           max(heavy_atoms) AS max_heavy_atoms\n",
    "    FROM {LIBRARY}\n",
    "    GROUP BY vendor\n",
    "    ORDER BY vendor\n",
    "\"\"\").df()\n",
    "print(summary.to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A filter on a descriptor range, the kind of question a chemist asks of a screening library: the\n",
    "five cheapest molecules with 25 to 30 heavy atoms and no halogens, with a tie-breaker on the id\n",
    "so the answer is always the same:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "         id   vendor  price_usd  heavy_atoms                                               smiles\n",
      "ML-00048100 Vendor B      20.00           25          Cc1nc(O)sc1C(=O)NC(C(=O)N)c2ccc(c8ccco8)cc2\n",
      "ML-00096200 Vendor C      20.00           27    c1ccc2c(c1)c(C8CCOCC8)cn2C(=O)c3ccc(C(=O)C)c(O)c3\n",
      "ML-00033079 Vendor B      20.01           25           Cc1nc(C8CC8)sc1C(=O)NC(N8CCCC8)c2ccc(C)cc2\n",
      "ML-00129279 Vendor A      20.01           26         c1c(OCC)cc(cc1C8CC8)C(=O)NC(Cc8ccncc8)C(=O)N\n",
      "ML-00018058 Vendor B      20.02           26 c1cc(c8cn[nH]c8)c(cc1)Oc2ccc(cc2)C(=O)N(C)S(C)(=O)=O\n"
     ]
    }
   ],
   "source": [
    "cheapest = con.sql(f\"\"\"\n",
    "    SELECT id, vendor, price_usd, heavy_atoms, smiles\n",
    "    FROM {LIBRARY}\n",
    "    WHERE heavy_atoms BETWEEN 25 AND 30 AND halogens = 0\n",
    "    ORDER BY price_usd, id\n",
    "    LIMIT 5\n",
    "\"\"\").df()\n",
    "print(cheapest.to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`EXPLAIN` shows how DuckDB will run a **query** (a question written in SQL), without running it.\n",
    "DuckDB draws its plan in boxes; the code removes the box lines and prints what is inside. The vendor\n",
    "filter is applied to the file paths (only 1 of the 3 files is scanned) and the heavy-atom filter is\n",
    "applied inside the Parquet reader, so row groups that cannot match are skipped:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Ungrouped Aggregate\n",
      "Aggregates: count_star()\n",
      "~1 row\n",
      "Read Parquet\n",
      "Function: READ_PARQUET\n",
      "Filters:\n",
      "(heavy_atoms >= 25) AND (heavy_atoms <= 30)\n",
      "File Filters: vendor = 'Vendor B'\n",
      "Scanning Files: 1/3\n",
      "~1 row\n"
     ]
    }
   ],
   "source": [
    "plan = con.sql(f\"\"\"\n",
    "    EXPLAIN SELECT count(*) FROM {LIBRARY}\n",
    "    WHERE vendor = 'Vendor B' AND heavy_atoms BETWEEN 25 AND 30\n",
    "\"\"\").fetchall()[0][1]\n",
    "for line in plan.splitlines():\n",
    "    text = line.strip(\"│╭╮╰╯─┬┴ \")  # drop the boxes DuckDB draws, keep their contents\n",
    "    if text:\n",
    "        print(text)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Why this scales\n",
    "\n",
    "DuckDB, like the large databases companies use for analysis (called data warehouses), reads only\n",
    "the columns a query names, skips partitions and row groups that cannot match, and processes data a\n",
    "couple of thousand values at a time, spread over all the computer's **cores** (the processors\n",
    "inside the chip, each able to work on its own; a laptop has several). A `GROUP BY` or `ORDER BY`\n",
    "that needs more memory than it is allowed **spills**: it writes part of its work to temporary files\n",
    "on disk instead of failing. We can cap its memory and see the same answer:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "154,943 molecules with 25 to 30 heavy atoms, counted within a 200MB limit\n"
     ]
    }
   ],
   "source": [
    "con.sql(f\"SET memory_limit = '{DUCKDB_MEMORY}'\")\n",
    "capped = con.sql(f\"SELECT count(*) FROM {LIBRARY} WHERE heavy_atoms BETWEEN 25 AND 30\").fetchall()[0]\n",
    "print(f\"{capped[0]:,} molecules with 25 to 30 heavy atoms, counted within a {DUCKDB_MEMORY} limit\")\n",
    "con.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### From 300,000 to millions and beyond\n",
    "\n",
    "Nothing in this module depends on the 300,000. To stream the whole teaching library, change\n",
    "`N_MOLECULES` in the Setup block to `chemlib.size()`: there are 70 batches instead of 12, the run\n",
    "takes about six times as long, and peak memory stays at one batch. Past a few hundred million rows,\n",
    "teams make the same choices at a larger scale: more partition columns (vendor and scaffold family,\n",
    "say), compact column types chosen once in the schema, files kept in cloud storage such as Amazon\n",
    "S3 (storage rented over the internet, which DuckDB and PyArrow read directly), and, when one\n",
    "machine is too slow rather than too small, the work spread over many cores or machines, which is\n",
    "[Module 9](../09-parallel-and-distributed/).\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",
    "- Irwin, J. J., Tang, K. G., Young, J., Dandarchuluun, C., Wong, B. R., Khurelbaatar, M., Moroz,\n",
    "  Y. S., Mayfield, J. & Sayle, R. A. (2020). ZINC20—A free ultralarge-scale chemical database for\n",
    "  ligand discovery. *Journal of Chemical Information and Modeling*, 60(12), 6065–6073.\n",
    "  <https://doi.org/10.1021/acs.jcim.0c00675>\n",
    "- Raasveldt, M. & Mühleisen, H. (2019). DuckDB. *Proceedings of the 2019 International Conference\n",
    "  on Management of Data (SIGMOD '19)*, 1981–1984. <https://doi.org/10.1145/3299869.3320212>\n",
    "- The Apache Parquet documentation. *File format*. <https://parquet.apache.org/docs/file-format/>\n",
    "- The Apache Arrow documentation. *Tabular Datasets* (PyArrow).\n",
    "  <https://arrow.apache.org/docs/python/dataset.html>\n",
    "- The DuckDB documentation. *Reading and writing Parquet files*.\n",
    "  <https://duckdb.org/docs/stable/data/parquet/overview>\n",
    "- The pandas documentation. *Scaling to large datasets* (compact types, categories, chunking).\n",
    "  <https://pandas.pydata.org/docs/user_guide/scale.html>\n",
    "- The Python documentation. *collections: container datatypes* (`Counter`, `defaultdict`, `deque`,\n",
    "  `namedtuple`). <https://docs.python.org/3/library/collections.html>\n",
    "- The Python documentation. *tracemalloc: trace memory allocations*.\n",
    "  <https://docs.python.org/3/library/tracemalloc.html>\n",
    "- The tqdm documentation. <https://tqdm.github.io/>\n",
    "- The Python documentation. *itertools: functions creating iterators for efficient looping*.\n",
    "  <https://docs.python.org/3/library/itertools.html>\n",
    "- The psutil documentation (process memory, used for the measurements here).\n",
    "  <https://psutil.readthedocs.io/en/latest/>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
