量測結果python畫圖
measure_result_plot.py
import numpy as np
from scipy.interpolate import Rbf
from matplotlib import cm
import math
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D
from mpl_toolkits.mplot3d import axes3d
from plot_1600 import get_1mm_dense_data
## 自動量測的路徑(目前用不到)
measure_result_txt = 'D:/MeasurementLog/MeasurementLog_result.txt'
# 觀測設定 / 畫出檔案設定
TH = '0010'
mea_height = 45
MAG_NAME = 'R' # R / TAI / CSC / desolver / resolver_de
# 圖片觀測角度
# ele_angle = 70
ele_angle = 70
rot_angle = 225
# -------------------------------------------------------------------------------------------------------------------------
# G code 路徑
if (MAG_NAME == 'R'):
# R 用的
txt_path = 'mea_result_R/Gcode_H' + str(mea_height) + '_TH' + TH + '.txt'
txt_path_1600 = 'mea_result_R/dense_1mm_mea_H' + str(mea_height) +'.txt'
else:
# Tai/CSC 用的
txt_path = 'mea_result_' + MAG_NAME + '/Gcode_' + MAG_NAME + '_TH' + TH + '_H' + str(mea_height) + '.txt'
txt_path_1600 = 'mea_result_' + MAG_NAME + '/dense_1mm_mea_H' + str(mea_height) + '_' + MAG_NAME + '.txt'
print('path : ', txt_path)
print('path : ', txt_path_1600)
# data
pos_x = []
pos_y = []
mag_tot = []
f = open(txt_path, 'r',encoding = "latin1")
# count the row of txt
txt_count_row = len(open(txt_path,'r',encoding = "latin1").readlines())
count = 0
# data
for line in f.readlines():
count = count+1
# 跳過第1筆資料與倒數最後兩筆資料
if ((count == 1) or (count == txt_count_row) or (count == (txt_count_row - 1))):
continue
s = line.split()
pos_x.append(int(s[3])) # x 座標
pos_y.append(int(s[4])) # y 座標
mag_tot.append(float(s[9])) # tot 磁通
f.close()
# 把陣列整理成跟插值的陣列一樣,刪除不必要的行列數
dense_1mm_data, data_lenx, data_leny, data_minx, data_miny = get_1mm_dense_data(txt_path_1600)
# 資料對齊
pos_x_max = data_minx
pos_y_max = data_miny
print("Gcode : , " , pos_x_max,"/", max(pos_x)," ", pos_y_max, "/", max(pos_y))
for i in range(len(pos_x)):
pos_x[i] = abs(pos_x_max - pos_x[i])
pos_y[i] = abs(pos_y_max - pos_y[i])
print("max(pos_x) : ", max(pos_x), " ", max(pos_y))
# 對其資料長寬
for i in range(data_lenx - max(pos_x)):
dense_1mm_data = np.delete(dense_1mm_data, data_lenx - i - 1, 0)
for i in range(data_leny - max(pos_y)):
dense_1mm_data = np.delete(dense_1mm_data, data_leny - i - 1, 1)
print("Gcode total point number: ", len(pos_x), "reduce point % : ", 1 - (len(pos_x) / (data_lenx * data_leny)))
pos_x = np.array(pos_x)
pos_y = np.array(pos_y)
mag_tot = np.array(mag_tot)
print("data len : ", len(pos_x))
# func_of_RBF = ['multiquadric', 'inverse', 'gaussian', 'thin_plate']
# for i in range(len(func_of_RBF)):
rbf = Rbf(pos_x, pos_y ,mag_tot,function = 'multiquadric' , smooth = 0.001) # epsilon 標準差/自由參數 4.75
print("test : ", rbf.epsilon)
x, y = np.mgrid[0:max(pos_x), 0:max(pos_y)]
z = rbf(x, y)
# compute the similarity result
z_diff = np.sum(abs((z - dense_1mm_data)/dense_1mm_data)) / (max(pos_x) * max(pos_y))
print("Function = ", 'multiquadric' , " relate error: ", z_diff * 100, "%")
print("Similarity(%) : ", (1 - z_diff) * 100, "%")
# RMSE (root mean square error)
RMSE_result = np.sqrt(np.sum(np.square(z - dense_1mm_data)) / (max(pos_x) * max(pos_y)))
print("RMSE_result : ", RMSE_result)
# max_epsilon_index =
# print("Nice similarity : ", max(similarity_array), " epsilon : ", epsilon_array[])
# ############################################## plot the 3d xyB
# plot 3D 2 subplot
fig = plt.figure(figsize=(20, 6))
ax = fig.add_subplot(1,3,1, projection = '3d')
ax.set_xlabel("x(mm)")
ax.set_ylabel("y(mm)")
ax.set_zlabel("B total(Gauss)")
ax.view_init(ele_angle, rot_angle) #仰角/水平
# ax.set_title("interpolate data")
ax.set_zticks(np.arange(0, max(mag_tot), 100))
a1 = ax.plot_surface(x, y, z, rstride=1, cstride=1,cmap=cm.coolwarm, edgecolor='none')
fig.colorbar(a1, label = "Gauss")
# plot2
ax = fig.add_subplot(1,3,2, projection = '3d')
ax.set_xlabel("x(mm)")
ax.set_ylabel("y(mm)")
ax.set_zlabel("B total(Gauss)")
ax.view_init(ele_angle, rot_angle) #仰角/水平
# ax.set_title("original data")
ax.set_zticks(np.arange(0, max(mag_tot), 100))
a2 = ax.plot_surface(x, y, dense_1mm_data, rstride=1, cstride=1,cmap=cm.coolwarm, edgecolor='none')
fig.colorbar(a2, label = "Gauss")
# plot3
ax = fig.add_subplot(1,3,3, projection = '3d')
ax.set_xlabel("x(mm)")
ax.set_ylabel("y(mm)")
ax.set_zlabel("B total(Gauss)")
ax.view_init(ele_angle, rot_angle) #仰角/水平
# ax.set_title("diff data")
ax.set_zticks(np.arange(-20, max(mag_tot), 10))
a3 = ax.plot_surface(x, y, z - dense_1mm_data, rstride=1, cstride=1,cmap=cm.coolwarm, edgecolor='none')
fig.colorbar(a3, label = "Gauss")
plt.savefig('meaturement.png', dpi=600)
plt.show()
############################################## plot the epsilon diagram
# plt.plot(epsilon_array, similarity_array, color='blue', marker = "o")
# plt.xlabel('epsilon') # 設定 x 軸標題
# plt.ylabel('similarity') # 設定 y 軸標題
# plt.title('Test title', fontsize="18")
# plt.xlim(0, 20)
# plt.show()
plot_1600.py
import numpy as np
def get_1mm_dense_data(txt_path_1600):
pos_x = []
pos_y = []
mag_tot = []
f = open(txt_path_1600, 'r',encoding = "utf-8")
# data
for line in f.readlines():
s = line.split()
pos_x.append(int(s[3]))
pos_y.append(int(s[4]))
mag_tot.append(float(s[9]))
f.close()
min_x = min(pos_x)
min_y = min(pos_y)
# 歸零
for i in range(len(pos_x)):
pos_x[i] = pos_x[i] - min_x
pos_y[i] = pos_y[i] - min_y
pos_x = np.array(pos_x)
pos_y = np.array(pos_y)
len_x = max(pos_x) - min(pos_x) + 1
len_y = max(pos_y) - min(pos_y) + 1
print("origin measure x * y: ", len_x, len_y, "total measure: ", len_x * len_y)
mag_tot = np.array(mag_tot).reshape(len_x, len_y)
return mag_tot, len_x, len_y, min_x, min_y
plot_diff_z.py
import numpy as np
from scipy.interpolate import Rbf
from matplotlib import cm
import matplotlib.colors
import math
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D
from mpl_toolkits.mplot3d import axes3d
## 自動量測的路徑(目前用不到)
measure_result_txt = 'D:/MeasurementLog/MeasurementLog_result.txt'
txtfile_count = 8
initial_height = 41
def load_diff_z_data(height):
# data
pos_x = []
pos_y = []
mag_tot = []
# G code 路徑
txt_path = 'mea_result_R/Gcode_path_H' + str(height) + '.txt'
f = open(txt_path, 'r',encoding = "utf-8")
# count the row of txt
txt_count_row = len(open(txt_path,'r',encoding = "utf-8").readlines())
count = 0
# data
for line in f.readlines():
count = count+1
# 跳過第1筆資料與倒數最後兩筆資料
if ((count == 1) or (count == txt_count_row) or (count == (txt_count_row - 1))):
continue
s = line.split()
pos_x.append(int(s[3]))
pos_y.append(int(s[4]))
mag_tot.append(float(s[9]))
f.close()
pos_x_max = min(pos_x)
pos_y_max = min(pos_y)
for i in range(len(pos_x)):
pos_x[i] = abs(pos_x_max - pos_x[i])
pos_y[i] = abs(pos_y_max - pos_y[i])
pos_x = np.array(pos_x)
pos_y = np.array(pos_y)
mag_tot = np.array(mag_tot)
rbf = Rbf(pos_x, pos_y ,mag_tot, epsilon=2)
x, y = np.mgrid[min(pos_x):max(pos_x), min(pos_y):max(pos_y)]
z = rbf(x, y)
min_x = min(pos_x)
min_y = min(pos_y)
max_x = max(pos_x)
max_y = max(pos_y)
return z, min_x, min_y, max_x, max_y
data_for_diff_z = []
for i in range(txtfile_count):
tmp_z, min_x, min_y, max_x, max_y = load_diff_z_data(initial_height + i)
data_for_diff_z.append(tmp_z)
# print(data_for_diff_z[0])
x, y = np.mgrid[min_x:max_x, min_y:max_y]
print(np.shape(x))
print(np.shape(y))
# plot 3D scatter point of diff z
fig = plt.figure()
ele_angle = 70
rot_angle = 225
ax = plt.axes(projection='3d')
ax.set_xlabel("x(mm)")
ax.set_ylabel("y(mm)")
ax.set_zlabel("z(gauss)")
ax.view_init(ele_angle, rot_angle) #仰角/水平
norm = matplotlib.colors.Normalize()
for i in range(txtfile_count):
ax.scatter(x, y, (data_for_diff_z[i] * 0 ) + (initial_height + i), c=data_for_diff_z[i], cmap=cm.coolwarm, marker='.', label='My Points 1')
ax.set_title("interpolate data")
plt.show()
import numpy as np
from scipy.interpolate import Rbf
from matplotlib import cm
import matplotlib.colors
import math
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D
from mpl_toolkits.mplot3d import axes3d
from mpl_toolkits.mplot3d import Axes3D
## 自動量測的路徑(目前用不到)
# measure_result_txt = 'D:/MeasurementLog/MeasurementLog_result.txt'
txtfile_count = 4
initial_height = 43
limit_H = 46
TH = '0015'
# data
pos_x = []
pos_y = []
pos_z = []
mag_x = []
mag_y = []
mag_z = []
mag_tot = []
def load_diff_z_data(height, pos_x, pos_y, pos_z, mag_x, mag_y, mag_z, mag_tot):
tmp_x = []
tmp_y = []
tmp_z = []
# G code 路徑
txt_path = 'mea_result_R/Gcode_H' + str(height) + '_TH' + TH + '.txt'
# txt_path = 'mea_result_test/Gcode_path_H' + str(height) + '.txt'
f = open(txt_path, 'r',encoding = "latin1")
# count the row of txt
txt_count_row = len(open(txt_path,'r',encoding = "latin1").readlines())
count = 0
# data
for line in f.readlines():
count = count+1
# 跳過第1筆資料與倒數最後兩筆資料
if ((count == 1) or (count == txt_count_row) or (count == (txt_count_row - 1))):
continue
s = line.split()
tmp_x.append(int(s[3]))
tmp_y.append(int(s[4]))
tmp_z.append(int(s[5]))
mag_x.append(float(s[6]))
mag_y.append(float(s[7]))
mag_z.append(float(s[8]))
mag_tot.append(float(s[9]))
f.close()
pos_x_max = min(tmp_x)
pos_y_max = min(tmp_y)
for i in range(len(tmp_x)):
pos_x.append(abs(pos_x_max - tmp_x[i]))
pos_y.append(abs(pos_y_max - tmp_y[i]))
pos_z.append(abs(limit_H - tmp_z[i]))
return 0
for i in range(0, txtfile_count, 2):
_ = load_diff_z_data(initial_height + i , pos_x, pos_y, pos_z, mag_x, mag_y, mag_z, mag_tot)
################################################## 3D
# plot 3D scatter point of diff z
fig = plt.figure()
# ax = fig.gca(projection='3d')
ax = fig.add_subplot(111, projection='3d')
## color
norm = matplotlib.colors.Normalize()
mag_tot = np.array(mag_tot)
# Flatten and normalize # .ptp() peak to peak
color_set = (mag_tot - mag_tot.min()) / mag_tot.ptp()
# Repeat for each body line and two head lines
color_set = np.concatenate((color_set, np.repeat(color_set, 2)))
# Colormap
color_set = plt.cm.coolwarm(color_set)
q = 0
for x1,y1,z1,u1,v1,w1,l,c in zip(pos_x,pos_y,pos_z,mag_x,mag_y,mag_z,mag_tot, color_set):
q = ax.quiver(x1, y1, z1, u1, v1, w1, color = c,length=l*0.006, normalize=True, arrow_length_ratio=0.30, cmap = 'coolwarm')
ele_angle = 70
rot_angle = 225
ax.view_init(elev=ele_angle, azim=rot_angle) #3D
ax.set_xlabel("x(mm)")
ax.set_ylabel("y(mm)")
ax.set_zlabel("z(mm)")
ax.set_zlim([-2, 5])
ax.set_title("Gcode measurement")
q.set_array(np.linspace(0,mag_tot.max(),10)) # 設定 colorbar 數值範圍
fig.colorbar(q)
q.set_edgecolor(color_set)
q.set_facecolor(color_set)
plt.show()
RBF_xyz.py
import numpy as np
from scipy.interpolate import Rbf
from matplotlib import cm
import matplotlib.colors
import math
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D
from mpl_toolkits.mplot3d import axes3d
## 自動量測的路徑(目前用不到)
measure_result_txt = 'D:/MeasurementLog/MeasurementLog_result.txt'
txtfile_count = 4
initial_height = 25
TH = '0020'
MAG_NAME = "desolver"
# data
pos_x = []
pos_y = []
pos_z = []
mag_tot = []
def load_diff_z_data(height, pos_x, pos_y, pos_z, mag_tot):
tmp_x = []
tmp_y = []
# G code 路徑
# txt_path = 'mea_result_' + MAG_NAME + '/Gcode_H' + str(height) + '_TH' + TH + '.txt'
txt_path = 'mea_result_' + MAG_NAME + '/Gcode_' + MAG_NAME + '_TH' + TH + '_H' + str(height) + '_diffz.txt'
# txt_path = 'mea_result_test/Gcode_path_H' + str(height) + '.txt'
f = open(txt_path, 'r',encoding = "latin1")
# count the row of txt
# latin1/utf-8
txt_count_row = len(open(txt_path,'r',encoding = "latin1").readlines())
count = 0
# data
for line in f.readlines():
count = count+1
# 跳過第1筆資料與倒數最後兩筆資料
if ((count == 1) or (count == txt_count_row) or (count == (txt_count_row - 1))):
continue
s = line.split()
tmp_x.append(int(s[3]))
tmp_y.append(int(s[4]))
pos_z.append(height)
mag_tot.append(float(s[9]))
f.close()
pos_x_max = min(tmp_x)
pos_y_max = min(tmp_y)
for i in range(len(tmp_x)):
pos_x.append(abs(pos_x_max - tmp_x[i]))
pos_y.append(abs(pos_y_max - tmp_y[i]))
return 0
for i in range(0, txtfile_count, 1):
_ = load_diff_z_data(initial_height + i , pos_x, pos_y, pos_z, mag_tot)
pos_x = np.array(pos_x)
pos_y = np.array(pos_y)
pos_z = np.array(pos_z)
mag_tot = np.array(mag_tot)
min_x = min(pos_x)
min_y = min(pos_y)
max_x = max(pos_x)
max_y = max(pos_y)
min_z = min(pos_z)
max_z = max(pos_z)
x, y, z = np.mgrid[min_x:max_x, min_y:max_y, initial_height+2:initial_height+3:4j]
rbf = Rbf(pos_x, pos_y, pos_z, mag_tot, smooth = 0.001)
mag_interpolate = rbf(x, y, z)
print(np.shape(x))
print(np.shape(y))
print(np.shape(z))
print(np.shape(mag_interpolate))
print(f"Length of x: {len(x)}")
print(f"Length of y: {len(y)}")
print(f"Length of z: {len(z)}")
if len(x) == len(y) == len(z):
print("散点数量确认: 数组长度匹配。")
else:
print("错误: 数组长度不匹配!")
print(f"网格数据形状: {x.shape}, {y.shape}, {z.shape}")
print(f"插值结果形状: {mag_interpolate.shape}")
# plot 3D scatter point of diff z
fig = plt.figure()
ele_angle = 25
rot_angle = 225
ax = plt.axes(projection='3d')
ax.set_xlabel("x(mm)")
ax.set_ylabel("y(mm)")
ax.set_zlabel("z(mm)")
ax.view_init(ele_angle, rot_angle) #仰角/水平
# 確保 x, y, z 是一維數據
x_flat = x.flatten()
y_flat = y.flatten()
z_flat = z.flatten()
# 確保 mag_interpolate 也是一維數據
mag_flat = mag_interpolate.flatten()
# norm = matplotlib.colors.Normalize()
norm = matplotlib.colors.Normalize(vmin=mag_interpolate.min(), vmax=mag_interpolate.max())
z = abs(z - 35)
# pos_z = abs(pos_z - 49)
print()
# q = ax.scatter(x, y, z, c=mag_interpolate, cmap=cm.coolwarm, marker='.', label='My Points 1')
# q = ax.scatter(x.flatten(), y.flatten(), z.flatten(), c=mag_interpolate.flatten(), cmap=cm.coolwarm, marker='.')
q = ax.scatter(x_flat, y_flat, z_flat, c=mag_flat, cmap=cm.coolwarm, marker='.')
# q = ax.scatter(pos_x, pos_y, pos_z, c=mag_tot, cmap=cm.coolwarm, marker='.', label='My Points 1')
# q.set_array(np.linspace(0,mag_tot.max(),10)) # 設定 colorbar 數值範圍
fig.colorbar(q, label = "Gauss")
# ax.set_title("diff z control points")
ax.set_title("Resolver interpolate diff z data")
plt.show()