完成了电流->转矩的转变,基本完成

This commit is contained in:
2025-01-22 16:14:19 +08:00
parent 7f815ac63e
commit 92bdf133f2
48 changed files with 662 additions and 870240 deletions

View File

@ -66,21 +66,21 @@ def get_configs(config_file, w2t):
try:
with open(config_file, mode="r", encoding="utf-8") as f_config:
configs = json.load(f_config)
p_dir = config_file.split('/')[-2]
if not re.match("^[jJ][123]$", p_dir):
w2t("被处理的根文件夹命名必须是 [Jj][123] 的格式", "red", "DirNameError")
axis = int(p_dir[-1])
rrs = [abs(_) for _ in configs["TRANSMISSION"]["REDUCTION_RATIO_NUMERATOR"]] # 减速比rr for reduction ratio
avs = configs["MOTION"]["JOINT_MAX_SPEED"]
rr = rrs[axis-1]
av = avs[axis-1]
return av, rr
except Exception as Err:
clibs.insert_logdb("ERROR", "current", f"get_config: 无法打开 {config_file},获取配置文件参数错误 {Err}")
w2t(f"无法打开 {config_file}", color="red", desc="OpenFileError")
p_dir = config_file.split('/')[-2]
if not re.match("^[jJ][123]$", p_dir):
w2t("被处理的根文件夹命名必须是 [Jj][123] 的格式", "red", "DirNameError")
axis = int(p_dir[-1])
rrs = [abs(_) for _ in configs["TRANSMISSION"]["REDUCTION_RATIO_NUMERATOR"]] # 减速比rr for reduction ratio
avs = configs["MOTION"]["JOINT_MAX_SPEED"]
rr = rrs[axis-1]
av = avs[axis-1]
return av, rr
clibs.insert_logdb("ERROR", "current", f"get_config: 无法打开 {config_file}获取配置文件参数错误 {Err}")
w2t(f"无法打开 {config_file},或者使用了错误的机型配置文件,需检查\n", color="red", desc="OpenFileError")
def now_doing_msg(docs, flag, w2t):

View File

@ -32,8 +32,8 @@ def initialization(path, w2t, insert_logdb):
return data_files, config_file
def current_max(data_files, rcs, trq, w2t, insert_logdb):
insert_logdb("INFO", "current", "MAX: 正在处理最大电流值逻辑...")
def current_max(data_files, rts, trq, w2t, insert_logdb):
insert_logdb("INFO", "current", "MAX: 正在处理最大转矩值逻辑...")
current = {1: [], 2: [], 3: [], 4: [], 5: [], 6: []}
for data_file in data_files:
if data_file.endswith(".data"):
@ -44,17 +44,17 @@ def current_max(data_files, rcs, trq, w2t, insert_logdb):
insert_logdb("INFO", "current", f"MAX: 正在处理 {data_file}")
cols = len(df.columns)
axis = int(data_file.split("/")[-1].split("_")[0].removeprefix("j"))
rca = rcs[axis-1]
insert_logdb("INFO", "current", f"MAX: 最大列数为 {cols}{axis} 轴的额定电流{rca}")
rt = rts[axis-1]
insert_logdb("INFO", "current", f"MAX: 最大列数为 {cols}{axis} 轴的额定转矩{rt}")
col = df.columns.values[trq-1] # 获取 "device_servo_trq_feedback"
c_max = df[col].abs().max()
scale = 1000
_ = abs(c_max/scale*rca)
_ = abs(c_max/scale*rt)
current[axis].append(_)
w2t(f"{data_file}: {_:.4f}\n")
insert_logdb("INFO", "current", f"MAX: 获取到的列名为 {col},最大电流{_}")
w2t(f"{data_file}: {_:.2f}\n")
insert_logdb("INFO", "current", f"MAX: 获取到的列名为 {col},最大转矩{_}")
with open(data_file, "a+") as f_data:
csv_writer = csv.writer(f_data, delimiter="\t")
@ -69,12 +69,12 @@ def current_max(data_files, rcs, trq, w2t, insert_logdb):
w2t(f"{value:.4f} ")
w2t("\n")
w2t("\n【MAX】数据处理完毕......")
insert_logdb("INFO", "current", f"MAX: 获取最大电流值结束 current_max = {current}")
insert_logdb("INFO", "current", f"MAX: 获取最大转矩值结束 current_max = {current}")
return current
def current_avg(data_files, rcs, trqh, w2t, insert_logdb):
insert_logdb("INFO", "current", "AVG: 正在处理平均电流值逻辑...")
def current_avg(data_files, rts, trqh, w2t, insert_logdb):
insert_logdb("INFO", "current", "AVG: 正在处理平均转矩值逻辑...")
current = {1: [], 2: [], 3: [], 4: [], 5: [], 6: []}
for data_file in data_files:
if data_file.endswith(".data"):
@ -85,19 +85,19 @@ def current_avg(data_files, rcs, trqh, w2t, insert_logdb):
insert_logdb("INFO", "current", f"AVG: 正在处理 {data_file}")
cols = len(df.columns)
axis = int(data_file.split("/")[-1].split("_")[0].removeprefix("j"))
rca = rcs[axis-1]
insert_logdb("INFO", "current", f"AVG: 最大列数为 {cols}{axis} 轴的额定电流{rca}")
rt = rts[axis-1]
insert_logdb("INFO", "current", f"AVG: 最大列数为 {cols}{axis} 轴的额定转矩{rt}")
col = df.columns.values[trqh-1]
c_std = df[col].std()
c_avg = df[col].mean()
scale = 1000
_ = (abs(c_avg)+c_std*3)/scale*rca
_ = (abs(c_avg)+c_std*3)/scale*rt
current[axis].append(_)
w2t(f"{data_file}: {_:.4f}\n")
w2t(f"{data_file}: {_:.2f}\n")
insert_logdb("INFO", "current", f"AVG: 获取到的列名为 {col},平均电流{_}")
insert_logdb("INFO", "current", f"AVG: 获取到的列名为 {col},平均转矩{_}")
with open(data_file, "a+") as f_data:
csv_writer = csv.writer(f_data, delimiter="\t")
csv_writer.writerow([""] * (cols-1) + [_])
@ -111,11 +111,11 @@ def current_avg(data_files, rcs, trqh, w2t, insert_logdb):
w2t(f"{value:.4f} ")
w2t("\n")
w2t("\n【AVG】数据处理完毕......\n")
insert_logdb("INFO", "current", f"AVG: 获取平均电流值结束 current_avg = {current}")
insert_logdb("INFO", "current", f"AVG: 获取平均转矩值结束 current_avg = {current}")
return current
def current_cycle(data_files, vel, trq, trqh, sensor, rrs, rcs, params, w2t, insert_logdb):
def current_cycle(data_files, vel, trq, trqh, sensor, rrs, rts, params, w2t, insert_logdb):
result, hold, single, scenario, dur_time = None, [], [], [], 0
for data_file in data_files:
filename = data_file.split("/")[-1]
@ -137,16 +137,17 @@ def current_cycle(data_files, vel, trq, trqh, sensor, rrs, rcs, params, w2t, ins
wb = openpyxl.load_workbook(result)
ws = wb["统计"]
for idx in range(len(params)):
for idx in range(len(params)-1):
row = idx + 2
for col in range(2, 8):
ws.cell(row=row, column=col).value = params[idx][col-2]
ws.cell(row=1, column=1).value = params[-1]
if hold:
avg = current_avg(hold, rcs, trqh, w2t, insert_logdb)
avg = current_avg(hold, rts, trqh, w2t, insert_logdb)
for axis, cur_value in avg.items():
sht_name = f"J{axis}"
wb[sht_name]["O4"].value = float(cur_value[0])
wb[sht_name]["P4"].value = float(cur_value[0])
if dur_time == 0:
p_single(wb, single, vel, trq, sensor, rrs, w2t, insert_logdb)
@ -303,29 +304,31 @@ def p_single(wb, single, vel, trq, sensor, rrs, w2t, insert_logdb):
if abs(row_end+row_start-2*row_middle) > 1000:
insert_logdb("WARNING", "current", f"{axis} 轴数据占空比异常!")
data, first_c, second_c, third_c = [], vel-1, trq-1, sensor-1
data, first_c, second_c, third_c, fourth_c = [], vel-1, trq-1, sensor-1, sensor
for row in range(row_start, row_end+1):
data.append(df_origin.iloc[row, first_c])
data.append(df_origin.iloc[row, second_c])
data.append(df_origin.iloc[row, third_c])
data.append(df_origin.iloc[row, fourth_c])
i = 0
for row in ws.iter_rows(min_row=2, min_col=2, max_row=150000, max_col=4):
for row in ws.iter_rows(min_row=2, min_col=2, max_row=150000, max_col=5):
for cell in row:
try:
if i % 3 == 0:
ws.cell((i//3)+2, 1).value = float(((i//3)+1)/1000)
if i % 4 == 0:
ws.cell((i//4)+2, 1).value = float(((i//4)+1)/1000)
_ = f"{data[i]:.2f}"
cell.value = float(_)
i += 1
except Exception:
if i % 3 == 0:
ws.cell((i//3)+2, 1).value = None
if i % 4 == 0:
ws.cell((i//4)+2, 1).value = None
cell.value = None
i += 1
def p_scenario(wb, scenario, vel, trq, sensor, rrs, dur_time, w2t):
w2t(f"本次处理的是电机电流场景数据,场景运动周期为 {dur_time}s\n", "blue")
for data_file in scenario:
cycle = 0.001
axis = int(data_file.split("/")[-1].split("_")[0].removeprefix("j"))
@ -344,64 +347,60 @@ def p_scenario(wb, scenario, vel, trq, sensor, rrs, dur_time, w2t):
if row_end > df.index[-1]:
w2t(f"位置超限:{data_file} 共有 {df.index[-1]} 条数据,无法取到第 {row_end} 条数据,需要确认场景周期时间...", "red", "DataOverLimit")
data, first_c, second_c, third_c = [], vel-1, trq-1, sensor-1
data, first_c, second_c, third_c, fourth_c = [], vel-1, trq-1, sensor-1, sensor
for row in range(row_start, row_end+1):
data.append(df_origin.iloc[row, first_c])
data.append(df_origin.iloc[row, second_c])
data.append(df_origin.iloc[row, third_c])
data.append(df_origin.iloc[row, fourth_c])
i = 0
for row in ws.iter_rows(min_row=2, min_col=2, max_row=250000, max_col=4):
for row in ws.iter_rows(min_row=2, min_col=2, max_row=250000, max_col=5):
for cell in row:
try:
if i % 3 == 0:
ws.cell((i//3)+2, 1).value = float(((i//3)+1)/1000)
if i % 4 == 0:
ws.cell((i//4)+2, 1).value = float(((i//4)+1)/1000)
_ = f"{data[i]:.2f}"
cell.value = float(_)
i += 1
except Exception:
cell.value = None
if i % 3 == 0:
ws.cell((i//3)+2, 1).value = None
if i % 4 == 0:
ws.cell((i//4)+2, 1).value = None
i += 1
def get_configs(config_file, w2t, insert_logdb):
try:
if re.match("^[NXEC]B.*", config_file.split("/")[-1]):
robot_type = "工业"
else:
robot_type = "协作"
with open(config_file, mode="r", encoding="utf-8") as f_config:
configs = json.load(f_config)
version = configs["VERSION"]
sc = [0.001, 0.001, 0.001, 0.001, 0.001, 0.001] # 采样周期sc for sample cycle
r_rrs = configs["TRANSMISSION"]["REDUCTION_RATIO_NUMERATOR"] # 减速比rr for reduction ratio
m_avs = configs["MOTION"]["JOINT_MAX_SPEED"]
m_stall_ts = configs["MOTOR"]["STALL_TORQUE"] # 电机堵转转矩
m_rts = configs["MOTOR"]["RATED_TORQUE"] # 电机额定转矩rt for rated torque
m_max_ts = configs["MOTOR"]["PEAK_TORQUE"] # 电机峰值转矩
m_r_rpms = configs["MOTOR"]["RATED_SPEED"] # 电机额定转速
m_max_rpms = configs["MOTOR"]["MAX_SPEED"] # 电机最大转速
r_max_sst = configs["TRANSMISSION"]["MAX_TORQUE_FOR_START_AND_STOP"] # 减速器最大启停转矩sst for start and stop torque
r_max_t = configs["TRANSMISSION"]["MAX_PEAK_TORQUE"] # 减速器瞬时最大转矩
r_avg_t = configs["TRANSMISSION"]["MAX_AVERAGE_TORQUE"] # 减速器平均负载转矩允许最大值
insert_logdb("INFO", "current", f"get_configs: 机型文件版本 {config_file}_{version}")
insert_logdb("INFO", "current", f"get_configs: 减速比 {r_rrs}")
insert_logdb("INFO", "current", f"get_configs: 额定转矩 {m_rts}")
insert_logdb("INFO", "current", f"get_configs: 最大角速度 {m_avs}")
return sc, r_rrs, m_avs, m_stall_ts, m_rts, m_max_ts, m_r_rpms, m_max_rpms, r_max_sst, r_max_t, r_avg_t, robot_type
except Exception as Err:
insert_logdb("ERROR", "current", f"get_config: 无法打开 {config_file},获取配置文件参数错误 {Err}")
w2t(f"无法打开 {config_file}", color="red", desc="OpenFileError")
# 最大角速度,额定电流,减速比,额定转速
version = configs["VERSION"]
m_rts = configs["MOTOR"]["RATED_TORQUE"] # 电机额定转矩rt for rated torque
m_max_ts = configs["MOTOR"]["PEAK_TORQUE"] # 电机峰值转矩
m_stall_ts = configs["MOTOR"]["STALL_TORQUE"] # 电机堵转转矩
m_tcs = [1, 1, 1, 1, 1, 1] # 电机转矩常数tc for torque constant
m_rcs, m_max_cs, m_stall_cs = [], [], []
for i in range(len(m_tcs)):
m_rcs.append(m_rts[i]/m_tcs[i]) # 电机额定电流rc for rated current
m_max_cs.append(m_max_ts[i]/m_tcs[i]) # 电机最大电流
m_stall_cs.append(m_stall_ts[i]/m_tcs[i]) # 电机堵转电流
m_r_rpms = configs["MOTOR"]["RATED_SPEED"] # 电机额定转速
m_max_rpms = configs["MOTOR"]["MAX_SPEED"] # 电机最大转速
r_rrs = [abs(_) for _ in configs["TRANSMISSION"]["REDUCTION_RATIO_NUMERATOR"]] # 减速比rr for reduction ratio
r_max_sst = configs["TRANSMISSION"]["MAX_TORQUE_FOR_START_AND_STOP"] # 减速器最大启停转矩sst for start and stop torque
r_max_t = configs["TRANSMISSION"]["MAX_PEAK_TORQUE"] # 减速器瞬时最大转矩
sc = [0.001, 0.001, 0.001, 0.001, 0.001, 0.001] # 采样周期sc for sample cycle
r_rts = [1, 1, 1, 1, 1, 1] # 减速器额定转矩
r_r_rpms = [1, 1, 1, 1, 1, 1] # 减速器额定转速
r_life_cycle = [10000, 10000, 10000, 10000, 10000, 10000] # 减速器L10寿命
r_avg_t = configs["TRANSMISSION"]["MAX_AVERAGE_TORQUE"] # 减速器平均负载转矩允许最大值
insert_logdb("INFO", "current", f"get_configs: 机型文件版本 {config_file}_{version}")
insert_logdb("INFO", "current", f"get_configs: 减速比 {r_rrs}")
insert_logdb("INFO", "current", f"get_configs: 额定电流 {m_rcs}")
return m_rcs, m_max_cs, m_stall_cs, m_rts, m_max_ts, m_r_rpms, m_max_rpms, m_tcs, r_rrs, r_max_sst, r_max_t, sc, r_rts, r_r_rpms, r_life_cycle, r_avg_t
insert_logdb("ERROR", "current", f"get_config: 无法打开 {config_file}获取配置文件参数错误 {Err}")
w2t(f"无法打开 {config_file},或者使用了错误的机型配置文件,需检查\n", color="red", desc="OpenFileError")
def main():
@ -418,13 +417,13 @@ def main():
data_files, config_file = initialization(path, w2t, insert_logdb)
params = get_configs(config_file, w2t, insert_logdb)
rcs, rrs = params[0], params[8]
rts, rrs = params[4], params[1]
if sub == "max":
current_max(data_files, rcs, trq, w2t, insert_logdb)
current_max(data_files, rts, trq, w2t, insert_logdb)
elif sub == "avg":
current_avg(data_files, rcs, trqh, w2t, insert_logdb)
current_avg(data_files, rts, trqh, w2t, insert_logdb)
elif sub == "cycle":
current_cycle(data_files, vel, trq, trqh, sensor, rrs, rcs, params, w2t, insert_logdb)
current_cycle(data_files, vel, trq, trqh, sensor, rrs, rts, params, w2t, insert_logdb)
w2t("-"*60 + "\n全部处理完毕\n")
time_end = time.time()

View File

@ -1,6 +1,7 @@
import pandas
import csv
import openpyxl
import chardet
from common import clibs
@ -9,7 +10,7 @@ def find_point(bof, step, margin, threshold, pos, data_file, flag, df, row, w2t)
# pos: used for debug
# flag: greater than or lower than
row_target = None
row_origin = df.index[-1] - margin + 1
row_origin = len(df) - margin + 1
if flag == "gt":
while 0 < row < row_origin:
value = float(df.iloc[row, 2])
@ -22,7 +23,7 @@ def find_point(bof, step, margin, threshold, pos, data_file, flag, df, row, w2t)
else:
if bof == "backward":
clibs.insert_logdb("ERROR", "wavelogger", f"find_point-gt: [{pos}] 在 {data_file} 中,无法正确识别数据,需要确认...")
w2t(f"[{pos}] 在 {data_file} 中,无法正确识别数据,需要确认...", "red", "DataError")
w2t(f"[{pos}] 在 {data_file} 中,无法正确识别数据,需要确认...\n", "red", "DataError")
elif bof == "forward":
row_target = row + margin # to end while loop in function `single_file_proc`
elif flag == "lt":
@ -37,7 +38,7 @@ def find_point(bof, step, margin, threshold, pos, data_file, flag, df, row, w2t)
else:
if bof == "backward":
clibs.insert_logdb("ERROR", "wavelogger", f"find_point-lt: [{pos}] 在 {data_file} 中,无法正确识别数据,需要确认...")
w2t(f"[{pos}] 在 {data_file} 中,无法正确识别数据,需要确认...", "red", "DataError")
w2t(f"[{pos}] 在 {data_file} 中,无法正确识别数据,需要确认...\n", "red", "DataError")
elif bof == "forward":
row_target = row + margin # to end while loop in function `single_file_proc`
return row_target
@ -49,10 +50,14 @@ def get_cycle_info(data_file, step, margin, threshold, w2t):
# 1. 从最后读取数据无论是大于1还是小于1都舍弃找到相反的值的起始点
# 2. 从起始点,继续往前寻找,找到与之数值相反的中间点
# 3. 从中间点,继续往前寻找,找到与之数值相反的结束点,至此,得到了高低数值的时间区间以及一轮的周期时间
csv_reader = csv.reader(open(data_file))
with open(data_file, "rb") as f:
raw_data = f.read(1000)
result = chardet.detect(raw_data)
encoding = result['encoding']
csv_reader = csv.reader(open(data_file, encoding=encoding))
begin = int(next(csv_reader)[1])
df = pandas.read_csv(data_file, sep=",", encoding="gbk", skip_blank_lines=False, header=begin - 1, on_bad_lines="skip")
row = df.index[-1] - margin
df = pandas.read_csv(data_file, sep=",", encoding=encoding, skip_blank_lines=False, header=begin - 1, on_bad_lines="skip")
row = len(df) - margin
if float(df.iloc[row, 2]) < threshold:
row = find_point("backward", step, margin, threshold, "a1", data_file, "lt", df, row, w2t)
@ -73,7 +78,7 @@ def initialization(path, w2t):
for data_file in data_files:
if not data_file.lower().endswith(".csv"):
clibs.insert_logdb("ERROR", "wavelogger", f"init: {data_file} 文件后缀错误,只允许 .csv 文件,需要确认!")
w2t(f"{data_file} 文件后缀错误,只允许 .csv 文件,需要确认!", "red", "FileTypeError")
w2t(f"{data_file} 文件后缀错误,只允许 .csv 文件,需要确认!\n", "red", "FileTypeError")
return data_files
@ -88,7 +93,7 @@ def preparation(data_file, step, margin, threshold, wb, w2t):
def single_file_proc(ws, data_file, step, threshold, margin, data_length, df, cycle, w2t):
row, row_lt, row_gt, count, count_i, data = 1, 1, 1, 1, 1, {}
row_max = df.index[-1] - margin
row_max = len(df) - margin
while row < row_max:
if count not in data.keys():
data[count] = []
@ -98,9 +103,9 @@ def single_file_proc(ws, data_file, step, threshold, margin, data_length, df, cy
row_lt = find_point("forward", step, margin, threshold, "c"+str(row), data_file, "lt", df, row, w2t)
start = int(row_gt + (row_lt - row_gt - data_length) / 2)
end = start + data_length
value = df.iloc[start:end, 2].mean() + 3 * df.iloc[start:end, 2].std()
value = df.iloc[start:end, 2].astype(float).mean() + 3 * df.iloc[start:end, 2].astype(float).std()
if value > 1:
msg = f"{data_file} 文件第 {count} 轮 第 {count_i} 个数据可能有问题,需人工手动确认,确认有问题可删除,无问题则保留"
msg = f"{data_file} 文件第 {count} 轮 第 {count_i} 个数据可能有问题,需人工手动确认,确认有问题可删除,无问题则保留\n"
clibs.insert_logdb("WARNING", "wavelogger", msg)
w2t(msg, "orange")
data[count].append(value)