"""第7章 検算：最大ニューロンと衝突の重みで解く巡回セールスマン問題（筆者が工夫して確かめた版）

Hopfield & Tank の当時のコードは見ていない。論文の式からの筆者の実装は ch07_hopfield_tank.py。
この版は論文の方法そのものではない。

第8章の四色問題で 100/100 になった組み合わせ（ch08_fourcolor_maxneuron.py）を、
Hopfield & Tank (1985) と同じ n×n の表し方（都市 X × 訪問の順番 i）に当てはめる。

  最大ニューロン：都市 X の行で、入力 U_Xi が最大の1つだけ発火（＝都市 X を i 番目に訪れる）。
                  「各都市を1回だけ」は構造で守られる（原典の A の項が要らない）。
  入力：          U_Xi = - B * w_i * sum_{Y!=X} V_Yi          （順番 i にほかの都市がいる罰）
                         - D * sum_Y d_XY (V_Y,i+1 + V_Y,i-1)    （原典と同じ距離の項）
                  w_i は順番 i の「衝突の重み」、最初は1。同点は今の位置を優先、なければ無作為。
  更新：          非同期。都市を無作為な順に1つずつ。
  局所最小：      1巡でどの都市も動かず、まだ同じ順番に2都市以上いたら、その順番の w_i を1増やす。
  終了：          1巡でどの都市も動かず、どの順番にも都市が1つずつ（正しい巡回路）になったら。

都市の配置・最短の長さ・判定は ch07_hopfield_tank.py と同じ（10都市、1辺1の正方形、総当たりで最短）。
B・D は筆者が決めた（下の定数）。どの都市の配置にも同じ値を使う。
"""
import sys

import numpy as np

from ch07_hopfield_tank import best_tour, tour_length

N_CITY = 10
TRIALS = 20
B = 1.0
D = 1.0
MAX_SWEEPS = 2000


def run(d, rng):
    n = len(d)
    pos = rng.integers(0, n, n)                      # 都市 X の順番（最初は無作為）
    w = np.ones(n)
    for _ in range(MAX_SWEEPS):
        moved = False
        for X in rng.permutation(n):
            V = np.zeros((n, n))
            V[np.arange(n), pos] = 1.0
            V[X] = 0.0                               # 自分を除いたほかの都市の配置
            occ = V.sum(axis=0)                      # 順番 i にいるほかの都市の数
            nb = np.roll(V, -1, axis=1) + np.roll(V, 1, axis=1)
            U = -B * w * occ - D * (d[X] @ nb)
            cand = np.flatnonzero(np.isclose(U, U.max()))
            if pos[X] in cand:
                p = pos[X]
            else:
                p = int(cand[0]) if len(cand) == 1 else int(rng.choice(cand))
            if p != pos[X]:
                pos[X] = p
                moved = True
        counts = np.bincount(pos, minlength=n)
        if not moved:
            if (counts == 1).all():
                order = list(np.argsort(pos))
                return order
            w[counts > 1] += 1.0                     # 局所最小：衝突している順番の重みを増やす
    return None


def main():
    seeds = [int(s) for s in sys.argv[1:]] or [1, 2, 3, 4, 5, 6]
    print(f"Python {sys.version.split()[0]} / NumPy {np.__version__}")
    print(f"都市 {N_CITY}、各配置 {TRIALS} 回、B={B} D={D}")
    for seed in seeds:
        rng_city = np.random.default_rng(seed)
        xy = rng_city.uniform(0.0, 1.0, size=(N_CITY, 2))
        d = np.sqrt(((xy[:, None, :] - xy[None, :, :]) ** 2).sum(axis=2))
        L_best = best_tour(d)
        rng = np.random.default_rng(1000 + seed)
        lens = []
        for _ in range(TRIALS):
            order = run(d, rng)
            if order is not None:
                lens.append(tour_length(order, d))
        hits = sum(1 for L in lens if L <= L_best * 1.0001)
        ratio = np.mean(lens) / L_best if lens else float("nan")
        print(f"seed={seed} 最短={L_best:.4f}  正しい巡回路 {len(lens):2d}/{TRIALS}  最短と同じ {hits:2d}/{TRIALS}"
              f"  平均は最短の {ratio:.3f} 倍", flush=True)


if __name__ == "__main__":
    main()
