import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
from scipy.cluster import vq

"""
Explanation: Title: Simple Clustering With SciPy
Slug: scipy_simple_clustering
Summary: Simple Clustering With SciPy
Date: 2016-05-01 12:00
Category: Python
Tags: Other
Authors: Chris Albon  
Import modules
End of explanation
"""


# create 100 coordinate pairs (i.e. two values), then add 5 to all of them
year_1 = np.random.randn(100, 2) + 5

# create 30 coordinatee pairs (i.e. two values), then subtract 5 to all of them
year_2 = np.random.randn(30, 2) - 5

# create 50 coordinatee pairs (i.e. two values)
year_3 = np.random.randn(50, 2)

"""
Explanation: Create coordinates for battles for each year of the war
End of explanation
"""


print('year 1 battles:',  year_1[0:3])
print('year 2 battles:', year_2[0:3])
print('year 3 battles:', year_3[0:3])

"""
Explanation: View the first 3 entries of each year of battles
End of explanation
"""


# vertically stack year_1, year_2, and year_3 elements
battles = np.vstack([year_1, year_2, year_3])

"""
Explanation: Pool all three years of coordinates
End of explanation
"""


# calculate the centroid coordinates of each cluster 
# and the variance of all the clusters
centroids, variance  = vq.kmeans(battles, 3)

"""
Explanation: Cluster the battle locations into three groups
End of explanation
"""


centroids

"""
Explanation: View the centroid coordinate for each of the three clusters
End of explanation
"""


variance

"""
Explanation: View the variance of the clusters (they all share the same)
End of explanation
"""


identified, distance = vq.vq(battles, centroids)

"""
Explanation: Seperate the battle data into clusters
End of explanation
"""


identified

"""
Explanation: View the cluster of each battle
End of explanation
"""


distance

"""
Explanation: View the distance of each individual battle from their cluster's centroid
End of explanation
"""


cluster_1 = battles[identified == 0]
cluster_2 = battles[identified == 1]
cluster_3 = battles[identified == 2]

"""
Explanation: Index the battles data by the cluster to which they belong
End of explanation
"""


print(cluster_1[0:3])
print(cluster_2[0:3])
print(cluster_3[0:3])

"""
Explanation: Print the first three coordinate pairs of each cluster
End of explanation
"""


# create a scatter plot there the x-axis is the first column of battles
# the y-axis is the second column of battles, the size is 100, and
# the color of each point is determined by the indentified variable
plt.scatter(battles[:,0], battles[:,1], s=100, c=identified)

"""
Explanation: Plot all the battles, color each battle by cluster
End of explanation
"""


