"""灯りの虫: 機首と 100 ms 後・100 ms 前の加速の相関を、模型 B（管・上向き、種 1〜3）で観察と同じ尺度で出す（2026-11-12）。
機首の角度は時間を逆にしても変わらず、速さの変化は符号が変わる。逆再生しても同じ統計になる過程なら 後 = −前 で、和が 0 になる。
和（時間反転で消えない成分）を観察（force_vs_back.py の 4 節）と比べる。
速さは 5 コマ（観察 0.00417 s × 5 ≈ 21 ms）と同じ幅でならし、時間で微分。虫ごとに、0.1〜0.8 m に途切れずいた区間のうち 200 コマ以上のものを使う。
使い方（リポジトリ直下から）: python3 ayumu-lab/research/insect-light/nose_acc_reversal.py
"""
import os, sys, json, subprocess, tempfile
from concurrent.futures import ThreadPoolExecutor
import numpy as np
here = os.path.dirname(os.path.abspath(__file__))
TUBE = dict(K1="6", K2="1", VT="2.0", PEXP="0.5", PEXP_GEOM="max", G2="5")
UP = dict(K1="6", K2="1", VT="1.3", PEXP="0.5", HALF="100", GLOW="0.3", G2="5")
DT = 0.00125; K = round(0.1 / DT); W = round(5 * 0.00417 / DT)
HP = round(0.5 / DT) if os.environ.get("DETREND") else 0   # DETREND=1 で 0.5 秒より遅い変化を抜く
tmp = tempfile.mkdtemp(prefix="nose_acc_rev_")


def run(lamp, seed):
    base, shape = (TUBE, "tubew") if lamp == "tube" else (UP, "bup")
    out = os.path.join(tmp, f"{lamp}_{seed}.npy")
    env = dict(os.environ, **base, DT=str(DT), RRANGE="0.1,0.8", DUMP=out)
    subprocess.run([sys.executable, os.path.join(here, "fabian_model.py"), "300", str(seed), "1.0", shape], env=env,
                   stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
    R = np.load(out); os.remove(out)
    res = []
    for i in np.unique(R[:, 0]):
        S = R[R[:, 0] == i]; t = S[:, 12]
        cut = np.nonzero(np.diff(t) > 1.5 * DT)[0] + 1
        for seg in np.split(np.arange(len(t)), cut):
            if len(seg) < 200 + 2 * K + 2 * HP: continue
            s = np.convolve(S[seg, 7], np.ones(W) / W, mode="same"); ds = np.gradient(s, DT)[W:-W]; n = S[seg, 9][W:-W]
            if HP:   # 0.5 秒より遅い変化を抜く（中心の移動平均を引く）
                m = np.ones(HP) / HP; x = (n - np.convolve(n, m, mode="same"))[HP:-HP]; y = (ds - np.convolve(ds, m, mode="same"))[HP:-HP]
            else: x = n - n.mean(); y = ds - ds.mean()
            res.append((np.corrcoef(x[:-K], y[K:])[0, 1], np.corrcoef(x[K:], y[:-K])[0, 1]))
    return res


OUT = {}
with ThreadPoolExecutor(2) as ex:
    jobs = [(l, s) for l in ("tube", "up") for s in (1, 2, 3)]
    for (l, s), res in zip(jobs, ex.map(lambda j: run(*j), jobs)):
        a = np.array(res); OUT[f"{l}|{s}"] = dict(n=len(a), after=float(np.median(a[:, 0])), before=float(np.median(a[:, 1])), sum=float(np.median(a[:, 0]) + np.median(a[:, 1])))   # 観察と同じく、後と前の中央値の和
        print(l, s, {k: round(v, 2) if isinstance(v, float) else v for k, v in OUT[f"{l}|{s}"].items()})
json.dump(OUT, open(os.path.join(here, "nose_acc_reversal_detrend.json" if HP else "nose_acc_reversal.json"), "w"), ensure_ascii=False, indent=1)
