{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":116062,"databundleVersionId":14875579,"sourceType":"competition"},{"sourceId":14452635,"sourceType":"datasetVersion","datasetId":9231252}],"dockerImageVersionId":31239,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2026-01-13T14:50:52.971023Z","iopub.execute_input":"2026-01-13T14:50:52.971416Z","iopub.status.idle":"2026-01-13T14:50:55.422316Z","shell.execute_reply.started":"2026-01-13T14:50:52.971386Z","shell.execute_reply":"2026-01-13T14:50:55.421270Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nfrom collections import defaultdict\n\n# ---------- GO Ontology ----------\nclass GOOntology:\n    ROOTS = {'GO:0003674', 'GO:0008150', 'GO:0005575'}\n\n    def __init__(self, obo):\n        self.parents = defaultdict(set)\n        self.anc = {}\n        with open(obo) as f:\n            tid = None\n            for l in f:\n                l = l.strip()\n                if l.startswith('id: '):\n                    tid = l[4:]\n                elif tid and (l.startswith('is_a: ') or l.startswith('relationship: part_of ')):\n                    self.parents[tid].add(l.split()[1])\n\n    def ancestors(self, t):\n        if t in self.anc:\n            return self.anc[t]\n        s = set(self.parents.get(t, []))\n        for p in list(s):\n            s |= self.ancestors(p)\n        self.anc[t] = s\n        return s\n\n# ---------- Load Predictions ----------\ndef load_preds(fp):\n    d = defaultdict(dict)\n    with open(fp) as f:\n        for l in f:\n            p, t, s = l.split('\\t')\n            s = float(s)\n            if t not in d[p] or s > d[p][t]:\n                d[p][t] = s\n    return d\n\n# ---------- Ensemble ----------\ndef ensemble(goa, prott5, w1=0.55):\n    w2 = 1 - w1\n    out = {}\n    for p in set(goa) | set(prott5):\n        a, b = goa.get(p, {}), prott5.get(p, {})\n        r = {}\n        for t in set(a) | set(b):\n            s = w1 * a.get(t, 0) + w2 * b.get(t, 0)\n            if s > 0:\n                r[t] = s\n        out[p] = r\n    return out\n\n# ---------- GOA+ Propagation ----------\ndef propagate(preds, ont, alpha=0.7, power=0.8, max_s=0.93, topk=270):\n    out = {}\n    for p, sc in preds.items():\n        u = sc.copy()\n\n        for t, s in sc.items():\n            for a in ont.ancestors(t):\n                u[a] = max(u.get(a, 0), s)\n\n        for t in list(u):\n            anc = ont.ancestors(t)\n            if anc:\n                m = min(u[a] for a in anc if a in u)\n                if m < u[t]:\n                    u[t] = alpha * m + (1 - alpha) * u[t]\n\n        vals = [v for k, v in u.items() if k not in ont.ROOTS]\n        if vals:\n            mx = max(vals)\n            if 0 < mx < max_s:\n                for k in u:\n                    if k not in ont.ROOTS:\n                        u[k] = min(1.0, (u[k] / mx) ** power * max_s)\n\n        for r in ont.ROOTS:\n            u[r] = 1.0\n\n        out[p] = dict(sorted(u.items(), key=lambda x: -x[1])[:topk])\n    return out\n\n# ---------- Save ----------\ndef save(preds, fp):\n    with open(fp, 'w') as f:\n        for p, ts in preds.items():\n            for t, s in ts.items():\n                if s >= 0.001:\n                    f.write(f\"{p}\\t{t}\\t{s:.6f}\\n\")\n\n# ---------- RUN ----------\nCOMP = '/kaggle/input/cafa-6-protein-function-prediction'\nPRED = '/kaggle/input/cafa6-goa-predictions'\n\nont = GOOntology(f'{COMP}/Train/go-basic.obo')\ngoa = load_preds(f'{PRED}/goa_submission.tsv')\npt5 = load_preds(f'{PRED}/prott5_interpro_predictions.tsv')\n\nens = ensemble(goa, pt5)\nfinal = propagate(ens, ont)\n\nsave(final, 'submission.tsv')","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}