{"cells": [{"cell_type": "markdown", "metadata": {}, "source": "# CAFA6 Score Recalibration - INNOVATIVE APPROACH\n\n## The Key Insight\nF-max finds the OPTIMAL threshold \u00cf\u201e on your predictions. This means:\n1. **Score ORDERING matters more than absolute values**\n2. If high-IA terms consistently rank higher than low-IA terms, the optimal threshold will capture them\n3. We need to **recalibrate scores** so that high-IA predictions rank higher\n\n## The Strategy\nTransform scores using:\n```\nscore_new = score^\u00ce\u00b1 * (1 + \u00ce\u00b2 * normalized_IA)\n```\nWhere:\n- \u00ce\u00b1 controls score compression (\u00ce\u00b1 > 1 spreads high scores, \u00ce\u00b1 < 1 compresses)\n- \u00ce\u00b2 controls IA boost (higher \u00ce\u00b2 = more boost to high-IA terms)\n\n## Why This Works\n- GOA/ProtT5 scores are not calibrated for F-max optimization\n- By boosting high-IA term scores, we ensure they're selected at the optimal threshold\n- This is like \"telling\" the F-max algorithm which terms matter most"}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "import os\nimport gc\nimport pandas as pd\nimport numpy as np\nimport networkx as nx\nfrom tqdm.auto import tqdm\nfrom collections import defaultdict\n\n# ==========================================\n# CONFIGURATION\n# ==========================================\nOBO_PATH = \"/kaggle/input/cafa-6-protein-function-prediction/Train/go-basic.obo\"\nIA_PATH = \"/kaggle/input/cafa-6-protein-function-prediction/IA.tsv\"\nGOA_PATH = '/kaggle/input/cafa6-goa-predictions/goa_submission.tsv'\nPROTT5_PATH = '/kaggle/input/cafa6-goa-predictions/prott5_interpro_predictions.tsv'\nSUBMISSION_OUTPUT = 'submission.tsv'\n\n# Blend weights\nW_GOA = 0.65  # Slightly higher weight on GOA (more reliable)\nW_PROTT5 = 0.35\n\n# RECALIBRATION PARAMETERS - THE MAGIC\nALPHA = 0.8  # Score power (< 1 compresses toward 1, making high scores stand out less)\nBETA = 0.5   # IA boost factor\nGAMMA = 2.0  # IA power (higher = more aggressive boosting of high-IA terms)\n\nMIN_SCORE_THRESHOLD = 0.001\n\nprint(f\"Blend: GOA={W_GOA}, ProtT5={W_PROTT5}\")\nprint(f\"Recalibration: \u00ce\u00b1={ALPHA}, \u00ce\u00b2={BETA}, \u00ce\u00b3={GAMMA}\")"}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "# ==========================================\n# 1. BUILD GO GRAPH & LOAD IA\n# ==========================================\ndef build_go_graph(go_obo_path):\n    print(f\"[1/6] Parsing OBO...\")\n    go_graph = nx.DiGraph()\n    \n    with open(go_obo_path, \"r\") as f:\n        cur_id = None\n        for line in f:\n            line = line.strip()\n            if line == \"[Term]\":\n                cur_id = None\n            elif line.startswith(\"id: \"):\n                cur_id = line.split(\"id: \")[1].strip()\n                go_graph.add_node(cur_id)\n            elif line.startswith(\"is_a: \"):\n                pid = line.split()[1].strip()\n                if cur_id:\n                    go_graph.add_edge(cur_id, pid)\n            elif line.startswith(\"relationship: part_of \"):\n                parts = line.split()\n                if len(parts) >= 3:\n                    pid = parts[2].strip()\n                    if cur_id:\n                        go_graph.add_edge(cur_id, pid)\n\n    if not nx.is_directed_acyclic_graph(go_graph):\n        cycles = list(nx.simple_cycles(go_graph))\n        for cycle in cycles:\n            go_graph.remove_edge(cycle[0], cycle[1])\n\n    topo_order = list(nx.topological_sort(go_graph))\n    term_parents_map = {n: list(go_graph.successors(n)) for n in go_graph.nodes()}\n    \n    print(f\"      -> Built graph with {len(go_graph)} nodes\")\n    return topo_order, term_parents_map\n\ntopo_order, term_parents_map = build_go_graph(OBO_PATH)\n\n# Load IA scores\nprint(f\"      -> Loading IA scores...\")\nia_df = pd.read_csv(IA_PATH, sep='\\t', header=None, names=['term', 'ia'])\nterm_ia = dict(zip(ia_df['term'], ia_df['ia']))\n\n# Normalize IA to [0, 1]\nmax_ia = ia_df['ia'].max()\nterm_ia_normalized = {k: v / max_ia for k, v in term_ia.items()}\n\nprint(f\"      -> Loaded IA for {len(term_ia):,} terms (max={max_ia:.4f})\")"}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "# ==========================================\n# 2. LOAD AND BLEND PREDICTIONS\n# ==========================================\nprint(f\"[2/6] Loading and blending predictions...\")\n\nmerged_preds = defaultdict(lambda: defaultdict(float))\n\n# Load GOA\nif os.path.exists(GOA_PATH):\n    print(f\"      -> Loading GOA...\")\n    for chunk in pd.read_csv(GOA_PATH, sep='\\t', header=None, \n                              names=['id', 'term', 'score'], chunksize=500000):\n        for row in chunk.itertuples(index=False):\n            merged_preds[row.id][row.term] += float(row.score) * W_GOA\n\n# Load ProtT5\nif os.path.exists(PROTT5_PATH):\n    print(f\"      -> Loading ProtT5...\")\n    for chunk in pd.read_csv(PROTT5_PATH, sep='\\t', header=None, \n                              names=['id', 'term', 'score'], chunksize=500000):\n        for row in chunk.itertuples(index=False):\n            merged_preds[row.id][row.term] += float(row.score) * W_PROTT5\n\nprint(f\"      -> Combined predictions for {len(merged_preds):,} proteins\")"}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "# ==========================================\n# 3. SCORE RECALIBRATION - THE INNOVATION\n# ==========================================\nprint(f\"[3/6] Recalibrating scores...\")\n\ndef recalibrate_score(score, ia_norm, alpha, beta, gamma):\n    \"\"\"\n    Recalibrate score to boost high-IA terms.\n    \n    Formula: score^\u00ce\u00b1 * (1 + \u00ce\u00b2 * ia_norm^\u00ce\u00b3)\n    \n    - \u00ce\u00b1 < 1: Compresses scores toward 1 (reduces gap between high/low scores)\n    - \u00ce\u00b2 > 0: Adds boost proportional to IA\n    - \u00ce\u00b3 > 1: Makes boost more aggressive for very high IA terms\n    \"\"\"\n    base = score ** alpha\n    ia_boost = 1 + beta * (ia_norm ** gamma)\n    return min(1.0, base * ia_boost)\n\n# Convert to DataFrame with recalibration\nrows = []\nfor protein_id, terms_dict in tqdm(merged_preds.items(), desc=\"Recalibrating\"):\n    for term, score in terms_dict.items():\n        if score >= MIN_SCORE_THRESHOLD:\n            ia_norm = term_ia_normalized.get(term, 0.0)\n            recal_score = recalibrate_score(score, ia_norm, ALPHA, BETA, GAMMA)\n            rows.append((protein_id, term, recal_score))\n\nsubmission = pd.DataFrame(rows, columns=['protein_id', 'go_term', 'score'])\nsubmission['score'] = submission['score'].astype(np.float32)\n\nprint(f\"      -> Recalibrated {len(submission):,} predictions\")\nprint(f\"      -> Score range: [{submission['score'].min():.4f}, {submission['score'].max():.4f}]\")\n\ndel merged_preds, rows\ngc.collect()"}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "# ==========================================\n# 4. HARD-MAX PROPAGATION\n# ==========================================\ndef propagate_hard_max(df, topo_order, term_parents_map):\n    print(\"[4/6] Propagating Scores (Hard Max)...\")\n    \n    groups = df.groupby('protein_id')\n    final_rows = []\n    \n    for pid, group in tqdm(groups, desc=\"Propagating\"):\n        scores = dict(zip(group['go_term'], group['score']))\n        \n        for child in topo_order:\n            if child in scores:\n                child_score = scores[child]\n                if child in term_parents_map:\n                    for parent in term_parents_map[child]:\n                        current_parent_score = scores.get(parent, 0.0)\n                        if child_score > current_parent_score:\n                            scores[parent] = child_score\n        \n        for term, score in scores.items():\n            if score >= MIN_SCORE_THRESHOLD:\n                final_rows.append((pid, term, score))\n\n    return pd.DataFrame(final_rows, columns=['protein_id', 'go_term', 'score'])\n\nsubmission_propagated = propagate_hard_max(submission, topo_order, term_parents_map)\nprint(f\"      -> After propagation: {len(submission_propagated):,} predictions\")\n\ndel submission\ngc.collect()"}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "# ==========================================\n# 5. FINAL SCORE NORMALIZATION\n# ==========================================\nprint(\"[5/6] Final normalization...\")\n\n# Ensure scores are in valid range\nsubmission_propagated['score'] = submission_propagated['score'].clip(0.001, 1.0)\n\n# Optional: Re-normalize to spread scores in [0.01, 1.0] range\n# This ensures the threshold optimization has a good range to work with\nmin_score = submission_propagated['score'].min()\nmax_score = submission_propagated['score'].max()\nsubmission_propagated['score'] = 0.01 + 0.99 * (submission_propagated['score'] - min_score) / (max_score - min_score)\n\nprint(f\"      -> Final score range: [{submission_propagated['score'].min():.4f}, {submission_propagated['score'].max():.4f}]\")"}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "# ==========================================\n# 6. SAVE SUBMISSION\n# ==========================================\nprint(f\"[6/6] Saving submission ({len(submission_propagated):,} rows)...\")\n\nsubmission_propagated['score'] = submission_propagated['score'].round(3)\nsubmission_propagated.to_csv(SUBMISSION_OUTPUT, sep='\\t', index=False, header=False)\n\nprint(\"------------------------------------------------\")\nprint(f\"[Done] Saved to {SUBMISSION_OUTPUT}\")\nprint(\"------------------------------------------------\")\nprint(f\"Recalibration parameters: \u00ce\u00b1={ALPHA}, \u00ce\u00b2={BETA}, \u00ce\u00b3={GAMMA}\")\nprint(f\"Blend: GOA={W_GOA}, ProtT5={W_PROTT5}\")\nprint(f\"\\nSample:\")\nprint(submission_propagated.head(10))\n\n# Verify\nif os.path.exists(SUBMISSION_OUTPUT):\n    size = os.path.getsize(SUBMISSION_OUTPUT)\n    print(f\"\\nSUCCESS: {SUBMISSION_OUTPUT} ({size:,} bytes)\")"}], "metadata": {"kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"}, "language_info": {"name": "python", "version": "3.10.12"}}, "nbformat": 4, "nbformat_minor": 5}