{"cells": [{"cell_type": "markdown", "metadata": {}, "source": "# CAFA6 GOA Baseline with Hard-Max Propagation\n\n**Objective**: Replicate the 0.378 score using GOA predictions with simple hard-max propagation.\n\n**Approach**:\n1. Load GOA predictions from `ymuroya47/cafa6-goa-predictions`\n2. Build GO DAG from `go-basic.obo`\n3. Apply hard-max propagation: parent_score = max(parent_score, child_score)\n4. Output submission.tsv\n\n**Reference**: This replicates the cafa6solution approach that scored 0.378."}, {"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'\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\"Output: {SUBMISSION_OUTPUT}\")"}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "# ==========================================\n# 1. FAST GRAPH BUILDER (NetworkX)\n# ==========================================\ndef build_go_graph(go_obo_path):\n    print(f\"[1/4] 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\n# ==========================================\nprint(f\"[2/4] Loading GOA predictions from {GOA_PATH}...\")\n\nif not os.path.exists(GOA_PATH):\n    raise FileNotFoundError(f\"GOA file not found: {GOA_PATH}\")\n\n# Load with proper column names\nsubmission = 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\nprint(f\"      -> Loaded {len(submission):,} predictions\")\nprint(f\"      -> Unique proteins: {submission['protein_id'].nunique():,}\")\nprint(f\"      -> Score range: [{submission['score'].min():.4f}, {submission['score'].max():.4f}]\")\nprint(submission.head())"}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "# ==========================================\n# 3. FAST PROPAGATION (HARD MAX)\n# ==========================================\ndef propagate_hard_max(df, topo_order, term_parents_map):\n    print(\"[3/4] Propagating Scores (Hard Max)...\")\n    print(\"      -> Grouping data...\")\n    \n    # Process by group to save memory and ensure isolation\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_improved = propagate_hard_max(submission, topo_order, term_parents_map)\nprint(f\"      -> After propagation: {len(submission_improved):,} predictions\")"}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "# ==========================================\n# 4. SAVE SUBMISSION\n# ==========================================\nprint(f\"[4/4] Saving improved submission ({len(submission_improved):,} rows)...\")\n\n# Round scores to 3 decimal places and clip to valid range\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(\"\\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}