import math

class Transformator(object):
    def __init__(self):
        pass
    
    def calculate(self, matrix):
        pass

class Binaryze(Transformator):
    def __init__(self):
        super(Binaryze, self).__init__()

    def calculate(self, matrix):
        w_matrix = []
        for v in matrix:
            v_m = []
            for vi in v:
                v_m.append(0 if vi == 0 else 1)
            w_matrix.append(v_m)
        return w_matrix

class Tf(Transformator):
    def __init__(self):
        super(Tf, self).__init__()

    def calculate(self, matrix):
        w_matrix = []
        for v in matrix:
            v_m = []
            for vi in v:
                v_m.append(float(vi) / sum(v))
            w_matrix.append(v_m)
        return w_matrix

class TfIdf(Transformator):
    def __init__(self):
        super(TfIdf, self).__init__()

    def calculate(self, matrix):
        D = len(matrix)
        w_matrix = []
        # TF
        for v in matrix:
            v_m = []
            for vi in v:
                v_m.append(float(vi) / sum(v))
            w_matrix.append(v_m)

        # idf
        f_freq = []
        for i in range(0, len(matrix[0])):
            f_freq.append(0)
            for m in range(0, D):
                f_freq[i] += matrix[m][i]
        
        # TF-IDF (TF*IDF)
        for r in range(0, D):
            for c in range(0, len(matrix[r])):
                w_matrix[r][c] *= math.log(float(D) / f_freq[c])

        return w_matrix
