'''
Created on Jun 21, 2016

@author: Ping
'''
import csv
import numpy as np

def read_csv_mat(train_file, par_file = 'sta_par.txt'):
    print '-------------------------------------------'
    print 'read csv and create a user-item matrix'
    print train_file
    
    user_data = {}
    item_data = {}
    
    fp = open(train_file, 'r')
    reader = csv.reader(fp, delimiter = ',')
    for row in reader:
        if row[0] == 'UserID':
            continue
        user_data[row[0]] = {}
        item_data[row[1]] = {}
    fp.close()
    fp = open(train_file, 'r')
    reader = csv.reader(fp, delimiter = ',')
    for row in reader:
        if row[0] == 'UserID':
            continue
        user_data[row[0]][row[1]] = float(row[2])
    fp.close()
    
    data = np.loadtxt(par_file)    
    n_user = int(data[0])
    n_item = int(data[1])
    
    rate_mat = np.zeros([n_user, n_item])
    for usr in user_data:
        for itm in user_data[usr]:
            rate_mat[int(usr)-1][int(itm)-1] = user_data[usr][itm]
    print n_user, n_item, np.sum(rate_mat)
    return rate_mat

def bsSVD(rate_mat, weight_mat, n_topic = 10):
    print '--------------------------------------'
    print 'SVD Algorithm'
    U, S, V = np.linalg.svd(rate_mat, full_matrices=False)
    S[n_topic::] = 0.0
    return (1.0 - weight_mat) * np.dot(np.dot(U, np.diag(S)), V)

if __name__ == '__main__':
    print 'Algorithm'
    for sp in range(5):
        file_name = 'input/5fold_data_1out/train-' + str(sp+1) +'.csv'
        rate_mat = read_csv_mat(file_name)
        weight_mat = np.zeros(rate_mat.shape)
        index = rate_mat > 0.0
        weight_mat[index] = 1.0
        recc_score = bsSVD(rate_mat, weight_mat, n_topic= 500)
        file_name = 'rec_scores/svd_rec_score_' + str(sp+1)
        np.save(file_name, recc_score)
    print 'Normal Terminate'
