
import numpy as np
import json
import os

try:
    from .som import SOM
except Exception: #ImportError
    from som import SOM


def L_p(u, v, p, axis=0):
    return np.sum(np.abs(u-v)**p, axis=axis) ** (1/p)


def L_2(u, v, axis=0):
    return L_p(u, v, p=2, axis=axis)


def newSom(rows, cols, inputsData):
    metric = L_2
    (dim, count) = inputsData.shape

    top_left = np.array((0, 0))
    bottom_right = np.array((rows - 1, cols - 1))
    lambda_s = metric(top_left, bottom_right) * 0.5

    model = SOM(dim, rows, cols, inputsData)
    model.train(inputsData, metric=metric, alpha_s=0.5, alpha_f=0.01, lambda_s=lambda_s,
                lambda_f=1, eps=250, trace_interval=10)
    return model


def saveSom(som, name):
    try:
        os.mkdir("./data/"+name+"/")
    except OSError:
        pass

    for i in range(som.weights.shape[0]):
        np.savetxt("./data/"+name+"/"+str(i)+".txt", som.weights[i])

if __name__ == "__main__":
    """
    Training of arm SOM
    training data are from ../../data.data
    """

    f = open("../../data.data")
    rawData = json.load(f)
    left = np.array([i["leftHandPro"] for i in rawData]).T
    right = np.array([i["rightHandPro"] for i in rawData]).T

    # train and save classic som
    leftSom  = newSom(9, 12, left)
    saveSom(som=leftSom, name="left_hand_som")
    rightSom = newSom(9, 12, right)
    saveSom(som=rightSom, name="right_hand_som")
