"""EEG-enhanced BMMS adaptation accepting env/onset/dom per candidate.

Architecture based on QiuZelin/BMMSNet, MIT; see ../../BMMSNet/LICENSE.
This is adapted to the project's 58 EEG channels and 10-second windows.
"""
import torch
from bmms_env_model import DensePath
from bmms_enhanced_model import BMMSEnhanced

class BMMS3Enhanced(BMMSEnhanced):
 def __init__(self,channels=58,features=3,backbone=None):
  if features!=3:raise ValueError('expected env,onset,dom')
  super().__init__(channels,1,backbone);self.speech=DensePath(3)
 def forward(self,E,S,feat=False):
  if feat:raise ValueError('domain-adversarial features not supported')
  if S.ndim!=4 or S.shape[2:]!=(2,3):raise ValueError('expected two env/onset/dom streams')
  B=E.shape[0];enhanced=self.enhance(E.transpose(1,2)).transpose(1,2)
  S=(S-S.mean(dim=1,keepdim=True))/(S.std(dim=1,keepdim=True,unbiased=False)+1e-6)
  eeg=self.eeg(torch.cat((E,enhanced),dim=-1).transpose(1,2))
  speech=self.speech(S.permute(0,2,3,1).reshape(2*B,3,-1))
  x=torch.cat(list(reversed(eeg)),1);y=torch.cat(speech,1).reshape(B,2,160,-1)
  x=x-x.mean(-1,keepdim=True);y=y-y.mean(-1,keepdim=True)
  num=(x[:,None]*y).sum(-1);den=((x[:,None].square().sum(-1)+1e-8)*(y.square().sum(-1)+1e-8)).sqrt()
  score=self.weight(num/den).squeeze(-1)
  return score[:,0]-score[:,1]
