{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Transformations with lineage\n",
    "\n",
    "Hand the staging and mart layers to dbt. Each table becomes one SELECT in a file; dbt works out the order to build them in from the references between them, builds them in DuckDB, records the lineage from raw table to mart, and writes the documentation. The compound dimension's chemistry runs as a Python model.\n",
    "\n",
    "The lesson's page: https://monstrous.com.ng/learn/data-engineering/series-2/04-transformations-with-lineage/"
   ]
  },
  {
   "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] dbt-core dbt-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": [
    "In Modules [1](../01-lab-data-architecture/) and [3](../03-modelling-the-warehouse/) we built the\n",
    "staging and mart layers with SQL statements run one after another from Python. That works for one\n",
    "person on one afternoon. It stops working when the warehouse grows: the order of the statements\n",
    "lives in one script and in its author's head, a change to a staging view means working out by hand\n",
    "which marts to rebuild, and nobody can see at a glance where a column in a dashboard came from. In\n",
    "Series 1 the [capstone](../../series-1/15-capstone/)'s `pipeline.py` had the same problem, solved\n",
    "with careful code.\n",
    "\n",
    "**dbt** (data build tool) is the open-source tool most data teams use for this layer. In dbt each\n",
    "table or view is a **model**: one `SELECT` statement in its own file, named after the table it\n",
    "makes. A model names the models it reads with `ref('...')` instead of writing table names, and from\n",
    "those references dbt works out the order to build everything in, builds it, and records the\n",
    "**lineage**: which tables each one was built from, all the way back to the raw layer. dbt does not\n",
    "store or move data itself. It turns each model into SQL and sends that SQL to the warehouse (here\n",
    "DuckDB, through the dbt-duckdb **adapter**), so the work happens where the data already is.\n",
    "\n",
    "By the end of this module you will be able to:\n",
    "\n",
    "- set up a dbt project and its connection to DuckDB;\n",
    "- declare the raw tables dlt loads as **sources**, and small decision tables as **seeds**;\n",
    "- write the lab's staging and mart layers as models that reference each other, including a Python\n",
    "  model that works out the chemistry of the compound dimension with RDKit;\n",
    "- build the whole project in the right order with one command, and see the SQL dbt sent;\n",
    "- read the lineage, select a model with everything upstream or downstream of it, and rebuild only\n",
    "  what a change affects;\n",
    "- document models and columns, and generate the documentation site.\n",
    "\n",
    "## Setup\n",
    "\n",
    "The raw layer comes from Module 2's dlt pipeline, as in Module 3 (`labstack.load_raw`, for the\n",
    "first six weeks). dbt is run from Python with `dbtRunner`, which does exactly what typing `dbt` and\n",
    "its arguments in a terminal does; that way the lesson runs the same in a notebook. Three settings\n",
    "help: `write` saves a file of the dbt project (each one shown in full in the lesson); `dbt` runs a\n",
    "dbt command on the project and logs what it built; and one environment variable stops dbt sending\n",
    "anonymous usage statistics to its makers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "import logging\n",
    "import os\n",
    "import shutil\n",
    "from pathlib import Path\n",
    "\n",
    "import duckdb\n",
    "import pandas as pd\n",
    "from dbt.cli.main import dbtRunner\n",
    "\n",
    "import labdata\n",
    "import labstack\n",
    "\n",
    "os.environ[\"DBT_SEND_ANONYMOUS_USAGE_STATS\"] = \"false\"  # no usage statistics sent to dbt's makers\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",
    "PROJECT = WORK / \"lab_dbt\"  # the lab's dbt project: one folder of text files\n",
    "WEEKS = 6  # the lab is at the end of week 6, as in Modules 1 to 3\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",
    "\n",
    "\n",
    "def write(name: str, text: str) -> None:\n",
    "    \"\"\"Save one file of the dbt project (made, with its folders, if it is new).\"\"\"\n",
    "    path = PROJECT / name\n",
    "    path.parent.mkdir(parents=True, exist_ok=True)\n",
    "    path.write_text(text.lstrip(\"\\n\"), encoding=\"utf-8\", newline=\"\\n\")\n",
    "\n",
    "\n",
    "def dbt(*args: str):\n",
    "    \"\"\"Run a dbt command on the lab's project, like `dbt <args>` in a terminal; log what it did.\"\"\"\n",
    "    result = dbtRunner().invoke(\n",
    "        [*args, \"--quiet\", \"--project-dir\", str(PROJECT), \"--profiles-dir\", str(PROJECT)]\n",
    "    )\n",
    "    if result.exception:\n",
    "        raise result.exception\n",
    "    if args[0] in (\"build\", \"run\", \"seed\", \"test\"):\n",
    "        for item in result.result:\n",
    "            log.info(\"%s %s: %s\", item.node.resource_type, item.node.name, item.status)\n",
    "        broken = [item.node.name for item in result.result if item.status == \"error\"]\n",
    "        if broken:\n",
    "            raise RuntimeError(f\"dbt could not build {broken}: see {PROJECT}/logs/dbt.log\")\n",
    "    return result.result\n",
    "\n",
    "\n",
    "def query(sql: str) -> pd.DataFrame:\n",
    "    \"\"\"Run one SQL query on the warehouse and return the answer as a table.\"\"\"\n",
    "    with duckdb.connect(str(WAREHOUSE)) as db:\n",
    "        return db.sql(sql).df()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`--quiet` keeps dbt's own messages (which carry times that change on every run) off the screen;\n",
    "the `dbt` function logs one line per thing built instead, and stops the lesson if anything could not\n",
    "be built (dbt's full log, with the reason, is in the project's `logs/` folder). `query` opens the database only for as\n",
    "long as one query takes, so it never holds the file while dbt is writing to it.\n",
    "\n",
    "## 1. A dbt project\n",
    "\n",
    "A dbt project is a folder of text files. The first, `dbt_project.yml`, names the project and sets\n",
    "defaults for its folders. It is written in **YAML**, a format for settings where indentation shows\n",
    "what belongs to what (Series 1 used it for [pandera-chem's\n",
    "rules](../../series-1/12-validating-data/)). Ours says that models in `models/staging/` become\n",
    "views in the `staging` schema and models in `models/marts/` become tables in `marts`, the layers of\n",
    "Module 1. How a model is stored is its **materialization**: a `view` is rebuilt every time it is\n",
    "read, a `table` is stored once per build. Staging is cheap to read and should always be current, so\n",
    "it is views; marts are read often by dashboards, so they are tables."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "write(\"dbt_project.yml\", \"\"\"\n",
    "name: lab\n",
    "version: \"1.0.0\"\n",
    "profile: lab\n",
    "\n",
    "vars:  # settings the models read with var('...')\n",
    "  project_start: \"2026-09-07\"  # the Monday of week 1\n",
    "  project_end: \"2026-11-30\"  # the Monday after week 12\n",
    "\n",
    "models:\n",
    "  lab:\n",
    "    staging:\n",
    "      +schema: staging\n",
    "      +materialized: view\n",
    "    marts:\n",
    "      +schema: marts\n",
    "      +materialized: table\n",
    "\n",
    "seeds:\n",
    "  lab:\n",
    "    +schema: staging\n",
    "\"\"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The second file says how to reach the warehouse. dbt calls it a **profile**, and it usually lives\n",
    "outside the project (it often holds passwords); ours has none, so it sits in the project folder.\n",
    "`env_var('LAB_WAREHOUSE', 'work/lab.duckdb')` reads the database's path from an environment\n",
    "variable, with a default for when it is not set: the same project can then build a copy of the\n",
    "warehouse for testing ([Module 9](../09-continuous-integration/) does exactly that) without\n",
    "changing a file."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "write(\"profiles.yml\", \"\"\"\n",
    "lab:\n",
    "  target: dev\n",
    "  outputs:\n",
    "    dev:\n",
    "      type: duckdb\n",
    "      path: \"{{ env_var('LAB_WAREHOUSE', 'work/lab.duckdb') }}\"\n",
    "      threads: 1\n",
    "\"\"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `{{ ... }}` is **Jinja**, a template language: dbt fills in everything between double braces\n",
    "before using a file. Models use it too. The last setting file is a small **macro**, a reusable\n",
    "piece of Jinja. By default dbt puts a model whose schema is `staging` into a schema called\n",
    "`main_staging` (the default schema's name, then the model's), which keeps different people's builds\n",
    "apart in a shared warehouse. Ours is one person's file, so this macro, which replaces dbt's own\n",
    "`generate_schema_name`, keeps the names as written:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "write(\"macros/generate_schema_name.sql\", \"\"\"\n",
    "{% macro generate_schema_name(custom_schema_name, node) -%}\n",
    "    {{ custom_schema_name or target.schema }}\n",
    "{%- endmacro %}\n",
    "\"\"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Sources and seeds\n",
    "\n",
    "The raw tables are not built by dbt; dlt loads them. dbt still needs to know about them, so that\n",
    "models can read them by name and the lineage starts at the right place. Tables that something else\n",
    "loads are **sources**, declared in a YAML file. A description on each makes the documentation say\n",
    "where they come from:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "write(\"models/staging/_sources.yml\", \"\"\"\n",
    "sources:\n",
    "  - name: raw\n",
    "    description: The lab's files, loaded unchanged by dlt (Module 2).\n",
    "    schema: raw\n",
    "    tables:\n",
    "      - name: registry\n",
    "        description: The latest compound registry export. Replaced on every load.\n",
    "      - name: assay\n",
    "        description: Every row of every assay file, merged on result_id.\n",
    "\"\"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Some tables are neither loaded nor computed: they are **decisions**, such as which unit spellings\n",
    "mean micromolar (Module 1 made that table with SQL). dbt's place for those is a **seed**, a small\n",
    "CSV file in the project. It is kept in version control next to the models, so a change to it is\n",
    "reviewed like a change to code, and `dbt seed` loads it into the warehouse. The targets are a\n",
    "decision too: which kinases the project measures, and which is the primary target."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO seed targets: success\n",
      "INFO seed unit_to_nm: success\n",
      "target  chembl_id    role\n",
      "  EGFR  CHEMBL203 primary\n",
      "  ABL1 CHEMBL1862   panel\n",
      "  BRAF CHEMBL5145   panel\n",
      "  CDK2  CHEMBL301   panel\n",
      "  JAK2 CHEMBL2971   panel\n"
     ]
    }
   ],
   "source": [
    "write(\"seeds/unit_to_nm.csv\", \"\"\"\n",
    "unit,factor\n",
    "nM,1.0\n",
    "µM,1000.0\n",
    "uM,1000.0\n",
    "μM,1000.0\n",
    "\"\"\")\n",
    "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",
    "write(\"seeds/targets.csv\", targets.to_csv(index=False, lineterminator=\"\\n\"))\n",
    "dbt(\"seed\")\n",
    "print(query(\"SELECT * FROM staging.targets\").to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Staging models\n",
    "\n",
    "A model is a `SELECT` with no `CREATE` around it: dbt adds that, according to the model's\n",
    "materialization. Here is Module 1's `staging.compounds`, as a model. The only change is the `FROM`:\n",
    "`{{ source('raw', 'registry') }}` instead of a table name."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "write(\"models/staging/stg_compounds.sql\", \"\"\"\n",
    "-- the current registry: one row per compound, the salt split from the parent that was tested\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 {{ source('raw', 'registry') }}\n",
    "\"\"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The results read a source and a seed. A seed is referenced like a model, with `ref`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO model stg_compounds: success\n",
      "INFO model stg_results: success\n"
     ]
    }
   ],
   "source": [
    "write(\"models/staging/stg_results.sql\", \"\"\"\n",
    "-- one row per result: the unit columns joined back together, every value in nanomolar\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",
    "           file_name\n",
    "    from {{ source('raw', 'assay') }}\n",
    ")\n",
    "select typed.* exclude (file_name),\n",
    "       value * u.factor              as ic50_nm,\n",
    "       9 - log10(value * u.factor)   as pic50,\n",
    "       file_name                     as source_file\n",
    "from typed\n",
    "left join {{ ref('unit_to_nm') }} as u using (unit)\n",
    "\"\"\")\n",
    "dbt(\"run\", \"--select\", \"staging\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`--select staging` builds only the models in the `staging` folder. Before sending a model to the\n",
    "warehouse, dbt **compiles** it: it fills in the Jinja and wraps the `SELECT` in the statement its\n",
    "materialization needs. The compiled SQL is kept in the project's `target/` folder, so you can always\n",
    "see exactly what dbt ran:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "       file_name                     as source_file\n",
      "from typed\n",
      "left join \"lab\".\"staging\".\"unit_to_nm\" as u using (unit)\n"
     ]
    }
   ],
   "source": [
    "compiled = PROJECT / \"target\" / \"compiled\" / \"lab\" / \"models\" / \"staging\" / \"stg_results.sql\"\n",
    "print(\"\\n\".join(compiled.read_text(encoding=\"utf-8\").splitlines()[-3:]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`ref('unit_to_nm')` became `\"lab\".\"staging\".\"unit_to_nm\"`: the database (`lab`, after the file's\n",
    "name), the schema and the table. Write `ref` and `source`, never the table name: they are how dbt\n",
    "learns the order and the lineage.\n",
    "\n",
    "![What dbt does with a model: the file stg_results.sql holds only a SELECT, with source() and ref() in place of table names; dbt compiles it, turning each into the table's full name (\"lab\".\"raw\".\"assay\", \"lab\".\"staging\".\"unit_to_nm\"), then wraps it in the statement its materialization needs (create or replace view, for staging) and runs it in DuckDB](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/04-transformations-with-lineage/figures/compile.svg)\n",
    "\n",
    "## 4. The marts\n",
    "\n",
    "The marts are Module 3's star. The target dimension adds a surrogate key to the seed. The date\n",
    "dimension reads the project's dates from `vars`, so a longer project changes one setting:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "write(\"models/marts/dim_target.sql\", \"\"\"\n",
    "-- one row per kinase; the primary target gets key 1\n",
    "select row_number() over (order by role desc, target) as target_key,\n",
    "       target, chembl_id, role\n",
    "from {{ ref('targets') }}\n",
    "\"\"\")\n",
    "write(\"models/marts/dim_date.sql\", \"\"\"\n",
    "-- one row per day of the project, with each way the lab groups days\n",
    "with days as (\n",
    "    select day::date as date_key\n",
    "    from generate_series(date '{{ var(\"project_start\") }}', date '{{ var(\"project_end\") }}',\n",
    "                         interval 1 day) as t(day)\n",
    ")\n",
    "select date_key,\n",
    "       (datediff('day', date '{{ var(\"project_start\") }}', date_key) // 7) + 1 as project_week,\n",
    "       isodow(date_key) > 5   as weekend,\n",
    "       dayname(date_key)      as weekday,\n",
    "       monthname(date_key)    as month\n",
    "from days\n",
    "\"\"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The compound dimension needs RDKit, which SQL cannot call. dbt-duckdb also runs **Python models**:\n",
    "a file with a function `model(dbt, session)` that returns a table. `dbt.ref(...)` reads another\n",
    "model, and whatever the function returns becomes the model's table. The chemistry is Module 3's,\n",
    "moved into the project, so that it is built, ordered and documented like everything else:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "write(\"models/marts/dim_compound.py\", '''\n",
    "\"\"\"One row per compound, with its series and properties worked out once (Module 3).\"\"\"\n",
    "from rdkit import Chem, RDLogger\n",
    "from rdkit.Chem import Crippen, Descriptors, Lipinski\n",
    "\n",
    "RDLogger.DisableLog(\"rdApp.*\")\n",
    "# the three chemical series, each as the core its compounds share\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",
    "CORES = {name: Chem.MolFromSmiles(core) for name, core in SERIES.items()}\n",
    "\n",
    "\n",
    "def series_of(mol):\n",
    "    \"\"\"The 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 model(dbt, session):\n",
    "    compounds = dbt.ref(\"stg_compounds\").df().sort_values(\"compound_id\", ignore_index=True)\n",
    "    mols = [Chem.MolFromSmiles(s) for s in compounds[\"parent_smiles\"]]\n",
    "    compounds.insert(0, \"compound_key\", range(1, len(compounds) + 1))\n",
    "    compounds[\"series\"] = [series_of(m) for m in mols]\n",
    "    compounds[\"mw\"] = [round(Descriptors.MolWt(m), 1) for m in mols]\n",
    "    compounds[\"clogp\"] = [round(Crippen.MolLogP(m), 2) for m in mols]\n",
    "    compounds[\"hbd\"] = [Lipinski.NumHDonors(m) for m in mols]\n",
    "    compounds[\"hba\"] = [Lipinski.NumHAcceptors(m) for m in mols]\n",
    "    compounds[\"heavy_atoms\"] = [m.GetNumHeavyAtoms() for m in mols]\n",
    "    return compounds\n",
    "''')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The fact table and the wide view are Module 3's SQL, with `ref` in place of table names. The wide\n",
    "view is set to be a view by a `config` line at the top of its file, which overrides the folder's\n",
    "default:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "write(\"models/marts/fact_measurement.sql\", \"\"\"\n",
    "-- one row per measurement: one compound, one target, one well (replicate) of one plate\n",
    "select r.result_id,\n",
    "       c.compound_key,\n",
    "       t.target_key,\n",
    "       r.run_date,\n",
    "       r.plate,\n",
    "       r.replicate,\n",
    "       r.relation,\n",
    "       r.ic50_nm,\n",
    "       r.pic50,\n",
    "       r.source_file\n",
    "from {{ ref('stg_results') }} as r\n",
    "join {{ ref('dim_compound') }} as c using (compound_id)\n",
    "join {{ ref('dim_target') }} as t using (target)\n",
    "\"\"\")\n",
    "write(\"models/marts/measurements_wide.sql\", \"\"\"\n",
    "{{ config(materialized='view') }}\n",
    "-- the star joined once, for dashboards and spreadsheets\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 {{ ref('fact_measurement') }} as f\n",
    "join {{ ref('dim_compound') }} as c using (compound_key)\n",
    "join {{ ref('dim_target') }} as t using (target_key)\n",
    "join {{ ref('dim_date') }} as d on d.date_key = f.run_date\n",
    "\"\"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now one command builds everything. `dbt build` loads the seeds, builds every model in order (and\n",
    "runs the tests, which Module 5 adds):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO model dim_date: success\n",
      "INFO model stg_compounds: success\n",
      "INFO seed targets: success\n",
      "INFO seed unit_to_nm: success\n",
      "INFO model dim_compound: success\n",
      "INFO model dim_target: success\n",
      "INFO model stg_results: success\n",
      "INFO model fact_measurement: success\n",
      "INFO model measurements_wide: success\n"
     ]
    }
   ],
   "source": [
    "built = dbt(\"build\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Nine things, in an order nobody wrote down: each model came after every model it references.\n",
    "`dim_date` references nothing, so it could go first; `dim_compound` waited for `stg_compounds`,\n",
    "`dim_target` for the `targets` seed, the fact table for the staging results and two dimensions,\n",
    "and the wide view came last, because it reads the other four. A quick check that the result is\n",
    "Module 3's star:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      " compounds  without_series  days  measurements  wide_rows\n",
      "       240               1    85           656        656\n"
     ]
    }
   ],
   "source": [
    "print(query(\"\"\"\n",
    "    SELECT (SELECT count(*) FROM marts.dim_compound)      AS compounds,\n",
    "           (SELECT count(*) FROM marts.dim_compound WHERE series IS NULL) AS without_series,\n",
    "           (SELECT count(*) FROM marts.dim_date)          AS days,\n",
    "           (SELECT count(*) FROM marts.fact_measurement)  AS measurements,\n",
    "           (SELECT count(*) FROM marts.measurements_wide) AS wide_rows\n",
    "\"\"\").to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The same numbers as Module 3: 240 compounds, LAB-0042 still in no series, 656 measurements.\n",
    "\n",
    "## 5. Lineage\n",
    "\n",
    "Every `ref` and `source` is an edge in a **graph**: from each table to the tables built from it.\n",
    "Because every edge points forward and none leads back to where it started, it is a **directed\n",
    "acyclic graph** (a DAG, which [Series 1, Module 5](../../series-1/05-graphs-and-graph-databases/)\n",
    "met as a kind of graph), and that is what lets dbt find a build order: a table comes after\n",
    "everything with an edge into it. dbt writes the graph, with everything else it knows about the\n",
    "project, to `target/manifest.json`. Here is each model with the tables it is built from:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "dim_compound       <- stg_compounds\n",
      "dim_date           <- \n",
      "dim_target         <- targets\n",
      "fact_measurement   <- dim_compound, dim_target, stg_results\n",
      "measurements_wide  <- dim_compound, dim_date, dim_target, fact_measurement\n",
      "stg_compounds      <- registry\n",
      "stg_results        <- assay, unit_to_nm\n"
     ]
    }
   ],
   "source": [
    "manifest = json.loads((PROJECT / \"target\" / \"manifest.json\").read_text(encoding=\"utf-8\"))\n",
    "for node in sorted(manifest[\"nodes\"].values(), key=lambda n: n[\"name\"]):\n",
    "    if node[\"resource_type\"] == \"model\":\n",
    "        parents = sorted(p.split(\".\")[-1] for p in node[\"depends_on\"][\"nodes\"])\n",
    "        print(f\"{node['name']:18} <- {', '.join(parents)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![The lab's lineage: the raw tables registry and assay (sources) and the seeds unit_to_nm and targets on the left; stg_compounds and stg_results; then dim_compound, dim_target and dim_date; then fact_measurement; then measurements_wide on the right](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/04-transformations-with-lineage/figures/lineage.svg)\n",
    "\n",
    "dbt's **selection** syntax reads the same graph. `+` before a name adds everything **upstream**\n",
    "(what the model is built from), `+` after it everything **downstream** (what is built from it).\n",
    "`dbt ls` lists what a selection picks, without building anything, and prints each as\n",
    "`project.schema.name` (sources begin `source:`):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO upstream of fact_measurement:\n",
      "lab.marts.dim_compound\n",
      "lab.marts.dim_target\n",
      "lab.marts.fact_measurement\n",
      "lab.staging.stg_compounds\n",
      "lab.staging.stg_results\n",
      "lab.targets\n",
      "lab.unit_to_nm\n",
      "source:lab.raw.assay\n",
      "source:lab.raw.registry\n",
      "INFO downstream of stg_compounds:\n",
      "lab.marts.dim_compound\n",
      "lab.marts.fact_measurement\n",
      "lab.marts.measurements_wide\n",
      "lab.staging.stg_compounds\n"
     ]
    }
   ],
   "source": [
    "log.info(\"upstream of fact_measurement:\")\n",
    "upstream = dbt(\"ls\", \"--select\", \"+fact_measurement\")\n",
    "log.info(\"downstream of stg_compounds:\")\n",
    "downstream = dbt(\"ls\", \"--select\", \"stg_compounds+\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The first answers \"what does this table depend on?\", which is how you trace a strange number in a\n",
    "dashboard back to its file. The second answers \"what does a change here affect?\". Note that\n",
    "`dim_date` is in neither list: it depends on nothing but the project's settings.\n",
    "\n",
    "Here is that second question in practice. The chemists want to filter measured values easily, so\n",
    "`stg_results` gets a new column, `is_measured`. Only `stg_results` and the models downstream of it\n",
    "need rebuilding:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "INFO model stg_results: success\n",
      "INFO model fact_measurement: success\n",
      "INFO model measurements_wide: success\n",
      " is_measured  results\n",
      "       False       47\n",
      "        True      609\n"
     ]
    }
   ],
   "source": [
    "text = (PROJECT / \"models\" / \"staging\" / \"stg_results.sql\").read_text(encoding=\"utf-8\")\n",
    "write(\"models/staging/stg_results.sql\", text.replace(\n",
    "    \"       9 - log10(value * u.factor)   as pic50,\",\n",
    "    \"       9 - log10(value * u.factor)   as pic50,\\n\"\n",
    "    \"       relation = '='                as is_measured,  -- a value, not a bound\",\n",
    "))\n",
    "rebuilt = dbt(\"build\", \"--select\", \"stg_results+\")\n",
    "print(query(\"SELECT is_measured, count(*) AS results FROM staging.stg_results \"\n",
    "            \"GROUP BY ALL ORDER BY is_measured\").to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Three models were rebuilt, and the dimensions, which the change cannot affect, were left alone. In\n",
    "a warehouse with hundreds of models, that is the difference between a rebuild of seconds and one of\n",
    "an hour.\n",
    "\n",
    "![The same lineage, with what dbt build --select stg_results+ rebuilt outlined in orange: stg_results, fact_measurement and measurements_wide; everything else, faded, was left as it was](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/04-transformations-with-lineage/figures/lineage-selection.svg)\n",
    "\n",
    "## 6. Documentation\n",
    "\n",
    "The last piece is the one most often skipped: saying what each table and column means. In dbt, the\n",
    "descriptions live in YAML files next to the models, and reach the documentation, the warehouse's\n",
    "catalogue and, in [Module 5](../05-tests-and-contracts/), the tests:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "{'result_id': 'VARCHAR', 'compound_key': 'BIGINT', 'target_key': 'BIGINT', 'run_date': 'DATE', 'plate': 'VARCHAR', 'replicate': 'INTEGER', 'relation': 'VARCHAR', 'ic50_nm': 'DOUBLE', 'pic50': 'DOUBLE', 'source_file': 'VARCHAR'}\n",
      "9 - log10(ic50_nm). Average potencies as pIC50, over measured values only.\n"
     ]
    }
   ],
   "source": [
    "write(\"models/marts/_marts.yml\", \"\"\"\n",
    "models:\n",
    "  - name: dim_compound\n",
    "    description: One row per compound in the current registry, with its chemical series and\n",
    "      properties worked out once with RDKit.\n",
    "    columns:\n",
    "      - name: compound_key\n",
    "        description: The warehouse's key for the compound (a surrogate key).\n",
    "      - name: compound_id\n",
    "        description: The lab's ID for the compound (the natural key), e.g. LAB-0042.\n",
    "      - name: series\n",
    "        description: The series whose core the parent contains; empty if none or several, for a\n",
    "          person to check.\n",
    "      - name: clogp\n",
    "        description: Crippen's estimate of the octanol-water partition coefficient (RDKit).\n",
    "  - name: fact_measurement\n",
    "    description: One row per measurement of one compound on one target, in one well of one plate.\n",
    "    columns:\n",
    "      - name: relation\n",
    "        description: \"'=' for a measured value; '>' when the compound was weaker than the highest\n",
    "          concentration tested, so ic50_nm is only a bound.\"\n",
    "      - name: pic50\n",
    "        description: 9 - log10(ic50_nm). Average potencies as pIC50, over measured values only.\n",
    "  - name: measurements_wide\n",
    "    description: The star joined once, for dashboards. Built from the star; never edit it.\n",
    "\"\"\")\n",
    "dbt(\"docs\", \"generate\")\n",
    "catalog = json.loads((PROJECT / \"target\" / \"catalog.json\").read_text(encoding=\"utf-8\"))\n",
    "columns = catalog[\"nodes\"][\"model.lab.fact_measurement\"][\"columns\"]\n",
    "print({name: column[\"type\"] for name, column in columns.items()})\n",
    "manifest = json.loads((PROJECT / \"target\" / \"manifest.json\").read_text(encoding=\"utf-8\"))\n",
    "print(manifest[\"nodes\"][\"model.lab.fact_measurement\"][\"columns\"][\"pic50\"][\"description\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`dbt docs generate` reads the descriptions (into `manifest.json`) and asks the warehouse for every\n",
    "column's type (into `catalog.json`), then writes `target/index.html`, a website of the whole\n",
    "project: every model, its columns, its SQL and an interactive lineage graph. On your own computer,\n",
    "`dbt docs serve` (in a terminal, in the project's folder) opens it in the browser. A new colleague\n",
    "can read it before ever opening the code.\n",
    "\n",
    "Here is the project as it stands, the folder the next modules build on:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "dbt_project.yml\n",
      "macros/generate_schema_name.sql\n",
      "models/marts/_marts.yml\n",
      "models/marts/dim_compound.py\n",
      "models/marts/dim_date.sql\n",
      "models/marts/dim_target.sql\n",
      "models/marts/fact_measurement.sql\n",
      "models/marts/measurements_wide.sql\n",
      "models/staging/_sources.yml\n",
      "models/staging/stg_compounds.sql\n",
      "models/staging/stg_results.sql\n",
      "profiles.yml\n",
      "seeds/targets.csv\n",
      "seeds/unit_to_nm.csv\n"
     ]
    }
   ],
   "source": [
    "for path in sorted(PROJECT.rglob(\"*\")):\n",
    "    made_by_dbt = {\"target\", \"logs\"} & set(path.relative_to(PROJECT).parts)  # dbt's own output\n",
    "    if path.is_file() and not made_by_dbt:\n",
    "        print(path.relative_to(PROJECT).as_posix())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Fourteen small text files describe the whole transformation layer: what is built from what, how\n",
    "each piece is stored, and what each column means. In [Module 5](../05-tests-and-contracts/) the\n",
    "same YAML files gain tests, so that every build also checks the data.\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",
    "- The dbt documentation. *About dbt models*: models, `ref`, materializations and the compiled SQL.\n",
    "  <https://docs.getdbt.com/docs/build/models>\n",
    "- The dbt documentation. *Node selection syntax*: `+`, folders, tags and the other ways to choose\n",
    "  what to build. <https://docs.getdbt.com/reference/node-selection/syntax>\n",
    "- The dbt documentation. *Python models*: when SQL is not enough, and how each adapter runs them.\n",
    "  <https://docs.getdbt.com/docs/build/python-models>\n",
    "- The dbt-duckdb adapter. Profiles, Python models and DuckDB's extensions in dbt.\n",
    "  <https://github.com/duckdb/dbt-duckdb>\n",
    "- Reis, J. & Housley, M. (2022). *Fundamentals of Data Engineering*. O'Reilly Media. Chapter 8,\n",
    "  on transformations: queries, data modelling and the tools that run them."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
