Python 做曲线拟合和求积分的方法


Posted in Python onDecember 29, 2018

这是一个由加油站油罐传感器测量的油罐高度数据和出油体积,根据体积和高度的倒数,用截面积来描述油罐形状,求出拟合曲线,再用标准数据,求积分来验证拟合曲线效果和误差的一个小项目。 主要的就是首先要安装Anaconda  python库,然后来运用这些数学工具。

###最小二乘法试验###
import numpy as np
import pymysql
from scipy.optimize import leastsq
from scipy import integrate
###绘图,看拟合效果###
import matplotlib.pyplot as plt
from sympy import *
 
 
path='E:\PythonProgram\oildata.txt'
 
lieh0 =[]   #初始第一列,油管高度
liev1 =[]   #初始第二列,油枪记录的体积
 
h_median =[]  # 高度相邻中位数
h_subtract =[]   #相邻高度作差
v_subtract =[]   #相邻体积作差
select_h_subtr =[]   #筛选的高度作差 ########
select_v_subtr =[]   #筛选的体积作差
 
VdtH=[]      #筛选的V 和 t 的 倒数。
 
def loadData(Spath,lie0,lie1):
 with open(Spath,'r') as f0:
   for i in f0:
    tmp=i.split()
    lie0.append(float(tmp[0]))
    lie1.append(float(tmp[2]))
 print ("source lie0",len(lie0))
 
 
def connectMySQL():
 db = pymysql.connect(host='10.**.**.**', user='root', passwd='***', db="zabbix", charset="utf8") # 校罐
 cur = db.cursor()
 
 try:
  # 查询
  cur.execute("SELECT * FROM station_snapshot limit 10 ")
  for row in cur.fetchall():
   # print(row)
   id = row[0]
   snapshot_id = row[1]
   DateTime = row[13]
   attr1V = row[5]
   attr2H = row[6]
   print("id=%d ,snapshot_id=%s,DateTime=%s,attr1V =%s, attr2H=%s ",
     (id, snapshot_id, DateTime, attr1V, attr2H))
 except:
  print("Error: unable to fecth data of station_stock")
 
 try:
  cur.execute("SELECT * FROM can_stock limit 5");
  for row in cur.fetchall():
   # print(row)
   stockid = row[0]
   stationid = row[1]
   DateTime = row[4]
   Volume = row[5]
   Height = row[8]
   print("stockid=%d ,stationid=%s,DateTime=%s,Volume =%f, Height=%f ",
     (stockid, stationid, DateTime, Volume, Height))
 except:
  print("Error: unable to fecth data of can_snapshot")
 
 cur.close()
 db.close()
 
 
def formatData(h_med,h_subtr,v_subtr):
 lh0 = lieh0[:]
 del lh0[0]
 print("lh0 size(): ",len(lh0))
 
 lh1 =lieh0[:]
 del lh1[len(lh1)-1]
 
 print("lh1 size() : ",len(lh1))
 
 lv0 =liev1[:]
 del lv0[0]
 #print (liev1)
 print ("Souce liev1 size() : ",len(liev1))
 print ("lv1 size() :",len(lv0))
 """
 lv1 =liev1[:]
 del lv1[len(lv1)-1]
 print("lv1 size(): ",len(lv1))
 """
 h_med[:] =[(x+y)/2 for x,y in zip(lh0,lh1)]  ###采样点(Xi,Yi)###
 print("h_med size() : ", len(h_med))
 
 h_subtr[:] = [(y-x) for x,y in zip(lh0,lh1)]
 print("h_subtr size() : ", len(h_subtr))
 # v_subtr[:] = [(y-x) for x,y in zip(lv0,lv1)]
 v_subtr[:] = lv0
 print("v_subtr size() : ", len(v_subtr))
 
 
def removeBadPoint(h_med,h_sub,v_sub):
 for val in h_sub:
  position=h_sub.index(val)
  if 0.01 > val > -0.01:
   del h_sub[position]
   del h_med[position]
   del v_sub[position]
 v_dt_h_ay = [(y/x) for x, y in zip(h_sub, v_sub)]
 return v_dt_h_ay
 
 
 
def selectRightPoint(h_med,h_subtr,v_dt_h_ay):
 for val in v_dt_h_ay:
  pos = v_dt_h_ay.index(val)
  if val > 20 :
   del v_dt_h_ay[pos]
   del h_med[pos]
   del h_subtr[pos]
 for val in v_dt_h_ay:
  ptr = v_dt_h_ay.index(val)
  if val < 14:
   del v_dt_h_ay[ptr]
   del h_med[ptr]
   del h_subtr[ptr]
 
 
def writeFile(h_mp, v_dt_h):
 s='\n'.join(str(num)[1:-1] for num in h_mp)
 v='\n'.join(str(vdt)[1:-1] for vdt in v_dt_h)
 open(r'h_2.txt','w').write(s)
 open(r'v_dt_h.txt','w').write(v)
 print("write h_median: ",len(h_mp))
 # print("V_dt also is (y-x) : ",v_dt_h,end="\n")
 print("Write V_dt_h : ",len(v_dt_h))
# file=open('data.txt','w')
# file.write(str(h_mp));
# file.close
 
 
def integralCalculate(coeff,xspace):
 vCalcute =[]
 x = Symbol('x')
 a, b, c, d = coeff[0]
 y = a * x ** 3 + b * x ** 2 + c * x + d
 i=0
 while (i< len(xspace)-1) :
  m = integrate(y, (x, xspace[i], xspace[i+1]))
  vCalcute.append(abs(m))
  i=i+1
 
 print("求导结果:",vCalcute)
 print("求导长度 len(VCalcute): ",len(vCalcute))
 return vCalcute
 
 ###需要拟合的函数func及误差error###
 
def func(p,x):
 a,b,c,d=p
 return a*x**3+b*x**2+c*x+d #指明待拟合的函数的形状,设定的拟合函数。
 
def error(p,x,y):
 return func(p,x)-y #x、y都是列表,故返回值也是个列表
 
def leastSquareFitting(h_mp,v_dt_hl):
 p0=[1,2,6,10]  #a,b,c 的假设初始值,随着迭代会越来越小
 #print(error(p0,h_mp,v_dt_h,"cishu")) #目标是让error 不断减小
 #s="Test the number of iteration" #试验最小二乘法函数leastsq得调用几次error函数才能找到使得均方误差之和最小的a~c
 Para=leastsq(error,p0,args=(h_mp,v_dt_hl)) #把error函数中除了p以外的参数打包到args中
 a,b,c,d=Para[0]   #leastsq 返回的第一个值是a,b,c 的求解结果,leastsq返回类型相当于c++ 中的tuple
 print(" a=",a," b=",b," c=",c," d=",d)
 plt.figure(figsize=(8,6))
 plt.scatter(h_mp,v_dt_hl,color="red",label="Sample Point",linewidth=3) #画样本点
 x=np.linspace(200,2200,1000)
 y=a*x**3+b*x**2+c*x+d
 
 integralCalculate(Para,h_subtract)
 plt.plot(x,y,color="orange",label="Fitting Curve",linewidth=2) #画拟合曲线
 # plt.plot(h_mp, v_dt_hl,color="blue", label='Origin Line',linewidth=1) #画连接线
 plt.legend()
 plt.show()
 
def freeParameterFitting(h_mp,v_dt_hl):
 z1 = np.polyfit(h_mp, v_dt_hl, 6) # 第一个拟合,自由度为6
  # 生成多项式对象
 p1 = np.poly1d(z1)
 print("Z1:")
 print(z1)
 print("P1:")
 print(p1)
 print("\n")
 x = np.linspace(400, 1700, 1000)
 plt.plot(h_mp, v_dt_hl, color="blue", label='Origin Line', linewidth=1) # 画连接线
 plt.plot(x, p1(x), 'gv--', color="black", label='Poly Fitting Line(deg=6)', linewidth=1)
 plt.legend()
 plt.show()
 
def main():
 loadData(path, lieh0, liev1)
 connectMySQL() # 读取oildata数据库
 
 formatData(h_median, h_subtract, v_subtract)
 
 # 去除被除数为0对应的点,并得到v 和 h 求导 值的列表
 VdtH[:] = removeBadPoint(h_median, h_subtract, v_subtract)
 print("h_median1:", len(h_median))
 
 print("VdtH1 : ", len(VdtH))
 
 # 赛选数据,去除异常点
 selectRightPoint(h_median, h_subtract, VdtH)
 print("h_median2:", len(h_median))
 print("h_subtract: ", len(h_subtract))
 print("VdtH2 : ", len(VdtH))
 h_mp = np.array(h_median)
 v_dt_h = np.array(VdtH)
 
 writeFile(h_mp, v_dt_h)
 # 最小二乘法作图
 leastSquareFitting(h_mp, v_dt_h)
 # 多项式自由参数法作图
 freeParameterFitting(h_mp, v_dt_h)
 
if __name__ == '__main__':
 main()

以上这篇Python 做曲线拟合和求积分的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python中精确输出JSON浮点数的方法
Apr 18 Python
Python判断文本中消息重复次数的方法
Apr 27 Python
Python拼接字符串的7种方法总结
Nov 01 Python
OpenCV搞定腾讯滑块验证码的实现代码
May 18 Python
python 实现查找文件并输出满足某一条件的数据项方法
Jun 12 Python
pytorch实现onehot编码转为普通label标签
Jan 02 Python
pytorch 实现在预训练模型的 input上增减通道
Jan 06 Python
Python 简单计算要求形状面积的实例
Jan 18 Python
python使用Word2Vec进行情感分析解析
Jul 31 Python
解决pytorch 保存模型遇到的问题
Mar 03 Python
Pytorch 中net.train 和 net.eval的使用说明
May 22 Python
Flask搭建一个API服务器的步骤
May 28 Python
python 画三维图像 曲面图和散点图的示例
Dec 29 #Python
python实现三维拟合的方法
Dec 29 #Python
Django数据库连接丢失问题的解决方法
Dec 29 #Python
Python Cookie 读取和保存方法
Dec 28 #Python
Python编程flask使用页面模版的方法
Dec 28 #Python
Python编程中flask的简介与简单使用
Dec 28 #Python
Python3 Post登录并且保存cookie登录其他页面的方法
Dec 28 #Python
You might like
发一个php简单的伪原创程序,配合商城采集用的
2010/10/12 PHP
IIS+fastcgi下PHP运行超时问题的解决办法详解
2013/06/20 PHP
PHP基于IMAP收取邮件的方法示例
2017/08/07 PHP
模拟用户操作Input元素,不会触发相应事件
2007/05/11 Javascript
js实现checkbox全选、不选与反选的方法
2015/02/09 Javascript
jQuery+ajax实现无刷新级联菜单示例
2015/05/21 Javascript
浅谈Nodejs应用主文件index.js
2016/08/28 NodeJs
jQuery下拉菜单的实现代码
2016/11/03 Javascript
JavaScript中的遍历详解(多种遍历)
2017/04/07 Javascript
详解nodejs微信公众号开发——2.自动回复
2017/04/10 NodeJs
详谈Node.js之操作文件系统
2017/08/29 Javascript
详解Node 定时器
2018/02/26 Javascript
浅谈vue项目可以从哪些方面进行优化
2018/05/05 Javascript
在Layui 的表格模板中,实现layer父页面和子页面传值交互的方法
2019/09/10 Javascript
使用 Angular RouteReuseStrategy 缓存(路由)组件的实例代码
2019/11/01 Javascript
小程序api实现promise封装过程解析
2019/11/21 Javascript
[02:10]DOTA2 TI10勇士令状玩法及不朽Ⅰ展示:焕新世界,如你所期
2020/05/29 DOTA
在Python的Tornado框架中实现简单的在线代理的教程
2015/05/02 Python
详解Python中break语句的用法
2015/05/14 Python
python制作爬虫并将抓取结果保存到excel中
2016/04/06 Python
Flask框架中密码的加盐哈希加密和验证功能的用法详解
2016/06/07 Python
用Python写王者荣耀刷金币脚本
2017/12/21 Python
python中pip的使用和修改下载源的方法
2019/07/08 Python
Python实现非正太分布的异常值检测方式
2019/12/09 Python
pytorch 实现在预训练模型的 input上增减通道
2020/01/06 Python
浅谈tensorflow 中tf.concat()的使用
2020/02/07 Python
纯CSS3大转盘抽奖示例代码(响应式、可配置)
2017/01/13 HTML / CSS
Pedro官网:新加坡时尚品牌
2019/08/27 全球购物
Python使用openpyxl复制整张sheet
2021/03/24 Python
医学专业大学生求职信
2014/07/12 职场文书
环保项目建议书
2014/08/26 职场文书
2014年电工工作总结
2014/11/20 职场文书
出生公证书
2015/01/23 职场文书
英文慰问信
2015/02/14 职场文书
升学宴祝酒词
2015/08/11 职场文书
如何让你的Nginx支持分布式追踪详解
2022/07/07 Servers