#-*- codeing = utf-8 -*-
#@Time : 2022/1/11 21:24
#@Author : HRoss717
#@File : test.py
#@Software : PyCharm
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import leastsq
import csv
import pandas as pd
filename ='test.csv'
with open(filename) as f:
reader =csv.reader(f)
first_row =next(reader)
second_row =next(reader)
# 分别删除最后一个空的元素
del first_row[len(first_row)-1]
del second_row[len(second_row)-1]
# 分别从str类型,转换为float类型
first_row=np.array(first_row).astype(np.float64)
second_row = np.array(second_row).astype(np.float64)
# //也可以通过这种方式进行数据转换
# first_row=list(map(float,first_row))
# second_row = list(map(float, second_row))
# # 待拟合的数据
# X = np.array([1,2,3,4,5,6])
# Y=np.array([9.1,18.3,32,47,69.5,94.8])
# x = np.array(second_row)
# y = np.array(first_row)
#
X = np.array(first_row)
Y = np.array(second_row)
# x=np.array(first_row)
# y=np.array(second_row)
# 用7次多项式拟合
f1 = np.polyfit(X, Y,7)
print('f1 is :\n', f1)
p1 = np.poly1d(f1)
print('p1 is :\n', p1)
print("-----------------------")
from sympy import *
x = symbols('x')
# ds=f1[0]*x**7+f1[1]*x+f1[2]*x+f[3]*x+f1[4]*x+f1[5]*x+f1[6]*x+f1[7]
ds=f1[0]*(x**7)+f1[1]*(x**6)+f1[2]*(x**5)+f1[3]*(x**4)+f1[4]*(x**3)+f1[5]*(x**2)+f1[6]*(x**1)+f1[7]*(x**0)
diff=diff(ds,x)
print(diff)
degreeMy=[]
for lena in range(0,382):
degreeMy.append( diff.evalf(subs={'x': lena}))
print(degreeMy)
degreeMy=np.array(degreeMy)
# 也可使用yvals=np.polyval(f1, x)
yvals = p1(X) # 拟合y值
print('yvals is :\n', yvals)
# 绘图
plot1 = plt.plot(X, -Y, 's', marker="o",label='original values')
plot2 = plt.plot(X,-yvals, 'r', label='polyfit values')
plt.xlabel('x')
plt.ylabel('y')
plt.legend(loc=3) # 指定legend的位置右下角---根据象限来设定1,2,3,4
plt.twinx()
plot3 = plt.plot(X, degreeMy, 'g', label='deri values')
plt.xlabel('x')
plt.ylabel('y')
plt.legend(loc=4) # 指定legend的位置右下角---根据象限来设定1,2,3,4
plt.title('polyfitting')
plt.show()