{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Modelling the warehouse\n",
    "\n",
    "Shape the lab's clean data as a star schema in DuckDB. Declare the grain, build dimensions for compounds, targets and dates (with properties and chemical series worked out once, with RDKit), a fact table of measurements with keys the database enforces, and answer the chemists' questions from it.\n",
    "\n",
    "The lesson's page: https://monstrous.com.ng/learn/data-engineering/series-2/03-modelling-the-warehouse/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Install what this lesson needs (in Colab, or any fresh environment)\n",
    "%pip install -q dlt[duckdb] duckdb pandas numpy rdkit\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\")\n",
    "if not pathlib.Path(\"labdata.py\").exists():\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/labdata.py\", \"labdata.py\")\n",
    "if not pathlib.Path(\"labstack.py\").exists():\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/labstack.py\", \"labstack.py\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[Module 1](../01-lab-data-architecture/) built the lab's three layers and two marts, each made for\n",
    "one question. [Module 2](../02-declarative-ingestion/) handed the raw layer to dlt. This module\n",
    "designs the marts properly. The chemists keep asking new questions, and a warehouse cannot add a\n",
    "mart for each one: it needs one shape that answers questions nobody has asked yet.\n",
    "\n",
    "That shape is the **star schema**, which [Series 1, Module\n",
    "4](../../series-1/04-databases-and-schemas/) introduced: a **fact table** of measurements in the\n",
    "middle, and **dimension tables** around it that describe the who, what and when of each\n",
    "measurement. There we reshaped a small normalised database to see the idea. Here we design a star\n",
    "from the start, for a real project, and meet the decisions that come with it: what one row of the\n",
    "fact table means, which descriptions belong in which dimension, which keys to use, and which\n",
    "numbers may be added up or averaged.\n",
    "\n",
    "By the end of this module you will be able to:\n",
    "\n",
    "- design a star schema in the four steps data teams use: the process, the grain, the dimensions\n",
    "  and the facts;\n",
    "- build a compound dimension that works out chemistry once (properties, and the chemical series by\n",
    "  substructure) so that no query has to;\n",
    "- use a date dimension in more than one role, and surrogate keys, and say why each matters;\n",
    "- make the database enforce the star's keys with primary and foreign key constraints;\n",
    "- tell additive measures from those that cannot be summed or averaged as they are, and handle\n",
    "  results reported only as \"weaker than\";\n",
    "- answer the chemists' questions from the star, and build a wide table for dashboards from it.\n",
    "\n",
    "## Setup\n",
    "\n",
    "The raw and staging layers come from the earlier modules. `labstack.py`, in the series folder,\n",
    "holds their code as those modules wrote it: `labstack.load_raw` runs Module 2's dlt pipeline for\n",
    "the first six weeks of the lab, and `labstack.stage` creates Module 1's staging views on top. The\n",
    "chemistry comes from RDKit: `Chem` reads SMILES, and `Crippen`, `Descriptors` and `Lipinski` work\n",
    "out properties."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import logging\n",
    "import shutil\n",
    "from pathlib import Path\n",
    "\n",
    "import duckdb\n",
    "import pandas as pd\n",
    "from rdkit import Chem, RDLogger\n",
    "from rdkit.Chem import Crippen, Descriptors, Lipinski\n",
    "\n",
    "import labdata\n",
    "import labstack\n",
    "\n",
    "RDLogger.DisableLog(\"rdApp.*\")  # RDKit's warnings would clutter the outputs; we check structures\n",
    "logging.basicConfig(level=logging.INFO, format=\"%(levelname)s %(message)s\", force=True)\n",
    "log = logging.getLogger(__name__)\n",
    "\n",
    "# where the lesson writes its files (git-ignored); change it to write somewhere else\n",
    "WORK = Path(\"work\")\n",
    "WAREHOUSE = WORK / \"lab.duckdb\"\n",
    "WEEKS = 6  # the lab is at the end of week 6, as in Modules 1 and 2\n",
    "# the three chemical series, each as the substructure its compounds share (its core)\n",
    "SERIES = {\n",
    "    \"aminopyrimidines\": \"c1ccc(nc1)Nc2ncccn2\",\n",
    "    \"pyrimidine piperazines\": \"c1nccc(n1)N2CCN(CC2)C(=O)c3ccccc3\",\n",
    "    \"ureas\": \"O=C(Nc1ccccc1)Nc2cccnc2\",\n",
    "}\n",
    "\n",
    "shutil.rmtree(WORK, ignore_errors=True)  # start clean\n",
    "lab = labdata.Lab()\n",
    "labstack.load_raw(lab, WEEKS, WORK / \"inbox\", WAREHOUSE, WORK / \"dlt\")\n",
    "db = duckdb.connect(str(WAREHOUSE))\n",
    "labstack.stage(db)\n",
    "db.execute(\"CREATE SCHEMA marts\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Four decisions\n",
    "\n",
    "The chemists' questions this week:\n",
    "\n",
    "1. How potent is each compound on EGFR, and is each series getting better week by week?\n",
    "2. Which chemist's compounds are the most potent, and which vendor's building blocks work best?\n",
    "3. Are the potent compounds just the greasy ones? (Potency often rises with lipophilicity, which\n",
    "   brings problems of its own.)\n",
    "4. Which compounds are potent on EGFR and weak on the four other kinases?\n",
    "\n",
    "They share a pattern. Each asks for a **number** (a potency) about a **measurement**, sliced by\n",
    "**descriptions** of what was measured: the compound's series, chemist, vendor or properties, the\n",
    "target, the week. That is exactly what a star separates: the numbers go in the fact table, the\n",
    "descriptions in the dimensions. Kimball and Ross, who wrote the standard book on this, design a\n",
    "star in four steps, and this module follows them:\n",
    "\n",
    "1. **The process.** Which activity of the lab do we record? Measuring compounds in assays.\n",
    "2. **The grain.** What exactly is one row of the fact table?\n",
    "3. **The dimensions.** What describes each row?\n",
    "4. **The facts.** Which numbers does each row hold?\n",
    "\n",
    "![The lab's star schema: fact_measurement in the middle with keys to dim_compound, dim_target and dim_date, and the measures relation, ic50_nm and pic50; dim_compound also points to dim_date through registered_on](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/03-modelling-the-warehouse/figures/lab-star.svg)\n",
    "\n",
    "## 2. The grain\n",
    "\n",
    "The **grain** says what one row of the fact table stands for, in one sentence. It is the decision\n",
    "everything else depends on: a fact table whose rows mean different things is how a warehouse\n",
    "starts giving wrong totals. The finest grain the lab has is one result from the plate reader, so\n",
    "we choose that: *one row per measurement of one compound on one target, in one well of one plate\n",
    "(one replicate)*. A coarser grain (one row per compound and target, averaged) would answer\n",
    "question 1, but no question about plates or weeks could ever be asked of it again. Start at the\n",
    "finest grain; averages can always be made from it, never the other way round.\n",
    "\n",
    "A grain is a claim, so we check it: the columns that name it must identify every row once."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      " results  distinct_at_grain\n",
      "     656                656\n"
     ]
    }
   ],
   "source": [
    "print(db.sql(\"\"\"\n",
    "    SELECT count(*)                                                  AS results,\n",
    "           count(DISTINCT (compound_id, target, plate, replicate))   AS distinct_at_grain\n",
    "    FROM staging.results\n",
    "\"\"\").df().to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![The grain: on plate P02-01, LAB-0007 was measured on EGFR in two wells, and each well becomes one row of fact_measurement (R-00013 at 842 nM and R-00014 at 703 nM, with plate and replicate kept); averaging to one row per compound and target would lose the plates for good](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/03-modelling-the-warehouse/figures/grain.svg)\n",
    "\n",
    "Every result is one compound, one target, one plate, one replicate. If two rows had shared those\n",
    "four, the grain would be wrong (or the data would hold a duplicate) and we would have to find out\n",
    "which before going on.\n",
    "\n",
    "## 3. The compound dimension\n",
    "\n",
    "A dimension has one row per thing it describes, with every description a question might slice\n",
    "by. For a compound that is its structure, salt, chemist, vendor and registration date, from the\n",
    "registry, and also things the registry does not say but chemists ask about: its chemical series,\n",
    "and properties such as molecular weight and lipophilicity.\n",
    "\n",
    "Working those out is chemistry, and doing it in the dimension means doing it **once**. Every query\n",
    "and every dashboard then reads the same series and the same cLogP, instead of each one computing\n",
    "its own (and getting slightly different answers, with slightly different code). Here is the\n",
    "chemistry, as Python functions:\n",
    "\n",
    "- the **series** is the one whose core the compound contains (`HasSubstructMatch`). A core\n",
    "  written as SMILES and used as a query matches any molecule that contains it, whatever is\n",
    "  attached; [Series 1, Module 2](../../series-1/02-text-patterns-and-numbers/), section 6, showed\n",
    "  where that is a trap, but here it is exactly what we want. A compound matching no core, or more\n",
    "  than one, gets no series, so that a person looks at it;\n",
    "- the properties come from RDKit (Series 1, Module 2, section 8): molecular weight, **cLogP** (Crippen's estimate of the\n",
    "  octanol-water partition coefficient, a measure of how greasy a molecule is), hydrogen-bond\n",
    "  donors and acceptors, and the number of heavy (non-hydrogen) atoms."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "series\n",
      "aminopyrimidines          132\n",
      "pyrimidine piperazines     55\n",
      "ureas                      52\n",
      "NaN                         1\n",
      "compound_id                   parent_smiles\n",
      "   LAB-0042 O=C(Cc1ccc(O)cc1)Nc2ccc(C#N)nc2\n"
     ]
    }
   ],
   "source": [
    "CORES = {name: Chem.MolFromSmiles(core) for name, core in SERIES.items()}\n",
    "\n",
    "\n",
    "def series_of(mol: Chem.Mol) -> str | None:\n",
    "    \"\"\"The chemical series whose core the molecule contains (None if no core, or several).\"\"\"\n",
    "    hits = [name for name, core in CORES.items() if mol.HasSubstructMatch(core)]\n",
    "    return hits[0] if len(hits) == 1 else None\n",
    "\n",
    "\n",
    "def describe(smiles: str) -> dict:\n",
    "    \"\"\"A compound's series and properties, worked out once for the dimension.\"\"\"\n",
    "    mol = Chem.MolFromSmiles(smiles)\n",
    "    return {\n",
    "        \"series\": series_of(mol),\n",
    "        \"mw\": round(Descriptors.MolWt(mol), 1),\n",
    "        \"clogp\": round(Crippen.MolLogP(mol), 2),\n",
    "        \"hbd\": Lipinski.NumHDonors(mol),\n",
    "        \"hba\": Lipinski.NumHAcceptors(mol),\n",
    "        \"heavy_atoms\": mol.GetNumHeavyAtoms(),\n",
    "    }\n",
    "\n",
    "\n",
    "compounds = db.sql(\"SELECT * FROM staging.compounds ORDER BY compound_id\").df()\n",
    "chemistry = pd.DataFrame([describe(s) for s in compounds[\"parent_smiles\"]])\n",
    "compounds = pd.concat([compounds, chemistry], axis=1)\n",
    "print(compounds[\"series\"].value_counts(dropna=False).to_string())\n",
    "print(compounds[compounds[\"series\"].isna()][[\"compound_id\", \"parent_smiles\"]]\n",
    "      .to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every compound fell into one series but one: `LAB-0042`. Its SMILES starts `O=C(Cc1...`, where a\n",
    "urea would start `O=C(Nc1...`: one nitrogen was registered as a carbon. The dimension did not\n",
    "guess a series for it; it left the gap where a person will see it. (The registry is corrected in\n",
    "week 7, and [Module 6](../06-history-and-corrections/) keeps both versions.) A dimension built\n",
    "with care is also a check on the data it describes.\n",
    "\n",
    "Now the table. We create it with its columns and types written out, and a **primary key**: a\n",
    "column whose values the database guarantees are present and unique. The key is not the\n",
    "`compound_id` the lab uses but a new number, `compound_key`, given by the warehouse. That is a\n",
    "**surrogate key**. The lab's own ID (the **natural key**) stays in the table, but the warehouse's\n",
    "joins use the surrogate. The reason comes in Module 6: when LAB-0042's structure is corrected, the\n",
    "dimension will hold two versions of the same compound, both with the ID `LAB-0042`, and only a key\n",
    "of the warehouse's own can tell them apart."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      " compound_key compound_id                                             parent_smiles salt                 series chemist   vendor registered_on    mw  clogp  hbd  hba  heavy_atoms\n",
      "            1    LAB-0001     c1nc(c8ccco8)cc(n1)N2CCN(CC2)C(=O)c3ccc(OC(F)(F)F)cc3      pyrimidine piperazines      CN Vendor A    2026-09-11 418.4   3.60    0    6           30\n",
      "            2    LAB-0002         c1cc(CC)c(nc1)Nc2nc(c8ccco8)c(c8ccc(F)cc8)c(OC)n2  TFA       aminopyrimidines      AO Vendor C    2026-09-11 390.4   5.25    1    6           29\n",
      "            3    LAB-0003 c1cc(C(C)C)c(nc1)Nc2nc(N(C)C)c(c8cn[nH]c8)c(c8cn[nH]c8)n2            aminopyrimidines      AO Vendor A    2026-09-11 389.5   3.58    3    7           29\n"
     ]
    }
   ],
   "source": [
    "db.execute(\"\"\"\n",
    "    CREATE TABLE marts.dim_compound (\n",
    "        compound_key  INTEGER PRIMARY KEY,\n",
    "        compound_id   VARCHAR NOT NULL,\n",
    "        parent_smiles VARCHAR NOT NULL,\n",
    "        salt          VARCHAR,\n",
    "        series        VARCHAR,\n",
    "        chemist       VARCHAR,\n",
    "        vendor        VARCHAR,\n",
    "        registered_on DATE,\n",
    "        mw            DOUBLE,\n",
    "        clogp         DOUBLE,\n",
    "        hbd           INTEGER,\n",
    "        hba           INTEGER,\n",
    "        heavy_atoms   INTEGER\n",
    "    )\n",
    "\"\"\")\n",
    "db.execute(\"\"\"\n",
    "    INSERT INTO marts.dim_compound\n",
    "    SELECT row_number() OVER (ORDER BY compound_id), compound_id, parent_smiles, salt, series,\n",
    "           chemist, vendor, registered_on, mw, clogp, hbd, hba, heavy_atoms\n",
    "    FROM compounds\n",
    "\"\"\")\n",
    "print(db.sql(\"SELECT * FROM marts.dim_compound LIMIT 3\").df().to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`FROM compounds` reads the pandas table of that name directly: DuckDB can query a pandas table in\n",
    "the same Python session as if it were one of its own. `row_number() OVER (ORDER BY compound_id)`\n",
    "numbers the compounds 1, 2, 3 and so on, which becomes their surrogate key.\n",
    "\n",
    "## 4. Targets and dates\n",
    "\n",
    "The target dimension is small: one row per kinase, with its ChEMBL ID and its role in the project.\n",
    "It is also **conformed**: when ChEMBL's activities join the warehouse, they will use the same\n",
    "`dim_target`, so the lab's own potencies and published ones line up target by target."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      " target_key target  chembl_id    role\n",
      "          1   EGFR  CHEMBL203 primary\n",
      "          2   ABL1 CHEMBL1862   panel\n",
      "          3   BRAF CHEMBL5145   panel\n",
      "          4   CDK2  CHEMBL301   panel\n",
      "          5   JAK2 CHEMBL2971   panel\n"
     ]
    }
   ],
   "source": [
    "targets = pd.DataFrame(\n",
    "    [(gene, chembl_id, \"primary\" if gene == labdata.PRIMARY else \"panel\")\n",
    "     for gene, chembl_id in labdata.TARGETS.items()],\n",
    "    columns=[\"target\", \"chembl_id\", \"role\"],\n",
    ")\n",
    "db.execute(\"\"\"\n",
    "    CREATE TABLE marts.dim_target (\n",
    "        target_key INTEGER PRIMARY KEY,\n",
    "        target     VARCHAR NOT NULL UNIQUE,\n",
    "        chembl_id  VARCHAR NOT NULL,\n",
    "        role       VARCHAR NOT NULL\n",
    "    )\n",
    "\"\"\")\n",
    "db.execute(\"INSERT INTO marts.dim_target \"\n",
    "           \"SELECT row_number() OVER (ORDER BY role DESC, target), * FROM targets\")\n",
    "print(db.sql(\"SELECT * FROM marts.dim_target ORDER BY target_key\").df().to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`ORDER BY role DESC` puts the primary target first (`primary` sorts after `panel`, and `DESC`\n",
    "reverses that), so EGFR gets key 1. `UNIQUE` asks the database to keep each gene name once.\n",
    "\n",
    "Dates get a dimension too, although a date seems to describe itself. The chemists think in the\n",
    "project's weeks, the managers in months, and a query should not have to work out \"week 4 of the\n",
    "project\" from a date each time. The **date dimension** has one row per day of the project and a\n",
    "column for each way of grouping days. DuckDB's `generate_series` makes the days, and the date\n",
    "itself is the key: a date is unique and never changes, so it needs no surrogate."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "  date_key  project_week  weekend   weekday     month\n",
      "2026-09-16             2    False Wednesday September\n",
      "2026-09-17             2    False  Thursday September\n",
      "2026-09-18             2    False    Friday September\n",
      "2026-09-19             2     True  Saturday September\n",
      "2026-09-20             2     True    Sunday September\n",
      "2026-09-21             3    False    Monday September\n"
     ]
    }
   ],
   "source": [
    "db.execute(f\"\"\"\n",
    "    CREATE TABLE marts.dim_date AS\n",
    "    SELECT day::DATE                                            AS date_key,\n",
    "           (datediff('day', DATE '{labdata.START}', day) // 7) + 1 AS project_week,\n",
    "           isodow(day) > 5                                      AS weekend,\n",
    "           dayname(day)                                         AS weekday,\n",
    "           monthname(day)                                       AS month\n",
    "    FROM generate_series(DATE '{labdata.START}',\n",
    "                         DATE '{labdata.monday(labdata.WEEKS + 1)}', INTERVAL 1 DAY) AS t(day)\n",
    "\"\"\")\n",
    "db.execute(\"ALTER TABLE marts.dim_date ADD PRIMARY KEY (date_key)\")\n",
    "print(db.sql(\"SELECT * FROM marts.dim_date WHERE date_key BETWEEN DATE '2026-09-16' \"\n",
    "             \"AND DATE '2026-09-21'\").df().to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`//` divides and keeps the whole part, so days 0 to 6 of the project fall in week 1, days 7 to 13\n",
    "in week 2. The same date dimension serves two **roles**: the date a measurement was run (from the\n",
    "fact table) and the date a compound was registered (from `dim_compound`). A dimension used in\n",
    "several roles is called a **role-playing dimension**, and it means that \"project week\" is worked\n",
    "out one way for both.\n",
    "\n",
    "## 5. The fact table\n",
    "\n",
    "The fact table holds, for each measurement at the grain, a key to each dimension and the\n",
    "measurements themselves. Its keys are **foreign keys**: each value must exist in the dimension it\n",
    "points to, and the database checks that on every insert. A measurement of a compound the\n",
    "dimension does not know is refused, instead of quietly dropping out of every join later.\n",
    "\n",
    "Some descriptions belong to a single measurement and to no dimension: the plate, the replicate,\n",
    "the result ID and the file it came from. They stay in the fact table as **degenerate dimensions**\n",
    "(a dimension with nothing to describe but its own value)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "656 measurements in the fact table, of 656 in staging\n"
     ]
    }
   ],
   "source": [
    "db.execute(\"\"\"\n",
    "    CREATE TABLE marts.fact_measurement (\n",
    "        result_id    VARCHAR PRIMARY KEY,\n",
    "        compound_key INTEGER NOT NULL REFERENCES marts.dim_compound (compound_key),\n",
    "        target_key   INTEGER NOT NULL REFERENCES marts.dim_target (target_key),\n",
    "        run_date     DATE    NOT NULL REFERENCES marts.dim_date (date_key),\n",
    "        plate        VARCHAR NOT NULL,\n",
    "        replicate    INTEGER NOT NULL,\n",
    "        relation     VARCHAR NOT NULL,\n",
    "        ic50_nm      DOUBLE,\n",
    "        pic50        DOUBLE,\n",
    "        source_file  VARCHAR NOT NULL\n",
    "    )\n",
    "\"\"\")\n",
    "db.execute(\"\"\"\n",
    "    INSERT INTO marts.fact_measurement\n",
    "    SELECT r.result_id, c.compound_key, t.target_key, r.run_date, r.plate, r.replicate,\n",
    "           r.relation, r.ic50_nm, r.pic50, r.source_file\n",
    "    FROM staging.results AS r\n",
    "    JOIN marts.dim_compound AS c USING (compound_id)\n",
    "    JOIN marts.dim_target AS t USING (target)\n",
    "\"\"\")\n",
    "print(db.sql(\"SELECT count(*) AS measurements FROM marts.fact_measurement\").fetchall()[0][0],\n",
    "      \"measurements in the fact table, of\", db.sql(\"SELECT count(*) FROM staging.results\")\n",
    "      .fetchall()[0][0], \"in staging\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The two counts must agree: a staging result whose compound or target was missing from a dimension\n",
    "would have been dropped by the joins. Now watch the database refuse a measurement of a compound it\n",
    "does not know (key 9999). `duckdb.ConstraintException` is the error DuckDB raises when a\n",
    "constraint is broken:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "ERROR refused: Constraint Error: Violates foreign key constraint because key \"compound_key: 9999\" does not exist in the referenced table\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    db.execute(\"\"\"\n",
    "        INSERT INTO marts.fact_measurement\n",
    "        VALUES ('R-TEST', 9999, 1, DATE '2026-09-16', 'P02-01', 1, '=', 10.0, 8.0, 'test.csv')\n",
    "    \"\"\")\n",
    "except duckdb.ConstraintException as error:\n",
    "    log.error(\"refused: %s\", str(error).splitlines()[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Constraints cost a little time on every insert and save a great deal of time later. A warehouse\n",
    "that does not enforce them (several large cloud warehouses only record them) needs tests instead,\n",
    "which is what [Module 5](../05-tests-and-contracts/) adds with dbt.\n",
    "\n",
    "## 6. Which numbers can be averaged\n",
    "\n",
    "The facts are `ic50_nm` and `pic50`, with `relation` saying whether each is a measured value (`=`)\n",
    "or only a bound (`>`, weaker than the highest concentration tested). Facts come in three kinds:\n",
    "\n",
    "- **additive** facts can be summed across every dimension (a count of measurements, an amount in\n",
    "  milligrams);\n",
    "- **semi-additive** facts can be summed across some dimensions but not others (stock in a\n",
    "  freezer: sum across freezers, but not across days);\n",
    "- **non-additive** facts cannot be summed at all, and must be averaged or combined with care.\n",
    "\n",
    "Potencies are non-additive, and they have a trap of their own. An IC50 is a concentration, and\n",
    "IC50s spread over orders of magnitude, so their plain average is pulled up by the weakest few. The\n",
    "right average is taken on the log scale: the mean pIC50, which is the same as the **geometric\n",
    "mean** of the IC50s. Here are both, by series, for EGFR:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "                series  measured  mean_ic50_nm  geometric_mean_nm  mean_pic50\n",
      "                   NaN         2          14.0               12.0        7.91\n",
      "      aminopyrimidines       214         562.0              206.0        6.69\n",
      "pyrimidine piperazines        98         314.0              222.0        6.65\n",
      "                 ureas        86         589.0              330.0        6.48\n"
     ]
    }
   ],
   "source": [
    "print(db.sql(\"\"\"\n",
    "    SELECT c.series,\n",
    "           count(*)                                    AS measured,\n",
    "           round(avg(f.ic50_nm))                       AS mean_ic50_nm,\n",
    "           round(10 ** (9 - avg(f.pic50)))             AS geometric_mean_nm,\n",
    "           round(avg(f.pic50), 2)                      AS mean_pic50\n",
    "    FROM marts.fact_measurement AS f\n",
    "    JOIN marts.dim_compound AS c USING (compound_key)\n",
    "    JOIN marts.dim_target AS t USING (target_key)\n",
    "    WHERE t.target = 'EGFR' AND f.relation = '='\n",
    "    GROUP BY ALL ORDER BY mean_pic50 DESC\n",
    "\"\"\").df().to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![EGFR IC50 by series, two ways: the plain mean of the IC50s (562, 314 and 589 nM for the aminopyrimidines, pyrimidine piperazines and ureas) against the geometric mean from the mean pIC50 (206, 222 and 330 nM); by the plain mean the piperazines look best, by the geometric mean the aminopyrimidines are](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/03-modelling-the-warehouse/figures/potency-means.svg)\n",
    "\n",
    "The plain mean of the IC50s is larger than the geometric mean in every series, nearly three\n",
    "times larger for the aminopyrimidines: a handful of weak compounds decide it. Worse, it changes\n",
    "the order. By the plain mean, the pyrimidine piperazines look the best series (314 nM against\n",
    "562 nM); by the geometric mean, and so by pIC50, the aminopyrimidines are (206 nM against 222 nM).\n",
    "A dashboard that averaged `ic50_nm` would rank the series by their weakest compounds. (The row\n",
    "with no series is LAB-0042, the compound of section 3.) In the warehouse, the rule goes where\n",
    "everyone will see it: potencies are averaged as pIC50, and only measured values (`=`) are\n",
    "averaged.\n",
    "\n",
    "The bounds need their own rule. A result reported as `> 30 µM` is not 30 µM; it is \"too weak to\n",
    "measure here\", and averaging it in as 30 µM would make a weak compound look stronger than it is.\n",
    "They are counted, not averaged:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "target  results  too_weak_to_measure\n",
      "  EGFR      400                    0\n",
      "  ABL1       64                    8\n",
      "  BRAF       64                    7\n",
      "  CDK2       64                   19\n",
      "  JAK2       64                   13\n"
     ]
    }
   ],
   "source": [
    "print(db.sql(\"\"\"\n",
    "    SELECT t.target,\n",
    "           count(*)                                    AS results,\n",
    "           count(*) FILTER (WHERE f.relation = '>')    AS too_weak_to_measure\n",
    "    FROM marts.fact_measurement AS f JOIN marts.dim_target AS t USING (target_key)\n",
    "    GROUP BY ALL ORDER BY results DESC, t.target\n",
    "\"\"\").df().to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "No EGFR result is a bound (the compounds were made for EGFR), but almost a third of the CDK2\n",
    "results are. On the panel, \"too weak to measure\" is the result the project hopes for, so a mart\n",
    "that dropped the bounds would throw away the best news about selectivity.\n",
    "\n",
    "## 7. The questions, answered from the star\n",
    "\n",
    "Every question now has the same shape: the fact table, joined to the dimensions it needs, grouped\n",
    "by the descriptions it slices by. Question 1, the series week by week, uses the date dimension in\n",
    "its *registration* role: each EGFR measurement counts towards the week its compound was\n",
    "registered, so a week's row shows how good that week's new compounds were:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "series              aminopyrimidines  pyrimidine piperazines  ureas\n",
      "registered_in_week                                                 \n",
      "1                               6.90                    6.60   6.40\n",
      "2                               6.59                    6.69   6.50\n",
      "3                               6.58                    6.64   6.67\n",
      "4                               6.58                    6.77   6.19\n",
      "5                               6.77                    6.58   6.47\n"
     ]
    }
   ],
   "source": [
    "print(db.sql(\"\"\"\n",
    "    SELECT d.project_week AS registered_in_week, c.series,\n",
    "           count(DISTINCT c.compound_key) AS compounds, round(avg(f.pic50), 2) AS mean_pic50\n",
    "    FROM marts.fact_measurement AS f\n",
    "    JOIN marts.dim_compound AS c USING (compound_key)\n",
    "    JOIN marts.dim_target AS t USING (target_key)\n",
    "    JOIN marts.dim_date AS d ON d.date_key = c.registered_on\n",
    "    WHERE t.target = 'EGFR' AND f.relation = '=' AND c.series IS NOT NULL\n",
    "    GROUP BY ALL ORDER BY c.series, registered_in_week\n",
    "\"\"\").df().pivot(index=\"registered_in_week\", columns=\"series\", values=\"mean_pic50\")\n",
    "    .to_string())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`pivot` (pandas) turns the series into columns, so each series reads down the page. Week 6's\n",
    "compounds have not been tested yet: they are tested the week after they are registered.\n",
    "\n",
    "Question 3 needs a property and a potency together, which is where computing cLogP in the\n",
    "dimension pays off. Medicinal chemists combine them as **lipophilic efficiency** (LipE, also\n",
    "called LLE): pIC50 minus cLogP. A compound that gains potency only by gaining greasiness keeps the\n",
    "same LipE; real improvements raise it. The query computes it for each compound's mean EGFR\n",
    "potency, then compares the series:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "                series  compounds  mean_pic50  mean_clogp  mean_lipe  potency_vs_clogp\n",
      "pyrimidine piperazines         49        6.65        2.37       4.29              0.18\n",
      "      aminopyrimidines        107        6.69        3.04       3.65              0.04\n",
      "                 ureas         43        6.48        3.64       2.85              0.19\n"
     ]
    }
   ],
   "source": [
    "print(db.sql(\"\"\"\n",
    "    WITH per_compound AS (\n",
    "        SELECT c.compound_key, c.series, c.clogp, avg(f.pic50) AS pic50\n",
    "        FROM marts.fact_measurement AS f\n",
    "        JOIN marts.dim_compound AS c USING (compound_key)\n",
    "        JOIN marts.dim_target AS t USING (target_key)\n",
    "        WHERE t.target = 'EGFR' AND f.relation = '=' AND c.series IS NOT NULL\n",
    "        GROUP BY ALL\n",
    "    )\n",
    "    SELECT series, count(*) AS compounds,\n",
    "           round(avg(pic50), 2) AS mean_pic50, round(avg(clogp), 2) AS mean_clogp,\n",
    "           round(avg(pic50 - clogp), 2) AS mean_lipe,\n",
    "           round(corr(pic50, clogp), 2) AS potency_vs_clogp\n",
    "    FROM per_compound GROUP BY ALL ORDER BY mean_lipe DESC\n",
    "\"\"\").df().to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`corr` is the correlation between two columns, from −1 to 1: near 0 means potency does not simply\n",
    "follow greasiness in that series. The aminopyrimidines are the most potent series on average, but\n",
    "the pyrimidine piperazines reach almost the same potency with much lower cLogP, so their LipE is\n",
    "the highest. That difference is what the question was really after. (The lab's\n",
    "potencies are synthetic: the numbers here show how to ask the question, not a finding about real\n",
    "kinase inhibitors.)\n",
    "\n",
    "## 8. A wide table for dashboards\n",
    "\n",
    "Dashboard tools and spreadsheets read one table more easily than five. A common answer is a\n",
    "**wide table** (some call it \"one big table\"): the star, joined once, with every description next\n",
    "to every measurement. It is not a replacement for the star. It repeats each compound's\n",
    "descriptions on every one of its measurements, and it is built *from* the star, so the rules (one\n",
    "series per compound, one definition of a project week) are the star's. We make it a view, so it\n",
    "always matches the tables beneath:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "656 rows, 17 columns\n",
      "target   ABL1  BRAF  CDK2  EGFR  JAK2\n",
      "chemist                              \n",
      "AO       5.59  5.17  5.58  6.55  5.27\n",
      "BK       5.32  5.59  5.39  6.49  5.36\n",
      "CN       5.17  5.43  5.31  6.78  5.31\n",
      "DS       5.29  5.40  5.60  6.72  5.60\n"
     ]
    }
   ],
   "source": [
    "db.execute(\"\"\"\n",
    "    CREATE VIEW marts.measurements_wide AS\n",
    "    SELECT f.result_id, f.plate, f.replicate, f.relation, f.ic50_nm, f.pic50,\n",
    "           c.compound_id, c.parent_smiles, c.series, c.chemist, c.vendor, c.mw, c.clogp,\n",
    "           t.target, t.role AS target_role,\n",
    "           d.date_key AS run_date, d.project_week AS run_week\n",
    "    FROM marts.fact_measurement AS f\n",
    "    JOIN marts.dim_compound AS c USING (compound_key)\n",
    "    JOIN marts.dim_target AS t USING (target_key)\n",
    "    JOIN marts.dim_date AS d ON d.date_key = f.run_date\n",
    "\"\"\")\n",
    "wide = db.sql(\"SELECT * FROM marts.measurements_wide\").df()\n",
    "print(len(wide), \"rows,\", len(wide.columns), \"columns\")\n",
    "print(wide.query(\"relation == '='\").groupby([\"chemist\", \"target\"])[\"pic50\"].mean().round(2)\n",
    "      .unstack().to_string())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Question 2, by chemist, is a one-line `groupby` on the wide table, which is exactly what a\n",
    "dashboard does. Here is what the warehouse holds now:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "       table_name table_type\n",
      "     dim_compound BASE TABLE\n",
      "         dim_date BASE TABLE\n",
      "       dim_target BASE TABLE\n",
      " fact_measurement BASE TABLE\n",
      "measurements_wide       VIEW\n"
     ]
    }
   ],
   "source": [
    "print(db.sql(\"\"\"\n",
    "    SELECT table_name, table_type FROM information_schema.tables\n",
    "    WHERE table_schema = 'marts' ORDER BY table_type, table_name\n",
    "\"\"\").df().to_string(index=False))\n",
    "db.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Four tables, with keys the database enforces, and a view for the tools that want everything in one\n",
    "place. In [Module 4](../04-transformations-with-lineage/), dbt takes over building them: each table\n",
    "becomes a SQL file, dbt works out the order to build them in, and the chemistry of the compound\n",
    "dimension moves into a Python model that dbt runs as well.\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",
    "- Kimball, R. & Ross, M. (2013). *The Data Warehouse Toolkit: The Definitive Guide to Dimensional\n",
    "  Modeling* (3rd ed.). Wiley. Chapters 1 to 3: the four steps, grain, facts and dimensions,\n",
    "  surrogate keys and date dimensions.\n",
    "- The DuckDB documentation. *Constraints*: primary keys, foreign keys, `UNIQUE`, `NOT NULL` and\n",
    "  `CHECK`, and what DuckDB enforces. <https://duckdb.org/docs/stable/sql/constraints>\n",
    "- Leeson, P. D. & Springthorpe, B. (2007). The influence of drug-like concepts on decision-making\n",
    "  in medicinal chemistry. *Nature Reviews Drug Discovery*, 6(11), 881–890.\n",
    "  <https://doi.org/10.1038/nrd2445>\n",
    "- Hopkins, A. L., Keserü, G. M., Leeson, P. D., Rees, D. C. & Reynolds, C. H. (2014). The role of\n",
    "  ligand efficiency metrics in drug discovery. *Nature Reviews Drug Discovery*, 13(2), 105–121.\n",
    "  <https://doi.org/10.1038/nrd4163>\n",
    "- Reis, J. & Housley, M. (2022). *Fundamentals of Data Engineering*. O'Reilly Media. Chapter 8,\n",
    "  on data modelling for analytics: Kimball, Inmon, Data Vault and wide tables compared."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
