"""灯りの虫: 実際のトンボは背が傾いたとき推力を増やして高さを保っているか（2026-11-11 20:4x）。
模型 C（高さを保つ推力 ALT）の仮定を、Fabian 2024 のモーションキャプチャで直接見る。
空気から受ける力（体重あたり）= 加速度 − 重力。速度を時間で差分し、移動平均でならしてから、
背の軸への成分 a_d と、上向きの成分 a_z を、背の傾き（鉛直からの角）の区切りごとに出す。
傾いたぶん推力を増やしているなら a_d は 1/cos(傾き) に近く増え、a_z は 9.8 m/s² 付近に保たれる。
使い方（リポジトリ直下から）: uv run python ayumu-lab/research/insect-light/thrust_tilt.py <Motion Capture Data のフォルダ>
"""
import sys, os
import numpy as np, pandas as pd
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import fabian_io

D = sys.argv[1]
W = int(os.environ.get("SMOOTH", "5"))   # 移動平均のコマ数（羽ばたきの揺れをならす）
LAMP = {1: "tube", 2: "down", 3: "up"}
rows = []
for r, tr in fabian_io.tracks(D, species=(2,), lighting=(1,), bulbs=(1, 2, 3)):
    t, v = tr["t"], tr["vel"]
    if len(t) < 3 * W: continue
    dt = np.median(np.diff(t))
    k = np.ones(W) / W
    vs = np.column_stack([np.convolve(v[:, i], k, mode="same") for i in range(3)])
    a = np.gradient(vs, dt, axis=0) + np.array([0, 0, 9.81])   # 空気からの力（体重あたり）
    m = tr["flying"] & (tr["speed"] > 0.3) & np.isfinite(tr["range"]) & (tr["range"] < 0.8) & np.isfinite(a).all(1)
    m[:W] = False; m[-W:] = False
    if m.sum() < 10: continue
    dz = tr["dorsal"][m]
    tilt = np.degrees(np.arccos(np.clip(dz[:, 2], -1, 1)))
    rows.append(pd.DataFrame(dict(lamp=LAMP[int(r.Bulb)], rec=int(r.Recording), tilt=tilt,
                                  a_d=(a[m] * dz).sum(1), a_z=a[m][:, 2], vz=v[m][:, 2],
                                  a_f=(a[m] * tr["forward"][m]).sum(1), a_l=(a[m] * tr["lateral"][m]).sum(1),
                                  force_tilt=np.degrees(np.arccos(np.clip(a[m][:, 2] / np.maximum(np.linalg.norm(a[m], axis=1), 1e-9), -1, 1))),
                                  nose=tr["nose_elev"][m])))
F = pd.concat(rows, ignore_index=True)
print(f"刻み {dt:.4f} 秒、移動平均 {W} コマ、コマ {len(F)}")
bins = [0, 15, 30, 45, 60, 75, 90, 180]
F["b"] = pd.cut(F.tilt, bins)
g = F.groupby(["b"], observed=True)
out = g.agg(n=("a_d", "size"), a_d=("a_d", "median"), a_f=("a_f", "median"), a_l=("a_l", "median"), a_z=("a_z", "median"), force_tilt=("force_tilt", "median"), nose=("nose", "median"), vz=("vz", "median"))
c0 = out.a_d.iloc[0]
out["1/cos 予想"] = [c0 / max(np.cos(np.radians((iv.left + min(iv.right, 90)) / 2)), 1 / 3) for iv in out.index]
# 録画の回ごとの、傾き 0〜30° に対する 45〜90° の a_d の比
per = []
for rec, h in F.groupby("rec"):
    lo = h[h.tilt < 30].a_d; hi = h[(h.tilt >= 45) & (h.tilt < 90)].a_d
    if len(lo) >= 20 and len(hi) >= 20: per.append((h.lamp.iloc[0], rec, round(hi.median() / lo.median(), 2), len(hi)))
print(out.round(2).to_string())
print("録画の回ごとの a_d の比（傾き 45〜90° ÷ 0〜30°）:", per)
print("比の中央値:", np.median([p[2] for p in per]) if per else None, "（1/cos の予想は 45〜90° の中ほど 67° で約 2.6）")
# 灯りごとの力の向きの傾き（背の傾きの区切りごと、中央値）
print(F.groupby(["lamp", "b"], observed=True).agg(n=("a_d", "size"), force_tilt=("force_tilt", "median"), nose=("nose", "median"), a_z=("a_z", "median")).round(1).unstack(0).to_string())
# 体の中での力の向き: 背の軸から前へ何度傾いているか（atan2(a_f, a_d)）。模型は前 5・背 15 で 18.4°
F["fwd_ang"] = np.degrees(np.arctan2(F.a_f, F.a_d))
print("体の中での力の前への傾き（度、中央値）")
print(F.groupby(["lamp", "b"], observed=True).fwd_ang.median().round(1).unstack(0).to_string())
print("全体:", F.groupby("lamp").fwd_ang.median().round(1).to_dict())
