# coding=utf-8
import xlrd
import xlwt
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch.autograd import Variable
import os
def get_grad(y):
x = np.arange(1, y.shape[0]+1, 1)
z1 = np.polyfit(x, y, 16)
#p1 = np.poly1d(z1)
#yvals=p1(x)
#plt.plot(x,y,"og")
#plt.plot(x, yvals, 'r',label='polyfit values')
x_tensor = Variable(torch.from_numpy(x).float(), requires_grad=True)
y_tensor=float(z1[0])*x_tensor**16+float(z1[1])*x_tensor**15+float(z1[2])*x_tensor**14+float(z1[3])*x_tensor**13+float(z1[4])*x_tensor**12+float(z1[5])*x_tensor**11+float(z1[6])*x_tensor**10+float(z1[7])*x_tensor**9+float(z1[8])*x_tensor**8+float(z1[9])*x_tensor**7+float(z1[10])*x_tensor**6+float(z1[11])*x_tensor**5+float(z1[12])*x_tensor**4+float(z1[13])*x_tensor**3+float(z1[14])*x_tensor**2+float(z1[15])*x_tensor**1+float(z1[16])*x_tensor**0
y_tensor.backward(x_tensor)
return x_tensor.grad
def read_xlrd(excelFile, tempfilename):
data = xlrd.open_workbook(excelFile)
table = data.sheet_by_index(0)
workbook = xlwt.Workbook(encoding = 'utf-8')
worksheet = workbook.add_sheet('My Worksheet')
for rowNum in range(table.nrows):
rowVale = table.row_values(rowNum)
if rowNum == 0:
for i,value in enumerate(rowVale[1:]):
worksheet.write(rowNum, i + 1, label = str(int(value)))
for colNum in range(table.ncols):
if rowNum > 0 and colNum == 0:
new_grad = get_grad(np.array(rowVale[1:]))
worksheet.write(rowNum,0, label = rowVale[0])
for k,grad in enumerate(new_grad):
worksheet.write(rowNum,k+1, label = str(float(grad)))
print(new_grad)
print("---------------")
workbook.save("new_grad/"+tempfilename)
if __name__ == '__main__':
lines = [line.strip() for line in open("list.txt", 'r').readlines()]
for line in lines:
excelFile = line
if not os.path.exists("new_grad"):
os.makedirs("new_grad")
(filepath, filename) = os.path.split(line)
read_xlrd(excelFile,"new_"+filename)