# 図1: 横から見た軌道。純粋な DLR（灯りの手前で降りる）と、高さを保つ版（灯りへ入る・回る）。運動は xsec.run と同じ式。
import os; EN=os.environ.get('FIG_LANG')=='en'; T=lambda ja,en: en if EN else ja  # FIG_LANG=en で英語の図（*_en.png）
import numpy as np, matplotlib; matplotlib.use('Agg')
import matplotlib.pyplot as plt, os
from matplotlib import font_manager as fm
from xsec import G, DT, RC, LAMP
fp='/mnt/c/Windows/Fonts/YuGothM.ttc'; fm.fontManager.addfont(fp)
plt.rcParams['font.family']=[fm.FontProperties(fname=fp).get_name(),'sans-serif']
def traj(I, level, B=1.0, k=8.0, X0=32.0, speed=1.5, noise=0.3, course=1.0, n=14, seed=3, T=50.0):
    rng=np.random.default_rng(seed)
    b=np.linspace(-1.2,1.2,n); z=np.linspace(0.8,2.8,n)[rng.permutation(n)]
    p=np.column_stack([-X0*np.ones(n),b,z]); z0=z.copy(); f=np.tile([1.0,0,0],(n,1)); v=f*speed; u=np.tile([0,0,1.0],(n,1))
    done=np.zeros(n,bool); hist=[p.copy()]
    for s in range(int(T/DT)):
        d=LAMP-p; r=np.linalg.norm(d,axis=1,keepdims=True)+1e-3
        bv=np.tile([0,0,B],(n,1))+I*d/r**3; bh=bv/np.linalg.norm(bv,axis=1,keepdims=True)
        u=u+k*DT*(bh-(bh*u).sum(1,keepdims=True)*u); u/=np.linalg.norm(u,axis=1,keepdims=True)
        f=f+course*DT*np.array([1.0,0,0])+noise*np.sqrt(DT)*rng.standard_normal((n,3))
        f-=(f*u).sum(1,keepdims=True)*u; f/=np.linalg.norm(f,axis=1,keepdims=True)
        thr=G*np.clip(1/np.maximum(u[:,2:3],1e-3),1,2.0) if level else G
        tgt=speed*f
        if level: tgt=np.column_stack([tgt[:,:2],0.5*(z0-p[:,2])])
        acc=thr*u-np.array([0,0,G])+3.0*(tgt-v)
        v=np.where(done[:,None],0,v+acc*DT); p=p+v*DT
        done|=(r[:,0]<RC)|(p[:,2]<=0)|(p[:,0]>12)
        p[:,2]=np.maximum(p[:,2],0)
        if s%10==0: hist.append(p.copy())
        if done.all(): break
    return np.array(hist)
fig,axs=plt.subplots(2,1,figsize=(7.2,5.6),sharex=True)
for ax,level,title in ((axs[0],False,T('純粋な DLR（推力 = 体重）: 灯りの手前で地面に降りる','Pure DLR (thrust = weight): insects land short of the lamp')),(axs[1],True,T('高さを保つ版（推力の上限 2g、元の高さへ戻る制御）: 灯りに入る・まわりを回る','Height-holding version (thrust limit 2g, return to original height): insects reach and circle the lamp'))):
    H=traj(64.0,level)
    for i in range(H.shape[1]): ax.plot(H[:,i,0],H[:,i,2],color='#1f5fa8',lw=0.9,alpha=0.75)
    ends=H[-1]; ax.plot(ends[:,0],ends[:,2],'o',color='#1f5fa8',ms=3)
    ax.plot([0],[LAMP[2]],marker='*',color='#e0a400',ms=16,mec='#7a5a00',zorder=5)
    ax.axhline(0,color='#555',lw=1); ax.set_ylim(-0.1,3.4); ax.set_xlim(-32,12)
    ax.set_title(title,fontsize=10,loc='left'); ax.set_ylabel(T('高さ z [m]','height z [m]'))
    ax.spines[['top','right']].set_visible(False)
axs[1].set_xlabel(T('灯りからの距離 x [m]（虫は左から右へ飛ぶ、I/B = 64、r* = 8 m、k = 8 /s）','distance from lamp x [m] (insects fly left to right; I/B = 64, r* = 8 m, k = 8 /s)'))
fig.tight_layout(); fig.savefig(T('fig_traj.png','fig_traj_en.png'),dpi=150)
