"""Two-tower network (enzyme tower + substrate tower) used in the aura-3 blend. Shared by train.py and model.py.""" import numpy as np import torch import torch.nn as nn from scipy.special import ndtri N_SEQ = 489 # handcrafted enzyme columns at the start of base_features; the rest of base_features is substrate def split_blocks(base, esm, prior): """Enzyme input = composition + ESM; substrate input = RDKit features + substrate prior.""" return np.hstack([base[:, :N_SEQ], esm]), np.hstack([base[:, N_SEQ:], prior]) def quantile_normal(X, quantiles, references, eps=1e-7): """Same mapping as sklearn QuantileTransformer(output_distribution='normal').transform, in numpy; NaN -> 0.""" X = np.asarray(X, dtype=np.float64) out = np.empty_like(X) for j in range(X.shape[1]): q, x = quantiles[:, j], X[:, j] u = 0.5 * (np.interp(x, q, references) - np.interp(-x, -q[::-1], -references[::-1])) u[x + eps > q[-1]] = 1.0 u[x - eps < q[0]] = 0.0 out[:, j] = u lo = ndtri(eps - np.spacing(1)) with np.errstate(invalid='ignore', divide='ignore'): out = np.clip(ndtri(out), lo, -lo) return np.nan_to_num(out, nan=0.0).astype(np.float32) ACT = {'gelu': nn.GELU, 'silu': nn.SiLU} def _block(d_in, d_out, p, act='gelu'): return nn.Sequential(nn.Linear(d_in, d_out), nn.BatchNorm1d(d_out), ACT[act](), nn.Dropout(p)) class Residual(nn.Module): def __init__(self, d, p, act='gelu'): super().__init__() self.f = nn.Sequential(nn.BatchNorm1d(d), nn.Linear(d, d), ACT[act](), nn.Dropout(p), nn.Linear(d, d)) def forward(self, x): return x + self.f(x) class TwoTower(nn.Module): def __init__(self, de, ds, out=2, h=256, p=0.3, act='gelu'): super().__init__() self.enz = nn.Sequential(nn.Dropout(0.1), _block(de, h, p, act)) self.sub = nn.Sequential(nn.Dropout(0.1), _block(ds, h, p, act)) self.fuse = _block(3 * h, 2 * h, p, act) self.trunk = nn.Sequential(Residual(2 * h, p, act), Residual(2 * h, p, act)) self.head = nn.Linear(2 * h, out) def forward(self, e, s): e, s = self.enz(e), self.sub(s) return self.head(self.trunk(self.fuse(torch.cat([e, s, e * s], 1))))