Upload 10 files
Browse files- .dockerignore +5 -0
- Dockerfile +9 -0
- README.md +37 -0
- ec_vocabulary.json +0 -0
- inputs.py +26 -0
- kmer.py +67 -0
- predict.py +98 -0
- requirements.txt +7 -0
- task.json +19 -0
- train.py +31 -0
.dockerignore
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.git
|
| 2 |
+
__pycache__
|
| 3 |
+
*.pyc
|
| 4 |
+
output/
|
| 5 |
+
data/
|
Dockerfile
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim-bookworm
|
| 2 |
+
RUN useradd --create-home --uid 1000 user
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
COPY requirements.txt .
|
| 5 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 6 |
+
COPY --chown=user:user . .
|
| 7 |
+
USER user
|
| 8 |
+
ENV OMP_NUM_THREADS=2 OPENBLAS_NUM_THREADS=2
|
| 9 |
+
CMD ["python", "/app/predict.py", "--help"]
|
README.md
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: mit
|
| 3 |
+
tags:
|
| 4 |
+
- enzyme-classification
|
| 5 |
+
- ec-number
|
| 6 |
+
---
|
| 7 |
+
|
| 8 |
+
# Leak CURBER enzyme classification — homology kNN
|
| 9 |
+
|
| 10 |
+
Predicts one EC number per protein sequence by transferring labels from the most similar training enzymes.
|
| 11 |
+
|
| 12 |
+
## Method
|
| 13 |
+
1. **Prefilter**: TF-IDF-weighted 5-mer presence vectors; cosine similarity against all 186k unique training sequences, top 1,000 candidates per query (sparse matrix product).
|
| 14 |
+
2. **Re-rank**: Smith-Waterman local alignment (BLOSUM62, gap open 11, extend 1) of the query against each candidate with SIMD Opal (`pyopal`).
|
| 15 |
+
3. **Vote**: ECs of all hits scoring within 10% of the best hit, weighted by alignment score (multi-EC hits split their weight).
|
| 16 |
+
|
| 17 |
+
Falls back to the k-mer nearest neighbour if the 480 s time budget is reached, and to the most frequent EC if a query has no candidates.
|
| 18 |
+
|
| 19 |
+
## Local validation
|
| 20 |
+
Validation sequences have no exact matches in train and very low k-mer overlap (median top-1 cosine 0.05), so a random split is misleading (median 0.65). The local hold-out is 4,915 training sequences drawn from the low-similarity pool, scored against the remaining 181k and importance-weighted to match the validation similarity distribution (effective sample size ~2,300).
|
| 21 |
+
|
| 22 |
+
| Metric | Weighted hold-out |
|
| 23 |
+
|---|---|
|
| 24 |
+
| L1 | 0.943 |
|
| 25 |
+
| L2 | 0.912 |
|
| 26 |
+
| L3 | 0.899 |
|
| 27 |
+
| L4 | 0.746 |
|
| 28 |
+
|
| 29 |
+
## Runtime
|
| 30 |
+
11,367 validation inputs: 233 s, 4.0 GB peak RAM on 2 vCPU.
|
| 31 |
+
|
| 32 |
+
## Files
|
| 33 |
+
- `predict.py` — inference entry point
|
| 34 |
+
- `kmer.py` — sparse k-mer index
|
| 35 |
+
- `train.py` — builds `weights/db.parquet` from `train.parquet`
|
| 36 |
+
- `inputs.py`, `task.json`, `ec_vocabulary.json` — from the starter
|
| 37 |
+
- `weights/db.parquet` — unique training sequences with their ECs
|
ec_vocabulary.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
inputs.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Prepare exactly the unique input rows used by the evaluator."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import pandas as pd
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def prepare_inputs(frame):
|
| 10 |
+
config = json.loads((Path(__file__).parent / 'task.json').read_text())
|
| 11 |
+
columns = ['id'] + config['input_columns']
|
| 12 |
+
if not set(columns) <= set(frame.columns):
|
| 13 |
+
raise ValueError('Missing input columns: ' + ', '.join(columns))
|
| 14 |
+
if frame.id.isna().any() or frame.id.duplicated().any():
|
| 15 |
+
raise ValueError('Input IDs must be present and unique.')
|
| 16 |
+
return frame[columns].drop_duplicates(config['input_columns'], keep='first').reset_index(drop=True)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
if __name__ == '__main__':
|
| 20 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 21 |
+
parser.add_argument('--input', required=True)
|
| 22 |
+
parser.add_argument('--output', required=True)
|
| 23 |
+
args = parser.parse_args()
|
| 24 |
+
frame = prepare_inputs(pd.read_parquet(args.input))
|
| 25 |
+
frame.to_parquet(args.output, index=False)
|
| 26 |
+
print(f'Wrote {len(frame)} unique inputs to {args.output}')
|
kmer.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Sparse k-mer index: TF-IDF-weighted, L2-normalised presence vectors for cosine search."""
|
| 2 |
+
import numpy as np
|
| 3 |
+
import scipy.sparse as sp
|
| 4 |
+
|
| 5 |
+
AA = 'ACDEFGHIKLMNPQRSTVWY'
|
| 6 |
+
LUT = np.full(256, 20, dtype=np.int64)
|
| 7 |
+
for i, c in enumerate(AA):
|
| 8 |
+
LUT[ord(c)] = i
|
| 9 |
+
LUT[ord(c.lower())] = i
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def kmer_ids(seq, k):
|
| 13 |
+
a = LUT[np.frombuffer(seq.encode('ascii', 'replace'), dtype=np.uint8)]
|
| 14 |
+
if len(a) < k:
|
| 15 |
+
return np.empty(0, dtype=np.int64)
|
| 16 |
+
ids = np.zeros(len(a) - k + 1, dtype=np.int64)
|
| 17 |
+
for j in range(k):
|
| 18 |
+
ids = ids * 21 + a[j:len(a) - k + 1 + j]
|
| 19 |
+
return np.unique(ids)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def presence_matrix(seqs, k):
|
| 23 |
+
rows, cols = [], []
|
| 24 |
+
for i, s in enumerate(seqs):
|
| 25 |
+
ids = kmer_ids(s, k)
|
| 26 |
+
rows.append(np.full(len(ids), i, dtype=np.int32))
|
| 27 |
+
cols.append(ids)
|
| 28 |
+
rows = np.concatenate(rows)
|
| 29 |
+
cols = np.concatenate(cols)
|
| 30 |
+
data = np.ones(len(rows), dtype=np.float32)
|
| 31 |
+
return sp.csr_matrix((data, (rows, cols)), shape=(len(seqs), 21 ** k))
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def weight(m, idf):
|
| 35 |
+
m = m.multiply(idf[None, :]).tocsr().astype(np.float32)
|
| 36 |
+
norms = np.sqrt(np.asarray(m.multiply(m).sum(axis=1)).ravel())
|
| 37 |
+
norms[norms == 0] = 1
|
| 38 |
+
return sp.diags(1 / norms).dot(m).tocsr().astype(np.float32)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class KmerIndex:
|
| 42 |
+
def __init__(self, seqs, k=5):
|
| 43 |
+
self.k = k
|
| 44 |
+
m = presence_matrix(seqs, k)
|
| 45 |
+
df = np.bincount(m.indices, minlength=m.shape[1]).astype(np.float32)
|
| 46 |
+
self.idf = np.log((1 + m.shape[0]) / (1 + df)).astype(np.float32)
|
| 47 |
+
self.T = weight(m, self.idf).T.tocsr() # (features x n_train)
|
| 48 |
+
|
| 49 |
+
def topk(self, seqs, k=50, chunk=256):
|
| 50 |
+
"""Return (indices, scores) arrays of shape (len(seqs), k)."""
|
| 51 |
+
n = len(seqs)
|
| 52 |
+
idx = np.full((n, k), -1, dtype=np.int64)
|
| 53 |
+
sc = np.zeros((n, k), dtype=np.float32)
|
| 54 |
+
for start in range(0, n, chunk):
|
| 55 |
+
q = weight(presence_matrix(seqs[start:start + chunk], self.k), self.idf)
|
| 56 |
+
s = (q @ self.T).tocsr()
|
| 57 |
+
for r in range(s.shape[0]):
|
| 58 |
+
lo, hi = s.indptr[r], s.indptr[r + 1]
|
| 59 |
+
if hi == lo:
|
| 60 |
+
continue
|
| 61 |
+
d, c = s.data[lo:hi], s.indices[lo:hi]
|
| 62 |
+
m = min(k, hi - lo)
|
| 63 |
+
part = np.argpartition(-d, m - 1)[:m]
|
| 64 |
+
part = part[np.argsort(-d[part])]
|
| 65 |
+
idx[start + r, :m] = c[part]
|
| 66 |
+
sc[start + r, :m] = d[part]
|
| 67 |
+
return idx, sc
|
predict.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Offline CPU inference: k-mer prefilter -> Smith-Waterman re-ranking -> score-weighted EC vote."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import time
|
| 6 |
+
from collections import Counter, defaultdict
|
| 7 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
import pandas as pd
|
| 12 |
+
import pyopal
|
| 13 |
+
|
| 14 |
+
from inputs import prepare_inputs
|
| 15 |
+
from kmer import KmerIndex
|
| 16 |
+
|
| 17 |
+
ROOT = Path(__file__).parent
|
| 18 |
+
T0 = time.time()
|
| 19 |
+
BUDGET = float(os.environ.get('TIME_BUDGET', 480)) # seconds; hard limit is 600
|
| 20 |
+
N_CAND = 1000 # k-mer candidates re-aligned per query
|
| 21 |
+
DELTA = 0.10 # vote among hits scoring within 10% of the best
|
| 22 |
+
THREADS = 2
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def log(msg):
|
| 26 |
+
print(f'[{time.time() - T0:6.1f}s] {msg}', flush=True)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def load_db():
|
| 30 |
+
db = pd.read_parquet(ROOT / 'weights/db.parquet')
|
| 31 |
+
vocab = set(json.loads((ROOT / 'ec_vocabulary.json').read_text()))
|
| 32 |
+
ecs = [[e for e in row if e in vocab] for row in db.ecs]
|
| 33 |
+
keep = [i for i, e in enumerate(ecs) if e]
|
| 34 |
+
seqs = [db.sequence.iat[i] for i in keep]
|
| 35 |
+
ecs = [ecs[i] for i in keep]
|
| 36 |
+
fallback = Counter(e for row in ecs for e in row).most_common(1)[0][0]
|
| 37 |
+
return seqs, ecs, fallback
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def vote(cand, scores, ecs, fallback):
|
| 41 |
+
if len(cand) == 0 or scores.max() <= 0:
|
| 42 |
+
return fallback
|
| 43 |
+
top = scores.max()
|
| 44 |
+
votes = defaultdict(float)
|
| 45 |
+
for c, s in zip(cand, scores):
|
| 46 |
+
if s >= top * (1 - DELTA):
|
| 47 |
+
row = ecs[c]
|
| 48 |
+
for e in row:
|
| 49 |
+
votes[e] += s / len(row)
|
| 50 |
+
return max(votes, key=votes.get)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def predict_file(input_path, output_path):
|
| 54 |
+
frame = prepare_inputs(pd.read_parquet(input_path))
|
| 55 |
+
queries = [s if isinstance(s, str) else '' for s in frame.sequence]
|
| 56 |
+
log(f'{len(queries)} unique inputs')
|
| 57 |
+
|
| 58 |
+
seqs, ecs, fallback = load_db()
|
| 59 |
+
index = KmerIndex(seqs, k=5)
|
| 60 |
+
log(f'k-mer index over {len(seqs)} sequences')
|
| 61 |
+
cand_idx, cand_sim = index.topk(queries, N_CAND)
|
| 62 |
+
log('k-mer candidates ready')
|
| 63 |
+
|
| 64 |
+
# Default prediction: k-mer nearest neighbour (used if alignment runs out of time).
|
| 65 |
+
preds = [ecs[i[0]][0] if i[0] >= 0 else fallback for i in cand_idx]
|
| 66 |
+
|
| 67 |
+
aligner = pyopal.Aligner('BLOSUM62', gap_open=11, gap_extend=1)
|
| 68 |
+
database = pyopal.Database(seqs)
|
| 69 |
+
|
| 70 |
+
def align(q):
|
| 71 |
+
if time.time() - T0 > BUDGET or not queries[q]:
|
| 72 |
+
return q, None
|
| 73 |
+
cand = [int(c) for c in cand_idx[q] if c >= 0]
|
| 74 |
+
if not cand:
|
| 75 |
+
return q, None
|
| 76 |
+
scores = np.array([r.score for r in aligner.align(queries[q], database.extract(cand))], float)
|
| 77 |
+
return q, vote(cand, scores, ecs, fallback)
|
| 78 |
+
|
| 79 |
+
done = 0
|
| 80 |
+
with ThreadPoolExecutor(THREADS) as pool:
|
| 81 |
+
for q, p in pool.map(align, range(len(queries))):
|
| 82 |
+
if p is not None:
|
| 83 |
+
preds[q] = p
|
| 84 |
+
done += 1
|
| 85 |
+
log(f'aligned {done}/{len(queries)} queries')
|
| 86 |
+
|
| 87 |
+
with Path(output_path).open('w') as out:
|
| 88 |
+
for key, p in zip(frame.id, preds):
|
| 89 |
+
out.write(json.dumps({'id': key, 'prediction': [p]}) + '\n')
|
| 90 |
+
log(f'wrote {output_path}')
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
if __name__ == '__main__':
|
| 94 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 95 |
+
parser.add_argument('--input', required=True)
|
| 96 |
+
parser.add_argument('--output', required=True)
|
| 97 |
+
args = parser.parse_args()
|
| 98 |
+
predict_file(args.input, args.output)
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
numpy==2.4.4
|
| 2 |
+
pandas==2.3.3
|
| 3 |
+
pyarrow==23.0.1
|
| 4 |
+
scipy==1.17.1
|
| 5 |
+
pyopal==0.7.3
|
| 6 |
+
scoring-matrices==0.3.5
|
| 7 |
+
archspec==0.2.6
|
task.json
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"title": "Leak CURBER enzyme classification",
|
| 3 |
+
"slug": "leak-curber-enzyme-classification",
|
| 4 |
+
"benchmark_id": "leak-curber-enzyme-classification-20261023",
|
| 5 |
+
"input_columns": [
|
| 6 |
+
"sequence"
|
| 7 |
+
],
|
| 8 |
+
"label_column": "ec_number",
|
| 9 |
+
"output_format": "jsonl",
|
| 10 |
+
"primary_metric": "accuracy_l4",
|
| 11 |
+
"metrics": [
|
| 12 |
+
"accuracy_l4",
|
| 13 |
+
"accuracy_l3",
|
| 14 |
+
"accuracy_l2",
|
| 15 |
+
"accuracy_l1"
|
| 16 |
+
],
|
| 17 |
+
"data_dir": "data/enzyme_tasks/classification",
|
| 18 |
+
"task_id": "enzyme-classification"
|
| 19 |
+
}
|
train.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build the reference database: one row per unique training sequence with its ECs (most frequent first)."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import pandas as pd
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def build(train_path, output_path):
|
| 10 |
+
root = Path(__file__).parent
|
| 11 |
+
vocab = set(json.loads((root / 'ec_vocabulary.json').read_text()))
|
| 12 |
+
frame = pd.read_parquet(train_path)[['sequence', 'ec_number']].dropna()
|
| 13 |
+
bad = sorted(set(frame.ec_number) - vocab)
|
| 14 |
+
if bad:
|
| 15 |
+
raise ValueError(f'{len(bad)} training ECs not in vocabulary, e.g. {bad[:5]}')
|
| 16 |
+
counts = frame.ec_number.value_counts()
|
| 17 |
+
frame = frame.drop_duplicates()
|
| 18 |
+
frame['n'] = frame.ec_number.map(counts)
|
| 19 |
+
frame = frame.sort_values(['sequence', 'n', 'ec_number'], ascending=[True, False, True])
|
| 20 |
+
db = frame.groupby('sequence', sort=False).ec_number.agg(list).reset_index(name='ecs')
|
| 21 |
+
Path(output_path).parent.mkdir(parents=True, exist_ok=True)
|
| 22 |
+
db.to_parquet(output_path, index=False, compression='zstd')
|
| 23 |
+
print(f'Wrote {len(db)} sequences, {frame.ec_number.nunique()} ECs to {output_path}')
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
if __name__ == '__main__':
|
| 27 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 28 |
+
parser.add_argument('--train', required=True)
|
| 29 |
+
parser.add_argument('--output', default=str(Path(__file__).parent / 'weights/db.parquet'))
|
| 30 |
+
args = parser.parse_args()
|
| 31 |
+
build(args.train, args.output)
|