"""
Simulated annealing: mCLASA and GDFCMSA
=======================================

Placing :math:`K^+` additional sensors to minimize the cost is a medoid problem on the
network (every state belongs to its nearest sensor). Leitold, Vathy-Fogarassy and
Abonyi solved it by simulated annealing: *mCLASA* replaces a random additional sensor by
a random state, *GDFCMSA* draws the replacement from the fuzzy memberships of the
states in the removed sensor, computed with geodesic distances and a fuzziness
exponent that falls from 10 to 2 during the run. The nodes required for observability
are kept fixed.
"""

# %%
# Cost against the number of additional sensors
# ---------------------------------------------
import matplotlib.pyplot as plt
import numpy as np

import nocad
from nocad.datasets import make_hen_case_study
from nocad.distances import geodesic_distances, placement_cost
from nocad.placement import Placement, anneal
from nocad.viz import plot_placement_history

hen = make_hen_case_study()
hist = {}
# [snippet:annealing]
for method in ("mclasa", "gdfcmsa"):
    p = Placement(kind="sensors", method=method, r_max=0, n_iter=400, n_runs=5, random_state=0).fit(hen.adj)
    hist[method] = p.history_
    print(method, p.history_[["n_added", "cost", "max_order", "mean_order"]].round(3).to_string(index=False))
# [/snippet:annealing]
fig, axes = plt.subplots(1, 2, figsize=(9.6, 3.4))
plot_placement_history(hist, ax=axes[0], value="cost", title="best cost of 5 runs")
plot_placement_history(hist, ax=axes[1], value="max_order", title="maximal relative order")
fig.tight_layout()

# %%
# Parameter study: iterations and convergence
# -------------------------------------------
# Mean and spread of the final cost of 20 independent runs with :math:`K^+=4` against the
# number of iterations: the membership-guided moves of GDFCMSA reach good
# configurations with fewer iterations.
G = nocad.as_adjacency(hen.adj).T
D = geodesic_distances(G)
D[~np.isfinite(D)] = D.shape[0]
fixed = nocad.sensor_nodes(hen.adj)
iters = [25, 50, 100, 200, 400]
rng = np.random.default_rng(0)
fig, ax = plt.subplots(figsize=(5.2, 3.4))
for k, method in enumerate(("mclasa", "gdfcmsa")):
    mean, lo, hi = [], [], []
    for it in iters:
        c = [placement_cost(D, anneal(D, fixed, 4, method=method, n_iter=it, rng=rng)[0])[0] for _ in range(20)]
        mean.append(np.mean(c))
        lo.append(np.percentile(c, 10))
        hi.append(np.percentile(c, 90))
    col = nocad.plotting.PALETTE[k]
    ax.plot(iters, mean, marker="os"[k], color=col, label=method)
    ax.fill_between(iters, lo, hi, color=col, alpha=0.15)
ax.set_xscale("log")
ax.set_xticks(iters, [str(i) for i in iters])
ax.minorticks_off()
ax.set_xlabel("iterations per run")
ax.set_ylabel("final cost ($K^+$ = 4)")
ax.set_title("convergence of the annealing methods", fontsize=10)
ax.grid(True, color="0.9")
ax.legend(frameon=False, fontsize=8)
fig.tight_layout()

# %%
# **Take-away.** Both annealing methods reduce the relative order steadily as sensors
# are added; guiding the moves by fuzzy memberships makes the search converge faster.
