{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Structure-activity dashboards\n",
    "\n",
    "Give the medicinal chemists their own view of the project, served from the warehouse. Build a Streamlit app part by part (filters, headline numbers, each series' progress, potency against selectivity, a table of structures and a page for each compound with its history) and test every part with Streamlit's AppTest before anyone opens it.\n",
    "\n",
    "The lesson's page: https://monstrous.com.ng/learn/data-engineering/series-2/10-structure-activity-dashboards/"
   ]
  },
  {
   "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 streamlit altair\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\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/dbt_project.yml\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/dbt_project.yml\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/dbt_project.yml\", \"stages/after-06/lab_dbt/dbt_project.yml\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/macros/generate_schema_name.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/macros/generate_schema_name.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/macros/generate_schema_name.sql\", \"stages/after-06/lab_dbt/macros/generate_schema_name.sql\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/macros/unique_combination.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/macros/unique_combination.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/macros/unique_combination.sql\", \"stages/after-06/lab_dbt/macros/unique_combination.sql\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/marts/_marts.yml\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/models/marts/_marts.yml\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/models/marts/_marts.yml\", \"stages/after-06/lab_dbt/models/marts/_marts.yml\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/marts/dim_compound.py\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/models/marts/dim_compound.py\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/models/marts/dim_compound.py\", \"stages/after-06/lab_dbt/models/marts/dim_compound.py\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/marts/dim_compound_history.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/models/marts/dim_compound_history.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/models/marts/dim_compound_history.sql\", \"stages/after-06/lab_dbt/models/marts/dim_compound_history.sql\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/marts/dim_date.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/models/marts/dim_date.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/models/marts/dim_date.sql\", \"stages/after-06/lab_dbt/models/marts/dim_date.sql\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/marts/dim_target.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/models/marts/dim_target.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/models/marts/dim_target.sql\", \"stages/after-06/lab_dbt/models/marts/dim_target.sql\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/marts/fact_measurement.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/models/marts/fact_measurement.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/models/marts/fact_measurement.sql\", \"stages/after-06/lab_dbt/models/marts/fact_measurement.sql\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/marts/measurements_wide.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/models/marts/measurements_wide.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/models/marts/measurements_wide.sql\", \"stages/after-06/lab_dbt/models/marts/measurements_wide.sql\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/staging/_sources.yml\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/models/staging/_sources.yml\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/models/staging/_sources.yml\", \"stages/after-06/lab_dbt/models/staging/_sources.yml\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/staging/_staging.yml\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/models/staging/_staging.yml\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/models/staging/_staging.yml\", \"stages/after-06/lab_dbt/models/staging/_staging.yml\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/staging/stg_compounds.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/models/staging/stg_compounds.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/models/staging/stg_compounds.sql\", \"stages/after-06/lab_dbt/models/staging/stg_compounds.sql\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/staging/stg_results.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/models/staging/stg_results.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/models/staging/stg_results.sql\", \"stages/after-06/lab_dbt/models/staging/stg_results.sql\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/profiles.yml\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/profiles.yml\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/profiles.yml\", \"stages/after-06/lab_dbt/profiles.yml\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/seeds/targets.csv\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/seeds/targets.csv\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/seeds/targets.csv\", \"stages/after-06/lab_dbt/seeds/targets.csv\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/seeds/unit_to_nm.csv\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/seeds/unit_to_nm.csv\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/seeds/unit_to_nm.csv\", \"stages/after-06/lab_dbt/seeds/unit_to_nm.csv\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/snapshots/registry_history.yml\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/snapshots/registry_history.yml\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/snapshots/registry_history.yml\", \"stages/after-06/lab_dbt/snapshots/registry_history.yml\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/tests/pic50_matches_ic50.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/tests/pic50_matches_ic50.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/tests/pic50_matches_ic50.sql\", \"stages/after-06/lab_dbt/tests/pic50_matches_ic50.sql\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/tests/potency_in_plausible_range.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/tests/potency_in_plausible_range.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/tests/potency_in_plausible_range.sql\", \"stages/after-06/lab_dbt/tests/potency_in_plausible_range.sql\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Everything so far has been for the people who run the data: layers, tests, history, flows,\n",
    "checks. This module is for the people who use it. A medicinal chemist on the EGFR project asks the\n",
    "same few questions every week: is each series getting better, which compounds are potent *and*\n",
    "selective, is potency coming from real improvements or only from greasier molecules, and what\n",
    "exactly was measured for this compound? [Module 3](../03-modelling-the-warehouse/) shaped the marts\n",
    "to answer those questions with a query. A **dashboard** answers them without one: a page the\n",
    "chemists open, with filters they can change and the structures in front of them.\n",
    "\n",
    "**Streamlit** is an open-source Python library for such pages. A Streamlit **app** is a Python\n",
    "script: each `st.` call puts something on the page (a title, a table, a chart, a filter), and\n",
    "whenever someone changes a filter, Streamlit runs the script again from the top with the new value.\n",
    "There is no web programming: the page is the script, read top to bottom.\n",
    "\n",
    "By the end of this module you will be able to:\n",
    "\n",
    "- write a Streamlit app that reads the warehouse's marts, read-only, with caching;\n",
    "- add filters, headline numbers, charts (with Altair) and a table that shows chemical structures;\n",
    "- give each compound a page with its measurements and its registration history;\n",
    "- choose colours that everyone can tell apart, and say what the numbers are;\n",
    "- test the app with Streamlit's **AppTest**, which runs it without a browser and checks what it\n",
    "  shows, and run it for real on your own computer.\n",
    "\n",
    "## Setup\n",
    "\n",
    "The warehouse is the lab's at the end of the project, week 12, built as in Module 6\n",
    "(`labstack.warehouse_at`). Then the build is **published**: copied, whole, to\n",
    "`work/published/lab.duckdb`, the file the dashboard reads. DuckDB lets one program write to a file\n",
    "at a time, and while it writes, no other program can open the file, so a dashboard reading the\n",
    "working warehouse would be locked out every time the pipeline builds. A copy made after each good\n",
    "build (the job of the `publish` task of [Module 7](../07-orchestration/)) can be read at any time.\n",
    "`COPY FROM DATABASE` copies every schema and table of one database into another, which `ATTACH`\n",
    "has opened alongside it.\n",
    "\n",
    "![One writer, many readers: the weekly pipeline writes work/lab.duckdb, which is locked while it is written; after each good build it is copied to published/lab.duckdb, which the Streamlit dashboard opens read-only for any number of chemists](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/10-structure-activity-dashboards/figures/publish.svg)\n",
    "\n",
    "The app is written to `work/dashboard.py`, part by part: `add` appends a part to the file. `AppTest` comes from Streamlit's testing tools. The logging filter hides one\n",
    "warning Streamlit prints, with the time, whenever an app runs outside a browser session, which is\n",
    "exactly what a test does."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "import logging\n",
    "import shutil\n",
    "from pathlib import Path\n",
    "\n",
    "import duckdb\n",
    "from streamlit.testing.v1 import AppTest\n",
    "\n",
    "import labdata\n",
    "import labstack\n",
    "\n",
    "logging.basicConfig(level=logging.INFO, format=\"%(levelname)s %(message)s\", force=True)\n",
    "log = logging.getLogger(__name__)\n",
    "logging.getLogger(\"streamlit.runtime.scriptrunner_utils.script_run_context\").addFilter(\n",
    "    lambda record: \"missing ScriptRunContext\" not in record.getMessage())  # expected in a test\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",
    "PUBLISHED = WORK / \"published\" / \"lab.duckdb\"  # the copy the dashboard reads\n",
    "APP = WORK / \"dashboard.py\"\n",
    "\n",
    "shutil.rmtree(WORK, ignore_errors=True)  # start clean\n",
    "lab = labdata.Lab()\n",
    "labstack.warehouse_at(lab, labdata.WEEKS, WORK)\n",
    "PUBLISHED.parent.mkdir(parents=True)\n",
    "with duckdb.connect(str(WAREHOUSE)) as db:\n",
    "    db.execute(f\"ATTACH '{PUBLISHED.as_posix()}' AS published\")\n",
    "    db.execute(\"COPY FROM DATABASE lab TO published\")\n",
    "    db.execute(\"DETACH published\")  # let go of the copy, so readers can open it\n",
    "\n",
    "\n",
    "def add(code: str) -> None:\n",
    "    \"\"\"Append one part to the app's file.\"\"\"\n",
    "    with APP.open(\"a\", encoding=\"utf-8\", newline=\"\\n\") as app:\n",
    "        app.write(code.lstrip(\"\\n\") + \"\\n\\n\")\n",
    "\n",
    "\n",
    "def run_app() -> AppTest:\n",
    "    \"\"\"Run the app as it is so far, without a browser, and return what it shows.\"\"\"\n",
    "    app = AppTest.from_file(str(APP.resolve()), default_timeout=120).run()\n",
    "    assert not app.exception, app.exception[0].message  # the app must run without an error\n",
    "    return app"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`run_app` is the test: it runs the whole app once, as a browser visit would, and gives back every\n",
    "element on the page, so the lesson can print what a chemist would see. If the app raised an error,\n",
    "the `assert` stops the lesson with Streamlit's message.\n",
    "\n",
    "## 1. The data, read once\n",
    "\n",
    "The app's first part sets up the page and reads the data. Three decisions matter more than the code:\n",
    "\n",
    "- **Read-only, from the published copy.** The app opens `work/published/lab.duckdb` with\n",
    "  `read_only=True`. A dashboard should never be able to change what it shows, and DuckDB lets any\n",
    "  number of readers share a file that nobody is writing. The environment variable `LAB_PUBLISHED`\n",
    "  can point it at another copy.\n",
    "- **Cached.** Streamlit runs the script again on every click, and reading the warehouse every time\n",
    "  would make every click slow. `@st.cache_data` keeps a function's result for the same arguments,\n",
    "  and `ttl=600` (time to live) throws it away after ten minutes, so new data appears within ten\n",
    "  minutes of a build.\n",
    "- **From the marts, not the raw layer.** The app reads `marts.measurements_wide` (Module 3, built by\n",
    "  dbt and tested every week) and the compound dimension, and leaves out superseded readings, as the\n",
    "  wide view already does. One mean pIC50 per compound and target, from measured values only (Module\n",
    "  3, section 6), and a count of the results that were only bounds."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "EGFR project: structure-activity\n",
      "Measurements up to 25 November 2026, from the lab's warehouse. Potencies are mean pIC50 over measured results; superseded readings are left out. The data are synthetic.\n"
     ]
    }
   ],
   "source": [
    "add('''\n",
    "\"\"\"The EGFR project's structure-activity dashboard (Series 2, Module 10).\n",
    "\n",
    "Run it with: streamlit run work/dashboard.py   (from the module's folder)\n",
    "\"\"\"\n",
    "\n",
    "import base64\n",
    "import os\n",
    "\n",
    "import altair as alt\n",
    "import duckdb\n",
    "import pandas as pd\n",
    "import streamlit as st\n",
    "from rdkit import Chem, RDLogger\n",
    "from rdkit.Chem import Draw\n",
    "\n",
    "RDLogger.DisableLog(\"rdApp.*\")\n",
    "WAREHOUSE = os.environ.get(\"LAB_PUBLISHED\", \"work/published/lab.duckdb\")  # published, read-only\n",
    "PANEL_CUTOFF = 7.0  # EGFR pIC50 at which a compound goes on to the selectivity panel\n",
    "# one colour per series, from Okabe and Ito's palette: distinct with colour-vision deficiency\n",
    "SERIES_COLOURS = {\"aminopyrimidines\": \"#0072B2\", \"pyrimidine piperazines\": \"#E69F00\",\n",
    "                  \"ureas\": \"#009E73\"}\n",
    "\n",
    "st.set_page_config(page_title=\"EGFR project: structure-activity\", layout=\"wide\")\n",
    "\n",
    "\n",
    "@st.cache_data(ttl=600)\n",
    "def load(sql: str) -> pd.DataFrame:\n",
    "    \"\"\"Run one query on the warehouse, read-only; the answer is kept for ten minutes.\"\"\"\n",
    "    with duckdb.connect(WAREHOUSE, read_only=True) as db:\n",
    "        return db.sql(sql).df()\n",
    "\n",
    "\n",
    "potency = load(\"\"\"\n",
    "    SELECT w.compound_id, w.parent_smiles, w.series, w.chemist, w.mw, w.clogp, w.target,\n",
    "           c.registered_on,\n",
    "           avg(w.pic50) FILTER (WHERE w.relation = '=')   AS pic50,\n",
    "           count(*) FILTER (WHERE w.relation = '>')       AS bounds\n",
    "    FROM marts.measurements_wide AS w\n",
    "    JOIN marts.dim_compound AS c USING (compound_id)\n",
    "    GROUP BY ALL\n",
    "\"\"\")\n",
    "start = load(\"SELECT min(date_key) AS d FROM marts.dim_date\")[\"d\"][0]\n",
    "potency[\"week\"] = (potency[\"registered_on\"] - start).dt.days // 7 + 1\n",
    "newest = load(\"SELECT max(run_date) AS d FROM marts.fact_measurement\")[\"d\"][0]\n",
    "\n",
    "st.title(\"EGFR project: structure-activity\")\n",
    "st.caption(f\"Measurements up to {newest:%d %B %Y}, from the lab's warehouse. Potencies are mean \"\n",
    "           \"pIC50 over measured results; superseded readings are left out. The data are synthetic.\")\n",
    "''')\n",
    "app = run_app()\n",
    "print(app.title[0].value)\n",
    "print(app.caption[0].value)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The page has its title and says where its numbers come from and what they are. That caption is part\n",
    "of the dashboard, not decoration: a number a chemist cannot trace is a number they should not use.\n",
    "\n",
    "## 2. Filters and headline numbers\n",
    "\n",
    "The second part turns the long table of potencies into one row per compound (EGFR in one column,\n",
    "the best panel kinase in another), works out each compound's selectivity and **lipophilic\n",
    "efficiency** (LipE, Module 3, section 7), and adds filters in the **sidebar**, the panel at the left\n",
    "of the page: which series, which weeks of registration, and whether to show only compounds that\n",
    "have been through the panel. Every later part uses the filtered table, `shown`.\n",
    "\n",
    "Then four **metrics**, the large numbers a page opens with: how many compounds are shown, how many\n",
    "reached the panel cut-off, how many went through the panel, and the best selectivity among them.\n",
    "`st.columns(4)` lays them side by side."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "{'Compounds': '440', 'EGFR pIC50 of 7 or more': '114', 'Tested on the panel': '95', 'Best selectivity': '3.5'}\n",
      "{'Compounds': '53', 'EGFR pIC50 of 7 or more': '8', 'Tested on the panel': '6', 'Best selectivity': '2.6'}\n"
     ]
    }
   ],
   "source": [
    "add('''\n",
    "wide = potency.pivot_table(index=[\"compound_id\", \"parent_smiles\", \"series\", \"chemist\", \"week\",\n",
    "                                  \"mw\", \"clogp\"], columns=\"target\", values=\"pic50\").reset_index()\n",
    "panel = [t for t in [\"ABL1\", \"BRAF\", \"CDK2\", \"JAK2\"] if t in wide]\n",
    "wide[\"best_panel\"] = wide[panel].max(axis=1)  # the panel kinase it hits hardest\n",
    "wide[\"selectivity\"] = wide[\"EGFR\"] - wide[\"best_panel\"]  # 2 = a hundred times more potent on EGFR\n",
    "wide[\"lipe\"] = wide[\"EGFR\"] - wide[\"clogp\"]\n",
    "\n",
    "with st.sidebar:\n",
    "    st.header(\"Filters\")\n",
    "    series = st.multiselect(\"Series\", list(SERIES_COLOURS), default=list(SERIES_COLOURS))\n",
    "    weeks = st.slider(\"Registered in weeks\", 1, int(wide[\"week\"].max()), (1, int(wide[\"week\"].max())))\n",
    "    panel_only = st.checkbox(\"Only compounds tested on the panel\")\n",
    "\n",
    "shown = wide[wide[\"series\"].isin(series) & wide[\"week\"].between(*weeks)]\n",
    "if panel_only:\n",
    "    shown = shown[shown[\"best_panel\"].notna()]\n",
    "\n",
    "tested = shown[shown[\"best_panel\"].notna()]\n",
    "columns = st.columns(4)\n",
    "columns[0].metric(\"Compounds\", len(shown))\n",
    "columns[1].metric(f\"EGFR pIC50 of {PANEL_CUTOFF:g} or more\", int((shown[\"EGFR\"] >= PANEL_CUTOFF).sum()))\n",
    "columns[2].metric(\"Tested on the panel\", len(tested))\n",
    "columns[3].metric(\"Best selectivity\", f\"{tested['selectivity'].max():.1f}\" if len(tested) else \"-\")\n",
    "''')\n",
    "app = run_app()\n",
    "print({metric.label: metric.value for metric in app.metric})\n",
    "app.sidebar.multiselect[0].set_value([\"ureas\"])\n",
    "app.sidebar.slider[0].set_value((1, 6))\n",
    "app.run()\n",
    "print({metric.label: metric.value for metric in app.metric})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The test did what a chemist would: it chose only the ureas registered in the first six weeks, and the\n",
    "app ran again with those filters. `set_value` changes a widget and `run` reruns the script, so every\n",
    "filter can be tested without a browser.\n",
    "\n",
    "## 3. Each series' progress\n",
    "\n",
    "The project's first question: is each series improving? The chart shows the mean EGFR pIC50 of the\n",
    "compounds registered each week, one line per series. It is drawn with **Altair**, which Streamlit\n",
    "uses for charts: a chart is the data, a **mark** (lines, points) and an **encoding** (which column\n",
    "goes on which axis, and which decides the colour). Three choices make it honest and readable:\n",
    "\n",
    "- the colours are fixed per series (`scale=alt.Scale(domain=..., range=...)`), so a series keeps its\n",
    "  colour whatever the filters, and they are colours that people with colour-vision deficiency can\n",
    "  tell apart;\n",
    "- the y axis starts where the data are, not at zero (a pIC50 of zero means nothing), and is\n",
    "  labelled with its unit;\n",
    "- a dashed line marks the panel cut-off, so \"good enough to go on\" is on the chart."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "1 chart; its marks: ['line', 'rule']\n"
     ]
    }
   ],
   "source": [
    "add('''\n",
    "st.subheader(\"Each series, week by week\")\n",
    "st.caption(\"Mean EGFR pIC50 of the compounds registered each week. Dashed: the panel cut-off.\")\n",
    "by_week = (shown.dropna(subset=[\"EGFR\"])\n",
    "           .groupby([\"week\", \"series\"], as_index=False)[\"EGFR\"].mean())\n",
    "colour = alt.Color(\"series:N\", title=\"Series\",\n",
    "                   scale=alt.Scale(domain=list(SERIES_COLOURS), range=list(SERIES_COLOURS.values())))\n",
    "lines = alt.Chart(by_week).mark_line(point=True).encode(\n",
    "    x=alt.X(\"week:O\", title=\"Week registered\"),\n",
    "    y=alt.Y(\"EGFR:Q\", title=\"Mean EGFR pIC50\", scale=alt.Scale(zero=False)),\n",
    "    color=colour,\n",
    "    tooltip=[\"series\", \"week\", alt.Tooltip(\"EGFR:Q\", format=\".2f\")],\n",
    ")\n",
    "cutoff = alt.Chart(pd.DataFrame({\"y\": [PANEL_CUTOFF]})).mark_rule(strokeDash=[4, 4]).encode(y=\"y\")\n",
    "st.altair_chart(lines + cutoff, width=\"stretch\")\n",
    "''')\n",
    "app = run_app()\n",
    "charts = app.get(\"vega_lite_chart\")\n",
    "print(len(charts), \"chart; its marks:\",\n",
    "      [layer[\"mark\"][\"type\"] for layer in json.loads(charts[0].proto.spec)[\"layer\"]])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The test cannot see the picture, but it can check that the chart is there and what it is made of: a\n",
    "line layer and a rule layer. (`json.loads` reads the chart's specification, which Altair writes\n",
    "as JSON.)\n",
    "\n",
    "## 4. Potency against selectivity\n",
    "\n",
    "The project's second question: which compounds are potent *and* selective? A scatter plot answers it\n",
    "at a glance: EGFR pIC50 across, best panel pIC50 up, one point per compound tested on the panel. The\n",
    "diagonal is \"as potent on the panel as on EGFR\"; points far below it are the selective ones, and the\n",
    "second line marks a hundredfold selectivity (2 log units). Hovering over a point shows the compound."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "2 charts\n"
     ]
    }
   ],
   "source": [
    "add('''\n",
    "st.subheader(\"Potency and selectivity\")\n",
    "st.caption(\"Each point is a compound tested on the panel. Below the solid line it is more potent on \"\n",
    "           \"EGFR than on any panel kinase; below the dashed line, a hundred times more.\")\n",
    "low, high = 6.5, 9.0  # only compounds at the panel cut-off (7) or near it reach the panel\n",
    "guides = pd.DataFrame({\"x\": [low, high], \"same\": [low, high], \"fold100\": [low - 2, high - 2]})\n",
    "points = alt.Chart(tested).mark_circle(size=70, opacity=0.8).encode(\n",
    "    x=alt.X(\"EGFR:Q\", title=\"EGFR pIC50\", scale=alt.Scale(domain=[low, high])),\n",
    "    y=alt.Y(\"best_panel:Q\", title=\"Best panel pIC50\", scale=alt.Scale(domain=[4.0, high])),\n",
    "    color=colour,\n",
    "    tooltip=[\"compound_id\", \"series\", alt.Tooltip(\"EGFR:Q\", format=\".2f\"),\n",
    "             alt.Tooltip(\"best_panel:Q\", format=\".2f\"), alt.Tooltip(\"selectivity:Q\", format=\".2f\")],\n",
    ")\n",
    "same = alt.Chart(guides).mark_line(color=\"#888888\").encode(x=\"x\", y=\"same\")\n",
    "fold100 = alt.Chart(guides).mark_line(color=\"#888888\", strokeDash=[4, 4]).encode(x=\"x\", y=\"fold100\")\n",
    "st.altair_chart(points + same + fold100, width=\"stretch\")\n",
    "''')\n",
    "app = run_app()\n",
    "print(len(app.get(\"vega_lite_chart\")), \"charts\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. A table of structures\n",
    "\n",
    "Chemists think in structures, so the table shows them. RDKit draws each parent as an SVG picture\n",
    "(Series 1, Module 5, \"Seeing the molecules\"); `base64` turns the picture into text that can sit\n",
    "inside the table as a **data URL** (an image carried in its own address); and Streamlit's\n",
    "`ImageColumn` shows it. `column_config` also names each column and gives its numbers a format, so\n",
    "the table reads like a report, not like a database."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "compound_id           series chemist  EGFR  selectivity  clogp  lipe\n",
      "   LAB-0023 aminopyrimidines      CN  8.37         2.92   4.82  3.55\n",
      "   LAB-0340 aminopyrimidines      BK  8.26         3.52   3.93  4.33\n",
      "   LAB-0246 aminopyrimidines      AO  8.26         3.43   4.17  4.09\n",
      "   LAB-0269 aminopyrimidines      BK  8.24         0.84   3.98  4.26\n",
      "   LAB-0267 aminopyrimidines      DS  8.15         2.75   3.19  4.96\n",
      "every row has a picture: True\n"
     ]
    }
   ],
   "source": [
    "add('''\n",
    "@st.cache_data\n",
    "def picture(smiles: str) -> str:\n",
    "    \"\"\"The molecule drawn as an SVG picture, as a data URL a table can show.\"\"\"\n",
    "    svg = Draw.MolsToGridImage([Chem.MolFromSmiles(smiles)], subImgSize=(220, 160), useSVG=True)\n",
    "    return \"data:image/svg+xml;base64,\" + base64.b64encode(svg.encode()).decode()\n",
    "\n",
    "\n",
    "st.subheader(\"The most potent compounds\")\n",
    "best = shown.dropna(subset=[\"EGFR\"]).sort_values(\"EGFR\", ascending=False).head(25).copy()\n",
    "best[\"structure\"] = best[\"parent_smiles\"].map(picture)\n",
    "st.dataframe(\n",
    "    best[[\"structure\", \"compound_id\", \"series\", \"chemist\", \"EGFR\", \"selectivity\", \"clogp\", \"lipe\"]],\n",
    "    column_config={\n",
    "        \"structure\": st.column_config.ImageColumn(\"Structure\", width=\"medium\"),\n",
    "        \"compound_id\": \"Compound\",\n",
    "        \"EGFR\": st.column_config.NumberColumn(\"EGFR pIC50\", format=\"%.2f\"),\n",
    "        \"selectivity\": st.column_config.NumberColumn(\"Selectivity\", format=\"%.2f\",\n",
    "                                                     help=\"EGFR pIC50 minus best panel pIC50\"),\n",
    "        \"clogp\": st.column_config.NumberColumn(\"cLogP\", format=\"%.2f\"),\n",
    "        \"lipe\": st.column_config.NumberColumn(\"LipE\", format=\"%.2f\", help=\"pIC50 minus cLogP\"),\n",
    "    },\n",
    "    hide_index=True, row_height=110,\n",
    ")\n",
    "''')\n",
    "app = run_app()\n",
    "table = app.dataframe[0].value\n",
    "print(table.drop(columns=\"structure\").head(5).round(2).to_string(index=False))\n",
    "print(\"every row has a picture:\", table[\"structure\"].str.startswith(\"data:image/svg+xml\").all())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The first rows are the compounds the project would discuss on Monday, with what makes them\n",
    "interesting next to their potency: their selectivity and LipE. `picture` is cached too, so each\n",
    "structure is drawn once, not on every click.\n",
    "\n",
    "## 6. A page for each compound\n",
    "\n",
    "The last question is about one compound: what exactly was measured, and is this the structure that\n",
    "was measured? A select box chooses the compound; the app shows its structure, every measurement\n",
    "(superseded readings included, marked as such, because this is the record), and its registration\n",
    "history from `dim_compound_history` (Module 6). `st.columns` puts the picture beside the tables."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "[\"LAB-0042's registration changed 1 time(s): measurements before the change were made under an earlier structure.\"]\n",
      "target   run_date  plate  replicate relation  ic50_nm  pic50 status\n",
      "  EGFR 2026-09-23 P03-03          1        =    22.20   7.65  final\n",
      "  EGFR 2026-09-23 P03-03          2        =     6.67   8.18  final\n",
      "  ABL1 2026-09-30 P04-01          1        = 25500.00   4.59  final\n",
      "  ABL1 2026-09-30 P04-01          2        = 16300.00   4.79  final\n",
      "  BRAF 2026-09-30 P04-01          1        =  9180.00   5.04  final\n",
      "  BRAF 2026-09-30 P04-01          2        = 19800.00   4.70  final\n",
      "  CDK2 2026-09-30 P04-01          1        > 30000.00   4.52  final\n",
      "  CDK2 2026-09-30 P04-01          2        > 30000.00   4.52  final\n",
      "  JAK2 2026-09-30 P04-01          1        =  3660.00   5.44  final\n",
      "  JAK2 2026-09-30 P04-01          2        =  5460.00   5.26  final\n",
      " version valid_from   valid_to\n",
      "       1 2026-09-14 2026-10-19\n",
      "       2 2026-10-19        NaT\n"
     ]
    }
   ],
   "source": [
    "add('''\n",
    "st.subheader(\"One compound\")\n",
    "choice = st.selectbox(\"Compound\", sorted(wide[\"compound_id\"]), index=None,\n",
    "                      placeholder=\"Choose a compound\")\n",
    "if choice:\n",
    "    measurements = load(f\"\"\"\n",
    "        SELECT t.target, f.run_date, f.plate, f.replicate, f.relation, f.ic50_nm,\n",
    "               round(f.pic50, 2) AS pic50, f.status\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 c.compound_id = '{choice}'\n",
    "        ORDER BY f.run_date, t.target, f.replicate, f.status DESC\n",
    "    \"\"\")\n",
    "    history = load(f\"\"\"\n",
    "        SELECT version, valid_from, valid_to, parent_smiles\n",
    "        FROM marts.dim_compound_history WHERE compound_id = '{choice}' ORDER BY version\n",
    "    \"\"\")\n",
    "    left, right = st.columns([1, 2])\n",
    "    left.image(picture(history[\"parent_smiles\"].iloc[-1]), caption=f\"{choice}, as registered now\")\n",
    "    right.dataframe(measurements, hide_index=True)\n",
    "    if len(history) > 1:\n",
    "        right.warning(f\"{choice}'s registration changed {len(history) - 1} time(s): \"\n",
    "                      \"measurements before the change were made under an earlier structure.\")\n",
    "    right.dataframe(history, hide_index=True)\n",
    "''')\n",
    "app = run_app()\n",
    "app.selectbox[0].set_value(\"LAB-0042\").run()\n",
    "print([warning.value for warning in app.warning])\n",
    "print(app.dataframe[1].value.to_string(index=False))\n",
    "print(app.dataframe[2].value.drop(columns=\"parent_smiles\").to_string(index=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "LAB-0042 shows what a dashboard built on the warehouse of Modules 2 to 9 can say that a spreadsheet\n",
    "could not: its current structure, every result with its status, and a warning that the measurements\n",
    "were made while the registry held a different structure, with the history to prove it. (`choice`\n",
    "comes from the select box, which only offers IDs from the warehouse, so putting it in the SQL is\n",
    "safe here; with free text from a user it would not be: [Series 1, Module\n",
    "4](../../series-1/04-databases-and-schemas/), section 8, shows the attack and the cure.)\n",
    "\n",
    "## 7. Running it\n",
    "\n",
    "The app is a file, and Streamlit serves it as a web page. On your own computer, in a terminal in\n",
    "the module's folder (after running the lesson, so the warehouse exists):\n",
    "\n",
    "```bash\n",
    "uv run streamlit run work/dashboard.py\n",
    "```\n",
    "\n",
    "Streamlit prints a local address, usually <http://localhost:8501>, and opens it in your browser.\n",
    "Change a filter and watch the page run again. This is what it looks like:\n",
    "\n",
    "![The dashboard: the title and caption, four headline numbers, the chart of each series' mean EGFR pIC50 by week with a dashed panel cut-off, and the scatter plot of EGFR against best panel pIC50](figures/dashboard.png)\n",
    "\n",
    "In Colab there is no browser on the machine that runs the code, so the lesson's tests are the way\n",
    "to check the app there; Colab can forward the app's port to your browser, but the steps change from\n",
    "time to time, so the course does not rely on them. For the lab, the app runs on a server next to\n",
    "the warehouse, started like the flow of [Module 7](../07-orchestration/) and refreshed by its\n",
    "weekly build; [Streamlit's documentation](https://docs.streamlit.io/deploy) lists the ways to\n",
    "deploy it, from a single server to managed hosting.\n",
    "\n",
    "The whole app is about 150 lines, and every part was tested before anyone opened it. In\n",
    "[Module 11](../11-capstone/) you build the whole stack for a lab of your own, from the files to a\n",
    "dashboard like this one.\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 Streamlit documentation. *Main concepts*: the script that reruns, widgets, caching and the\n",
    "  testing framework. <https://docs.streamlit.io/develop/concepts>\n",
    "- The Streamlit documentation. *App testing*: `AppTest`, its elements and widgets.\n",
    "  <https://docs.streamlit.io/develop/concepts/app-testing>\n",
    "- Satyanarayan, A., Moritz, D., Wongsuphasawat, K. & Heer, J. (2017). Vega-Lite: A Grammar of\n",
    "  Interactive Graphics. *IEEE Transactions on Visualization and Computer Graphics*, 23(1),\n",
    "  341–350. <https://doi.org/10.1109/TVCG.2016.2599030>\n",
    "- Okabe, M. & Ito, K. (2008). *Color Universal Design (CUD): How to make figures and presentations\n",
    "  that are friendly to colorblind people*. <https://jfly.uni-koeln.de/color/>\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>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
