{"cells": [{"cell_type": "markdown", "metadata": {}, "source": "# CAFA6 GOA + ProtT5 Blend with Hard-Max Propagation\n\n**Objective**: Improve on the 0.378 baseline by blending GOA and ProtT5 predictions.\n\n**Approach**:\n1. Load GOA predictions (high precision)\n2. Load ProtT5 + InterPro predictions (high coverage)\n3. Blend with simple weighted averaging (GOA=0.6, ProtT5=0.4)\n4. Apply hard-max propagation\n5. Output submission.tsv\n\n**Key Insight**: Keep it simple - no complex IC weighting, just straightforward blending."}, {"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\"\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# Weights for blending\nW_GOA = 0.60\nW_PROTT5 = 0.40\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\"Weights: GOA={W_GOA}, ProtT5={W_PROTT5}\")\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\ntopo_order, term_parents_map = build_go_graph(OBO_PATH)"}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "# ==========================================\n# 2. LOAD AND BLEND PREDICTIONS\n# ==========================================\nprint(f\"[2/5] Loading and blending predictions...\")\n\n# Use defaultdict for easy blending\nmerged_preds = defaultdict(lambda: defaultdict(float))\n\n# Load GOA\nif os.path.exists(GOA_PATH):\n    print(f\"      -> Loading GOA from {GOA_PATH}...\")\n    goa_count = 0\n    for chunk in pd.read_csv(GOA_PATH, sep='\\t', header=None, \n                              names=['id', 'term', 'score'], \n                              chunksize=500000):\n        for row in chunk.itertuples(index=False):\n            merged_preds[row.id][row.term] += float(row.score) * W_GOA\n            goa_count += 1\n    print(f\"      -> Loaded {goa_count:,} GOA predictions\")\nelse:\n    print(f\"WARNING: GOA file not found at {GOA_PATH}!\")\n\n# Load ProtT5\nif os.path.exists(PROTT5_PATH):\n    print(f\"      -> Loading ProtT5 from {PROTT5_PATH}...\")\n    prott5_count = 0\n    for chunk in pd.read_csv(PROTT5_PATH, sep='\\t', header=None, \n                              names=['id', 'term', 'score'], \n                              chunksize=500000):\n        for row in chunk.itertuples(index=False):\n            merged_preds[row.id][row.term] += float(row.score) * W_PROTT5\n            prott5_count += 1\n    print(f\"      -> Loaded {prott5_count:,} ProtT5 predictions\")\nelse:\n    print(f\"WARNING: ProtT5 file not found at {PROTT5_PATH}!\")\n\nprint(f\"      -> Combined predictions for {len(merged_preds):,} proteins\")\ngc.collect()"}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "# ==========================================\n# 3. CONVERT TO DATAFRAME\n# ==========================================\nprint(f\"[3/5] Converting to DataFrame...\")\n\nrows = []\nfor protein_id, terms_dict in tqdm(merged_preds.items(), desc=\"Converting\"):\n    for term, score in terms_dict.items():\n        if score >= MIN_SCORE_THRESHOLD:\n            rows.append((protein_id, term, score))\n\nsubmission = pd.DataFrame(rows, columns=['protein_id', 'go_term', 'score'])\nsubmission['score'] = submission['score'].astype(np.float32)\n\nprint(f\"      -> Created DataFrame with {len(submission):,} predictions\")\nprint(f\"      -> Unique proteins: {submission['protein_id'].nunique():,}\")\n\n# Free memory\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/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        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                        if child_score > current_parent_score:\n                            scores[parent] = child_score\n        \n        # Collect results\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_improved = propagate_hard_max(submission, topo_order, term_parents_map)\nprint(f\"      -> After propagation: {len(submission_improved):,} predictions\")\n\ndel submission\ngc.collect()"}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "# ==========================================\n# 5. SAVE SUBMISSION\n# ==========================================\nprint(f\"[5/5] Saving submission ({len(submission_improved):,} rows)...\")\n\n# Clip and round scores\nsubmission_improved['score'] = submission_improved['score'].clip(0.001, 1.0).round(3)\n\n# Save without header (CAFA format)\nsubmission_improved.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_improved):,}\")\nprint(f\"  - Unique proteins: {submission_improved['protein_id'].nunique():,}\")\nprint(f\"  - Score range: [{submission_improved['score'].min():.3f}, {submission_improved['score'].max():.3f}]\")\nprint(f\"\\nBlend weights: GOA={W_GOA}, ProtT5={W_PROTT5}\")\nprint(\"\\nSample:\")\nprint(submission_improved.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}