# -*- coding: utf-8 -*-
# Copyright (C) 2008-2013, Luis Pedro Coelho <luis@luispedro.org>
# vim: set ts=4 sts=4 sw=4 expandtab smartindent:
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.

from __future__ import division
import numpy as np
from numpy import linalg

from . import _kmeans
from ..utils import get_pyrandom
from .normalise import zscore

__all__ = [
        'kmeans',
        'select_best_kmeans',
        'repeated_kmeans',
        ]


try:
    # This tests for the presence of 3-argument np.dot
    # with the 3rd argument being the output argument
    _x = np.array([
            [1., 1.],
            [0.,1.]] )
    _y = np.array([2., 4.])
    _r = np.array([0.,0.])
    np.dot(_x, _y, _r)
    if _r[0] != 6 or _r[1] != 4:
        raise NotImplementedError
    _dot3 = np.dot
except:
    def _dot3(x, y, _):
        return np.dot(x,y)
finally:
    del _x
    del _y
    del _r

def _mahalanobis2(fmatrix, x, icov):
    diff = fmatrix-x
    # The expression below seems to be faster than looping over the elements and summing
    return np.dot(diff, np.dot(icov, diff.T)).diagonal()

def centroid_errors(fmatrix, assignments, centroids):
    '''
    errors = centroid_errors(fmatrix, assignments, centroids)

    Computes the following::

        for all i, j:
            ci = assignments[i]
            errors[i,j] = fmatrix[ci, j] - centroids[ci, j]

    Parameters
    ----------
    fmatrix : 2D ndarray
        feature matrix
    assignments : 1D ndarray
        Assignments array
    centroids : 2D ndarray
        centroids

    Returns
    -------
    errors : float
        Difference between fmatrix and corresponding centroid
    '''
    errors = []
    for k,c in enumerate(centroids):
        errors.append(fmatrix[assignments == k] - c)
    return np.concatenate(errors)

def residual_sum_squares(fmatrix,assignments,centroids,distance='euclidean',**kwargs):
    '''