{"cells": [{"cell_type": "markdown", "metadata": {}, "source": "# CAFA6 Smart Fallback Strategy\n\n**Key Insight**: Blending GOA + ProtT5 HURTS score (0.361 vs 0.378 pure GOA).\n\n**New Strategy**: Use ProtT5 as FALLBACK ONLY for proteins without GOA predictions.\n\n**Logic**:\n- If protein has GOA predictions -> Use GOA (high quality, proven 0.378)\n- If protein has NO GOA predictions -> Use ProtT5 (coverage boost)\n\nThis preserves GOA quality while gaining ProtT5 coverage."}, {"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\n\n# ==========================================\n# CONFIGURATION\n# ==========================================\nOBO_PATH = \"/kaggle/input/cafa-6-protein-function-prediction/Train/go-basic.obo\"\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# Threshold to remove weak noise\nMIN_SCORE_THRESHOLD = 0.001\n\nprint(f\"OBO Path: {OBO_PATH}\")\nprint(f\"GOA Path: {GOA_PATH}\")\nprint(f\"ProtT5 Path: {PROTT5_PATH}\")\nprint(f\"Output: {SUBMISSION_OUTPUT}\")"}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "# ==========================================\n# 1. BUILD GO GRAPH (NetworkX)\n# ==========================================\ndef build_go_graph(go_obo_path):\n    print(f\"[1/5] Parsing OBO into DAG from {go_obo_path}...\")\n    go_graph = nx.DiGraph()\n    \n    if not os.path.exists(go_obo_path):\n        raise FileNotFoundError(f\"OBO not found: {go_obo_path}\")\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    print(\"      -> Calculating Topological Order...\")\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\n# Build the graph\ntopo_order, term_parents_map = build_go_graph(OBO_PATH)"}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "# ==========================================\n# 2. LOAD GOA PREDICTIONS (PRIMARY SOURCE)\n# ==========================================\nprint(f\"[2/5] Loading GOA predictions (PRIMARY) from {GOA_PATH}...\")\n\nif not os.path.exists(GOA_PATH):\n    raise FileNotFoundError(f\"GOA file not found: {GOA_PATH}\")\n\ngoa_df = pd.read_csv(GOA_PATH, sep='\\t', header=None, \n                     names=['protein_id', 'go_term', 'score'], \n                     dtype={'score': np.float32},\n                     on_bad_lines='skip')\n\ngoa_proteins = set(goa_df['protein_id'].unique())\n\nprint(f\"      -> Loaded {len(goa_df):,} GOA predictions\")\nprint(f\"      -> Unique GOA proteins: {len(goa_proteins):,}\")\nprint(f\"      -> Score range: [{goa_df['score'].min():.4f}, {goa_df['score'].max():.4f}]\")"}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "# ==========================================\n# 3. LOAD PROTT5 PREDICTIONS (FALLBACK ONLY)\n# ==========================================\nprint(f\"[3/5] Loading ProtT5 predictions (FALLBACK) from {PROTT5_PATH}...\")\n\nif not os.path.exists(PROTT5_PATH):\n    print(\"      -> ProtT5 file not found, using GOA only\")\n    prott5_fallback = pd.DataFrame(columns=['protein_id', 'go_term', 'score'])\nelse:\n    prott5_df = pd.read_csv(PROTT5_PATH, sep='\\t', header=None, \n                           names=['protein_id', 'go_term', 'score'], \n                           dtype={'score': np.float32},\n                           on_bad_lines='skip')\n    \n    prott5_proteins = set(prott5_df['protein_id'].unique())\n    print(f\"      -> Loaded {len(prott5_df):,} ProtT5 predictions\")\n    print(f\"      -> Unique ProtT5 proteins: {len(prott5_proteins):,}\")\n    \n    # KEY INSIGHT: Only use ProtT5 for proteins NOT in GOA\n    proteins_needing_fallback = prott5_proteins - goa_proteins\n    print(f\"      -> Proteins needing fallback: {len(proteins_needing_fallback):,}\")\n    \n    # Filter ProtT5 to only fallback proteins\n    prott5_fallback = prott5_df[prott5_df['protein_id'].isin(proteins_needing_fallback)].copy()\n    print(f\"      -> ProtT5 fallback predictions: {len(prott5_fallback):,}\")\n    \n    del prott5_df\n    gc.collect()"}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "# ==========================================\n# 4. COMBINE: GOA (primary) + ProtT5 (fallback only)\n# ==========================================\nprint(\"[4/5] Combining predictions (NO BLENDING - just concatenation)...\")\n\n# Simply concatenate - no blending of scores!\n# GOA proteins get GOA predictions\n# Non-GOA proteins get ProtT5 predictions\ncombined_df = pd.concat([goa_df, prott5_fallback], ignore_index=True)\n\nprint(f\"      -> Combined predictions: {len(combined_df):,}\")\nprint(f\"      -> Total unique proteins: {combined_df['protein_id'].nunique():,}\")\nprint(f\"      -> From GOA: {len(goa_df):,} ({len(goa_df)/len(combined_df)*100:.1f}%)\")\nprint(f\"      -> From ProtT5 fallback: {len(prott5_fallback):,} ({len(prott5_fallback)/len(combined_df)*100:.1f}%)\")\n\ndel goa_df, prott5_fallback\ngc.collect()"}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "# ==========================================\n# 5. HARD-MAX PROPAGATION\n# ==========================================\ndef propagate_hard_max(df, topo_order, term_parents_map):\n    print(\"[5/5] Propagating Scores (Hard Max)...\")\n    print(\"      -> Grouping data...\")\n    \n    groups = df.groupby('protein_id')\n    final_rows = []\n    \n    for pid, group in tqdm(groups, desc=\"Propagating\"):\n        # Map term -> score\n        scores = dict(zip(group['go_term'], group['score']))\n        \n        # Propagate from leaves to roots\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                        # HARD MAX RULE: Parent score must be at least child score\n                        if child_score > current_parent_score:\n                            scores[parent] = child_score\n        \n        # Filter and collect\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\n# Propagate\nsubmission_final = propagate_hard_max(combined_df, topo_order, term_parents_map)\nprint(f\"      -> After propagation: {len(submission_final):,} predictions\")\n\ndel combined_df\ngc.collect()"}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "# ==========================================\n# 6. SAVE SUBMISSION\n# ==========================================\nprint(f\"Saving submission ({len(submission_final):,} rows)...\")\n\n# Round scores to 3 decimal places and clip to valid range\nsubmission_final['score'] = submission_final['score'].clip(0.001, 1.0).round(3)\n\n# Save without header (CAFA format)\nsubmission_final.to_csv(SUBMISSION_OUTPUT, sep='\\t', index=False, header=False)\n\nprint(\"================================================\")\nprint(f\"[Done] Saved to {SUBMISSION_OUTPUT}\")\nprint(\"================================================\")\nprint(f\"Final stats:\")\nprint(f\"  - Total predictions: {len(submission_final):,}\")\nprint(f\"  - Unique proteins: {submission_final['protein_id'].nunique():,}\")\nprint(f\"  - Score range: [{submission_final['score'].min():.3f}, {submission_final['score'].max():.3f}]\")\nprint(\"\\nSample:\")\nprint(submission_final.head(10))"}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "# Verify file was created\nimport os\nif os.path.exists(SUBMISSION_OUTPUT):\n    size = os.path.getsize(SUBMISSION_OUTPUT)\n    print(f\"SUCCESS: {SUBMISSION_OUTPUT} created ({size:,} bytes)\")\nelse:\n    print(f\"ERROR: {SUBMISSION_OUTPUT} not found!\")"}], "metadata": {"kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"}, "language_info": {"name": "python", "version": "3.10.12"}}, "nbformat": 4, "nbformat_minor": 5}