如图要加工一工件,Python计算车床的走刀路径
环境:WIN10+VS Code
用到的库:matplotlib.pyplot , numpy, sys
最后的3D图形是用matlab画的,将图形沿其中心轴旋转,再进行坐标转换。进刀步长为0.02mm,各个交点和圆心坐标需要提前计算好,大致步骤在原点画好图形,再移至相应位置,分为4个部分,如下图:
Python代码:
import matplotlib.pyplot as plt
import numpy as np
import sys
from mpl_toolkits.mplot3d import Axes3D
sys.setrecursionlimit(1000000)#递归限制
print("start")
Fm = 0 #初始偏差
Xe, Ye = 40, 18 #直线终点
X0, Y0 = 44.95, 15.95 #c1圆终点
c1 = (40,11) #circular1 center
c2 = (61.92, 32.92) # circular2 center
m = (61.92, 8.92) #圆2弧中点
z = (80.2,18) #圆2终点
h = 20
LineRange = [(0.0, 0.0)] #路径list
StepSize = 0.02 #进刀步长
length = int((Xe+Ye)/StepSize) #直线总步数
Nxy1 = int((X0-Xe+Ye-Y0)/StepSize) #圆1总步数
Nxy2 = int((m[0]-X0+Y0-m[1])/StepSize) #圆2第3象限部分
Nxy3 = int((z[0]-m[0]+z[1]-m[1])/StepSize)#圆2第4象限部分
CSX, CSY = Xe*StepSize, Ye*StepSize # a number of straightline caculate
CC = 2*StepSize # a number of circular caculate
def plot_straightline(L, F):
if L==0:
return
if F>=0:
LineRange.append( (LineRange[length-L][0]+StepSize,LineRange[length-L][1])) #x进一步
L-=1 #步数减一
Fm1 = F-CSY #计算偏差
print("x进1步 "+str(LineRange[length-L])+" 偏差:"+str(Fm1))
else :
LineRange.append( (LineRange[length-L][0], LineRange[length-L][1]+StepSize) )
L-=1
Fm1 = F + CSX
print("y进1步 "+str(LineRange[length-L])+" 偏差:"+str(Fm1))
plot_straightline(L, Fm1)
def plot_circular1(N, Fm, Xm, Ym): #last Lm 、Xm and Ym
if N==0:
return
if Fm>=0: # -y forward
Ym1 = Ym - StepSize
Xm1 = Xm
Fm1 = Fm-CC*Ym #计算偏差 Fm1 = Fm - 2*StepSize*Ym
N-=1 #步数减一
print("y减1步 "+str(Xm1)+", "+str(Ym1)+" 偏差:"+str(Fm1))
else : # +x forward
Xm1 = Xm + StepSize
Ym1 = Ym
N-=1
Fm1 = Fm + CC*Xm
print("x进1步 "+str(Xm1)+", "+str(Ym1)+" 偏差:"+str(Fm1))
LineRange.append((Xm1+c1[0], Ym1+c1[1]))
plot_circular1(N, Fm1, Xm1, Ym1)
def plot_circular2(N, Fm, Xm, Ym): #last Lm 、Xm and Ym 第三象限逆时针圆弧
if N==0:
return
if Fm>=0: # +x forward
Ym1 = Ym
Xm1 = Xm + StepSize
Fm1 = Fm + CC*Xm #计算偏差
N-=1 #步数减一
print("x进1步 "+str(Xm1)+", "+str(Ym1)+" 偏差:"+str(Fm1))
else : # -y forward
Xm1 = Xm
Ym1 = Ym - StepSize
N-=1
Fm1 = Fm - CC*Ym
print("Y减1步 "+str(Xm1)+", "+str(Ym1)+" 偏差:"+str(Fm1))
LineRange.append((Xm1+c2[0], Ym1+c2[1]))
plot_circular2(N, Fm1, Xm1, Ym1)
def plot_circular3(N, Fm, Xm, Ym): #last Lm 、Xm and Ym 第四象限逆时针圆弧
if N==0:
return
if Fm>=0: # +y forward
Ym1 = Ym + StepSize
Xm1 = Xm
Fm1 = Fm+CC*Ym #计算偏差 书本计算偏差公式有误Fm-2*Ym+1
N-=1 #步数减一
print("y进1步 "+str(Xm1)+", "+str(Ym1)+" 偏差:"+str(Fm1))
else : # +x forward
Xm1 = Xm + StepSize
Ym1 = Ym
N-=1
Fm1 = Fm + CC*Xm
print("x进1步 "+str(Xm1)+", "+str(Ym1)+" 偏差:"+str(Fm1))
LineRange.append((Xm1+c2[0], Ym1+c2[1]))
plot_circular3(N, Fm1, Xm1, Ym1)
plot_straightline(length, Fm)
plot_circular1(Nxy1, Fm, Xe-c1[0], Ye-c1[1])
plot_circular2(Nxy2, Fm, X0-c2[0], Y0-c2[1])
plot_circular3(Nxy3, Fm, m[0]-c2[0], m[1]-c2[1])
X = []
Y = []
for i in LineRange:
X.append(i[0])
Y.append(i[1])#极坐标的R
#Z.append(np.square(i)+np.square(i))
plt.plot(X, Y)
#plt.savefig("1.png")#保存图像
plt.show()#显示图像
递归计算还要几秒钟才算完,代码里的偏差计算公式是简化过的,高次项忽略掉了,看看结果吧:
用matlab画的3D图: