{"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},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# better score prediction ","metadata":{}},{"cell_type":"code","source":"import os\nfrom collections import defaultdict\nimport math\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.depth = {}\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        for t in self.parents:\n            self._depth(t)\n\n    def _depth(self, t):\n        if t in self.depth:\n            return self.depth[t]\n        if t in self.ROOTS or t not in self.parents:\n            self.depth[t] = 0\n        else:\n            self.depth[t] = 1 + max(self._depth(p) for p in self.parents[t])\n        return self.depth[t]\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            d[p][t] = max(d[p].get(t, 0), s)\n    return d\n\n# ---------- Stronger Ensemble ----------\ndef ensemble(goa, pt5, w1=0.55):\n    out = {}\n    for p in set(goa) | set(pt5):\n        a, b = goa.get(p, {}), pt5.get(p, {})\n        r = {}\n        for t in set(a) | set(b):\n            sa, sb = a.get(t, 0), b.get(t, 0)\n            if sa > 0 and sb > 0:\n                r[t] = (sa * sb) ** 0.5 + 0.15 * (sa + sb)\n            else:\n                r[t] = max(sa, sb)\n        out[p] = r\n    return out\n\n# ---------- Score Optimized Propagation ----------\ndef propagate(preds, ont):\n    out = {}\n    for p, sc in preds.items():\n        u = sc.copy()\n\n        # Positive propagation (mean aggregation)\n        for t, s in sc.items():\n            for a in ont.ancestors(t):\n                u[a] = max(u.get(a, 0), 0.85 * s)\n\n        # Adaptive negative propagation\n        for t in list(u):\n            anc = ont.ancestors(t)\n            if anc:\n                anc_scores = [u[a] for a in anc if a in u]\n                if anc_scores:\n                    m = min(anc_scores)\n                    depth = ont.depth.get(t, 1)\n                    alpha = 0.5 + 0.1 * min(depth, 3)\n                    if m < u[t]:\n                        u[t] = alpha * m + (1 - alpha) * u[t]\n\n        # Depth-aware scaling\n        for t in u:\n            if t not in ont.ROOTS:\n                boost = 1 + 0.08 * math.log1p(ont.depth.get(t, 1))\n                u[t] = min(1.0, u[t] * boost)\n\n        # Root normalization\n        for r in ont.ROOTS:\n            u[r] = 1.0\n\n        # Dynamic top-K\n        scores = sorted(u.items(), key=lambda x: -x[1])\n        k = min(350, max(150, int(len(scores) * 0.6)))\n        out[p] = dict(scores[:k])\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)\nsave(final, 'submission.tsv')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-13T15:00:20.088138Z","iopub.execute_input":"2026-01-13T15:00:20.088396Z"}},"outputs":[],"execution_count":null}]}