{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Molecules as graphs and matrices\n",
    "\n",
    "A molecule is a graph of atoms and bonds; as matrices it becomes something algorithms and models can compute on.\n",
    "\n",
    "The lesson's page: https://monstrous.com.ng/learn/data-engineering/series-1/01-graphs-and-matrices/"
   ]
  },
  {
   "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 networkx numpy pandas"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A chemist looks at a drawing and sees aspirin. A computer sees nothing until the molecule is\n",
    "written down as text, numbers or a graph, and every way of writing it down keeps some things and\n",
    "loses others. Data engineering for chemistry starts here: before we can store, search, clean or\n",
    "scale anything, we have to decide what a molecule *is* inside our systems. This module starts with\n",
    "the most fundamental answer: a molecule is a graph.\n",
    "\n",
    "By the end of this module you will be able to:\n",
    "\n",
    "- read a molecule into RDKit and go through its atoms and bonds;\n",
    "- build the same molecule as a graph (atoms joined by bonds) with NetworkX;\n",
    "- write it as tables of numbers (matrices) that say which atoms are bonded, and how far apart\n",
    "  atoms are;\n",
    "- turn what each atom and bond is (element, charge, bond type) into numbers a program can use;\n",
    "- answer simple questions about a molecule with arithmetic on those tables.\n",
    "\n",
    "The lesson uses four Python packages (code other people wrote, which you load with `import`):\n",
    "\n",
    "- **RDKit**, the standard open-source toolkit for chemistry in Python: it reads molecules and\n",
    "  knows their atoms, bonds and properties;\n",
    "- **NetworkX**, for graphs: things (nodes) joined by links (edges);\n",
    "- **NumPy**, for arrays of numbers and fast arithmetic on them;\n",
    "- **pandas**, for tables with named rows and columns (used here to print matrices readably).\n",
    "\n",
    "You do not need to know any of them: each is introduced as it is used. Everything here runs in a\n",
    "browser notebook or on any laptop.\n",
    "\n",
    "## Setup\n",
    "\n",
    "Every lesson in the course starts with this block. It loads (imports) the packages the lesson uses,\n",
    "and sets the lesson's settings, written in CAPITALS, so they can be changed in one place. Run it\n",
    "first. It also sets up `log`, which later code uses to report what it did; you can ignore it for\n",
    "now: [the end of this lesson](#why-log-and-not-print) explains it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import logging\n",
    "\n",
    "import networkx as nx\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from rdkit import Chem\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",
    "# elements that get their own one-hot column (section 2); every other element shares \"other\".\n",
    "# Add \"S\", \"F\", \"Cl\" and so on for a drug-like library.\n",
    "ELEMENTS = [\"C\", \"N\", \"O\"]\n",
    "# RDKit's bond types, one layer of the bond tensor and one edge feature each (section 2)\n",
    "BOND_TYPES = [\"SINGLE\", \"DOUBLE\", \"TRIPLE\", \"AROMATIC\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. A molecule is a graph\n",
    "\n",
    "To RDKit, a molecule is a graph: **atoms are nodes and bonds are edges**. Hydrogens are usually\n",
    "left implicit, so only the heavy atoms appear. Here is aspirin, with every atom numbered in the\n",
    "order RDKit reads it.\n",
    "\n",
    "The code reads aspirin from **SMILES**, a way of writing a molecule as one line of text:\n",
    "`CC(=O)Oc1ccccc1C(=O)O` is aspirin, letters are atoms (lower case for aromatic ones), `=` is a\n",
    "double bond, brackets are branches and the two `1`s close the ring. Module 2 explains SMILES fully;\n",
    "here we only need RDKit to read it:\n",
    "\n",
    "![Aspirin drawn by RDKit with every atom numbered](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/01-graphs-and-matrices/figures/aspirin-atoms.svg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "13 heavy atoms, 13 bonds\n",
      "atom 0: C, bonded to [1]\n",
      "atom 1: C, bonded to [0, 2, 3]\n",
      "atom 2: O, bonded to [1]\n",
      "atom 3: O, bonded to [1, 4]\n",
      "atom 4: C, bonded to [3, 5, 9]\n"
     ]
    }
   ],
   "source": [
    "aspirin = Chem.MolFromSmiles(\"CC(=O)Oc1ccccc1C(=O)O\")\n",
    "print(aspirin.GetNumAtoms(), \"heavy atoms,\", aspirin.GetNumBonds(), \"bonds\")\n",
    "for atom in list(aspirin.GetAtoms())[:5]:\n",
    "    neighbours = [n.GetIdx() for n in atom.GetNeighbors()]\n",
    "    print(f\"atom {atom.GetIdx()}: {atom.GetSymbol()}, bonded to {neighbours}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The same molecule as a plain graph in NetworkX, the way a graph library or a graph database sees it.\n",
    "Every node carries the atom's properties and every edge the bond's; the next section turns them\n",
    "into numbers.\n",
    "\n",
    "![Aspirin as a graph: atoms as circles, bonds as lines](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/01-graphs-and-matrices/figures/aspirin-graph.svg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "13 nodes, 13 edges\n",
      "rings: [[4, 5, 6, 7, 8, 9]]\n",
      "bonds between the two carbonyl carbons: 4\n"
     ]
    }
   ],
   "source": [
    "def to_graph(mol: Chem.Mol) -> nx.Graph:\n",
    "    \"\"\"A molecule as a NetworkX graph: atoms as nodes, bonds as edges, each with its properties.\"\"\"\n",
    "    g = nx.Graph()\n",
    "    for atom in mol.GetAtoms():\n",
    "        g.add_node(\n",
    "            atom.GetIdx(),\n",
    "            element=atom.GetSymbol(),\n",
    "            hydrogens=atom.GetTotalNumHs(),\n",
    "            charge=atom.GetFormalCharge(),\n",
    "            aromatic=atom.GetIsAromatic(),\n",
    "        )\n",
    "    for bond in mol.GetBonds():\n",
    "        g.add_edge(\n",
    "            bond.GetBeginAtomIdx(),\n",
    "            bond.GetEndAtomIdx(),\n",
    "            bond_type=str(bond.GetBondType()),\n",
    "            order=bond.GetBondTypeAsDouble(),\n",
    "        )\n",
    "    return g\n",
    "\n",
    "\n",
    "graph = to_graph(aspirin)\n",
    "print(graph.number_of_nodes(), \"nodes,\", graph.number_of_edges(), \"edges\")\n",
    "print(\"rings:\", [sorted(ring) for ring in nx.cycle_basis(graph)])\n",
    "print(\"bonds between the two carbonyl carbons:\", nx.shortest_path_length(graph, 1, 10))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Graph questions (rings, paths, which atoms are connected) are chemistry questions. [Module 5](../05-graphs-and-graph-databases/) comes\n",
    "back to this when we store molecules in a graph database.\n",
    "\n",
    "## 2. Molecules as matrices\n",
    "\n",
    "Algorithms, and graph neural networks in particular, see a molecule as matrices. NetworkX builds\n",
    "them straight from the graph. The **adjacency matrix** has one row and one column per atom, with a\n",
    "1 where two atoms are bonded. Here it is for acetic acid, each atom labelled by element and index,\n",
    "checked against RDKit's own:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "    C0  C1  O2  O3\n",
      "C0   0   1   0   0\n",
      "C1   1   0   1   1\n",
      "O2   0   1   0   0\n",
      "O3   0   1   0   0\n",
      "symmetric: True\n",
      "bonds per atom (row sums): [1, 3, 1, 1]\n",
      "same as RDKit's: True\n"
     ]
    }
   ],
   "source": [
    "acetic_acid = Chem.MolFromSmiles(\"CC(=O)O\")\n",
    "g = to_graph(acetic_acid)\n",
    "atoms = sorted(g)\n",
    "labels = [f\"{g.nodes[i]['element']}{i}\" for i in atoms]\n",
    "adjacency = nx.to_numpy_array(g, nodelist=atoms, weight=None, dtype=int)\n",
    "print(pd.DataFrame(adjacency, index=labels, columns=labels))\n",
    "print(\"symmetric:\", bool((adjacency == adjacency.T).all()))  # .T flips rows and columns\n",
    "print(\"bonds per atom (row sums):\", adjacency.sum(axis=1).tolist())\n",
    "print(\"same as RDKit's:\", bool((adjacency == Chem.GetAdjacencyMatrix(acetic_acid)).all()))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Bonds have no direction, so the matrix is symmetric, and each row adds up to the number of bonds\n",
    "that atom makes (its degree). For aspirin the matrix is 13 by 13 and mostly zeros: each atom is\n",
    "bonded to only a few others.\n",
    "\n",
    "![Aspirin's adjacency matrix as a grid: a coloured square wherever two atoms are bonded, darker for double and aromatic bonds](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/01-graphs-and-matrices/figures/aspirin-adjacency.svg)\n",
    "\n",
    "### Encoding a molecule's properties\n",
    "\n",
    "A plain adjacency matrix says only *which* atoms are bonded. Chemistry needs more: what each atom\n",
    "is, and what kind each bond is. There are four standard ways to put those properties into numbers.\n",
    "\n",
    "**1. Weights in the matrix.** Put a number in each cell instead of a 1. With the bond order as the\n",
    "weight, the cells read 1, 1.5 (aromatic), 2 or 3:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "     C0   C1   O2   O3\n",
      "C0  0.0  1.0  0.0  0.0\n",
      "C1  1.0  0.0  2.0  1.0\n",
      "O2  0.0  2.0  0.0  0.0\n",
      "O3  0.0  1.0  0.0  0.0\n"
     ]
    }
   ],
   "source": [
    "orders = nx.to_numpy_array(g, nodelist=atoms, weight=\"order\")\n",
    "print(pd.DataFrame(orders, index=labels, columns=labels))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "One number per cell can carry one property only, so the other properties go beside the matrix.\n",
    "\n",
    "**2. An atom feature matrix.** One row per atom, one column per property. Numbers (charge,\n",
    "hydrogens) go in as numbers; categories (the element) are **one-hot encoded**, one column per\n",
    "category with a 1 in the right one, so that a model never reads \"oxygen = 8\" as \"more than carbon\".\n",
    "The elements that get a column are `ELEMENTS`, set in the Setup block:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "    C  N  O  other  hydrogens  charge  aromatic\n",
      "C0  1  0  0      0          3       0         0\n",
      "C1  1  0  0      0          0       0         0\n",
      "O2  0  0  1      0          0       0         0\n",
      "O3  0  0  1      0          1       0         0\n"
     ]
    }
   ],
   "source": [
    "def atom_features(data: dict) -> list[int]:\n",
    "    \"\"\"One row of the atom feature matrix: one-hot element, then hydrogens, charge, aromatic.\"\"\"\n",
    "    element = [int(data[\"element\"] == e) for e in ELEMENTS]\n",
    "    other = int(data[\"element\"] not in ELEMENTS)\n",
    "    return [*element, other, data[\"hydrogens\"], data[\"charge\"], int(data[\"aromatic\"])]\n",
    "\n",
    "\n",
    "columns = [*ELEMENTS, \"other\", \"hydrogens\", \"charge\", \"aromatic\"]\n",
    "X = np.array([atom_features(g.nodes[i]) for i in atoms])\n",
    "print(pd.DataFrame(X, index=labels, columns=columns))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**3. A bond tensor: one adjacency matrix per bond type.** Stack one matrix for single bonds, one\n",
    "for double, one for triple, one for aromatic. Each \"layer\" is an ordinary adjacency matrix, and\n",
    "together they say exactly which kind of bond joins which atoms (the layers are `BOND_TYPES`, from\n",
    "the Setup block):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "SINGLE bonds:\n",
      "    C0  C1  O2  O3\n",
      "C0   0   1   0   0\n",
      "C1   1   0   0   1\n",
      "O2   0   0   0   0\n",
      "O3   0   1   0   0\n",
      "DOUBLE bonds:\n",
      "    C0  C1  O2  O3\n",
      "C0   0   0   0   0\n",
      "C1   0   0   1   0\n",
      "O2   0   1   0   0\n",
      "O3   0   0   0   0\n",
      "shape of the bond tensor (types, atoms, atoms): (4, 4, 4)\n"
     ]
    }
   ],
   "source": [
    "tensor = np.zeros((len(BOND_TYPES), len(atoms), len(atoms)), dtype=int)\n",
    "for i, j, data in g.edges(data=True):\n",
    "    k = BOND_TYPES.index(data[\"bond_type\"])\n",
    "    tensor[k, i, j] = tensor[k, j, i] = 1\n",
    "for name, layer in zip(BOND_TYPES[:2], tensor[:2], strict=True):\n",
    "    print(f\"{name} bonds:\")\n",
    "    print(pd.DataFrame(layer, index=labels, columns=labels))\n",
    "print(\"shape of the bond tensor (types, atoms, atoms):\", tensor.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**4. An edge list with edge features.** Instead of n-by-n matrices, list each bond once in each\n",
    "direction, with a row of features per entry. This is what graph neural network libraries take: it\n",
    "grows with the bonds, not with the square of the atoms:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "edge index (from, to):\n",
      "[[0 1 1 1 2 3]\n",
      " [1 2 3 0 1 1]]\n",
      "edge features (one-hot bond type):\n",
      "     SINGLE  DOUBLE  TRIPLE  AROMATIC\n",
      "0-1       1       0       0         0\n",
      "1-2       0       1       0         0\n",
      "1-3       1       0       0         0\n",
      "1-0       1       0       0         0\n",
      "2-1       0       1       0         0\n",
      "3-1       1       0       0         0\n"
     ]
    }
   ],
   "source": [
    "pairs = [(i, j) for i, j in g.edges()] + [(j, i) for i, j in g.edges()]\n",
    "edge_index = np.array(pairs).T\n",
    "edge_features = np.array(\n",
    "    [[int(g.edges[i, j][\"bond_type\"] == t) for t in BOND_TYPES] for i, j in pairs]\n",
    ")\n",
    "print(\"edge index (from, to):\")\n",
    "print(edge_index)\n",
    "print(\"edge features (one-hot bond type):\")\n",
    "print(pd.DataFrame(edge_features, columns=BOND_TYPES, index=[f\"{i}-{j}\" for i, j in pairs]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Together, the atom feature matrix `X` and either the bond tensor or the edge list with its features\n",
    "describe the whole molecule as numbers. The MLOps track builds models on exactly these.\n",
    "\n",
    "### Distances\n",
    "\n",
    "The **distance matrix** counts the bonds on the shortest path between every pair of atoms.\n",
    "NetworkX and RDKit give the same answer:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "bonds between the two carbonyl carbons: 4\n",
      "the two atoms furthest apart are 6 bonds apart\n",
      "same as RDKit's: True\n"
     ]
    }
   ],
   "source": [
    "aspirin_graph = to_graph(aspirin)\n",
    "distances = nx.floyd_warshall_numpy(aspirin_graph, nodelist=sorted(aspirin_graph))\n",
    "print(\"bonds between the two carbonyl carbons:\", int(distances[1, 10]))\n",
    "print(\"the two atoms furthest apart are\", int(distances.max()), \"bonds apart\")\n",
    "print(\"same as RDKit's:\", bool((distances == Chem.GetDistanceMatrix(aspirin)).all()))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Graph operations with NumPy\n",
    "\n",
    "*This part is optional: it shows where the matrices lead (graph neural networks, fingerprints, salt\n",
    "detection). Skip to [Why log and not print](#why-log-and-not-print) if the maths is new: nothing\n",
    "later in the course depends on it.*\n",
    "\n",
    "Once a molecule is a matrix, graph questions become arithmetic. In Python, `A @ B` multiplies two\n",
    "matrices. With aspirin's adjacency matrix\n",
    "`A`, row sums give each atom's degree and the non-zero entries of a row are its neighbours. Squaring\n",
    "the matrix counts routes: `(A @ A)[i, j]` is the number of two-bond walks from atom `i` to atom `j`,\n",
    "and its diagonal gives the degrees back:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "degrees: [1, 3, 1, 2, 3, 2, 2, 2, 2, 3, 3, 1, 1]\n",
      "neighbours of atom 4: [3, 5, 9]\n",
      "two-bond walks from atom 1 to atom 4: 1\n",
      "diagonal of A @ A equals the degrees: True\n"
     ]
    }
   ],
   "source": [
    "A = nx.to_numpy_array(aspirin_graph, nodelist=sorted(aspirin_graph), weight=None, dtype=int)\n",
    "print(\"degrees:\", A.sum(axis=1).tolist())\n",
    "print(\"neighbours of atom 4:\", np.nonzero(A[4])[0].tolist())\n",
    "A2 = A @ A\n",
    "print(\"two-bond walks from atom 1 to atom 4:\", int(A2[1, 4]))\n",
    "print(\"diagonal of A @ A equals the degrees:\", bool((np.diag(A2) == A.sum(axis=1)).all()))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Multiplying the adjacency matrix by the atom feature matrix adds up each atom's neighbours'\n",
    "features: after one step, every atom \"knows\" what it is bonded to. This is one round of **message\n",
    "passing**, the core operation of graph neural networks, and the same idea a Morgan fingerprint uses\n",
    "when it grows each atom's environment one bond at a time:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "    C  N  O  other  hydrogens  charge  aromatic\n",
      "C0  1  0  0      0          0       0         0\n",
      "C1  1  0  2      0          3       0         0\n",
      "O2  1  0  0      0          0       0         0\n",
      "O3  2  0  0      0          0       0         1\n",
      "C4  2  0  1      0          1       0         2\n"
     ]
    }
   ],
   "source": [
    "aspirin_atoms = sorted(aspirin_graph)\n",
    "aspirin_labels = [f\"{aspirin_graph.nodes[i]['element']}{i}\" for i in aspirin_atoms]\n",
    "X_aspirin = np.array([atom_features(aspirin_graph.nodes[i]) for i in aspirin_atoms])\n",
    "messages = A @ X_aspirin\n",
    "print(pd.DataFrame(messages, index=aspirin_labels, columns=columns).head(5))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Atom 1, the acetyl carbon, receives one carbon and two oxygens from its neighbours; atom 4 receives\n",
    "two aromatic carbons and an oxygen.\n",
    "\n",
    "The **graph Laplacian**, `L = D - A` (the degrees on the diagonal minus the adjacency matrix), has\n",
    "one zero eigenvalue for every separate piece of a graph. (An eigenvalue is one of a set of numbers\n",
    "that summarise a square matrix; `np.linalg.eigvalsh` computes them. Here we only count how many are\n",
    "zero.) A record of sodium acetate holds two pieces,\n",
    "the acetate and the sodium ion, and the arithmetic finds both, a check Module 6 uses to spot salts\n",
    "and mixtures:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Laplacian eigenvalues: [0.0, 0.0, 1.0, 1.0, 4.0]\n",
      "pieces: 2  RDKit agrees: 2\n"
     ]
    }
   ],
   "source": [
    "salt = Chem.MolFromSmiles(\"CC(=O)[O-].[Na+]\")\n",
    "A_salt = Chem.GetAdjacencyMatrix(salt)\n",
    "laplacian = np.diag(A_salt.sum(axis=1)) - A_salt\n",
    "eigenvalues = np.linalg.eigvalsh(laplacian)\n",
    "print(\n",
    "    \"Laplacian eigenvalues:\", (np.round(eigenvalues, 3) + 0.0).tolist()\n",
    ")  # + 0.0 turns -0.0 into 0.0\n",
    "print(\n",
    "    \"pieces:\", int(np.isclose(eigenvalues, 0).sum()), \" RDKit agrees:\", len(Chem.GetMolFrags(salt))\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Matrices are convenient for computation but wasteful for storage: an adjacency matrix grows with\n",
    "the square of the number of atoms, while a list of bonds grows only with the bonds. Store the\n",
    "molecule (or its bond list) and build matrices when an algorithm needs them.\n",
    "\n",
    "## Why log and not print\n",
    "\n",
    "Some code in this lesson, and much more in the later ones, reports with `log.info(...)` rather\n",
    "than `print(...)`. A script that reads a vendor file could report its progress with `print`. Pipeline code uses the\n",
    "`logging` module instead, for four reasons:\n",
    "\n",
    "- **Every line has a level.** `DEBUG` for detail while you develop, `INFO` for what a job did,\n",
    "  `WARNING` for records it skipped, `ERROR` for failures. You choose how much to see by setting a\n",
    "  level, without editing the code: everything while developing, warnings only in a nightly job.\n",
    "- **Every line says where it came from.** Each logger has a name (usually the module it is in), and\n",
    "  a real job adds a timestamp to every line, so you can tell which step wrote what, and when.\n",
    "- **One line can go to many places.** Add handlers and the same line goes to the screen, a file\n",
    "  and a monitoring system at once. `print` only reaches the screen, and when a job runs unattended\n",
    "  overnight nobody is watching the screen.\n",
    "- **Libraries already log.** RDKit, requests and Dask report through logging (or can be made to:\n",
    "  Module 6 does it for RDKit, and shows how to turn its messages down or off), so your messages\n",
    "  sit alongside theirs and are controlled the same way.\n",
    "\n",
    "`print` stays useful for looking at results while you explore: a matrix, a table, a SMILES. The\n",
    "rule in this course: if a line would still be wanted when the code runs unattended as a job, it is a\n",
    "log line; if it is there to show you something, it is a print. Here are three lines at three\n",
    "levels. The level was set to `INFO` above, so the `DEBUG` line is not shown:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO read 2000 molecules from vendor.sdf\n",
      "WARNING skipped record 153: valence error on atom 0\n"
     ]
    }
   ],
   "source": [
    "log.debug(\"atom 4 of aspirin has %d neighbours\", 3)\n",
    "log.info(\"read %d molecules from %s\", 2_000, \"vendor.sdf\")\n",
    "log.warning(\"skipped record %d: %s\", 153, \"valence error on atom 0\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Raise the level to `WARNING`, as a nightly job might, and only the warning is left. The code that\n",
    "logs has not changed:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "WARNING skipped record 153: valence error on atom 0\n"
     ]
    }
   ],
   "source": [
    "log.setLevel(logging.WARNING)\n",
    "log.info(\"read %d molecules from %s\", 2_000, \"vendor.sdf\")\n",
    "log.warning(\"skipped record %d: %s\", 153, \"valence error on atom 0\")\n",
    "log.setLevel(logging.INFO)  # back to the lesson's level"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Module 14 builds on this to monitor whole pipelines.\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",
    "- Hagberg, A., Schult, D. & Swart, P. (2008). Exploring network structure, dynamics, and function\n",
    "  using NetworkX. *Proceedings of the 7th Python in Science Conference (SciPy 2008)*.\n",
    "  <https://proceedings.scipy.org/articles/TCWV9851>\n",
    "- Harris, C. R. et al. (2020). Array programming with NumPy. *Nature*, 585(7825), 357–362.\n",
    "  <https://doi.org/10.1038/s41586-020-2649-2>\n",
    "- Gilmer, J., Schoenholz, S. S., Riley, P. F., Vinyals, O. & Dahl, G. E. (2017). Neural message\n",
    "  passing for quantum chemistry. *Proceedings of the 34th International Conference on Machine\n",
    "  Learning*. <https://arxiv.org/abs/1704.01212>\n",
    "- David, L., Thakkar, A., Mercado, R. & Engkvist, O. (2020). Molecular representations in AI-driven\n",
    "  drug discovery: a review and practical guide. *Journal of Cheminformatics*, 12, 56.\n",
    "  <https://doi.org/10.1186/s13321-020-00460-5>\n",
    "- The NetworkX documentation. <https://networkx.org/documentation/stable/>\n",
    "- The Python documentation. *Logging HOWTO*. <https://docs.python.org/3/howto/logging.html>\n",
    "- The RDKit documentation. *Getting Started with the RDKit in Python*.\n",
    "  <https://www.rdkit.org/docs/GettingStartedInPython.html>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
