"""Shared ensemble members for m1_seed_ensemble.py and st_ensemble.py: the rate-aux Transformer and BMMS3.

Transformer: the four stage-2 seeds of nested_schedule_rate_aux (model_fusion_<outer>_s<i>.pt), trained without the
outer dataset ('ALL' = trained on all five, used for AASD / Carta). Input = the 16 evidence streams of ONE group of
four first-stage seeds in nested_stack_fusion.join order: 4 DirectNet logits, then 3 targets x 4 decoders. The
checkpoints were trained on seeds 0-3; applied to seeds 4-7 they see same-recipe models of other seeds (assumption).
BMMS3: mean of the requested seeds' logits, aligned on the fused frame times.
"""
import numpy as np
import torch

import antisym_transformer_experiment as T
import bmms3_enhanced_4seed_mix_score as B4
import rate_aux_baseline_ensemble as RA

_DEV = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
_CACHE = {}


def transformers(outer):
    if outer not in _CACHE:
        _CACHE.clear()
        _CACHE[outer] = [RA.model_for(outer, i, _DEV) for i in range(4)]
    return _CACHE[outer]


def x16(x, clf_cols, dec_cols):
    """clf_cols: 4 column indices of DirectNet logits; dec_cols: 4 start columns of 3-target decoder blocks."""
    return np.concatenate([x[:, list(clf_cols)]] + [x[:, c:c + 3] for c in dec_cols], axis=1).astype(np.float32)


def t_score(outer, x):
    return np.mean([T.predict(m, x, sc, _DEV) for m, sc in transformers(outer)], axis=0)


def bm_mean(objs, t_end, y, idx):
    vs = []
    for i in idx:
        z, att = B4.bvec(objs[i], t_end)
        if not np.array_equal(np.asarray(att).astype(int), np.asarray(y).astype(int)):
            raise ValueError('BMMS label mismatch')
        vs.append(z)
    return np.mean(vs, axis=0)
