{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Designing a lab data architecture\n",
    "\n",
    "From a folder of spreadsheets to layers a team can trust. Land the lab's files untouched, clean them in one place, shape them for the questions chemists ask, and see where each piece of Series 1 fits in a modern data stack.\n",
    "\n",
    "The lesson's page: https://monstrous.com.ng/learn/data-engineering/series-2/01-lab-data-architecture/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Install what this lesson needs (in Colab, or any fresh environment)\n",
    "%pip install -q pandas duckdb 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\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In Series 1 we worked with a small drug-discovery lab without naming it: its molecules came from\n",
    "`chemlib`, and its measurements, in [Module 12](../../series-1/12-validating-data/), were\n",
    "potencies against five kinases (enzymes that many cancer drugs target). In this series the lab\n",
    "has a project and a timeline. Its target is **EGFR**, a kinase that drives several cancers. Each\n",
    "week the chemists register about forty new compounds. The week after, each compound is tested on\n",
    "EGFR, twice. The potent ones are then tested on four other kinases (ABL1, BRAF, CDK2 and JAK2), to\n",
    "check that they are **selective**: that they hit EGFR and not the others.\n",
    "\n",
    "Every week the lab's computers produce files: an export of the **compound registry** (the\n",
    "spreadsheet in which the chemists record every compound they make) and the **assay results** from\n",
    "the plate reader (the instrument that measures how strongly each compound blocks the enzyme). At\n",
    "the moment these files go into a shared folder, and anyone with a question opens them in a\n",
    "spreadsheet. This works for a few weeks. Then a file is sent twice, a software update renames a\n",
    "column, one plate writes micromolar as `uM` and another as `µM`, and the answers people get from\n",
    "the folder start to disagree.\n",
    "\n",
    "This module designs the alternative: an **architecture**, meaning a decision about where data\n",
    "lives, in which form, and how it moves from one form to the next. It is the plan the rest of the\n",
    "series fills in with industry tools. As in Series 1, we build it by hand first, with DuckDB and\n",
    "SQL, so that each tool, when it arrives, replaces something you have already seen work.\n",
    "\n",
    "By the end of this module you will be able to:\n",
    "\n",
    "- explain what goes wrong when a team works from a shared folder of files;\n",
    "- describe the three layers of a modern data architecture (raw, staging and marts) and say what\n",
    "  belongs in each;\n",
    "- explain the difference between ETL and ELT, and why modern stacks keep the raw data untouched;\n",
    "- build the three layers for the lab's first six weeks of files in DuckDB, so that a question has\n",
    "  one answer;\n",
    "- say where each module of Series 1 belongs in the architecture, and which tool of this series\n",
    "  takes it over.\n",
    "\n",
    "The lab's data comes from `labdata`, this series' companion to `chemlib`. It makes the lab's\n",
    "files week by week, the same on every computer, with problems planted on purpose (a list says\n",
    "which, and when). The potencies are made up, but they are not random: they follow from the\n",
    "structure of each molecule, so later in the series the dashboards show real-looking patterns.\n",
    "Every number in this module is therefore synthetic, made for teaching.\n",
    "\n",
    "![The lab's data flow, from files to answers: the weekly files arrive in an inbox, are copied unchanged into the raw layer, cleaned and typed once in the staging layer, and shaped into marts that answer the chemists' questions; each later module of the series takes over one arrow](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/01-lab-data-architecture/figures/three-layers.svg)\n",
    "\n",
    "## Setup\n",
    "\n",
    "Everything this lesson needs is imported and set here, so the settings can be changed in one\n",
    "place. As in Series 1, pipeline steps report with `log`, and `print` is kept for showing you\n",
    "results.\n",
    "\n",
    "The block imports pandas (tables in Python), DuckDB (a database that runs inside Python, from\n",
    "[Series 1, Module 4](../../series-1/04-databases-and-schemas/)) and `labdata`, which makes the\n",
    "lab's files. From Python itself it imports `shutil`, to delete a folder so the lesson starts\n",
    "clean, and `Path`, for file names."
   ]
  },
  {
   "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",
    "\n",
    "import labdata\n",
    "\n",
    "# log lines: level and message only, so the lesson's outputs are the same on every run\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",
    "INBOX = WORK / \"inbox\"  # where the lab's files arrive, one set per week\n",
    "WAREHOUSE = WORK / \"lab.duckdb\"  # the database that holds the three layers\n",
    "# how many weeks of the project this module loads (the lab's story runs for twelve)\n",
    "WEEKS = 6\n",
    "# the compound whose potency we ask about in sections 1 and 6\n",
    "QUESTION_COMPOUND = \"LAB-0057\"\n",
    "\n",
    "# start clean: a run of the lesson always begins with an empty inbox and an empty warehouse\n",
    "shutil.rmtree(WORK, ignore_errors=True)\n",
    "WORK.mkdir()\n",
    "lab = labdata.Lab()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. The lab and its folder of files\n",
    "\n",
    "First we let six weeks of the project happen. `lab.write_week(week, folder)` writes the files\n",
    "that arrived in that week, exactly as the lab's computers produce them:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO week 1: registry_2026-09-07.csv\n",
      "INFO week 2: registry_2026-09-14.csv, assay_2026-09-14.csv\n",
      "INFO week 3: registry_2026-09-21.csv, assay_2026-09-21.csv\n",
      "INFO week 4: registry_2026-09-28.csv, assay_2026-09-28.csv, assay_2026-09-21_resent.csv\n",
      "INFO week 5: registry_2026-10-05.csv, assay_2026-10-05.csv\n",
      "INFO week 6: registry_2026-10-12.csv, assay_2026-10-12.csv\n"
     ]
    }
   ],
   "source": [
    "for week in range(1, WEEKS + 1):\n",
    "    written = lab.write_week(week, INBOX)\n",
    "    log.info(\"week %d: %s\", week, \", \".join(p.name for p in written))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Each file name carries the Monday of the week it arrived. Two kinds of file arrive: a registry\n",
    "export every week, and from week 2 an assay file (in week 1 nothing has been tested yet). Here\n",
    "are the first rows of each, as they are in the files:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "compound_id                                                           smiles salt  batch chemist   vendor registered_on\n",
      "   LAB-0001            c1nc(c8ccco8)cc(n1)N2CCN(CC2)C(=O)c3ccc(OC(F)(F)F)cc3  NaN      1      CN Vendor A    2026-09-11\n",
      "   LAB-0002 c1cc(CC)c(nc1)Nc2nc(c8ccco8)c(c8ccc(F)cc8)c(OC)n2.O=C(O)C(F)(F)F  TFA      1      AO Vendor C    2026-09-11\n",
      "   LAB-0003        c1cc(C(C)C)c(nc1)Nc2nc(N(C)C)c(c8cn[nH]c8)c(c8cn[nH]c8)n2  NaN      1      AO Vendor A    2026-09-11\n",
      "\n",
      "result_id compound_id target  plate  replicate relation  value units   run_date\n",
      "  R-00001    LAB-0001   EGFR P02-01          1        =  150.0    nM 2026-09-16\n",
      "  R-00002    LAB-0001   EGFR P02-01          2        =  101.0    nM 2026-09-16\n",
      "  R-00003    LAB-0002   EGFR P02-01          1        =  703.0    nM 2026-09-16\n"
     ]
    }
   ],
   "source": [
    "registry = pd.read_csv(INBOX / \"registry_2026-10-12.csv\")\n",
    "print(registry.head(3).to_string(index=False))\n",
    "print()\n",
    "assay = pd.read_csv(INBOX / \"assay_2026-09-14.csv\")\n",
    "print(assay.head(3).to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A registry export is a **snapshot**: every compound registered so far, so each week's file is\n",
    "longer than the last. In the `salt` column, `NaN` (\"not a number\") is how pandas shows an empty\n",
    "cell: those compounds were registered without a salt; `LAB-0002` was registered as its salt with\n",
    "trifluoroacetic acid (TFA), which is why its SMILES ends with a second molecule after a dot. An\n",
    "assay file holds only that week's measurements. `relation` is `=` for a\n",
    "measured IC50, the concentration at which the compound blocks half of the enzyme's activity, and\n",
    "`>` when the compound was too weak to measure, so the value is only a lower limit. `labdata` also\n",
    "keeps a list of the problems it planted, and when:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      " week            kind                                                                    what  module\n",
      "    2  unit spellings                    results in µM are written as uM or μM on some plates       2\n",
      "    4     resent file                     week 3's assay file arrives again, under a new name       2\n",
      "    5   schema change the plate reader's export renames 'units' to 'unit' and adds 'operator'       2\n",
      "    7 re-registration                       LAB-0042's structure is corrected in the registry       6\n",
      "    8 corrected plate   plate P08-01 is re-read; its corrected results replace the first ones       6\n",
      "   10       late file                week 10's assay file arrives a week late, with week 11's       8\n",
      "   11           drift              a new chemist, EF, makes larger, greasier aminopyrimidines       8\n"
     ]
    }
   ],
   "source": [
    "print(lab.events.to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![The lab's twelve weeks: forty compounds registered every week, and from week 2 the results measured each week (80 to 192 rows); orange markers show the planted problems: unit spellings and the resent file (Module 2), the schema change (Module 2), the re-registration and the corrected plate (Module 6), the late file and the drift (Module 8)](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/01-lab-data-architecture/figures/lab-timeline.svg)\n",
    "\n",
    "The last column says which module of this series deals with each problem. Three of them happen in\n",
    "the six weeks we have: unit spellings from week 2, a file sent twice in week 4, and a renamed\n",
    "column in week 5.\n",
    "\n",
    "Now suppose a medicinal chemist asks a plain question: *how potent is compound\n",
    "`LAB-0057` against EGFR?* With a folder of files, the natural answer is to open all the assay\n",
    "files, stack them into one table and look the compound up. That is what pandas' `concat` does:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "result_id  value units relation\n",
      "  R-00209  228.0    nM        =\n",
      "  R-00210  342.0    nM        =\n",
      "  R-00209  228.0    nM        =\n",
      "  R-00210  342.0    nM        =\n",
      "832 rows; 176 result ids appear twice\n",
      "columns: ['result_id', 'compound_id', 'target', 'plate', 'replicate', 'relation', 'value', 'units', 'run_date', 'unit', 'operator']\n"
     ]
    }
   ],
   "source": [
    "files = sorted(INBOX.glob(\"assay_*.csv\"))\n",
    "stacked = pd.concat([pd.read_csv(f) for f in files], ignore_index=True)\n",
    "answer = stacked[(stacked[\"compound_id\"] == QUESTION_COMPOUND) & (stacked[\"target\"] == \"EGFR\")]\n",
    "print(answer[[\"result_id\", \"value\", \"units\", \"relation\"]].to_string(index=False))\n",
    "print(f\"{len(stacked)} rows; {stacked['result_id'].duplicated().sum()} result ids appear twice\")\n",
    "print(\"columns:\", list(stacked.columns))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The answer looks reasonable, but the stacked table has three problems that nobody asked for:\n",
    "\n",
    "- some results appear twice, because week 3's file arrived again in week 4 under a new name, so\n",
    "  any average or count over the table is wrong;\n",
    "- from week 5 the unit sits in a column called `unit`, not `units`, so the stacked table has both,\n",
    "  each empty for half the rows: a filter on `units` silently misses the newer results;\n",
    "- micromolar is written three ways (`µM`, `uM` and `μM`, the last with the Greek letter mu),\n",
    "  so a table that converts units by spelling misses some of them.\n",
    "\n",
    "Each person who uses the folder has to know all of this and fix it in their own copy, every time.\n",
    "Two people who fix it differently get two different answers, and neither can show how they got\n",
    "theirs. That is the problem an architecture solves: the fixes are made **once**, in a known place,\n",
    "and everyone reads the result.\n",
    "\n",
    "## 2. Three layers\n",
    "\n",
    "A modern data architecture keeps data in three layers. The names vary between teams (some say\n",
    "bronze, silver and gold), but the idea is the same:\n",
    "\n",
    "- **Raw**: the data exactly as it arrived, copied into the warehouse with a note of where and when\n",
    "  it came from, and never changed. If a cleaning step later turns out to be wrong, the original is\n",
    "  still there to clean again.\n",
    "- **Staging**: one cleaned table per source. Here each column gets its proper type (a number, a\n",
    "  date), names and units are made consistent, duplicates are removed, and nothing else: no\n",
    "  business questions yet. Every fix from section 1 is made here, once.\n",
    "- **Marts**: tables shaped for the questions people ask, such as \"how potent is each compound on\n",
    "  each target?\" or \"which compounds are selective?\". A mart joins and summarises staging tables;\n",
    "  dashboards and models read marts, never raw files.\n",
    "\n",
    "A **warehouse** is the database that holds the layers. Ours is a DuckDB file; in a large company\n",
    "it may be a service such as Snowflake or BigQuery, but the layers are the same.\n",
    "\n",
    "Moving data into a warehouse used to follow **ETL**: *extract* the data from its source,\n",
    "*transform* it (clean and reshape it) on the way, then *load* only the result. If the\n",
    "transformation had a mistake, the original was gone. Modern stacks follow **ELT**: extract and\n",
    "*load* the data first, unchanged, into the raw layer, then *transform* it inside the warehouse,\n",
    "where the raw copy stays. Storage is now cheap and warehouses are fast, so keeping everything\n",
    "costs little, and it means any transformation can be fixed and run again.\n",
    "\n",
    "The layers also split the work. In this series, **dlt** will load the raw layer (Module 2),\n",
    "**dbt** will build the staging and mart layers from SQL (Modules 4 to 6), and **Prefect** will run\n",
    "the whole thing every week (Module 7). In this module we build all three layers by hand, in a\n",
    "DuckDB database, so that you see exactly what those tools will do.\n",
    "\n",
    "DuckDB keeps related tables in **schemas**, named groups of tables in one database, like folders.\n",
    "We make one schema per layer:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "[('main',), ('marts',), ('raw',), ('staging',)]\n"
     ]
    }
   ],
   "source": [
    "db = duckdb.connect(str(WAREHOUSE))\n",
    "for layer in [\"raw\", \"staging\", \"marts\"]:\n",
    "    db.execute(f\"CREATE SCHEMA IF NOT EXISTS {layer}\")\n",
    "print(db.sql(\"SELECT schema_name FROM information_schema.schemata \"\n",
    "             \"WHERE catalog_name = 'lab' ORDER BY schema_name\").fetchall())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`information_schema` is a set of tables every SQL database keeps about itself; here it lists the\n",
    "schemas of our database (`lab`, after the file name), including `main`, which DuckDB always has.\n",
    "\n",
    "## 3. The raw layer: the files, unchanged\n",
    "\n",
    "The raw layer is a copy of every file, row for row. To make the copy faithful we tell DuckDB's\n",
    "CSV reader three things:\n",
    "\n",
    "- `all_varchar = true`: keep every value as text, exactly as written, instead of guessing types;\n",
    "  guessing is a kind of transformation, and transformations belong in staging;\n",
    "- `union_by_name = true`: line the files up by column name, so a file with a renamed or extra\n",
    "  column still loads (the missing columns are left empty);\n",
    "- `filename = true`: add a column saying which file each row came from, so every row can be traced\n",
    "  back to the file it arrived in.\n",
    "\n",
    "Loading the raw layer is then one statement per source. `CREATE OR REPLACE TABLE ... AS SELECT`\n",
    "builds a table from a query, replacing any earlier version:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO raw.registry: 840 rows\n",
      "INFO raw.assay: 832 rows\n",
      "column_name column_type\n",
      "  result_id     VARCHAR\n",
      "compound_id     VARCHAR\n",
      "     target     VARCHAR\n",
      "      plate     VARCHAR\n",
      "  replicate     VARCHAR\n",
      "   relation     VARCHAR\n",
      "      value     VARCHAR\n",
      "      units     VARCHAR\n",
      "   run_date     VARCHAR\n",
      "       unit     VARCHAR\n",
      "   operator     VARCHAR\n",
      "   filename     VARCHAR\n"
     ]
    }
   ],
   "source": [
    "def load_raw(db: duckdb.DuckDBPyConnection) -> None:\n",
    "    \"\"\"Copy every file in the inbox into the raw layer, as text and unchanged.\"\"\"\n",
    "    for source in [\"registry\", \"assay\"]:\n",
    "        db.execute(f\"\"\"\n",
    "            CREATE OR REPLACE TABLE raw.{source} AS\n",
    "            SELECT * FROM read_csv('{INBOX.as_posix()}/{source}_*.csv',\n",
    "                                   all_varchar = true, union_by_name = true, filename = true)\n",
    "        \"\"\")\n",
    "        rows = db.sql(f\"SELECT count(*) FROM raw.{source}\").fetchall()[0][0]\n",
    "        log.info(\"raw.%s: %d rows\", source, rows)\n",
    "\n",
    "\n",
    "load_raw(db)\n",
    "print(db.sql(\"DESCRIBE raw.assay\").df()[[\"column_name\", \"column_type\"]].to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every column is `VARCHAR` (text), as intended. The raw assay table has both `units` and `unit`,\n",
    "and `operator`, the column added in week 5: the raw layer records what arrived, problems\n",
    "included. Rebuilding the raw layer from the inbox gives the same tables every time, so loading is\n",
    "**idempotent**: running it twice does no harm ([Series 1, Module\n",
    "10](../../series-1/10-pipelines-that-survive-failure/)). Real pipelines load only the files they\n",
    "have not seen before, which Module 2 does with dlt.\n",
    "\n",
    "## 4. The staging layer: each fix made once\n",
    "\n",
    "Staging tables are built from raw tables with SQL. We make them **views**: a view is a saved\n",
    "query that looks like a table and runs whenever it is read, so it is always up to date with the\n",
    "raw layer beneath it.\n",
    "\n",
    "First the compounds. Every registry export is a full snapshot, so the current registry is simply\n",
    "the latest file. In each SMILES, the salt (if any) follows a dot, after the parent molecule;\n",
    "`split_part(smiles, '.', 1)` keeps the part before the first dot, the parent that was tested.\n",
    "`::DATE` and `::INTEGER` give each column its type:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      " compounds  salts\n",
      "       240     33\n"
     ]
    }
   ],
   "source": [
    "db.execute(\"\"\"\n",
    "    CREATE OR REPLACE VIEW staging.compounds AS\n",
    "    SELECT compound_id,\n",
    "           smiles                       AS smiles_as_registered,\n",
    "           split_part(smiles, '.', 1)   AS parent_smiles,\n",
    "           coalesce(salt, '')           AS salt,\n",
    "           batch::INTEGER               AS batch,\n",
    "           chemist,\n",
    "           vendor,\n",
    "           registered_on::DATE          AS registered_on\n",
    "    FROM raw.registry\n",
    "    WHERE filename = (SELECT max(filename) FROM raw.registry)\n",
    "\"\"\")\n",
    "print(db.sql(\"SELECT count(*) AS compounds, count(*) FILTER (WHERE salt <> '') AS salts \"\n",
    "             \"FROM staging.compounds\").df().to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`max(filename)` picks the latest file because the names carry their dates in year-month-day\n",
    "order, which sorts in time order as text. `count(*) FILTER (WHERE ...)` counts only the rows that\n",
    "match.\n",
    "\n",
    "Then the results, where all three problems of section 1 are fixed. Each fix is one line of SQL,\n",
    "with a comment saying why it is there:\n",
    "\n",
    "- `coalesce(unit, units)` takes the first of the two that is not empty, so the renamed column and\n",
    "  the old one become one column again;\n",
    "- a small table of known unit spellings converts every value to nanomolar; a spelling not in the\n",
    "  table gives an empty value, which we count instead of hiding;\n",
    "- `QUALIFY row_number() OVER (PARTITION BY result_id ORDER BY filename) = 1` keeps one row per\n",
    "  `result_id`: `row_number()` numbers the copies of each result in order of file name, and\n",
    "  `QUALIFY` keeps only the first. The resent file's copies are numbered 2 and dropped.\n",
    "\n",
    "The view also works out the **pIC50**, the negative log of the molar IC50 (9 − log₁₀ of the value\n",
    "in nanomolar), which chemists use because each unit is a factor of ten in potency."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      " results  distinct_ids  unknown_units      spellings\n",
      "     656           656              0 nM, uM, µM, μM\n"
     ]
    }
   ],
   "source": [
    "db.execute(\"\"\"\n",
    "    CREATE OR REPLACE TABLE staging.unit_to_nm AS\n",
    "    SELECT * FROM (VALUES ('nM', 1.0), ('µM', 1000.0), ('uM', 1000.0), ('μM', 1000.0))\n",
    "           AS t(unit, factor)\n",
    "\"\"\")\n",
    "db.execute(\"\"\"\n",
    "    CREATE OR REPLACE VIEW staging.results AS\n",
    "    WITH typed AS (\n",
    "        SELECT result_id, compound_id, target, plate,\n",
    "               replicate::INTEGER          AS replicate,\n",
    "               relation,\n",
    "               value::DOUBLE               AS value,\n",
    "               coalesce(unit, units)       AS unit,      -- 'units' was renamed 'unit' in week 5\n",
    "               run_date::DATE              AS run_date,\n",
    "               filename\n",
    "        FROM raw.assay\n",
    "        -- week 3's file was sent twice: keep the first copy of every result\n",
    "        QUALIFY row_number() OVER (PARTITION BY result_id ORDER BY filename) = 1\n",
    "    )\n",
    "    SELECT typed.* EXCLUDE (filename),\n",
    "           value * u.factor                    AS ic50_nm,   -- empty if the unit is unknown\n",
    "           9 - log10(value * u.factor)         AS pic50,\n",
    "           filename                            AS source_file\n",
    "    FROM typed LEFT JOIN staging.unit_to_nm AS u USING (unit)\n",
    "\"\"\")\n",
    "print(db.sql(\"\"\"\n",
    "    SELECT count(*)                                  AS results,\n",
    "           count(DISTINCT result_id)                 AS distinct_ids,\n",
    "           count(*) FILTER (WHERE ic50_nm IS NULL)   AS unknown_units,\n",
    "           string_agg(DISTINCT unit, ', ' ORDER BY unit) AS spellings\n",
    "    FROM staging.results\n",
    "\"\"\").df().to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every result appears once, every unit spelling is known and every value is in nanomolar. The\n",
    "spellings are still there to see in the `unit` column, because staging cleans data without hiding\n",
    "where it came from; `source_file` keeps the file name too.\n",
    "\n",
    "A `LEFT JOIN` keeps every result even if its unit is not in the table (its `ic50_nm` is then\n",
    "empty), and `EXCLUDE` leaves a column out of `*`. Section 4 of [Series 1, Module\n",
    "12](../../series-1/12-validating-data/) explained why spellings are converted by a written table\n",
    "rather than guessed: the table is a decision, on record, that a new spelling has to pass.\n",
    "\n",
    "## 5. Marts: tables for the chemists' questions\n",
    "\n",
    "A mart answers a kind of question directly. The lab's first is the one from section 1, for every\n",
    "compound at once: the potency of each compound on each target. Each compound is measured twice,\n",
    "so the mart averages the measured replicates, and counts those reported only as weaker than the\n",
    "highest concentration tested (`>`), which cannot be averaged:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "compound_id                                            parent_smiles target  n_results  n_measured  mean_pic50\n",
      "   LAB-0023  c1cc(C(F)(F)F)c(nc1)Nc2nc(N8CCCC8)c(C(C)C)c(C8CCNCC8)n2   EGFR          2           2        8.37\n",
      "   LAB-0036 c1cc(C)c(nc1)Nc2nc(c8ccncc8)c(c8cn[nH]c8)c(c8cn[nH]c8)n2   EGFR          2           2        8.01\n",
      "   LAB-0042                          O=C(Cc1ccc(O)cc1)Nc2ccc(C#N)nc2   EGFR          2           2        7.91\n",
      "   LAB-0076               c1cc(Cl)c(nc1)Nc2nc(Br)c(c8cn[nH]c8)c(O)n2   EGFR          2           2        7.79\n",
      "   LAB-0119    c1cc(C8CCOCC8)c(nc1)Nc2nc(Br)c(c8cn[nH]c8)c(C(=O)N)n2   EGFR          2           2        7.77\n"
     ]
    }
   ],
   "source": [
    "db.execute(\"\"\"\n",
    "    CREATE OR REPLACE VIEW marts.potency AS\n",
    "    SELECT r.compound_id,\n",
    "           c.parent_smiles,\n",
    "           r.target,\n",
    "           count(*)                                   AS n_results,\n",
    "           count(*) FILTER (WHERE r.relation = '=')   AS n_measured,\n",
    "           round(avg(r.pic50) FILTER (WHERE r.relation = '='), 2) AS mean_pic50\n",
    "    FROM staging.results AS r\n",
    "    JOIN staging.compounds AS c USING (compound_id)\n",
    "    GROUP BY ALL\n",
    "\"\"\")\n",
    "print(db.sql(\"SELECT * FROM marts.potency ORDER BY mean_pic50 DESC NULLS LAST LIMIT 5\")\n",
    "      .df().to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`GROUP BY ALL` groups by every column that is not a summary (here the compound, its SMILES and\n",
    "the target), and `NULLS LAST` puts compounds with no measured value at the end. The second mart\n",
    "answers the project's own question: which compounds are both potent on EGFR and selective? We\n",
    "call a compound's **selectivity** the difference between its EGFR pIC50 and its best pIC50 on the\n",
    "other four kinases: a difference of 2 means it is a hundred times more potent on EGFR."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "32 compounds have been through the selectivity panel\n",
      "compound_id  egfr_pic50  best_other_pic50  panel_targets  selectivity\n",
      "   LAB-0023        8.37              5.45              4         2.92\n",
      "   LAB-0015        7.42              4.70              4         2.72\n",
      "   LAB-0042        7.91              5.35              4         2.56\n",
      "   LAB-0039        7.66              5.12              4         2.54\n",
      "   LAB-0115        7.41              5.03              4         2.38\n"
     ]
    }
   ],
   "source": [
    "db.execute(\"\"\"\n",
    "    CREATE OR REPLACE VIEW marts.selectivity AS\n",
    "    WITH egfr AS (SELECT compound_id, mean_pic50 AS egfr_pic50\n",
    "                  FROM marts.potency WHERE target = 'EGFR'),\n",
    "         panel AS (SELECT compound_id, max(mean_pic50) AS best_other_pic50,\n",
    "                          count(*) AS panel_targets\n",
    "                   FROM marts.potency WHERE target <> 'EGFR' GROUP BY compound_id)\n",
    "    SELECT compound_id, egfr_pic50, best_other_pic50, panel_targets,\n",
    "           round(egfr_pic50 - best_other_pic50, 2) AS selectivity\n",
    "    FROM egfr JOIN panel USING (compound_id)\n",
    "\"\"\")\n",
    "print(db.sql(\"SELECT count(*) AS on_panel FROM marts.selectivity\").fetchall()[0][0],\n",
    "      \"compounds have been through the selectivity panel\")\n",
    "print(db.sql(\"SELECT * FROM marts.selectivity ORDER BY selectivity DESC LIMIT 5\")\n",
    "      .df().to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`WITH` gives names to two intermediate queries (`egfr` and `panel`) so the final `SELECT` reads\n",
    "like the sentence it answers. In the panel's `max`, a compound reported as `>` on a kinase has no\n",
    "mean, so its weak result does not count as its best: the selectivity shown is the margin over the\n",
    "kinases where it did show activity.\n",
    "\n",
    "## 6. The question again\n",
    "\n",
    "Back to the chemist's question. With the layers in place, everyone reads the same mart:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "compound_id target  n_results  n_measured  mean_pic50\n",
      "   LAB-0057   EGFR          2           2        6.55\n",
      "(the truth labdata made it from: pIC50 6.66)\n"
     ]
    }
   ],
   "source": [
    "print(db.sql(f\"\"\"\n",
    "    SELECT compound_id, target, n_results, n_measured, mean_pic50\n",
    "    FROM marts.potency\n",
    "    WHERE compound_id = '{QUESTION_COMPOUND}' AND target = 'EGFR'\n",
    "\"\"\").df().to_string(index=False))\n",
    "print(f\"(the truth labdata made it from: pIC50 {lab.true_pic50(QUESTION_COMPOUND, 'EGFR'):.2f})\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Two measurements, not four: the duplicate from the resent file is gone. Because `labdata` made the\n",
    "data, we can compare with the potency it started from; the mart's mean is within the measurement\n",
    "noise of it. In a real lab nobody knows the truth, which is exactly why the steps between the\n",
    "files and the answer must be written down, tested and run the same way every time.\n",
    "\n",
    "The layers can also be checked against each other, which is how a team trusts them. Every\n",
    "distinct result in the raw layer should be in staging exactly once, and every staged result\n",
    "should reach the mart:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "raw distinct results 656 = staged 656 = counted in the mart 656: True\n"
     ]
    }
   ],
   "source": [
    "raw_ids = db.sql(\"SELECT count(DISTINCT result_id) FROM raw.assay\").fetchall()[0][0]\n",
    "staged = db.sql(\"SELECT count(*) FROM staging.results\").fetchall()[0][0]\n",
    "in_mart = db.sql(\"SELECT sum(n_results) FROM marts.potency\").fetchall()[0][0]\n",
    "print(f\"raw distinct results {raw_ids} = staged {staged} = counted in the mart {in_mart}:\",\n",
    "      raw_ids == staged == in_mart)\n",
    "db.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Counts that **reconcile** (agree from one layer to the next) were the backbone of monitoring in\n",
    "[Series 1, Module 14](../../series-1/14-monitoring-pipelines/). In this series they become tests\n",
    "that run on every build (Module 5).\n",
    "\n",
    "## 7. Where Series 1 fits\n",
    "\n",
    "Series 1 built each part of a chemical data pipeline by hand. In the architecture, each part has a\n",
    "layer, and in this series each is taken over by a tool:\n",
    "\n",
    "| Series 1 module (built by hand) | Layer | Series 2 module (the tool) |\n",
    "|---|---|---|\n",
    "| 3. Files and identity; 11. Incremental ingestion | Raw | 2. Declarative ingestion (dlt) |\n",
    "| 4. Databases and schemas | Marts (the shape) | 3. Modelling the warehouse (DuckDB) |\n",
    "| 6. Validating molecules; 7. Standardisation; 12. Validating data | Staging | 4. Transformations (dbt); 5. Tests and contracts (dbt, pandera-chem) |\n",
    "| 13. Versioning everything | All layers | 6. History and corrections (dbt); 9. Continuous integration |\n",
    "| 10. Pipelines that survive failure | Moving between layers | 7. Orchestration (Prefect) |\n",
    "| 14. Monitoring pipelines | All layers | 8. Observability |\n",
    "| 15. Capstone | All layers | 10. Dashboards (Streamlit); 11. Capstone |\n",
    "\n",
    "The by-hand versions are not wasted. A tool does a known job faster and with fewer mistakes, but\n",
    "when it fails or does something unexpected, the person who understands what it was doing is the\n",
    "one who can fix it. Series 1 is what lets you understand each tool of this series.\n",
    "\n",
    "Three principles from this module carry through the series:\n",
    "\n",
    "1. **Keep the raw data untouched.** Every later step can be fixed and run again, because the\n",
    "   original is always there.\n",
    "2. **Make each fix once, in staging, and write down why.** Every reader then gets the same\n",
    "   answer, and the reason for each fix is in the code, next to the fix.\n",
    "3. **Check that the layers reconcile.** Counts that agree from raw to staging to marts are the\n",
    "   first sign that nothing was lost or added on the way.\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",
    "- Reis, J. & Housley, M. (2022). *Fundamentals of Data Engineering: Plan and Build Robust Data\n",
    "  Systems*. O'Reilly Media. In particular chapter 3, on designing good data architecture.\n",
    "- Kimball, R. & Ross, M. (2013). *The Data Warehouse Toolkit: The Definitive Guide to Dimensional\n",
    "  Modeling*, 3rd edition. Wiley. The classic book on shaping data for questions, the subject of\n",
    "  Module 3.\n",
    "- The dbt documentation. *How we structure our dbt projects*: the staging, intermediate and marts\n",
    "  layers, as dbt users build them.\n",
    "  <https://docs.getdbt.com/best-practices/how-we-structure/1-guide-overview>\n",
    "- The Databricks documentation. *What is the medallion lakehouse architecture?*: the same three\n",
    "  layers, named bronze, silver and gold. <https://docs.databricks.com/aws/en/lakehouse/medallion>\n",
    "- The DuckDB documentation. *CSV import*: every option of `read_csv`, including `union_by_name`\n",
    "  and `filename`. <https://duckdb.org/docs/stable/data/csv/overview>\n",
    "- Free, S. M. & Wilson, J. W. (1964). A Mathematical Contribution to Structure-Activity Studies.\n",
    "  *Journal of Medicinal Chemistry*, 7(4), 395–399. The additive model `labdata` uses to make\n",
    "  potencies from structure. <https://doi.org/10.1021/jm00334a001>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
