"""
Fuzzy partitions and robot paths: geometry an expert can judge
==============================================================

Two design problems whose quality is easy to see and hard to write down. A
fuzzy partition of an input variable should be ordered, cover the domain, and
not overlap too much — the interpretability criteria of fuzzy modelling
(Setnes et al., 1998; Gacto et al., 2011). A robot path should be short,
smooth and keep a safe distance from obstacles. Both problems are *editable*:
a person may drag a peak of a membership function or a via point of the path.
"""

# %%
# Interpretable fuzzy partitions
# ------------------------------
import matplotlib.pyplot as plt

import easyiec as ei
from easyiec.problems import FuzzyPartitionDesign, PathPlanning
from easyiec.strategies import InteractiveES, InteractiveGA

fuzzy = FuzzyPartitionDesign(n_terms=5)
user = ei.SimulatedUser(fuzzy, target="uniform Ruspini", noise=0.04, seed=1)
res_f = ei.run(fuzzy, InteractiveES(pop_size=9), user, generations=12, seed=1)
print({k: round(v, 3) for k, v in fuzzy.objectives(res_f.best.genome).items()})
ei.viz.plot_history(res_f.log, fuzzy, steps=[0, 4, 11], max_items=9, size=1.0)

# %%
# Collision-free paths
# --------------------
# The simulated operator penalizes collisions strongly, length and curvature
# mildly, and rewards clearance. The landscape is rugged — a small move of a
# via point can cut through an obstacle — and the best path an offline
# optimizer finds with the same utility scores about 0.8.
paths = PathPlanning(n_via=5, n_obstacles=8, seed=0)
user = ei.SimulatedUser(paths, target=None, noise=0.04, seed=2)
res_p = ei.run(paths, InteractiveGA(pop_size=9), user, generations=25, seed=2)
ei.viz.plot_history(res_p.log, paths, steps=[0, 8, 16, 24], max_items=9, size=0.95)
print({k: round(v, 3) for k, v in paths.objectives(res_p.best.genome).items()}, round(res_p.best_true, 3))
plt.show()
