"""Linear Softmax Classifier."""
# pylint: disable=invalid-name
import numpy as np

from .linear_classifier import LinearClassifier


def cross_entropy_loss_naive(W, X, y, reg):
    """
    Cross-entropy loss function, naive implementation (with loops)

    Inputs have dimension D, there are C classes, and we operate on minibatches
    of N examples.

    Inputs:
    - W: A numpy array of shape (D, C) containing weights.
    - X: A numpy array of shape (N, D) containing a minibatch of data.
    - y: A numpy array of shape (N,) containing training labels; y[i] = c means
      that X[i] has label c, where 0 <= c < C.
    - reg: (float) regularization strength

    Returns a tuple of:
    - loss as single float
    - gradient with respect to weights W; an array of same shape as W
    """
    # pylint: disable=too-many-locals
    # Initialize the loss and gradient to zero.
    loss = 0.0
    dW = np.zeros_like(W)

    ############################################################################
    # TODO: Compute the cross-entropy loss and its gradient using explicit     #
    # loops. Store the loss in loss and the gradient in dW. If you are not     #
    # careful here, it is easy to run into numeric instability. Don't forget   #
    # the regularization!                                                      #
    ############################################################################
    num_train = X.shape[0]
    num_features, num_class = W.shape
    for n in range(num_train):
        x = X[n]
        #loss
        score = x.dot(W)
        # shift values for numeric stablity
        score -= np.max(score)
        score_exp = np.exp(score)
        score_expsum = np.sum(score_exp)
        softmax_output = score_exp / score_expsum
        loss += -np.log(softmax_output[y[n]])

        #gradient
        for i in range(num_features):
            for j in range(num_class):
                # dw[i,j] += (softmax_output[j] - (j == y[n])) * x[i]
                if j == y[n]:
                    dW[i,j] += (softmax_output[j] - 1) * x[i]
                else:
                    dW[i,j] += softmax_output[j] * x[i]

    # the loss is a sum over all training examples, but we want it to be
    # an average instead so we divide by num_train
    loss /= num_train
    dW /= num_train
    # add regularization to the loss
    loss += reg * np.sum(W*W)
    dW += 2 * reg * W

    ############################################################################
    #                          END OF YOUR CODE                                #
    ############################################################################

    return loss, dW


def cross_entropy_loss_vectorized(W, X, y, reg):
    """
    Cross-entropy loss function, vectorized version.

    Inputs and outputs are the same as in cross_entropy_loss_naive.
    """
    # Initialize the loss and gradient to zero.
    loss = 0.0
    dW = np.zeros_like(W)

    ############################################################################
    # TODO: Compute the cross-entropy loss and its gradient without explicit   #
    # loops. Store the loss in loss and the gradient in dW. If you are not     #
    # careful here, it is easy to run into numeric instability. Don't forget   #
    # the regularization!                                                      #
    ############################################################################
    num_train = X.shape[0]
    num_class = W.shape[1]
    score = np.dot(X,W)
    # Broadcasting
    shift_score = score - np.max(score, axis=1).reshape(-1,1)
    softmax_output = np.exp(shift_score) / np.sum(np.exp(shift_score), axis=1).reshape(-1,1)
    loss = - np.sum(np.log(softmax_output[range(num_train), list(y)]))
    loss /= num_train
    loss += reg * np.sum(W*W)

    ds = softmax_output.copy()
    ds[range(num_train), list(y)] -= 1
    # ds[list(range(num_train)), y] -= 1
    dW = np.dot(X.T, ds)
    dW /= num_train
    dW += 2 * reg * W

    ############################################################################
    #                          END OF YOUR CODE                                #
    ############################################################################

    return loss, dW


class SoftmaxClassifier(LinearClassifier):
    """The softmax classifier which uses the cross-entropy loss."""

    def loss(self, X_batch, y_batch, reg):
        return cross_entropy_loss_vectorized(self.W, X_batch, y_batch, reg)


def softmax_hyperparameter_tuning(X_train, y_train, X_val, y_val):
    # results is dictionary mapping tuples of the form
    # (learning_rate, regularization_strength) to tuples of the form
    # (training_accuracy, validation_accuracy). The accuracy is simply the
    # fraction of data points that are correctly classified.
    results = {}
    best_val = -1
    best_softmax = None
    all_classifiers = []
    learning_rates = [3e-6, 4.5e-6]
    regularization_strengths = [2.5e3, 5.5e3]

    ############################################################################
    # TODO:                                                                    #
    # Write code that chooses the best hyperparameters by tuning on the        #
    # validation set. For each combination of hyperparameters, train a         #
    # classifier on the training set, compute its accuracy on the training and #
    # validation sets, and  store these numbers in the results dictionary.     #
    # In addition, store the best validation accuracy in best_val and the      #
    # Softmax object that achieves this accuracy in best_softmax.              #                                      #
    #                                                                          #
    # Hint: You should use a small value for num_iters as you develop your     #
    # validation code so that the classifiers don't take much time to train;   #
    # once you are confident that your validation code works, you should rerun #
    # the validation code with a larger value for num_iters.                   #
    ############################################################################
    for lr in learning_rates:
        for rs in regularization_strengths:
            softmax = SoftmaxClassifier()
            softmax.train(X_train, y_train, lr, rs, num_iters=3000)
            y_train_pred = softmax.predict(X_train)
            train_accuracy = np.mean(y_train == y_train_pred)
            # print('training accuracy: %f' % train_accuracy)
            y_val_pred = softmax.predict(X_val)
            val_accuracy = np.mean(y_val == y_val_pred)
            # print('validation accuracy: %f' % val_accuracy)

            if val_accuracy > best_val:
                best_val = val_accuracy
                best_softmax = softmax

            results[(lr,rs)] = train_accuracy, val_accuracy
            # save akk classifiers and keep track the best one
            all_classifiers.append((softmax, val_accuracy, lr, rs))
    ############################################################################
    #                              END OF YOUR CODE                            #
    ############################################################################

    # Print out results.
    for (lr, reg) in sorted(results):
        train_accuracy, val_accuracy = results[(lr, reg)]
        print('lr %e reg %e train accuracy: %f val accuracy: %f' % (
              lr, reg, train_accuracy, val_accuracy))

    print('best validation accuracy achieved during validation: %f' % best_val)

    return best_softmax, results, all_classifiers
