'''
Find linear & ranked correlation
'''

import numpy
import scipy.stats

fdIn = open('snapshot_7days.txt', 'r')
fdOut = open('correlation_7days.txt', 'w')

data = []
line = fdIn.readline()
tmp = line.split('\t')
tmpStr = ''
numAtt = len(tmp) - 2
for i in range(numAtt):
    data.append([])
    if i != numAtt - 1: tmpStr += tmp[i + 2] + '\t' 
    else: tmpStr += tmp[i + 2]
fdOut.write(tmpStr)

for line in fdIn:
    tmp = line.split('\t')
    for i in range(len(tmp)):
        if i <= 1: continue
        data[i - 2].append(float(tmp[i]))
fdIn.close()


#Linear correlation
p = numpy.corrcoef(data)
for i in range(len(p)):
    tmpStr = ''
    for j in range(i + 1): 
        tmpStr += str(round(p[i][j], 4)) + '\t'
    fdOut.write(tmpStr + '\n')

fdOut.write('\n\n')
#ranked correlation
for i in range(numAtt): 
    tmpStr = ''
    for j in range(i + 1):
        rho, pval = scipy.stats.spearmanr(data[i], data[j])
        tmpStr += str(round(rho, 4)) + '\t'
    fdOut.write(tmpStr + '\n')

fdOut.close()
