import os
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D  # noqa: F401
from common import load_iris, FEATURES, CLASSES, COLORS, MEDIA

os.makedirs(MEDIA, exist_ok=True)
X, y = load_iris()
SL, SW, PL, PW = 0, 1, 2, 3

plt.rcParams.update({"font.family": ["Arial", "DejaVu Sans"], "font.size": 11})


def save(fig, name):
    path = os.path.join(MEDIA, name)
    fig.savefig(path, dpi=200, bbox_inches="tight")
    plt.close(fig)
    print("saved", path)


# Fig 1: one feature at a time (project onto a single axis)
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
for ax, j in zip(axes, [PL, SW]):
    bins = np.linspace(X[:, j].min(), X[:, j].max(), 21)
    for c in range(3):
        ax.hist(X[y == c, j], bins=bins, alpha=0.6, color=COLORS[c],
                label=CLASSES[c], edgecolor="white")
    ax.set_xlabel(FEATURES[j])
    ax.set_ylabel("count")
axes[0].legend(frameon=False, loc="upper right")
fig.tight_layout()
save(fig, "p2_fig1_1d_histograms.png")

# Fig 2: two features at a time (project onto a plane)
fig, axes = plt.subplots(1, 2, figsize=(10, 4.4))
for ax, (a, b) in zip(axes, [(PL, PW), (SL, SW)]):
    for c in range(3):
        ax.scatter(X[y == c, a], X[y == c, b], s=22, color=COLORS[c],
                   alpha=0.8, label=CLASSES[c])
    ax.set_xlabel(FEATURES[a])
    ax.set_ylabel(FEATURES[b])
    ax.grid(alpha=0.25)
axes[0].legend(frameon=False, loc="upper left")
fig.tight_layout()
save(fig, "p2_fig2_2d_scatter.png")

# Fig 3: three features at a time
fig = plt.figure(figsize=(8, 6.5))
ax = fig.add_subplot(111, projection="3d")
for c in range(3):
    ax.scatter(X[y == c, PL], X[y == c, PW], X[y == c, SL], s=22,
               color=COLORS[c], alpha=0.8, label=CLASSES[c])
ax.set_xlabel(FEATURES[PL], labelpad=8)
ax.set_ylabel(FEATURES[PW], labelpad=8)
ax.text2D(1.1, 0.5, FEATURES[SL], transform=ax.transAxes, rotation=90,
          va="center", ha="left")
ax.view_init(elev=20, azim=-60)
ax.legend(frameon=False, loc="upper left")
fig.subplots_adjust(left=0.0, right=0.86, bottom=0.05, top=0.98)
save(fig, "p2_fig3_3d_scatter.png")

# Numbers for the written comments: per-class min, max and mean of each feature
print()
for j in range(4):
    print(FEATURES[j])
    for c in range(3):
        v = X[y == c, j]
        print("  %-16s min %.1f  max %.1f  mean %.3f" % (CLASSES[c], v.min(), v.max(), v.mean()))
