{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Molecules as graphs, and graph databases\n",
    "\n",
    "Work with molecules as graphs (rings, paths, substructure as graph matching, the largest shared substructure), then store chemistry that is all about links, synthesis routes and drug targets, in a Neo4j graph database and query it with Cypher.\n",
    "\n",
    "The lesson's page: https://monstrous.com.ng/learn/data-engineering/series-1/05-graphs-and-graph-databases/"
   ]
  },
  {
   "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 pandas duckdb neo4j python-dotenv\n",
    "\n",
    "# Cells that start with %%needs use a database. They run only where it is set up (see\n",
    "# the database guide); elsewhere, such as in Colab, they are skipped and the rest of the\n",
    "# lesson still runs. Their outputs are on the lesson's page.\n",
    "import os\n",
    "from IPython.core.magic import register_cell_magic\n",
    "\n",
    "\n",
    "@register_cell_magic\n",
    "def needs(service, cell):\n",
    "    \"\"\"Run this cell only if the database it needs is set up.\"\"\"\n",
    "    variable = {'neo4j': 'NEO4J_URI'}[service.strip()]\n",
    "    if os.environ.get(variable):\n",
    "        get_ipython().run_cell(cell)\n",
    "    else:\n",
    "        print(f\"Skipped: this cell needs {service.strip()}, which is not set up here.\"\n",
    "              \" Its output is shown on the lesson's page.\")\n",
    "\n",
    "\n",
    "import pathlib\n",
    "import urllib.request\n",
    "if not pathlib.Path(\"drawing.py\").exists():\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/05-graphs-and-graph-databases/drawing.py\", \"drawing.py\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[Module 1](../01-graphs-and-matrices/) showed that a molecule is a graph: atoms are the **nodes**\n",
    "and bonds the **edges** (the links between them). This module puts that to work. First we answer\n",
    "chemical questions with graph methods: where the rings are, how far apart two atoms are, whether\n",
    "one molecule contains another, and what several molecules have in common. Then we go up a level.\n",
    "Chemistry is full of links *between* molecules as well: a reaction turns some compounds into\n",
    "others, a drug acts on a protein, a protein sits in a pathway. Questions such as \"what can we make\n",
    "from phenol, and in how many steps?\" are about following those links, and a **graph database** is\n",
    "built for exactly that.\n",
    "\n",
    "By the end of this module you will be able to:\n",
    "\n",
    "- find a molecule's rings and the shortest path between two atoms, with NetworkX and with RDKit;\n",
    "- explain substructure search as graph matching, and why the pattern must say how many hydrogens\n",
    "  an atom carries;\n",
    "- find the largest part several molecules share (the maximum common substructure);\n",
    "- store compounds, reactions and drug targets in Neo4j, as nodes joined by relationships;\n",
    "- ask Neo4j questions in its language, Cypher, including questions that follow links any number of\n",
    "  steps;\n",
    "- compare the same question in a graph database and in SQL, and say where each one wins.\n",
    "\n",
    "From earlier modules we use: the molecular graph and RDKit ([Module 1](../01-graphs-and-matrices/)),\n",
    "SMILES, SMARTS and InChIKeys ([Module 2](../02-text-patterns-and-numbers/)), and SQL and DuckDB\n",
    "([Module 4](../04-databases-and-schemas/)).\n",
    "\n",
    "The lesson uses these packages:\n",
    "\n",
    "- **RDKit**, **NetworkX** and **pandas**, as in Module 1;\n",
    "- **DuckDB**, the database in one file from Module 4, for the comparison in section 6;\n",
    "- **neo4j**, the official Python driver for **Neo4j**, the most widely used graph database (from\n",
    "  section 3 onwards).\n",
    "\n",
    "**What runs where.** Sections 1 and 2 run in Colab or on any computer. Sections 3 to 6 need Neo4j\n",
    "running on your own computer in Docker: [the database\n",
    "guide](https://monstrous.com.ng/learn/databases/) shows how to install Docker and start it, step\n",
    "by step, and how to log in to Neo4j's own web page. Their code starts with the line\n",
    "`# needs: neo4j`; without Neo4j those blocks do nothing, and you can still read them and their\n",
    "outputs here.\n",
    "\n",
    "## Setup\n",
    "\n",
    "Every lesson starts with this block. It loads the packages and sets the lesson's settings, written\n",
    "in CAPITALS, so they can be changed in one place. Run it first. Neo4j's address, user name and\n",
    "password come from **environment variables** (named values your terminal passes to programs), kept\n",
    "on your own computer in the course's `.env` file as Module 4 set it up, never in the code: [Module 4](../04-databases-and-schemas/#8-safe-access-accounts-rights-and-passwords)\n",
    "explains why."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import logging\n",
    "import os\n",
    "from pathlib import Path\n",
    "\n",
    "import duckdb\n",
    "import networkx as nx\n",
    "import pandas as pd\n",
    "from dotenv import find_dotenv, load_dotenv\n",
    "from networkx.algorithms import isomorphism\n",
    "from neo4j import GraphDatabase\n",
    "from neo4j.exceptions import ConstraintError\n",
    "from rdkit import Chem, RDLogger\n",
    "from rdkit.Chem import rdFMCS\n",
    "\n",
    "from drawing import grid_svg, scheme_svg\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",
    "logging.getLogger(\"neo4j\").setLevel(logging.WARNING)  # the driver's own notes on each query: hidden\n",
    "\n",
    "# molecules of sections 1 and 2\n",
    "ASPIRIN = \"CC(=O)Oc1ccccc1C(=O)O\"\n",
    "METHYL_SALICYLATE = \"COC(=O)c1ccccc1O\"\n",
    "SALICYLIC_ACID = \"OC(=O)c1ccccc1O\"\n",
    "MCS_TIMEOUT_S = 10  # give up the common-substructure search after this many seconds\n",
    "\n",
    "# Neo4j (sections 3 to 6): where it is and how to log in\n",
    "# passwords and addresses: from the environment, or from the course's .env file (copied from\n",
    "# .env.example at the repository's root); find_dotenv looks for it in this folder and the ones\n",
    "# above, and settings already in the environment are kept\n",
    "load_dotenv(find_dotenv(usecwd=True))\n",
    "NEO4J_URI = os.environ.get(\"NEO4J_URI\", \"\")\n",
    "NEO4J_USER = os.environ.get(\"NEO4J_USER\", \"neo4j\")\n",
    "NEO4J_PASSWORD = os.environ.get(\"NEO4J_PASSWORD\", \"\")\n",
    "LESSON_LABEL = \"Module5\"  # every node the lesson makes carries it, so the lesson can remove its own\n",
    "\n",
    "# the lesson's chemistry network: textbook syntheses and well-established drug targets\n",
    "# (compound name: SMILES)\n",
    "COMPOUNDS = {\n",
    "    \"phenol\": \"Oc1ccccc1\",\n",
    "    \"nitric acid\": \"O=[N+]([O-])O\",\n",
    "    \"4-nitrophenol\": \"O=[N+]([O-])c1ccc(O)cc1\",\n",
    "    \"hydrogen\": \"[HH]\",\n",
    "    \"4-aminophenol\": \"Nc1ccc(O)cc1\",\n",
    "    \"acetic anhydride\": \"CC(=O)OC(C)=O\",\n",
    "    \"paracetamol\": \"CC(=O)Nc1ccc(O)cc1\",\n",
    "    \"carbon dioxide\": \"O=C=O\",\n",
    "    \"salicylic acid\": SALICYLIC_ACID,\n",
    "    \"aspirin\": ASPIRIN,\n",
    "    \"methanol\": \"CO\",\n",
    "    \"methyl salicylate\": METHYL_SALICYLATE,\n",
    "    \"isobutylbenzene\": \"CC(C)Cc1ccccc1\",\n",
    "    \"4-isobutylacetophenone\": \"CC(=O)c1ccc(CC(C)C)cc1\",\n",
    "    \"1-(4-isobutylphenyl)ethanol\": \"CC(O)c1ccc(CC(C)C)cc1\",\n",
    "    \"carbon monoxide\": \"[C-]#[O+]\",\n",
    "    \"ibuprofen\": \"CC(C)Cc1ccc(cc1)C(C)C(=O)O\",\n",
    "    \"celecoxib\": \"Cc1ccc(-c2cc(C(F)(F)F)nn2-c2ccc(S(N)(=O)=O)cc2)cc1\",\n",
    "}\n",
    "# (reaction name, reactants, products)\n",
    "REACTIONS = [\n",
    "    (\"nitration of phenol\", [\"phenol\", \"nitric acid\"], [\"4-nitrophenol\"]),\n",
    "    (\"reduction of 4-nitrophenol\", [\"4-nitrophenol\", \"hydrogen\"], [\"4-aminophenol\"]),\n",
    "    (\"acetylation of 4-aminophenol\", [\"4-aminophenol\", \"acetic anhydride\"], [\"paracetamol\"]),\n",
    "    (\"Kolbe-Schmitt carboxylation\", [\"phenol\", \"carbon dioxide\"], [\"salicylic acid\"]),\n",
    "    (\"acetylation of salicylic acid\", [\"salicylic acid\", \"acetic anhydride\"], [\"aspirin\"]),\n",
    "    (\"esterification of salicylic acid\", [\"salicylic acid\", \"methanol\"], [\"methyl salicylate\"]),\n",
    "    (\"Friedel-Crafts acylation\", [\"isobutylbenzene\", \"acetic anhydride\"], [\"4-isobutylacetophenone\"]),\n",
    "    (\"hydrogenation of the ketone\", [\"4-isobutylacetophenone\", \"hydrogen\"], [\"1-(4-isobutylphenyl)ethanol\"]),\n",
    "    (\"carbonylation\", [\"1-(4-isobutylphenyl)ethanol\", \"carbon monoxide\"], [\"ibuprofen\"]),\n",
    "]  # fmt: skip\n",
    "# (target ChEMBL id, name, gene) and which compounds inhibit it (well established)\n",
    "TARGETS = [(\"CHEMBL221\", \"Cyclooxygenase-1\", \"PTGS1\"), (\"CHEMBL230\", \"Cyclooxygenase-2\", \"PTGS2\")]\n",
    "INHIBITS = [(\"aspirin\", \"CHEMBL221\"), (\"aspirin\", \"CHEMBL230\"), (\"ibuprofen\", \"CHEMBL221\"),\n",
    "            (\"ibuprofen\", \"CHEMBL230\"), (\"celecoxib\", \"CHEMBL230\")]  # fmt: skip\n",
    "START = \"phenol\"  # the starting material of section 4's questions\n",
    "DRUG = \"aspirin\"  # the route drawn at the end of section 4\n",
    "WORK = Path(\"work\")  # where the lesson saves its drawings (git-ignored)\n",
    "\n",
    "RDLogger.DisableLog(\"rdApp.*\")  # RDKit warns about hydrogen gas ([HH]), which has no heavy atom\n",
    "WORK.mkdir(exist_ok=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Graph questions about one molecule\n",
    "\n",
    "We turn a molecule into a NetworkX graph as in Module 1: one node per atom, carrying its element and\n",
    "how many hydrogens it holds, and one edge per bond, carrying the bond order (1 single, 2 double,\n",
    "1.5 aromatic):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "13 atoms, 13 bonds\n"
     ]
    }
   ],
   "source": [
    "def to_graph(mol: Chem.Mol) -> nx.Graph:\n",
    "    \"\"\"A molecule as a NetworkX graph: atoms (element, hydrogens) as nodes, bonds (order) as edges.\"\"\"\n",
    "    g = nx.Graph()\n",
    "    for atom in mol.GetAtoms():\n",
    "        g.add_node(atom.GetIdx(), element=atom.GetSymbol(), hydrogens=atom.GetTotalNumHs())\n",
    "    for bond in mol.GetBonds():\n",
    "        g.add_edge(bond.GetBeginAtomIdx(), bond.GetEndAtomIdx(), order=bond.GetBondTypeAsDouble())\n",
    "    return g\n",
    "\n",
    "\n",
    "aspirin = Chem.MolFromSmiles(ASPIRIN)\n",
    "aspirin_graph = to_graph(aspirin)\n",
    "print(aspirin_graph.number_of_nodes(), \"atoms,\", aspirin_graph.number_of_edges(), \"bonds\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Rings.** In graph language a ring is a **cycle**: a path that comes back to where it started.\n",
    "`nx.cycle_basis` finds a set of cycles from which every other cycle can be built; RDKit finds the\n",
    "same rings with its own ring perception (`GetRingInfo`). Both give the benzene ring of aspirin, as\n",
    "the numbers of its six atoms (sorted, so the two can be compared: a ring has no first atom):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "NetworkX: [[4, 5, 6, 7, 8, 9]]\n",
      "RDKit:    [[4, 5, 6, 7, 8, 9]]\n"
     ]
    }
   ],
   "source": [
    "print(\"NetworkX:\", [sorted(ring) for ring in nx.cycle_basis(aspirin_graph)])\n",
    "print(\"RDKit:   \", [sorted(ring) for ring in aspirin.GetRingInfo().AtomRings()])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Paths.** How many bonds separate two atoms is the **shortest path** between them. Atom 0 is the\n",
    "acetyl methyl carbon and atom 12 the acid's OH oxygen (the numbering is the order of the SMILES):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "atoms on the way: [0, 1, 3, 4, 9, 10, 12]\n",
      "bonds apart: 6   RDKit agrees: 6\n"
     ]
    }
   ],
   "source": [
    "path = nx.shortest_path(aspirin_graph, 0, 12)\n",
    "print(\"atoms on the way:\", path)\n",
    "print(\"bonds apart:\", len(path) - 1, \"  RDKit agrees:\", int(Chem.GetDistanceMatrix(aspirin)[0, 12]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Distances like these are what 3D-free descriptors and graph neural networks are built from, and a\n",
    "**topological distance** of this kind is what a medicinal chemist means by \"three bonds away\".\n",
    "\n",
    "## 2. Substructure search is graph matching\n",
    "\n",
    "\"Does this molecule contain a carboxylic acid?\" is a graph question: is there a way to place the\n",
    "small graph of the pattern onto the big graph of the molecule, so that every pattern atom lands on\n",
    "an atom of the same element and every pattern bond on a bond of the same order? This is called\n",
    "**subgraph matching**, and NetworkX does it with a `GraphMatcher`. Our pattern is the acid group\n",
    "C(=O)O, three atoms; we try it twice, once without saying anything about hydrogens and once saying\n",
    "the single-bonded oxygen must carry exactly one hydrogen, as the SMARTS `[CX3](=O)[OX2H1]` did in\n",
    "Module 2:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "aspirin            C(=O)O: True   C(=O)O-H: True   RDKit SMARTS: True\n",
      "methyl salicylate  C(=O)O: True   C(=O)O-H: False  RDKit SMARTS: False\n"
     ]
    }
   ],
   "source": [
    "def acid_pattern(require_hydrogen: bool) -> nx.Graph:\n",
    "    \"\"\"The carboxyl group C(=O)O as a small graph; optionally the OH oxygen must carry one H.\"\"\"\n",
    "    pattern = nx.Graph()\n",
    "    pattern.add_node(\"C\", element=\"C\")\n",
    "    pattern.add_node(\"O=\", element=\"O\")\n",
    "    pattern.add_node(\"OH\", element=\"O\", **({\"hydrogens\": 1} if require_hydrogen else {}))\n",
    "    pattern.add_edge(\"C\", \"O=\", order=2.0)\n",
    "    pattern.add_edge(\"C\", \"OH\", order=1.0)\n",
    "    return pattern\n",
    "\n",
    "\n",
    "def atoms_match(atom: dict, wanted: dict) -> bool:\n",
    "    \"\"\"A molecule's atom matches a pattern atom: same element, and same hydrogens if given.\"\"\"\n",
    "    return atom[\"element\"] == wanted[\"element\"] and atom[\"hydrogens\"] == wanted.get(\"hydrogens\", atom[\"hydrogens\"])\n",
    "\n",
    "\n",
    "def contains(mol: Chem.Mol, pattern: nx.Graph) -> bool:\n",
    "    \"\"\"Whether the molecule's graph contains the pattern's graph (atoms and bond orders matching).\"\"\"\n",
    "    matcher = isomorphism.GraphMatcher(\n",
    "        to_graph(mol), pattern, node_match=atoms_match,\n",
    "        edge_match=lambda bond, wanted: bond[\"order\"] == wanted[\"order\"],\n",
    "    )  # fmt: skip\n",
    "    return matcher.subgraph_is_monomorphic()\n",
    "\n",
    "\n",
    "for name, smiles in [(\"aspirin\", ASPIRIN), (\"methyl salicylate\", METHYL_SALICYLATE)]:\n",
    "    mol = Chem.MolFromSmiles(smiles)\n",
    "    print(f\"{name:18} C(=O)O: {contains(mol, acid_pattern(False))!s:5}  \"\n",
    "          f\"C(=O)O-H: {contains(mol, acid_pattern(True))!s:5}  \"\n",
    "          f\"RDKit SMARTS: {mol.HasSubstructMatch(Chem.MolFromSmarts('[CX3](=O)[OX2H1]'))}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(`atom.get(\"hydrogens\", default)` reads a value from a dictionary, or gives the default when it is\n",
    "not there; `!s:5` prints a value as text padded to five characters, so the columns line up;\n",
    "`subgraph_is_monomorphic` asks whether the pattern fits inside the molecule.) Without hydrogens,\n",
    "the ester of methyl salicylate matches as if it were an acid: the same trap as the loose SMILES\n",
    "pattern in Modules 2 and 4. With the hydrogen in the pattern, the graph matcher, RDKit and the\n",
    "database all agree.\n",
    "\n",
    "Subgraph matching is slow in general: in the worst case the time grows faster than any power of\n",
    "the molecule's size, because many placements must be tried. That is why chemistry software first\n",
    "rules out most molecules with a quick fingerprint test, and why the database index of Module 4\n",
    "matters: it is that quick test, stored.\n",
    "\n",
    "### What several molecules share: the maximum common substructure\n",
    "\n",
    "The **maximum common substructure** (MCS) is the largest graph that fits inside every molecule of a\n",
    "set. It is how chemists find the shared core of a series, and RDKit's `rdFMCS.FindMCS` computes it,\n",
    "returning the core as SMARTS. Aspirin, methyl salicylate and salicylic acid share:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "shared core: [#8]-[#6](=[#8])-[#6]1:[#6]:[#6]:[#6]:[#6]:[#6]:1-[#8]\n",
      "10 atoms, 10 bonds; search finished in time: True\n"
     ]
    }
   ],
   "source": [
    "salicylates = [Chem.MolFromSmiles(s) for s in (ASPIRIN, METHYL_SALICYLATE, SALICYLIC_ACID)]\n",
    "mcs = rdFMCS.FindMCS(salicylates, timeout=MCS_TIMEOUT_S)\n",
    "print(\"shared core:\", mcs.smartsString)\n",
    "print(mcs.numAtoms, \"atoms,\", mcs.numBonds, \"bonds; search finished in time:\", not mcs.canceled)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The core is salicylic acid's skeleton: the benzene ring with a carboxyl carbon and its two oxygens\n",
    "on one carbon, and an oxygen on the next (`#8` is oxygen and `#6` carbon by atomic number; `:` is an\n",
    "aromatic bond). Each of the three adds its own groups to that core. Finding an MCS is even harder\n",
    "than a substructure match, hence the timeout.\n",
    "\n",
    "## 3. A graph database: Neo4j\n",
    "\n",
    "So far each graph was one molecule. The links that matter most in a research group are between\n",
    "molecules and other things: this compound is made from those two in this reaction; that drug\n",
    "inhibits this enzyme. In the relational database of Module 4, each kind of link is a table of\n",
    "pairs of keys, and a question that follows links several steps deep needs a join for every step.\n",
    "A **graph database** stores the links themselves:\n",
    "\n",
    "- **nodes** are the things, each with one or more **labels** saying what kind of thing it is\n",
    "  (`Compound`, `Reaction`, `Target`) and **properties** (name, SMILES);\n",
    "- **relationships** join two nodes, each with a **type** saying what the link means\n",
    "  (`REACTANT_OF`, `PRODUCES`, `INHIBITS`) and a direction, and they can carry properties too.\n",
    "\n",
    "Following a relationship is as cheap as reading a property, however many there are in the\n",
    "database, so questions that walk many steps stay fast. **Neo4j** is the most widely used graph\n",
    "database, and **Cypher** its query language. Cypher draws the pattern you are looking for:\n",
    "`(c:Compound)` is a node with the label `Compound`, called `c` in the query, and\n",
    "`(c)-[:INHIBITS]->(t)` is a relationship of type `INHIBITS` from `c` to `t`.\n",
    "\n",
    "*Sections 3 to 6 need Neo4j running (see [the database\n",
    "guide](https://monstrous.com.ng/learn/databases/)), and `NEO4J_URI`, `NEO4J_USER` and\n",
    "`NEO4J_PASSWORD` set in the terminal you started Python or Jupyter from. In Colab their blocks do\n",
    "nothing; read them and their outputs here.*\n",
    "\n",
    "`GraphDatabase.driver` connects to Neo4j, and `driver.execute_query(query, parameters)` runs one\n",
    "Cypher query and returns its records. Values go in as **parameters**, written `$name` in the query,\n",
    "never pasted into the query text (the same rule as `%s` in Module 4). The lesson first removes the\n",
    "nodes of any earlier run of itself, which all carry the extra label `Module5`, and makes sure that\n",
    "no two compounds can share an InChIKey and no two reactions a name: a **constraint**, as in a\n",
    "relational database:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO connected to Neo4j; constraints in place\n"
     ]
    }
   ],
   "source": [
    "%%needs neo4j\n",
    "# needs: neo4j\n",
    "driver = GraphDatabase.driver(NEO4J_URI, auth=(NEO4J_USER, NEO4J_PASSWORD))\n",
    "driver.verify_connectivity()\n",
    "driver.execute_query(f\"MATCH (n:{LESSON_LABEL}) DETACH DELETE n\")  # remove the last run's nodes\n",
    "driver.execute_query(\"CREATE CONSTRAINT compound_key IF NOT EXISTS \"\n",
    "                     \"FOR (c:Compound) REQUIRE c.inchikey IS UNIQUE\")  # fmt: skip\n",
    "driver.execute_query(\"CREATE CONSTRAINT reaction_name IF NOT EXISTS \"\n",
    "                     \"FOR (r:Reaction) REQUIRE r.name IS UNIQUE\")  # fmt: skip\n",
    "log.info(\"connected to Neo4j; constraints in place\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(`DETACH DELETE` removes a node together with its relationships; Neo4j will not leave a\n",
    "relationship pointing at nothing. The driver also writes notes about each query to the log, mostly\n",
    "performance hints for large databases; the Setup block hides them.)\n",
    "\n",
    "Now the network. `UNWIND $rows AS row` takes a list sent as a parameter and runs the rest of the\n",
    "query once per item, so one query loads every compound. `MERGE` finds a node matching the pattern,\n",
    "or creates it if there is none, so running the load twice does not make copies; `SET` writes\n",
    "properties:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Compound  18 nodes\n",
      "Reaction  9 nodes\n",
      "Target    2 nodes\n",
      "INHIBITS     5 relationships\n",
      "PRODUCES     9 relationships\n",
      "REACTANT_OF  18 relationships\n"
     ]
    }
   ],
   "source": [
    "%%needs neo4j\n",
    "# needs: neo4j\n",
    "compound_rows = [\n",
    "    {\"name\": name, \"smiles\": Chem.MolToSmiles(Chem.MolFromSmiles(smiles)),\n",
    "     \"inchikey\": Chem.MolToInchiKey(Chem.MolFromSmiles(smiles))}\n",
    "    for name, smiles in COMPOUNDS.items()\n",
    "]  # fmt: skip\n",
    "driver.execute_query(f\"\"\"\n",
    "    UNWIND $rows AS row\n",
    "    MERGE (c:Compound {{inchikey: row.inchikey}})\n",
    "    SET c:{LESSON_LABEL}, c.name = row.name, c.smiles = row.smiles\"\"\", rows=compound_rows)\n",
    "reaction_rows = [{\"name\": n, \"reactants\": r, \"products\": p} for n, r, p in REACTIONS]\n",
    "driver.execute_query(f\"\"\"\n",
    "    UNWIND $rows AS row\n",
    "    MERGE (r:Reaction {{name: row.name}}) SET r:{LESSON_LABEL}\n",
    "    WITH r, row\n",
    "    UNWIND row.reactants AS reactant\n",
    "    MATCH (c:Compound {{name: reactant}})\n",
    "    MERGE (c)-[:REACTANT_OF]->(r)\"\"\", rows=reaction_rows)\n",
    "driver.execute_query(\"\"\"\n",
    "    UNWIND $rows AS row\n",
    "    MATCH (r:Reaction {name: row.name})\n",
    "    UNWIND row.products AS product\n",
    "    MATCH (c:Compound {name: product})\n",
    "    MERGE (r)-[:PRODUCES]->(c)\"\"\", rows=reaction_rows)\n",
    "driver.execute_query(f\"\"\"\n",
    "    UNWIND $targets AS t\n",
    "    MERGE (target:Target {{chembl_id: t[0]}}) SET target:{LESSON_LABEL}, target.name = t[1], target.gene = t[2]\n",
    "    WITH count(*) AS made\n",
    "    UNWIND $links AS link\n",
    "    MATCH (c:Compound {{name: link[0]}}), (target:Target {{chembl_id: link[1]}})\n",
    "    MERGE (c)-[:INHIBITS]->(target)\"\"\", targets=TARGETS, links=INHIBITS)\n",
    "records, _, _ = driver.execute_query(f\"\"\"\n",
    "    MATCH (n:{LESSON_LABEL}) WITH labels(n) AS kinds\n",
    "    RETURN [k IN kinds WHERE k <> '{LESSON_LABEL}'][0] AS kind, count(*) AS nodes ORDER BY kind\"\"\")\n",
    "for record in records:\n",
    "    print(f\"{record['kind']:9} {record['nodes']} nodes\")\n",
    "records, _, _ = driver.execute_query(f\"\"\"\n",
    "    MATCH (:{LESSON_LABEL})-[rel]->(:{LESSON_LABEL})\n",
    "    RETURN type(rel) AS kind, count(*) AS links ORDER BY kind\"\"\")\n",
    "for record in records:\n",
    "    print(f\"{record['kind']:12} {record['links']} relationships\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(In these queries `{LESSON_LABEL}` is filled in by Python's f-string, and the doubled braces\n",
    "`{{ }}` stand for Cypher's own single braces, which hold a node's properties. `WITH` passes values\n",
    "from one part of a query to the next, like a pipe.)\n",
    "\n",
    "The constraint works like Module 4's `UNIQUE`: trying to create a second aspirin with the same\n",
    "InChIKey is refused. Neo4j's error code names the rule that was broken:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "refused: Neo.ClientError.Schema.ConstraintValidationFailed\n"
     ]
    }
   ],
   "source": [
    "%%needs neo4j\n",
    "# needs: neo4j\n",
    "try:\n",
    "    driver.execute_query(\"CREATE (:Compound {inchikey: $key, name: 'aspirin, typed again'})\",\n",
    "                         key=Chem.MolToInchiKey(aspirin))  # fmt: skip\n",
    "except ConstraintError as error:\n",
    "    print(\"refused:\", error.code)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Seeing the graph\n",
    "\n",
    "Neo4j comes with its own web page, **Neo4j Browser**, which draws the results of a query as a\n",
    "picture. Open <http://localhost:7474>, log in as the database guide shows, type this query on the\n",
    "`$` line and click **Run**:\n",
    "\n",
    "```text\n",
    "MATCH p = (:Module5)-[:REACTANT_OF|PRODUCES|INHIBITS]->(:Module5) RETURN p\n",
    "```\n",
    "\n",
    "(`:Module5` keeps the picture to this lesson's nodes.) The network appears: compounds,\n",
    "reactions and the two enzymes as circles (Neo4j gives each label its own colour), joined by labelled arrows. If the names\n",
    "do not show, zoom in with the + button at the bottom right of the picture. You can drag the circles about, and click one to see its properties.\n",
    "\n",
    "![Neo4j Browser showing the lesson's network: compound, reaction and target circles joined by arrows labelled REACTANT_OF, PRODUCES and INHIBITS; phenol branches to the paracetamol and aspirin routes, the three-step ibuprofen route stands apart, and aspirin, ibuprofen and celecoxib point to the two cyclooxygenase targets](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/05-graphs-and-graph-databases/figures/neo4j-network.png)\n",
    "\n",
    "## 4. Following links: Cypher questions\n",
    "\n",
    "A Cypher query is a pattern to find (`MATCH`), conditions (`WHERE`), and what to give back\n",
    "(`RETURN`). Which compounds inhibit which targets:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Cyclooxygenase-1  ['aspirin', 'ibuprofen']\n",
      "Cyclooxygenase-2  ['aspirin', 'celecoxib', 'ibuprofen']\n"
     ]
    }
   ],
   "source": [
    "%%needs neo4j\n",
    "# needs: neo4j\n",
    "records, _, _ = driver.execute_query(\"\"\"\n",
    "    MATCH (c:Compound)-[:INHIBITS]->(t:Target)\n",
    "    RETURN t.name AS target, collect(c.name) AS inhibitors ORDER BY target\"\"\")\n",
    "for record in records:\n",
    "    print(f\"{record['target']:17} {sorted(record['inhibitors'])}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(`collect` gathers the values of a group into a list, like `GROUP BY` with a list in SQL.)\n",
    "\n",
    "The strength of a graph database is in links of any length. `-[:REACTANT_OF|PRODUCES*]->` means\n",
    "\"one or more relationships of either type, in the arrow's direction\", so the pattern below finds\n",
    "every compound reachable from phenol by any number of reactions. Each reaction is two relationships\n",
    "(reactant of, then produces), so the number of steps is half the path's length:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "1 step(s): 4-nitrophenol\n",
      "1 step(s): salicylic acid\n",
      "2 step(s): 4-aminophenol\n",
      "2 step(s): aspirin\n",
      "2 step(s): methyl salicylate\n",
      "3 step(s): paracetamol\n"
     ]
    }
   ],
   "source": [
    "%%needs neo4j\n",
    "# needs: neo4j\n",
    "records, _, _ = driver.execute_query(\"\"\"\n",
    "    MATCH path = (start:Compound {name: $start})-[:REACTANT_OF|PRODUCES*]->(product:Compound)\n",
    "    RETURN product.name AS product, min(length(path)) / 2 AS steps\n",
    "    ORDER BY steps, product\"\"\", start=START)\n",
    "for record in records:\n",
    "    print(f\"{record['steps']} step(s): {record['product']}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The question a project actually asks joins the two kinds of link: which of the drugs we can make\n",
    "from phenol act on a cyclooxygenase, and by which route?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "aspirin inhibits Cyclooxygenase-1, via: Kolbe-Schmitt carboxylation, acetylation of salicylic acid\n",
      "aspirin inhibits Cyclooxygenase-2, via: Kolbe-Schmitt carboxylation, acetylation of salicylic acid\n"
     ]
    }
   ],
   "source": [
    "%%needs neo4j\n",
    "# needs: neo4j\n",
    "records, _, _ = driver.execute_query(\"\"\"\n",
    "    MATCH route = (start:Compound {name: $start})-[:REACTANT_OF|PRODUCES*]->(drug:Compound)\n",
    "                  -[:INHIBITS]->(target:Target)\n",
    "    RETURN drug.name AS drug, target.name AS target,\n",
    "           [n IN nodes(route) WHERE n:Reaction | n.name] AS reactions\n",
    "    ORDER BY drug, target\"\"\", start=START)\n",
    "for record in records:\n",
    "    print(f\"{record['drug']} inhibits {record['target']}, via: {', '.join(record['reactions'])}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(`nodes(route)` lists the nodes along the path, and `[n IN ... WHERE n:Reaction | n.name]` keeps the\n",
    "reactions and takes their names, like a Python list comprehension.) Phenol leads to aspirin, which\n",
    "inhibits both enzymes; paracetamol is made from phenol too, but has no `INHIBITS` link in our\n",
    "network, so it does not appear. A graph only answers from the links it has been given.\n",
    "\n",
    "One more question that is natural in a graph: which compounds are used in more than one reaction?\n",
    "These are the shared building blocks a group would keep in stock:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "acetic anhydride  used in 3 reactions\n",
      "hydrogen          used in 2 reactions\n",
      "phenol            used in 2 reactions\n",
      "salicylic acid    used in 2 reactions\n"
     ]
    }
   ],
   "source": [
    "%%needs neo4j\n",
    "# needs: neo4j\n",
    "records, _, _ = driver.execute_query(\"\"\"\n",
    "    MATCH (c:Compound)-[:REACTANT_OF]->(r:Reaction)\n",
    "    WITH c, count(r) AS uses WHERE uses > 1\n",
    "    RETURN c.name AS compound, uses ORDER BY uses DESC, compound\"\"\")\n",
    "for record in records:\n",
    "    print(f\"{record['compound']:17} used in {record['uses']} reactions\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Seeing the molecules\n",
    "\n",
    "Neo4j Browser draws every node as a circle with a caption: it does not know that a SMILES string\n",
    "is a molecule. Chemists want to see structures, so we let each tool do what it is good at: Neo4j\n",
    "finds the answer, and RDKit draws it. The course's small helper file `drawing.py`, next to the\n",
    "lesson (in Colab the first cell downloads it), draws each molecule in its own square box with its\n",
    "name underneath:\n",
    "\n",
    "- `grid_svg` puts several molecules side by side;\n",
    "- `scheme_svg` draws a route as a reaction scheme: boxes joined by arrows, with the other\n",
    "  reactants written over each arrow and the reaction's name under it.\n",
    "\n",
    "Both return an **SVG** picture (a text format for drawings that browsers and notebooks show). In a\n",
    "notebook, a cell that ends with the picture shows it; we also save it in `work/`, as a file any\n",
    "browser opens. First, everything phenol leads to, from the reachability question above, with the\n",
    "number of steps in each caption:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "drew 6 molecules in work/from-phenol.svg\n"
     ]
    }
   ],
   "source": [
    "%%needs neo4j\n",
    "# needs: neo4j\n",
    "records, _, _ = driver.execute_query(\"\"\"\n",
    "    MATCH path = (start:Compound {name: $start})-[:REACTANT_OF|PRODUCES*]->(product:Compound)\n",
    "    RETURN product.name AS name, product.smiles AS smiles, min(length(path)) / 2 AS steps\n",
    "    ORDER BY steps, name\"\"\", start=START)\n",
    "grid = grid_svg([(r[\"smiles\"], f\"{r['name']} ({r['steps']} step{'s' if r['steps'] > 1 else ''})\")\n",
    "                 for r in records])  # fmt: skip\n",
    "(WORK / \"from-phenol.svg\").write_text(grid, encoding=\"utf-8\")\n",
    "print(f\"drew {len(records)} molecules in work/from-phenol.svg\")\n",
    "grid  # in a notebook, the last line of a cell is shown: here, the picture"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![Six structures, each in a square box with its name and number of steps underneath: 4-nitrophenol and salicylic acid after one step; 4-aminophenol, aspirin and methyl salicylate after two; paracetamol after three](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/05-graphs-and-graph-databases/figures/from-phenol.svg)\n",
    "\n",
    "Then the route itself. `ORDER BY length(route) LIMIT 1` keeps the shortest path from phenol to\n",
    "aspirin, and for each node on it the query returns either the compound (name and SMILES) or the\n",
    "reaction with all its reactants. In Python we drop, from each reaction's reactants, the compound\n",
    "the route arrives with, which leaves the other reagents to write over the arrow:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "phenol\n",
      "  --[Kolbe-Schmitt carboxylation, with carbon dioxide]-->\n",
      "salicylic acid\n",
      "  --[acetylation of salicylic acid, with acetic anhydride]-->\n",
      "aspirin\n"
     ]
    }
   ],
   "source": [
    "%%needs neo4j\n",
    "# needs: neo4j\n",
    "records, _, _ = driver.execute_query(\"\"\"\n",
    "    MATCH route = (start:Compound {name: $start})-[:REACTANT_OF|PRODUCES*]->(drug:Compound {name: $drug})\n",
    "    RETURN [n IN nodes(route) | CASE WHEN n:Reaction\n",
    "        THEN {reaction: n.name, reactants: [(c:Compound)-[:REACTANT_OF]->(n) | c.name]}\n",
    "        ELSE {compound: n.name, smiles: n.smiles} END] AS steps\n",
    "    ORDER BY length(route) LIMIT 1\"\"\", start=START, drug=DRUG)\n",
    "steps = records[0][\"steps\"]\n",
    "for k, step in enumerate(steps):\n",
    "    if \"reaction\" in step:  # the other reactants: all of them except the compound we arrive with\n",
    "        step[\"with\"] = sorted(set(step[\"reactants\"]) - {steps[k - 1][\"compound\"]})\n",
    "        print(f\"  --[{step['reaction']}, with {', '.join(step['with'])}]-->\")\n",
    "    else:\n",
    "        print(step[\"compound\"])\n",
    "scheme = scheme_svg(steps)\n",
    "(WORK / f\"route-{DRUG}.svg\").write_text(scheme, encoding=\"utf-8\")\n",
    "scheme"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![The route from phenol to aspirin as a reaction scheme: phenol, salicylic acid and aspirin each drawn in a square box with its name underneath, joined by two arrows; the first arrow reads carbon dioxide above and Kolbe-Schmitt carboxylation below, the second acetic anhydride above and acetylation of salicylic acid below](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-1/05-graphs-and-graph-databases/figures/route-aspirin.svg)\n",
    "\n",
    "(`[(c:Compound)-[:REACTANT_OF]->(n) | c.name]` is a **pattern comprehension**: it finds every\n",
    "compound that is a reactant of `n` and collects their names, inside the query. `CASE WHEN ... THEN\n",
    "... ELSE ... END` chooses between two results, like `if` and `else`; `{reaction: ..., ...}` builds\n",
    "a small record, which arrives in Python as a dictionary.) Change `DRUG` in the Setup block to\n",
    "`\"paracetamol\"` or `\"methyl salicylate\"` and run the two blocks again to draw their routes.\n",
    "\n",
    "## 5. A molecule inside a graph database\n",
    "\n",
    "Module 1 promised to come back to storing a molecule itself in a graph database, atoms as nodes and\n",
    "bonds as relationships. It can be done, and Cypher can then walk the bonds:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "atom 0 to atom 12: 6 bonds, through CCOCCCO\n"
     ]
    }
   ],
   "source": [
    "%%needs neo4j\n",
    "# needs: neo4j\n",
    "atoms = [{\"i\": a.GetIdx(), \"element\": a.GetSymbol()} for a in aspirin.GetAtoms()]\n",
    "bonds = [{\"a\": b.GetBeginAtomIdx(), \"b\": b.GetEndAtomIdx(), \"order\": b.GetBondTypeAsDouble()}\n",
    "         for b in aspirin.GetBonds()]  # fmt: skip\n",
    "driver.execute_query(f\"\"\"\n",
    "    UNWIND $atoms AS atom CREATE (:Atom:{LESSON_LABEL} {{molecule: 'aspirin', i: atom.i, element: atom.element}})\n",
    "    WITH count(*) AS made\n",
    "    UNWIND $bonds AS bond\n",
    "    MATCH (a:Atom {{molecule: 'aspirin', i: bond.a}}), (b:Atom {{molecule: 'aspirin', i: bond.b}})\n",
    "    CREATE (a)-[:BOND {{order: bond.order}}]->(b)\"\"\", atoms=atoms, bonds=bonds)\n",
    "records, _, _ = driver.execute_query(\"\"\"\n",
    "    MATCH (a:Atom {molecule: 'aspirin', i: 0}), (b:Atom {molecule: 'aspirin', i: 12}),\n",
    "          path = shortestPath((a)-[:BOND*..30]-(b))\n",
    "    RETURN length(path) AS bonds_apart, [n IN nodes(path) | n.element] AS elements\"\"\")\n",
    "print(\"atom 0 to atom 12:\", records[0][\"bonds_apart\"], \"bonds, through\", \"\".join(records[0][\"elements\"]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The answer matches section 1 (`[:BOND*..30]` means one to thirty bonds; an upper limit keeps a\n",
    "search from wandering through a large graph). But this is rarely how molecules are stored: one molecule becomes\n",
    "dozens of nodes, and a substructure search becomes a large pattern match over all of them, which is\n",
    "what RDKit and the cartridge of Module 4 already do far better. The usual design keeps each\n",
    "molecule as **one** node with its SMILES (and searches it with RDKit), and uses the graph for the\n",
    "links *between* molecules, as in sections 3 and 4.\n",
    "\n",
    "## 6. The same question in SQL, and where each wins\n",
    "\n",
    "To compare fairly, we store the same network in DuckDB, as Module 4 would: a table of compounds and\n",
    "two tables of links, which reaction uses which reactant and which produces which product.\n",
    "Following links any number of steps in SQL needs a **recursive query**, `WITH RECURSIVE`: it starts\n",
    "from one row (phenol, 0 steps) and repeatedly adds the products of reactions whose reactants are\n",
    "already found, until nothing new turns up:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "          product  steps\n",
      "    4-nitrophenol      1\n",
      "   salicylic acid      1\n",
      "    4-aminophenol      2\n",
      "          aspirin      2\n",
      "methyl salicylate      2\n",
      "      paracetamol      3\n"
     ]
    }
   ],
   "source": [
    "db = duckdb.connect()  # a database in memory: nothing is written to disk\n",
    "db.execute(\"CREATE TABLE reactant (reaction VARCHAR, compound VARCHAR)\")\n",
    "db.execute(\"CREATE TABLE product (reaction VARCHAR, compound VARCHAR)\")\n",
    "db.executemany(\"INSERT INTO reactant VALUES (?, ?)\", [(n, c) for n, rs, _ in REACTIONS for c in rs])\n",
    "db.executemany(\"INSERT INTO product VALUES (?, ?)\", [(n, c) for n, _, ps in REACTIONS for c in ps])\n",
    "print(db.sql(\"\"\"\n",
    "    WITH RECURSIVE reachable (compound, steps) AS (\n",
    "        SELECT ?::VARCHAR, 0\n",
    "        UNION\n",
    "        SELECT p.compound, r.steps + 1\n",
    "        FROM reachable r\n",
    "        JOIN reactant a ON a.compound = r.compound\n",
    "        JOIN product p ON p.reaction = a.reaction\n",
    "        WHERE r.steps < 10\n",
    "    )\n",
    "    SELECT compound AS product, min(steps) AS steps FROM reachable\n",
    "    WHERE steps > 0 GROUP BY compound ORDER BY steps, product\"\"\", params=[START]).df().to_string(index=False))\n",
    "db.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(`?` marks a value passed in `params`, as `$start` did in Cypher. `UNION` adds rows not already\n",
    "found; `steps < 10` stops a network with loops from going round for ever.) The answer is the same\n",
    "as Cypher's in section 4. The SQL is longer and harder to read, and every extra kind of link (who\n",
    "inhibits what, who sells what) would add more joins inside the recursion, while the Cypher pattern\n",
    "just gets one more arrow.\n",
    "\n",
    "Where each one wins:\n",
    "\n",
    "- **A graph database** when the questions follow links, especially of varying or unknown length:\n",
    "  routes, networks of reactions or of compounds, targets and pathways, \"what is connected to\n",
    "  what\". The model is also easy to extend: a new kind of link needs no change to existing tables.\n",
    "- **A relational database** when the questions are about the records themselves: filtering,\n",
    "  summing and comparing many rows, with strict rules on every value and transactions across many\n",
    "  tables (Module 4). It is also the safer home for the data a group must never lose, with more\n",
    "  tools and more people who know it.\n",
    "\n",
    "Many groups use both: the relational database is the record, and a graph is built from it for the\n",
    "questions about links. Before the next question, we close the connection to Neo4j:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%needs neo4j\n",
    "# needs: neo4j\n",
    "driver.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 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",
    "- Robinson, I., Webber, J. & Eifrem, E. (2015). *Graph Databases: New Opportunities for Connected\n",
    "  Data* (2nd ed.). O'Reilly Media. ISBN 978-1-491-93089-2.\n",
    "- Raymond, J. W. & Willett, P. (2002). Maximum common subgraph isomorphism algorithms for the\n",
    "  matching of chemical structures. *Journal of Computer-Aided Molecular Design*, 16(7), 521-533.\n",
    "  <https://doi.org/10.1023/A:1021271615909>\n",
    "- The Neo4j documentation. *Cypher Manual*. <https://neo4j.com/docs/cypher-manual/current/>\n",
    "- The Neo4j documentation. *Neo4j Python Driver Manual*.\n",
    "  <https://neo4j.com/docs/python-manual/current/>\n",
    "- The NetworkX documentation. *VF2 algorithm* (graph and subgraph matching).\n",
    "  <https://networkx.org/documentation/stable/reference/algorithms/isomorphism.vf2.html>\n",
    "- The RDKit documentation. *Getting Started in Python*, section \"Maximum Common Substructure\".\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
}
