{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d748c489",
   "metadata": {},
   "source": [
    "# Predicting signal peptide cleavage sites with a simple neural network\n",
    "\n",
    "We have  a set of proteins where we know **where the cut happens**. Now we want a model that finds it.\n",
    "\n",
    "**The idea:** we slide a small window along the provided sequences and ask a yes/no question at every\n",
    "position: *\"does the cut happen inside **this** window?\"*\n",
    "\n",
    "One protein with a 70 amino acids sequence then gives us ~70 training examples.\n",
    "\n",
    "---\n",
    "\n",
    "### The window\n",
    "\n",
    "We use a window of **K** residues, positioned so that the cut falls **after position K-2**:\n",
    "\n",
    "\n",
    "```\n",
    "K = 10\n",
    "            1  2  3  4  5  6  7  8 | 9 10\n",
    "            A  L  A  G  V  T  A  A | D  P\n",
    "                                   ^\n",
    "                              the cut\n",
    "```\n",
    "\n",
    "**Question 1:** Why we want to use a window where the cut takes place at position `K-2`?\n",
    "\n",
    "**Hint:** go back to the wiki page and look at the logo plot of the cleavage site:\n",
    "https://teaching.healthtech.dtu.dk/22111/index.php/Exercise:_Neural_networks\n",
    "\n",
    "### Three datasets, three jobs\n",
    "\n",
    "In this exercise of training artificial neural networks, we are going to use three datasets \n",
    "\n",
    "**Question 2:** What are the datasets been used for?\n",
    "\n",
    "| set | what it is for |\n",
    "|---|---|\n",
    "| **train** | ? |\n",
    "| **validation** | ? |\n",
    "| **test** | ? |\n",
    "\n",
    "\n",
    "\n",
    "### Things you will change in the exercise\n",
    "\n",
    "| parameter | what it does |\n",
    "|---|---|\n",
    "| `SPLIT` | which file is train / validation / test |\n",
    "| `K` | how many residues the network sees |\n",
    "| `ENCODING` | `\"onehot\"` or `\"blosum\"` |\n",
    "| `HIDDEN` | no hidden layers, one, two, ... |"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "efb34173-2895-4ea1-be18-11a29f6680ec",
   "metadata": {},
   "outputs": [],
   "source": [
    "#install some libraries\n",
    "\n",
    "!pip install logomaker\n",
    "!pip install biopython"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0bb8bbba",
   "metadata": {},
   "outputs": [],
   "source": [
    "import copy, warnings\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.neural_network import MLPClassifier\n",
    "from sklearn.metrics import log_loss\n",
    "from Bio.Align import substitution_matrices\n",
    "\n",
    "warnings.filterwarnings(\"ignore\")      # silence per-epoch convergence warnings\n",
    "\n",
    "# - DATASET NAMES\n",
    "A = \"EUK_SP_0\"\n",
    "B = \"EUK_SP_1\"\n",
    "C = \"EUK_SP_2\"\n",
    "\n",
    "# ---- THE PARAMETERS YOU CHANGE ----\n",
    "SPLIT = {\n",
    "    \"train\":      A,\n",
    "    \"validation\": B,\n",
    "    \"test\":       C,\n",
    "}                      # <-- swap these three splits around and re-run the notebook (A, B, C);(C, B, A);...\n",
    "\n",
    "K        = 10          # window size\n",
    "ENCODING = \"blosum\"    # \"onehot\" or \"blosum\"\n",
    "HIDDEN = (32,)        # () = no hidden layer, (32,) = one, (32,16) = two, ...\n",
    "\n",
    "DATA_DIR = \"/home/projects/22111/ANN\"   # folder with the .fasta files\n",
    "\n",
    "# -----------------------------------\n",
    "#other parameters\n",
    "UP, DOWN = K - 2, 2\n",
    "SCALE    = 4.0         # blosum only: shrinks the numbers\n",
    "\n",
    "print(f\"Selected Parameters:\\n\")\n",
    "for role, f in SPLIT.items():\n",
    "    print(f\"{role:>11} : {f}\")\n",
    "print(f\"\\nK = {K}  ({UP} before the cut, {DOWN} after)   encoding = {ENCODING}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ed512f27",
   "metadata": {},
   "source": [
    "## 1. Load the three datasets\n",
    "\n",
    "The files are in the SignalP 3-line format:\n",
    "\n",
    "```\n",
    ">P12345|EUKARYA|SP|1\n",
    "MKWVTFISLLLLFSSAYSRGVFRR...     <- the protein sequence\n",
    "SSSSSSSSSSSSSSSSSSOOOOOO...     <- S = signal peptide, O = mature protein\n",
    "```\n",
    "\n",
    "The cut is at the **last S**. 18 S's means the cut is between residue 18 and 19, which we store\n",
    "as `site = 17` (counting from 0): *\"cut after the residue at index 17\"*.\n",
    "\n",
    "**Question 3:** These three files are **homology-reduced** against each other, what does this mean? Why do we do this?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "76769cba",
   "metadata": {},
   "outputs": [],
   "source": [
    "def load_fasta(path):\n",
    "    \"\"\"Return (list of sequences, array of cut positions).\"\"\"\n",
    "    lines = [l.strip() for l in open(path) if l.strip()]\n",
    "    if not lines[0].startswith('>'):                 # tolerate a stray prefix\n",
    "        lines[0] = lines[0][lines[0].index('>'):]\n",
    "\n",
    "    seqs, sites = [], []\n",
    "    for i in range(0, len(lines), 3):\n",
    "        seq, ann = lines[i+1], lines[i+2]\n",
    "        n_S = 0\n",
    "        while n_S < len(ann) and ann[n_S] == 'S':    # count the S's at the start\n",
    "            n_S += 1\n",
    "        if 0 < n_S < len(seq):\n",
    "            seqs.append(seq)\n",
    "            sites.append(n_S - 1)\n",
    "    return seqs, np.array(sites)\n",
    "\n",
    "\n",
    "train_seqs, train_sites = load_fasta(f\"{DATA_DIR}/{SPLIT['train']}.fasta\")\n",
    "val_seqs,   val_sites   = load_fasta(f\"{DATA_DIR}/{SPLIT['validation']}.fasta\")\n",
    "test_seqs,  test_sites  = load_fasta(f\"{DATA_DIR}/{SPLIT['test']}.fasta\")\n",
    "\n",
    "for role, (s, _) in zip(SPLIT, [(train_seqs, 0), (val_seqs, 0), (test_seqs, 0)]):\n",
    "    print(f\"{role:>11} ({SPLIT[role]}): {len(s)} proteins\")\n",
    "\n",
    "print(f\"\\n\")\n",
    "print(f\"This part of the code 'parses' the fasta files to find where the cutting site is for each protein in each data set.\\n\")\n",
    "print(f\"For example:\\n\")\n",
    "print(\" \", train_seqs[0][:40], \"...\")\n",
    "print(\"  cut after index\", train_sites[0],\n",
    "      \"-> signal peptide =\", train_seqs[0][:train_sites[0]+1])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "19fe6255",
   "metadata": {},
   "source": [
    "## 2. Turn letters into numbers\n",
    "\n",
    "A neural network cannot read the amino acid symbols `A`, `L`, `G`. Therefore we need to transform \n",
    "the letters in the amino acid alphabet into numbers. There are two options.\n",
    "\n",
    "**One-hot.** Each amino acid gets its own input vector of 21 numbers, all zeros except one. \n",
    "For example: A = [1,0,0,..,0]; R = [0,1,0,..,0]; N =[0,0,1,..,0]\n",
    "Simple, but it says *every amino acid is equally different from every other* — swapping leucine\n",
    "for isoleucine (nearly interchangeable) looks as drastic as swapping it for aspartate.\n",
    "\n",
    "**BLOSUM62.** Each amino acid is described by how readily it swaps for each of the other 20,\n",
    "counted from real protein alignments. L and I get almost the same row, so what the network learns\n",
    "about one transfers to the other.\n",
    "\n",
    "**Question 4:**\n",
    "Which encoding scheme do you think will be more useful for our network? Make your guess now and after solving the full exercise contrast your guessing with results.\n",
    "\n",
    "#other parameters you could change in the first setup (Optional)\n",
    "**Why divide by `SCALE`?** Raw BLOSUM runs from -4 to +11. Numbers that big saturate the hidden\n",
    "neurons and waste the early training undoing it. Dividing brings them into the range where\n",
    "networks learn well. Try `SCALE = 1` later and watch the accuracy drop."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "15c05492",
   "metadata": {},
   "outputs": [],
   "source": [
    "AA   = \"ACDEFGHIKLMNPQRSTVWY\"\n",
    "TO_N = {a: i for i, a in enumerate(AA)}\n",
    "PAD  = 20                      # 21st slot: padding or unknown residue\n",
    "\n",
    "\n",
    "def to_numbers(seq):\n",
    "    return np.array([TO_N.get(c, PAD) for c in seq])\n",
    "\n",
    "\n",
    "def build_encoder(kind):\n",
    "    \"\"\"Lookup table: row i = the numbers that represent amino acid i.\"\"\"\n",
    "    if kind == \"onehot\":\n",
    "        return np.eye(21)                      # 21 rows x 21 columns\n",
    "\n",
    "    blosum = substitution_matrices.load(\"BLOSUM62\")\n",
    "    M = np.zeros((21, 20))                     # 21 rows x 20 columns\n",
    "    for i, a in enumerate(AA):\n",
    "        for j, b in enumerate(AA):\n",
    "            M[i, j] = blosum[a, b]\n",
    "    return M / SCALE                           # last row (PAD) stays all zeros\n",
    "\n",
    "\n",
    "ENCODER = build_encoder(ENCODING)\n",
    "\n",
    "oh, bl = build_encoder(\"onehot\"), build_encoder(\"blosum\")\n",
    "print(\"How different are two residues under each encoding?\")\n",
    "\n",
    "oh     = build_encoder(\"onehot\")\n",
    "blosum = substitution_matrices.load(\"BLOSUM62\")\n",
    "\n",
    "print(f\"{'swap':>10} {'one-hot':>9} {'BLOSUM62':>10}\")\n",
    "for a, b in [(\"L\", \"L\"), (\"L\", \"I\"), (\"L\", \"D\")]:\n",
    "    print(f\"{a} -> {b:<5} {oh[TO_N[a]][TO_N[b]]:>9.0f} {blosum[a, b]:>10.0f}\")\n",
    "\n",
    "print(\"\\n  one-hot gives 0 to BOTH swaps - it cannot tell them apart\")\n",
    "print(\"  BLOSUM gives +2 to L->I (common) and -4 to L->D (rare)\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "31bee195",
   "metadata": {},
   "source": [
    "## 3. Cut every protein into windows\n",
    "\n",
    "Slide the window along the protein; each position gives one window.\n",
    "\n",
    "- window landing exactly on the true cut -> **label 1**\n",
    "- every other window                      -> **label 0**\n",
    "\n",
    "At the start of the protein the window hangs off the edge, so we pad with the `PAD` symbol."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f4dcda48",
   "metadata": {},
   "outputs": [],
   "source": [
    "def protein_to_windows(seq):\n",
    "    \"\"\"All windows of one protein. Row i = the window whose cut would be after residue i.\"\"\"\n",
    "    nums = to_numbers(seq)\n",
    "    L = len(nums)\n",
    "\n",
    "    padded = np.full(L + UP - 1 + DOWN, PAD)\n",
    "    padded[UP - 1 : UP - 1 + L] = nums\n",
    "\n",
    "    n_windows = L - 1\n",
    "    return padded[np.arange(n_windows)[:, None] + np.arange(K)[None, :]]\n",
    "\n",
    "\n",
    "def build_dataset(seqs, sites):\n",
    "    \"\"\"Stack the windows of all proteins into X (inputs), y (labels), groups (which protein).\"\"\"\n",
    "    X, y, groups = [], [], []\n",
    "    for p, (seq, site) in enumerate(zip(seqs, sites)):\n",
    "        w = protein_to_windows(seq)\n",
    "        labels = np.zeros(len(w), dtype=int)\n",
    "        labels[site] = 1                           # exactly one positive per protein\n",
    "        X.append(ENCODER[w].reshape(len(w), -1))\n",
    "        y.append(labels)\n",
    "        groups.append(np.full(len(w), p))\n",
    "    return np.vstack(X), np.concatenate(y), np.concatenate(groups)\n",
    "\n",
    "\n",
    "# --- check it on the first training protein ---\n",
    "seq, site = train_seqs[0], train_sites[0]\n",
    "letters = \"\".join(AA[c] if c < 20 else '-' for c in protein_to_windows(seq)[site])\n",
    "print(\"protein:\", seq[:30], \"...   true cut after index\", site)\n",
    "print()\n",
    "print(\"the POSITIVE window:\", letters[:UP], \"|\", letters[UP:])\n",
    "print(\"                     \", \" \" * (UP - 1) + \"^ cut goes here\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a664acde",
   "metadata": {},
   "outputs": [],
   "source": [
    "X_train, y_train, _          = build_dataset(train_seqs, train_sites)\n",
    "X_val,   y_val,   groups_val = build_dataset(val_seqs,   val_sites)\n",
    "\n",
    "print(\"Here we build the dataset that we will use to train the network:\\n\")\n",
    "print(\"What is the shape fo our dataset after slicing the train and validation sets\")\n",
    "print(f\"in all possible windows of size: K \\n\")\n",
    "print(f\"X_train : {X_train.shape}   ({X_train.shape[1]} = {K} x {ENCODER.shape[1]})\")\n",
    "print(f\"X_val   : {X_val.shape}\")\n",
    "print(f\"\\ntraining positives: {y_train.sum()}   negatives: {(y_train==0).sum()}\")\n",
    "print(f\"ratio: 1 positive per {(y_train==0).sum() // y_train.sum()} negatives\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "32de535e",
   "metadata": {},
   "source": [
    "## 4. Train, and watch the validation set\n",
    "\n",
    "We train **one epoch at a time** (`warm_start=True, max_iter=1`) so that after every epoch we can\n",
    "measure the loss on the validation set as well as on the training set.\n",
    "\n",
    "We deliberately keep going for 100 iterations, so you can see what happens."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7e33e550",
   "metadata": {},
   "outputs": [],
   "source": [
    "N_EPOCHS = 100\n",
    "\n",
    "model = MLPClassifier(\n",
    "    hidden_layer_sizes=HIDDEN,\n",
    "    alpha=1e-4,                 # weak regularisation, so overfitting is visible\n",
    "    learning_rate_init=3e-4,\n",
    "    max_iter=1,                 # one epoch per .fit() call\n",
    "    warm_start=True,            # ...and carry on from where we left off\n",
    "    random_state=0,\n",
    ")\n",
    "\n",
    "train_loss, val_loss = [], []\n",
    "best_loss, best_epoch, best_weights = np.inf, 0, None\n",
    "\n",
    "for epoch in range(1, N_EPOCHS + 1):\n",
    "    model.fit(X_train, y_train)                    # one more epoch\n",
    "    train_loss.append(model.loss_)\n",
    "\n",
    "    p_val = model.predict_proba(X_val)[:, 1]\n",
    "    vl = log_loss(y_val, p_val, labels=[0, 1])\n",
    "    val_loss.append(vl)\n",
    "\n",
    "    if vl < best_loss:                             # remember the best moment\n",
    "        best_loss, best_epoch = vl, epoch\n",
    "        best_weights = (copy.deepcopy(model.coefs_),\n",
    "                        copy.deepcopy(model.intercepts_))\n",
    "\n",
    "print(f\"best validation loss at epoch {best_epoch}  ({best_loss:.4f})\")\n",
    "print(f\"after {N_EPOCHS} epochs: train {train_loss[-1]:.4f}, validation {val_loss[-1]:.4f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "642c9dc9",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots(figsize=(10, 4.5))\n",
    "ax.plot(range(1, N_EPOCHS+1), train_loss, color=\"steelblue\", lw=2, label=\"training loss\")\n",
    "ax.plot(range(1, N_EPOCHS+1), val_loss,   color=\"crimson\",   lw=2, label=\"validation loss\")\n",
    "ax.axvline(best_epoch, color=\"green\", ls=\"--\", lw=2, label=f\"stop here (epoch {best_epoch})\")\n",
    "ax.axvspan(best_epoch, N_EPOCHS, color=\"red\", alpha=.06)\n",
    "ax.text((best_epoch + N_EPOCHS)/2, max(val_loss)*0.75,\n",
    "        \"training loss keeps falling,\\nvalidation loss rises\",\n",
    "        ha=\"center\", color=\"darkred\", fontsize=10)\n",
    "ax.set_xlabel(\"epoch\"); ax.set_ylabel(\"loss\")\n",
    "ax.set_title(\"Why we stop early\")\n",
    "ax.legend(); ax.grid(alpha=.3)\n",
    "plt.tight_layout(); plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6426d8d5",
   "metadata": {},
   "source": [
    "**Question 5:**\n",
    "Explain the plot with your own words. What is the red curve and the blue curve? What is happening after the green line? Is there a name for this effect?\n",
    "\n",
    "As an illustrative example of what happens with the model trained on 100 epochs, we are going to continue with that."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "00a3cf67",
   "metadata": {},
   "outputs": [],
   "source": [
    "#model.coefs_, model.intercepts_ = best_weights      # rewind to the best epoch\n",
    "#print(f\"restored the weights from epoch {best_epoch}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "060fa769",
   "metadata": {},
   "source": [
    "## 5. Test: scan one protein\n",
    "\n",
    "For a new protein we score **every** window of size K, and select the window with the highest score. \n",
    "That position is our prediction for the cleavage site."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c4e2419f",
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "def predict_site(seq, m=None):\n",
    "    \"\"\"Score every window of a protein; return (best position, all scores).\"\"\"\n",
    "    m = m or model\n",
    "    w = protein_to_windows(seq)\n",
    "    scores = m.predict_proba(ENCODER[w].reshape(len(w), -1))[:, 1]\n",
    "    return int(np.argmax(scores)), scores\n",
    "\n",
    "\n",
    "i = 1\n",
    "pred, scores = predict_site(test_seqs[i])\n",
    "true = test_sites[i]\n",
    "\n",
    "plt.figure(figsize=(11, 2.5))\n",
    "plt.plot(scores, color=\"steelblue\", lw=1.5, label=\"model score\")\n",
    "plt.axvline(true, color=\"green\", lw=2, label=f\"true cut ({true})\")\n",
    "plt.axvline(pred, color=\"red\", ls=\"--\", lw=2, label=f\"predicted ({pred})\")\n",
    "plt.xlabel(\"position in protein\"); plt.ylabel(\"P(cut here)\")\n",
    "plt.title(f\"Scanning one protein from the TEST set ({SPLIT['test']})\")\n",
    "plt.legend(); plt.grid(alpha=.3); plt.tight_layout(); plt.show()\n",
    "\n",
    "print(\"correct!\" if pred == true else f\"missed by {abs(pred-true)} positions\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2976747a",
   "metadata": {},
   "source": [
    "## 6. How good is it?\n",
    "\n",
    "Scan **every** protein and count how often the top-scoring window is the right one.\n",
    "\n",
    "We report train / validation / test side by side. \n",
    "\"within 1\" and \"within 2\" tell us whether our mistakes are small slips or real failures.\n",
    "\n",
    "**Question 6:**\n",
    "Do you notice something weird about them?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "796c19aa",
   "metadata": {},
   "outputs": [],
   "source": [
    "def evaluate(seqs, sites):\n",
    "    preds = np.array([predict_site(s)[0] for s in seqs])\n",
    "    err = np.abs(preds - sites)\n",
    "    return (err == 0).mean(), (err <= 1).mean(), (err <= 2).mean(), preds - sites\n",
    "\n",
    "\n",
    "results = {}\n",
    "for role, (s, t) in [(\"train\", (train_seqs, train_sites)),\n",
    "                     (\"validation\", (val_seqs, val_sites)),\n",
    "                     (\"test\", (test_seqs, test_sites))]:\n",
    "    results[role] = evaluate(s, t)\n",
    "\n",
    "print(f\"K = {K}   encoding = {ENCODING}\\n\")\n",
    "print(f\"{'set':>11} {'file':>10} {'n':>5} {'exact':>8} {'within 1':>9} {'within 2':>9}\")\n",
    "for role in [\"train\", \"validation\", \"test\"]:\n",
    "    e, w1, w2, _ = results[role]\n",
    "    n = len({\"train\": train_seqs, \"validation\": val_seqs, \"test\": test_seqs}[role])\n",
    "    print(f\"{role:>11} {SPLIT[role]:>10} {n:>5} {e*100:>7.1f}% {w1*100:>8.1f}% {w2*100:>8.1f}%\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5d50a932",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots(1, 2, figsize=(13, 4))\n",
    "\n",
    "roles = [\"train\", \"validation\", \"test\"]\n",
    "x = np.arange(3)\n",
    "for j, (lbl, col) in enumerate([(\"exact\", \"#2a7\"), (\"within 1\", \"#7b4\"), (\"within 2\", \"#cc5\")]):\n",
    "    vals = [results[r][j]*100 for r in roles]\n",
    "    ax[0].bar(x + (j-1)*0.27, vals, 0.27, color=col, label=lbl)\n",
    "ax[0].set_xticks(x); ax[0].set_xticklabels([f\"{r}\\n({SPLIT[r]})\" for r in roles])\n",
    "ax[0].set_ylabel(\"accuracy (%)\"); ax[0].set_ylim(0, 100)\n",
    "ax[0].set_title(\"Train vs validation vs test\"); ax[0].legend(); ax[0].grid(alpha=.3, axis=\"y\")\n",
    "\n",
    "errors = results[\"test\"][3]\n",
    "ax[1].hist(np.clip(errors, -10, 10), bins=np.arange(-10.5, 11.5),\n",
    "           color=\"steelblue\", edgecolor=\"w\")\n",
    "ax[1].axvline(0, color=\"green\", lw=2)\n",
    "ax[1].set_xlabel(\"predicted - true  (0 = correct)\"); ax[1].set_ylabel(\"proteins\")\n",
    "ax[1].set_title(f\"Test-set mistakes ({SPLIT['test']})\")\n",
    "\n",
    "plt.tight_layout(); plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9704b0b5-8ed7-4662-aeb1-d6994e2c50b5",
   "metadata": {},
   "source": [
    "\n",
    "**Question 7:** What happens if we add early stopping? (Remove the # symbols in the next code cell and run again the cells in point 5 and 6.\n",
    "Can you observe any differences? Why?\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "01d288f6-3d36-4f21-b99c-c2ac9ee27a96",
   "metadata": {},
   "outputs": [],
   "source": [
    "model.coefs_, model.intercepts_ = best_weights      # rewind to the best epoch\n",
    "print(f\"restored the weights from the best epoch {best_epoch}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4be80347",
   "metadata": {},
   "source": [
    "## 7. Choosing K and the encoding — properly (THIS CELL NEEDS EDIT BEFORE RUNNING)\n",
    "\n",
    "Now we use all three sets the way they are meant to be used:\n",
    "\n",
    "1. train many models on the **training** set\n",
    "2. pick the best one using the **validation** set\n",
    "3. report that one model's number on the **test** set, once\n",
    "\n",
    "This is the whole point of having three files. If we picked the best `K` by looking at the test\n",
    "set, the number we report would be flattering and wrong.\n",
    "\n",
    "(For speed this part uses scikit-learn's built-in `early_stopping`, which carves a slice out of\n",
    "the training data, rather than our manual epoch loop.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9171de4a",
   "metadata": {},
   "outputs": [],
   "source": [
    "def run_experiment(k, encoder):\n",
    "    \"\"\"Train on train, return (validation accuracy, test accuracy).\"\"\"\n",
    "    global K, UP, ENCODER\n",
    "    keep = (K, UP, ENCODER)\n",
    "    K, UP, ENCODER = k, k - 2, encoder\n",
    "\n",
    "    Xtr, ytr, _ = build_dataset(train_seqs, train_sites)\n",
    "    m = MLPClassifier(hidden_layer_sizes=(32,), alpha=1e-2, max_iter=100,\n",
    "                      early_stopping=True, random_state=0).fit(Xtr, ytr)\n",
    "\n",
    "    accs = []\n",
    "    for seqs, sites in [(val_seqs, val_sites), (test_seqs, test_sites)]:\n",
    "        preds = [predict_site(s, m)[0] for s in seqs]\n",
    "        accs.append((np.array(preds) == sites).mean())\n",
    "\n",
    "    K, UP, ENCODER = keep\n",
    "    return accs[0], accs[1]\n",
    "\n",
    "# GRID SEARCH --------- => EDIT HERE\n",
    "\n",
    "Ks = [X1, X2, X3, .., XN] # For example to try 4,6,8 and 10 use Ks = [4, 6, 8, 10]\n",
    "scores = {enc: [run_experiment(k, build_encoder(enc)) for k in Ks]\n",
    "          for enc in [\"onehot\", \"blosum\"]}\n",
    "\n",
    "#  ---------\n",
    "\n",
    "print(f\"{'K':>3} {'onehot val':>11} {'onehot test':>12} {'blosum val':>11} {'blosum test':>12}\")\n",
    "for i, k in enumerate(Ks):\n",
    "    ov, ot = scores[\"onehot\"][i]; bv, bt = scores[\"blosum\"][i]\n",
    "    print(f\"{k:>3} {ov*100:>10.1f}% {ot*100:>11.1f}% {bv*100:>10.1f}% {bt*100:>11.1f}%\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2657be18",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots(1, 2, figsize=(13, 4))\n",
    "\n",
    "for enc, col in [(\"onehot\", \"steelblue\"), (\"blosum\", \"darkorange\")]:\n",
    "    ax[0].plot(Ks, [v*100 for v, _ in scores[enc]], \"o-\", color=col, lw=2, label=f\"{enc}\")\n",
    "ax[0].set_xlabel(\"window size K\"); ax[0].set_ylabel(\"VALIDATION accuracy (%)\")\n",
    "ax[0].set_title(\"Validation set: Choose using validation only\"); ax[0].legend(); ax[0].grid(alpha=.3)\n",
    "\n",
    "# the winner, chosen on validation\n",
    "best_enc, best_i = max(((e, i) for e in scores for i in range(len(Ks))),\n",
    "                       key=lambda t: scores[t[0]][t[1]][0])\n",
    "best_K = Ks[best_i]\n",
    "ax[0].plot(best_K, scores[best_enc][best_i][0]*100, \"*\", ms=22, color=\"red\", zorder=5)\n",
    "\n",
    "for enc, col in [(\"onehot\", \"steelblue\"), (\"blosum\", \"darkorange\")]:\n",
    "    ax[1].plot(Ks, [t*100 for _, t in scores[enc]], \"o--\", color=col, lw=2, label=f\"{enc}\")\n",
    "ax[1].set_xlabel(\"window size K\"); ax[1].set_ylabel(\"TEST accuracy (%)\")\n",
    "ax[1].set_title(\"Test set: Only looked at afterwards\"); ax[1].legend(); ax[1].grid(alpha=.3)\n",
    "\n",
    "plt.tight_layout(); plt.show()\n",
    "\n",
    "v, t = scores[best_enc][best_i]\n",
    "print(f\"chosen on the validation set the best parameters are: {best_enc}, K = {best_K}   (validation {v*100:.1f}%)\")\n",
    "print(f\"The honest score ot the TEST SET {t*100:.1f}%\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "41e49c11-2ecd-4615-8cd4-684ed10c1311",
   "metadata": {},
   "source": [
    "**Question 8:** Which parameters were best in your validation set? Was it best using one-hot or Blosum encoding? \n",
    "\n",
    "**TIP:**\n",
    "If your best model is in one end of the grid search, consider if you want to add more values in that direction.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "913527a2",
   "metadata": {},
   "source": [
    "## 8. Playing with hidden layers. (THIS CELL NEEDS EDIT BEFORE RUNNING)\n",
    "\n",
    "**Question 9:** What do you expect to happen with the ANN if there are no hidden layers?\n",
    "\n",
    "**Question 10:** What do you expect to happen with 1, 2, 3 hidden layers? How the number of hidden neurons affects the run time and accuracy?\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9c17d68e-2661-424f-8fb3-1ac0a5eca287",
   "metadata": {},
   "outputs": [],
   "source": [
    "architectures = [ (), (17,), (4,), (16,), (32,)] # Example ---=> architectures = [(), (4,), (16,), (32,), (64,), (32, 16), (64, 32, 16)]\n",
    "\n",
    "K, UP, ENCODER = 17, 15, build_encoder(ENCODING)\n",
    "Xtr, ytr, _ = build_dataset(train_seqs, train_sites)\n",
    "\n",
    "rows = []\n",
    "for h in architectures:\n",
    "    m = MLPClassifier(hidden_layer_sizes=h, alpha=1e-2, max_iter=300,\n",
    "                      early_stopping=True, random_state=0).fit(Xtr, ytr)\n",
    "    val  = np.mean([predict_site(s, m)[0] == t for s, t in zip(val_seqs, val_sites)])\n",
    "    test = np.mean([predict_site(s, m)[0] == t for s, t in zip(test_seqs, test_sites)])\n",
    "    n_par = sum(c.size for c in m.coefs_)\n",
    "    rows.append((h, n_par, val, test))\n",
    "    print(f\"{str(h):>14} {n_par:>7} weights   val {val*100:5.1f}%   test {test*100:5.1f}%\")\n",
    "\n",
    "plt.figure(figsize=(9, 4))\n",
    "x = np.arange(len(rows))\n",
    "plt.bar(x - 0.2, [r[2]*100 for r in rows], 0.4, label=\"validation\")\n",
    "plt.bar(x + 0.2, [r[3]*100 for r in rows], 0.4, label=\"test\")\n",
    "plt.xticks(x, [\"none\" if r[0] == () else str(r[0]) for r in rows], rotation=20)\n",
    "plt.ylabel(\"accuracy (%)\"); plt.xlabel(\"hidden layers\")\n",
    "plt.legend(); plt.grid(alpha=.3, axis=\"y\"); plt.tight_layout(); plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "66fc59b6-9eeb-4019-911b-83adebdea946",
   "metadata": {},
   "source": [
    "## 9. What did the network learn?\n",
    "\n",
    "Each block of weights in the first layer belongs to one window position. Adding up the size of the\n",
    "weights in each block tells us **how much the network relies on each position**.\n",
    "To make a simple test we are going to eliminate the hidden layer.\n",
    "\n",
    "If our story about the biology is right, the positions just before the cut should dominate."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2f6aa292",
   "metadata": {},
   "outputs": [],
   "source": [
    "K, UP, ENCODER = 17, 15, build_encoder(ENCODING)\n",
    "Xtr, ytr, _ = build_dataset(train_seqs, train_sites)\n",
    "m = MLPClassifier(hidden_layer_sizes=(), alpha=1e-2, max_iter=300,\n",
    "                  early_stopping=True, random_state=0).fit(Xtr, ytr)\n",
    "\n",
    "W = np.abs(m.coefs_[0])\n",
    "importance = W.reshape(K, ENCODER.shape[1], -1).sum(axis=(1, 2))\n",
    "importance /= importance.sum()\n",
    "\n",
    "labels = [str(p) for p in range(-UP, 0)] + [f\"+{p}\" for p in range(1, DOWN + 1)]\n",
    "\n",
    "plt.figure(figsize=(11, 4))\n",
    "plt.bar(range(K), importance, color=[\"steelblue\"]*UP + [\"darkorange\"]*DOWN)\n",
    "plt.xticks(range(K), labels)\n",
    "plt.axvline(UP - 0.5, color=\"k\", lw=2)\n",
    "plt.xlabel(\"position relative to the cut  (black line = the cut)\")\n",
    "plt.ylabel(\"how much the network uses it\")\n",
    "plt.title(f\"Which positions matter?  ({ENCODING})\")\n",
    "plt.tight_layout(); plt.show()\n",
    "\n",
    "print(\"most used positions:\", [labels[i] for i in np.argsort(-importance)[:3]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "83a1ff1c-e1a1-4d4e-8826-66b6b80e8675",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ---- The cleavage motif in all three datasets ----\n",
    "import pandas as pd, logomaker\n",
    "\n",
    "K, UP = 17, 15\n",
    "\n",
    "def window_freqs(seqs, sites):\n",
    "    \"\"\"Amino acid frequencies at each window position.\"\"\"\n",
    "    C = np.full((K, 21), 0.5)\n",
    "    for seq, s in zip(seqs, sites):\n",
    "        for j, sym in enumerate(protein_to_windows(seq)[min(s, len(seq)-2)]):\n",
    "            C[j, sym] += 1\n",
    "    return C / C.sum(1, keepdims=True)\n",
    "\n",
    "def logo_data(seqs, sites, n_null=200):\n",
    "    \"\"\"Real frequencies, information content, and the null-test floor.\"\"\"\n",
    "    real = window_freqs(seqs, sites)\n",
    "\n",
    "    # NULL TEST: put the cut in the WRONG place, 200 times. This is also our\n",
    "    # background, so everything that is merely \"typical of a signal peptide\"\n",
    "    # cancels out and only what marks the cut itself survives.\n",
    "    rng   = np.random.default_rng(0)\n",
    "    nulls = np.array([window_freqs(seqs, rng.choice(sites, len(seqs)))\n",
    "                      for _ in range(n_null)])\n",
    "    bg = nulls.mean(0)\n",
    "\n",
    "    def info(f):\n",
    "        with np.errstate(divide=\"ignore\", invalid=\"ignore\"):\n",
    "            return np.nansum(np.where(f > 0, f*(np.log2(f)-np.log2(bg)), 0), axis=1)\n",
    "\n",
    "    return real, info(real), np.percentile([info(n) for n in nulls], 95, axis=0)\n",
    "\n",
    "\n",
    "labels = [str(p) for p in range(-UP, 0)] + [f\"+{p}\" for p in range(1, DOWN+1)]\n",
    "sets = [(\"train\",      train_seqs, train_sites),\n",
    "        (\"validation\", val_seqs,   val_sites),\n",
    "        (\"test\",       test_seqs,  test_sites)]\n",
    "\n",
    "fig, axes = plt.subplots(3, 1, figsize=(12, 9), sharex=True)\n",
    "for ax, (role, seqs, sites) in zip(axes, sets):\n",
    "    real, ic, floor = logo_data(seqs, sites)\n",
    "    heights = pd.DataFrame(real[:, :20] * np.clip(ic, 0, None)[:, None], columns=list(AA))\n",
    "    logomaker.Logo(heights, ax=ax, color_scheme=\"chemistry\", show_spines=False)\n",
    "    ax.plot(range(K), floor, \"r--\", lw=1.3)\n",
    "    ax.axvline(UP - 0.5, color=\"k\", lw=2)\n",
    "    ax.set_ylabel(\"bits\"); ax.set_ylim(0, 1.35)\n",
    "    ax.set_title(f\"{role}  ({SPLIT[role]}, n={len(seqs)})\", loc=\"left\", fontsize=11)\n",
    "    print(f\"{role:>11}: top 3 =\", [labels[i] for i in np.argsort(-ic)[:3]])\n",
    "\n",
    "axes[-1].set_xticks(range(K)); axes[-1].set_xticklabels(labels)\n",
    "axes[-1].set_xlabel(\"position relative to the cut   \"\n",
    "                    \"(black line = the cut, red dashed = null test)\")\n",
    "fig.suptitle(\"The cleavage motif, seen in all three datasets\", y=0.995)\n",
    "plt.tight_layout(); plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f363e671-96d8-405a-8359-1a3f389984c7",
   "metadata": {},
   "source": [
    "**Question 11:** What can you say about the three splits? Do they look the same? Can you guess what will happen if you select a different split of the one you tried?\n",
    "\n",
    "## If you have extra time, other things you can try\n",
    "\n",
    "1. **Reframe the problem.** \"Where is the cut?\" In the begining we set K-2 as the optimal. Where can you change this?\n",
    "2. **Encoding matters.** BLOSUM62 knows leucine and isoleucine are near-interchangeable however the\n",
    "   matrix values are somewhat big and not optimal. You can play with SCALE to change this parameter.\n",
    "    - Set `SCALE = 1` and re-run. Why does BLOSUM get worse?\n",
    "4. **Three sets, three jobs.** Train fits the weights, validation decides when to stop and which\n",
    "   settings to use, test is opened once at the end. What happens if you change the order?\n",
    "    - **Rotate the files** in `SPLIT` (there are 6 orderings). How much does the test number move?\n",
    "      That spread is your real uncertainty — a single split can flatter you by several percent.\n",
    "5. **What is alpha?**\n",
    "    - Raise `alpha` to `1e-2` in the epoch loop. What happens to the red curve?\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f7b102fb-9955-446e-b152-a64b7fd0bf60",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c82a674b-8ba6-4a35-a1e8-2614c06093fe",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
