"""Causal logit transformer, second round.

Same leave-one-dataset-out protocol as ensemble_clf_transformer.py:
  * train only on datasets that are neither the outer (held-out) nor the inner dataset
  * choose the model and the HMM (p_stay, emission scale) by the acc74 rule on inner
    scores only: among settings with mean inner Acc >= 74, maximise inner H
    (ties: higher Acc, then lower SDT). If none reach 74, take the highest inner Acc
  * refit on the four non-held-out datasets and score the held-out dataset once
    with score.score_dataset

H is the official harmonic mean of accuracy (fraction) and switch score L
(aggregate() in the challenge scorer). Accuracy is the official subject-mean
sample accuracy. Neither split nor metric is changed.

What is new, relative to tf_hp_w48 (H 0.8208, Acc 78.09):
  recipe_hp48  same width, depth, window and hp120 features, but every causal
               position is supervised, dataset-balanced batches, cosine LR,
               EMA, input noise, seed dropout, time masking, post-switch
               loss weights, and a zero-init residual over a linear skip
  ms_w96       24-d causal features (raw, hp60, hp120, z60, 1 s slope, 2 s mean),
               d=64, window 96, same training recipe
  ms_w192      those features with a 48 s window
  stem_ms96    depthwise causal conv + dilated residual conv stem in front of
               the ms_w96 transformer
  ens_all      equal average of the four evidence streams (HMM still chosen on inner)

Train seed 20270101. usage: python ensemble_clf_transformer_v2.py
writes results/research/ensemble_clf_transformer_v2.csv and _inner.csv
"""
import copy
import math
import os
import time

import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F

import ensemble_clf_nested as N
from common import DS_KEYS

EXP = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(EXP, "results", "research", "ensemble_clf_transformer_v2.csv")
INNER = os.path.join(EXP, "results", "research", "ensemble_clf_transformer_v2_inner.csv")
CKPT = os.path.join(EXP, "models", "logit_tf_v2")
LOG = os.path.join(EXP, "experiments", "transformer_v2.log")

TRAIN_SEED = 20270101
STEPS = int(os.environ.get("STEPS", "800"))
BATCH = int(os.environ.get("BATCH", "512"))
P_STAY = (0.994, 0.996, 0.997, 0.998)
SCALES = (0.8, 0.9, 1.0)
THR = 74.0

# name, feature family, window, d_model, layers, conv stem, lr
CONFIGS = (
    ("recipe_hp48", "hp", 48, 32, 2, False, 1e-3),
    ("ms_w96", "ms", 96, 64, 2, False, 8e-4),
    ("ms_w192", "ms", 192, 48, 2, False, 8e-4),
    ("stem_ms96", "ms", 96, 64, 2, True, 8e-4),
)


class DilatedResidual(nn.Module):
    """Causal dilated conv. Zero-init so the block starts as the identity."""

    def __init__(self, d, k=5, dilation=1, dropout=0.1):
        super().__init__()
        self.pad = (k - 1) * dilation
        self.conv = nn.Conv1d(d, d, k, dilation=dilation)
        self.norm = nn.LayerNorm(d)
        self.drop = nn.Dropout(dropout)
        nn.init.zeros_(self.conv.weight)
        nn.init.zeros_(self.conv.bias)

    def forward(self, x):
        h = self.conv(F.pad(x.transpose(1, 2), (self.pad, 0))).transpose(1, 2)
        return x + self.drop(F.gelu(self.norm(h)))


class LogitTransformer(nn.Module):
    """Causal window encoder. Logit at position t uses only frames <= t.

    The linear skip is initialised to the mean of the raw logit channels and the
    transformer head starts at zero, so the network begins as that linear readout.
    """

    def __init__(self, c_in, window, d_model=32, nhead=4, nlayers=2, dropout=0.1, stem=False):
        super().__init__()
        self.window = window
        self.dw_pad = 8
        self.dw = None
        if stem:
            self.dw = nn.Conv1d(c_in, c_in, self.dw_pad + 1, groups=c_in)
            nn.init.zeros_(self.dw.weight)
            nn.init.zeros_(self.dw.bias)
        self.proj = nn.Linear(c_in, d_model)
        self.blocks = nn.ModuleList([
            DilatedResidual(d_model, k=5, dilation=d, dropout=dropout)
            for d in (1, 2, 4, 8)
        ]) if stem else nn.ModuleList()
        self.pos = nn.Parameter(torch.randn(1, window, d_model) * 0.02)
        layer = nn.TransformerEncoderLayer(
            d_model=d_model, nhead=nhead, dim_feedforward=d_model * 2,
            dropout=dropout, batch_first=True, norm_first=True, activation="gelu")
        self.enc = nn.TransformerEncoder(layer, num_layers=nlayers, enable_nested_tensor=False)
        self.head = nn.Linear(d_model, 1)
        self.skip = nn.Linear(c_in, 1, bias=False)
        mask = nn.Transformer.generate_square_subsequent_mask(window)
        self.register_buffer("mask", mask)
        nn.init.zeros_(self.head.weight)
        nn.init.zeros_(self.head.bias)
        nn.init.zeros_(self.skip.weight)
        with torch.no_grad():
            self.skip.weight[0, : min(4, c_in)] = 1.0 / 4.0

    def forward(self, x):
        raw = x
        if self.dw is not None:
            x = x + self.dw(F.pad(x.transpose(1, 2), (self.dw_pad, 0))).transpose(1, 2)
        h = self.proj(x)
        for block in self.blocks:
            h = block(h)
        h = h + self.pos[:, : h.size(1)]
        h = self.enc(h, mask=self.mask)
        return self.head(h).squeeze(-1) + self.skip(raw).squeeze(-1)


def causal_mean(D, k):
    cs = np.vstack([np.zeros((1, D.shape[1])), np.cumsum(D, axis=0)])
    idx = np.arange(len(D))
    left = np.maximum(0, idx - (k - 1))
    return (cs[idx + 1] - cs[left]) / (idx - left + 1)[:, None]


def build_features():
    """Full-history causal features. hp matches ensemble_clf_transformer.build_features."""
    hp, ms = {}, {}
    alpha120 = 1.0 - np.exp(-0.25 / 120.0)
    for ds in DS_KEYS:
        hp[ds], ms[ds] = {}, {}
        for key, D0 in N.G["base"]["id"][ds].items():
            D = np.asarray(D0, np.float64)
            h60 = N.xform_array(D, "hp60")
            h120 = D - N.ema_2d(D, alpha120)
            z = N.xform_array(D, "z60")
            slope = np.zeros_like(D)
            if len(D) > 4:
                slope[4:] = D[4:] - D[:-4]
            mean = causal_mean(D, 8)
            hp[ds][key] = np.concatenate([D, h120], 1).astype(np.float32)
            ms[ds][key] = np.concatenate([D, h60, h120, z, slope, mean], 1).astype(np.float32)
    return {"hp": hp, "ms": ms}


def norm_stats(feat, datasets):
    acc_n = 0
    acc_s = None
    acc_sq = None
    for ds in datasets:
        for X in feat[ds].values():
            acc_n += len(X)
            s = X.sum(0).astype(np.float64)
            sq = np.square(X, dtype=np.float64).sum(0)
            acc_s = s if acc_s is None else acc_s + s
            acc_sq = sq if acc_sq is None else acc_sq + sq
    mu = acc_s / acc_n
    sd = np.sqrt(np.maximum(acc_sq / acc_n - mu ** 2, 1e-8))
    return mu.astype(np.float32), sd.astype(np.float32)


def trial_groups(feat, datasets):
    groups = []
    y_parts = []
    for ds in datasets:
        att = N.G["att"][ds]
        trials = []
        for key, X in feat[ds].items():
            y = (att[key] == 0).astype(np.float32)
            if len(y) != len(X):
                raise RuntimeError(f"label length {len(y)} != {len(X)} for {ds}/{key}")
            trials.append((X, y))
            y_parts.append(y)
        lengths = np.array([len(y) for _, y in trials], np.int64)
        groups.append(dict(trials=trials, lengths=lengths, total=int(lengths.sum()),
                           ends=np.cumsum(lengths)))
    return groups, np.concatenate(y_parts)


def sample_batch(rng, groups, W, batch, mu, sd):
    """Dataset-balanced windows. Each row ends at a uniform frame of one dataset."""
    C = groups[0]["trials"][0][0].shape[1]
    Xo = np.zeros((batch, W, C), np.float32)
    yo = np.zeros((batch, W), np.float32)
    mo = np.zeros((batch, W), np.float32)
    ds_of = np.arange(batch) % len(groups)
    for g_i, g in enumerate(groups):
        rows = np.flatnonzero(ds_of == g_i)
        if len(rows) == 0:
            continue
        pick = rng.integers(0, g["total"], size=len(rows))
        which = np.searchsorted(g["ends"], pick, side="right")
        local = pick - (g["ends"] - g["lengths"])[which]
        trials = g["trials"]
        for row, ti, t in zip(rows, which, local):
            x, y = trials[int(ti)]
            t = int(t)
            a = t - W + 1
            if a >= 0:
                Xo[row] = x[a:t + 1]
                yo[row] = y[a:t + 1]
                mo[row] = 1.0
            else:
                n = t + 1
                Xo[row, -n:] = x[:n]
                yo[row, -n:] = y[:n]
                mo[row, -n:] = 1.0
    Xo -= mu
    Xo /= sd
    return Xo, yo, mo


def switch_weights(y, mask):
    """Upweight the frames that follow a label change. Causal in the labels."""
    change = torch.zeros_like(y)
    change[:, 1:] = (y[:, 1:] - y[:, :-1]).abs().gt(0.5).float() * mask[:, 1:] * mask[:, :-1]
    horizon = 12
    decay = torch.exp(-torch.arange(horizon, device=y.device, dtype=y.dtype) / 4.0)
    kernel = decay.flip(0).view(1, 1, -1)
    smooth = F.conv1d(F.pad(change.unsqueeze(1), (horizon - 1, 0)), kernel).squeeze(1)
    return 1.0 + 2.5 * smooth


def augment(x):
    x = x + torch.randn_like(x) * 0.1
    B, T, C = x.shape
    drop = torch.rand(B, device=x.device) < 0.3
    seed = torch.randint(0, 4, (B,), device=x.device)
    ch = torch.arange(C, device=x.device)
    kill = drop[:, None] & (ch[None, :] % 4 == seed[:, None])
    x = x.masked_fill(kill[:, None, :], 0.0)
    do = torch.rand(B, device=x.device) < 0.3
    span = torch.randint(2, 9, (B,), device=x.device)
    start = torch.randint(0, T, (B,), device=x.device)
    t_idx = torch.arange(T, device=x.device)
    end = torch.clamp(start + span, max=T)
    cut = do[:, None] & (t_idx[None, :] >= start[:, None]) & (t_idx[None, :] < end[:, None])
    return x.masked_fill(cut[:, :, None], 0.0)


def set_lr(opt, step, total, base):
    warm = min(40, max(total // 10, 1))
    if step < warm:
        lr = base * (step + 1) / warm
    else:
        p = (step - warm) / max(total - warm, 1)
        lr = 1e-5 + 0.5 * (base - 1e-5) * (1.0 + math.cos(math.pi * p))
    for group in opt.param_groups:
        group["lr"] = lr
    return lr


def ema_update(src, dst, decay):
    with torch.no_grad():
        for ps, pd in zip(src.parameters(), dst.parameters()):
            pd.mul_(decay).add_(ps, alpha=1.0 - decay)


def train_model(cfg, datasets, feat, device, steps):
    name, family, window, d_model, nlayers, stem, lr = cfg
    groups, y_all = trial_groups(feat[family], datasets)
    mu, sd = norm_stats(feat[family], datasets)
    pos = float(y_all.mean())
    pos_weight = torch.tensor([(1.0 - pos) / max(pos, 1e-3)], device=device)
    c_in = groups[0]["trials"][0][0].shape[1]
    torch.manual_seed(TRAIN_SEED)
    if device.type == "cuda":
        torch.cuda.manual_seed_all(TRAIN_SEED)
    model = LogitTransformer(c_in, window, d_model=d_model, nlayers=nlayers, stem=stem).to(device)
    ema = copy.deepcopy(model).eval()
    opt = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=1e-4)
    rng = np.random.default_rng(TRAIN_SEED)
    model.train()
    t0 = time.time()
    last = None
    for step in range(steps):
        set_lr(opt, step, steps, lr)
        xb, yb, mb = sample_batch(rng, groups, window, BATCH, mu, sd)
        x = torch.from_numpy(xb).to(device, non_blocking=True)
        y = torch.from_numpy(yb).to(device, non_blocking=True)
        m = torch.from_numpy(mb).to(device, non_blocking=True)
        x = augment(x)
        opt.zero_grad(set_to_none=True)
        logit = model(x)
        sw = switch_weights(y, m)
        bce = F.binary_cross_entropy_with_logits(logit, y, pos_weight=pos_weight, reduction="none")
        denom = (sw * m).sum().clamp_min(1.0)
        loss = (bce * sw * m).sum() / denom
        dv = (logit[:, 1:] - logit[:, :-1]).abs()
        m2 = m[:, 1:] * m[:, :-1]
        loss = loss + 0.05 * (dv * m2).sum() / m2.sum().clamp_min(1.0)
        if not torch.isfinite(loss):
            raise RuntimeError(f"non-finite loss at step {step} for {name}")
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        opt.step()
        ema_update(model, ema, 0.995)
        last = float(loss.item())
    ema.eval()
    acc = train_frame_acc(ema, groups, window, mu, sd, device)
    print(f"  trained {name} on {'+'.join(datasets)}  loss {last:.3f}  frame-acc {acc:.3f}  "
          f"({time.time() - t0:.0f}s)", flush=True)
    return ema, mu, sd


def train_frame_acc(model, groups, window, mu, sd, device):
    rng = np.random.default_rng(0)
    xb, yb, mb = sample_batch(rng, groups, window, 2048, mu, sd)
    with torch.no_grad():
        logit = model(torch.from_numpy(xb).to(device))
    pred = (logit[:, -1] > 0).cpu().numpy()
    return float((pred == (yb[:, -1] > 0.5)).mean())


@torch.no_grad()
def infer_all(model, feat_ds, mu, sd, window, device):
    model.eval()
    out = {}
    mu_t = torch.from_numpy(mu.reshape(1, 1, -1))
    sd_t = torch.from_numpy(sd.reshape(1, 1, -1))
    for ds, table in feat_ds.items():
        out[ds] = {}
        for key, X in table.items():
            T, C = X.shape
            pad = np.zeros((window - 1, C), np.float32)
            xp = torch.from_numpy(np.concatenate([pad, X], 0))
            pieces = []
            for i in range(0, T, 2048):
                sl = xp[i:i + 2048 + window - 1]
                w = sl.unfold(0, window, 1).permute(0, 2, 1).contiguous()
                w = (w - mu_t) / sd_t
                pieces.append(model(w.to(device))[:, -1].cpu().numpy())
            pred = np.concatenate(pieces).astype(np.float64)
            if len(pred) != T:
                raise RuntimeError(f"length {len(pred)} != {T} for {key}")
            out[ds][key] = pred
    return out


def assert_causal(device):
    torch.manual_seed(0)
    model = LogitTransformer(8, 16, d_model=32, nlayers=1, stem=True).to(device).eval()
    x = torch.randn(2, 16, 8, device=device)
    x2 = x.clone()
    x2[:, -1] = torch.randn(2, 8, device=device)
    with torch.no_grad():
        y1 = model(x)
        y2 = model(x2)
    if not torch.allclose(y1[:, :-1], y2[:, :-1], atol=1e-5):
        raise RuntimeError("transformer readout is not causal")
    print("causality check passed", flush=True)


def average_streams(stream_list):
    out = {}
    for ds in stream_list[0]:
        out[ds] = {}
        for key, v0 in stream_list[0][ds].items():
            acc = np.array(v0, copy=True)
            for other in stream_list[1:]:
                acc += other[ds][key]
            out[ds][key] = acc / len(stream_list)
    return out


def triplet_key(excluded):
    return "ex-" + "-".join(excluded)


def select_rule(m, thr):
    picks = []
    n_ok = 0
    for _, g in m.groupby("outer"):
        ok = g[g.Acc >= thr]
        if len(ok):
            n_ok += 1
            picks.append(ok.sort_values(["H", "Acc", "SDT"], ascending=[False, False, True]).iloc[0])
        else:
            picks.append(g.sort_values(["Acc", "H", "SDT"], ascending=[False, False, True]).iloc[0])
    return pd.DataFrame(picks).reset_index(drop=True), n_ok


def score_pick(streams, ds, p_stay, scale):
    ev = N.to_ev(streams)
    return N.official(ds, ev, float(p_stay), float(scale))


def wanted_configs():
    only = os.environ.get("ONLY", "").strip()
    if not only:
        return list(CONFIGS)
    names = {n.strip() for n in only.split(",") if n.strip()}
    cfgs = [c for c in CONFIGS if c[0] in names]
    missing = names - {c[0] for c in cfgs}
    if missing:
        raise SystemExit(f"unknown ONLY names: {sorted(missing)}")
    return cfgs


def log_line(text):
    print(text, flush=True)
    os.makedirs(os.path.dirname(LOG), exist_ok=True)
    with open(LOG, "a") as fh:
        fh.write(text + "\n")


def main():
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    log_line(f"device {device}  steps {STEPS}  batch {BATCH}")
    torch.backends.cuda.matmul.allow_tf32 = True
    torch.backends.cudnn.allow_tf32 = True
    N.load_all()
    checks = N.check_fast_matches_official()
    base_H = float(np.mean([c[1]["H"] for c in checks]))
    base_Acc = float(np.mean([c[1]["Acc"] for c in checks]))
    log_line(f"reproduced lda4 @ 0.998  H {base_H:.4f}  Acc {base_Acc:.2f}")
    if abs(base_H - 0.7965) > 5e-4 or abs(base_Acc - 73.01) > 0.02:
        raise RuntimeError("baseline reproduction does not match the published LDA numbers")
    assert_causal(device)
    feat = build_features()
    os.makedirs(CKPT, exist_ok=True)
    cfgs = wanted_configs()

    if os.environ.get("SMOKE"):
        cfg = cfgs[0]
        train_ds = [d for d in DS_KEYS if d not in ("AVGC", "DTU")]
        model, mu, sd = train_model(cfg, train_ds, feat, device, steps=min(STEPS, 40))
        streams = infer_all(model, feat[cfg[1]], mu, sd, cfg[2], device)
        mu_e, sd_e = N.emis({d: streams[d] for d in train_ds}, train_ds)
        t1 = time.time()
        r = N.evaluate("DTU", streams["DTU"], mu_e, sd_e * 0.9, 0.996)
        log_line(f"smoke DTU inner H {r['H']:.4f} Acc {r['Acc']:.2f} L {r['L']:.3f} "
                 f"({time.time() - t1:.1f}s)")
        return

    cache = {}
    rows = []
    excluded_pairs = []
    for i, a in enumerate(DS_KEYS):
        for b in DS_KEYS[i + 1:]:
            excluded_pairs.append((a, b))

    def score_name(name):
        for outer in DS_KEYS:
            for inner_ds in DS_KEYS:
                if inner_ds == outer:
                    continue
                train_ds = [d for d in DS_KEYS if d not in (outer, inner_ds)]
                streams = cache[(name, outer, inner_ds)]
                mu, sd = N.emis({d: streams[d] for d in train_ds}, train_ds)
                for p in P_STAY:
                    for scale in SCALES:
                        r = N.evaluate(inner_ds, streams[inner_ds], mu, sd * scale, p)
                        rows.append(dict(outer=outer, inner=inner_ds, model=name, p_stay=p,
                                         scale=scale, **r))
        sub = pd.DataFrame([r for r in rows if r["model"] == name])
        grouped_one = sub.groupby(["outer", "p_stay", "scale"])[["H", "Acc", "SDT"]].mean().reset_index()
        picks, n_ok = select_rule(grouped_one.assign(model=name), THR)
        log_line(f"inner {name}: {n_ok}/5 Acc>=74  H {picks.H.mean():.4f} Acc {picks.Acc.mean():.2f}")

    for cfg in cfgs:
        name, family, window = cfg[0], cfg[1], cfg[2]
        for a, b in excluded_pairs:
            train_ds = [d for d in DS_KEYS if d not in (a, b)]
            model, mu, sd = train_model(cfg, train_ds, feat, device, STEPS)
            path = os.path.join(CKPT, f"{name}__{triplet_key((a, b))}.pt")
            torch.save({"state": model.state_dict(), "mu": mu, "sd": sd, "cfg": cfg,
                        "train": train_ds}, path)
            streams = infer_all(model, feat[family], mu, sd, window, device)
            cache[(name, a, b)] = streams
            cache[(name, b, a)] = streams
            del model
            if device.type == "cuda":
                torch.cuda.empty_cache()
        score_name(name)

    names = [c[0] for c in cfgs]
    if len(names) >= 2:
        for a, b in excluded_pairs:
            avg = average_streams([cache[(n, a, b)] for n in names])
            cache[("ens_all", a, b)] = avg
            cache[("ens_all", b, a)] = avg
        model_names = names + ["ens_all"]
        score_name("ens_all")
    else:
        model_names = names

    inner = pd.DataFrame(rows)
    os.makedirs(os.path.dirname(INNER), exist_ok=True)
    inner.to_csv(INNER, index=False)
    log_line(f"wrote {INNER}")
    grouped = inner.groupby(["outer", "model", "p_stay", "scale"])[["H", "Acc", "SDT", "L", "acc1"]].mean().reset_index()

    refit = {}

    def streams_for(name, outer):
        key = (name, outer)
        if key in refit:
            return refit[key]
        if name == "ens_all":
            parts = [streams_for(n, outer) for n in names]
            refit[key] = average_streams(parts)
            return refit[key]
        cfg = next(c for c in cfgs if c[0] == name)
        train_ds = [d for d in DS_KEYS if d != outer]
        model, mu, sd = train_model(cfg, train_ds, feat, device, STEPS)
        path = os.path.join(CKPT, f"{name}__held-{outer}.pt")
        torch.save({"state": model.state_dict(), "mu": mu, "sd": sd, "cfg": cfg, "train": train_ds}, path)
        refit[key] = infer_all(model, feat[cfg[1]], mu, sd, cfg[2], device)
        del model
        if device.type == "cuda":
            torch.cuda.empty_cache()
        return refit[key]

    out_rows = []

    def emit(role, picks):
        for _, b in picks.iterrows():
            streams = streams_for(b.model, b.outer)
            off = score_pick(streams, b.outer, b.p_stay, b.scale)
            out_rows.append(dict(role=role, ds=b.outer, model=b.model, p_stay=float(b.p_stay),
                                 scale=float(b.scale), H=off["H"], Acc=off["Acc"], SDT=off["SDT"],
                                 L=off["L"], acc1=off["acc1"], inner_H=float(b.H), inner_Acc=float(b.Acc),
                                 scorer="official"))
            log_line(f"{role} {b.outer} {b.model} p {b.p_stay} sc {b.scale}  "
                     f"H {off['H']:.4f} Acc {off['Acc']:.2f} SDT {off['SDT']:.2f} L {off['L']:.3f}")

    picks, n_ok = select_rule(grouped, THR)
    log_line(f"select acc74: {n_ok}/5 folds reached inner Acc>={THR:g}  "
             f"inner H {picks.H.mean():.4f} Acc {picks.Acc.mean():.2f}")
    for _, b in picks.iterrows():
        log_line(f"  {b.outer} {b.model} p {b.p_stay} sc {b.scale}  inner H {b.H:.4f} Acc {b.Acc:.2f}")
    emit("acc74", picks)

    for name in model_names:
        sub = grouped[grouped.model == name]
        fp, n_ok = select_rule(sub, THR)
        log_line(f"family {name}: {n_ok}/5 inner Acc>=74  inner H {fp.H.mean():.4f} Acc {fp.Acc.mean():.2f}")
        emit(f"family_{name}", fp)

    df = pd.DataFrame(out_rows)
    df.to_csv(OUT, index=False)
    log_line("means:")
    for role, sub in df.groupby("role"):
        m = sub[["H", "Acc", "SDT", "L", "acc1"]].mean()
        log_line(f"  {role:20s}  H {m.H:.4f}  Acc {m.Acc:.2f}  SDT {m.SDT:.2f}  L {m.L:.3f}  acc1 {m.acc1:.3f}")
    prim = df[df.role == "acc74"]
    h, acc = float(prim.H.mean()), float(prim.Acc.mean())
    log_line(f"PRIMARY acc74  H {h:.4f}  Acc {acc:.2f}")
    log_line(f"goal H>0.85 and Acc>80: {bool(h > 0.85 and acc > 80)}")
    log_line(f"wrote {OUT}")


if __name__ == "__main__":
    main()
