"""
Goal-oriented projection with symbolic features
===============================================

Dimension reduction optimizes a cost: variance for principal components,
distances for Sammon mapping. Dörgő, Kulcsár and Abonyi (2021) proposed to define
the cost by the goal of the analysis and to find the projection functions by
multi-gene genetic programming, so that the map is made of a few explicit,
interpretable equations. :class:`~eqdisco.SymbolicTransformer` evolves two
features that separate the three cultivars of the wine data set (goal
``"fisher"``) and compares the map with the first two principal components.
"""

import matplotlib.pyplot as plt
from sklearn.datasets import load_wine
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler

import eqdisco as eq

data = load_wine()
X, y = data.data, data.target
names = [n.replace("/", "_").replace("od280_od315_of_diluted_wines", "od280") for n in data.feature_names]

# %%
# Two symbolic features
# ---------------------
st = eq.SymbolicTransformer(n_components=2, goal="fisher", population_size=250, generations=30, functions=("add", "sub", "mul", "div", "log"), variable_penalty=0.002, feature_names=names, random_state=0)
Z = st.fit_transform(X, y)
for k, e in enumerate(st.equations_):
    print(f"z{k} =", e)
P = PCA(2).fit_transform(StandardScaler().fit_transform(X))
fig, axs = plt.subplots(1, 2, figsize=(10, 3.8))
for ax, M, title in ((axs[0], P, "principal components (13 variables)"), (axs[1], Z, "two symbolic features")):
    for c in range(3):
        ax.scatter(M[y == c, 0], M[y == c, 1], s=12, color=eq.viz.OKABE_ITO[c], label=data.target_names[c])
    ax.set_title(title, fontsize=9)
    ax.set_xticks([])
    ax.set_yticks([])
axs[1].set_xlabel("$z_0$ = " + str(st.equations_[0])[:45], fontsize=8)
axs[1].set_ylabel("$z_1$ = " + str(st.equations_[1])[:45], fontsize=8)
axs[0].legend(frameon=False, fontsize=8)
fig.tight_layout()

# %%
# Parameter study: the goal
# -------------------------
goals = ["fisher", "knn", "sammon"]
fig, axs = plt.subplots(1, 3, figsize=(11, 3.2))
for ax, g in zip(axs, goals):
    m = eq.SymbolicTransformer(n_components=2, goal=g, population_size=150, generations=20, functions=("add", "sub", "mul", "div", "log"), random_state=0)
    Zg = m.fit_transform(X, y if g != "sammon" else None)
    for c in range(3):
        ax.scatter(Zg[y == c, 0], Zg[y == c, 1], s=8, color=eq.viz.OKABE_ITO[c])
    used = sorted({v for e in m.equations_ for v in e.variables})
    print(f"goal {g}: variables used: {used}")
    ax.set_title(f"goal {g}: {len(used)} variables", fontsize=9)
    ax.set_xticks([])
    ax.set_yticks([])
plt.show()
