#!/usr/bin/python
# -*- coding: utf-8 -*-
import numpy as np
from scipy.misc import face, imshow
from m2l2.clustering import kMeans, GaussianMixtureEM

X = np.array(face().reshape((-1, 3)), dtype=np.float)

cluster = GaussianMixtureEM(X, 4)
cluster.run(threshold=0.01)

Xp = np.array(cluster.mu[cluster.cl, :], dtype=np.uint8)

imshow(Xp.reshape((768, 1024, 3)))
ax.set_xlim(x_min, x_max)
ax.set_ylim(y_min, y_max)
xx, yy = np.meshgrid(np.linspace(x_min, x_max, 200), np.linspace(y_min, y_max, 200))
plt.xlabel("Sepal Width")
plt.ylabel("Sepal Length")
plt.title("Fisher Iris Data (clustering)")


## model
def EllipseFromSigma(Sigma, mu):
    w, v = np.linalg.eigh(Sigma)
    angle = np.arctan2(v[1, 0], v[0, 0])
    return Ellipse(xy=mu, width=w[0] * 4, height=w[1] * 4, angle=angle / np.pi * 180, fill=False, color="black")


km = GaussianMixtureEM(X, n=2)

# set a nice starting position
km.mu = np.array([[4.5, 2.5], [6.5, 4]])
km.E_step()

scatter = ax.scatter(X[:, 0], X[:, 1], c=km.cl, cmap=cm_bright)
means = ax.scatter(km.mu[:, 0], km.mu[:, 1], c=np.arange(km._ncl), cmap=cm_bright, marker="+", s=60)
ells = [EllipseFromSigma(S, m) for (S, m) in zip(km.Sigma, km.mu)]
for e in ells:
    ax.add_artist(e)

## animation
def update_plot(i):
    scatter.set_array(km.cl)
    means.set_offsets(km.mu)