SAGE / realman /plot_from_hdf5.py
Jerrremy's picture
Upload realman data part 001
f99e13f verified
Raw
History Blame Contribute Delete
10.9 kB
import h5py
import numpy as np
import matplotlib.pyplot as plt
import os
from datetime import datetime
PLOT_SINGLE_JOINT = False # Whether to plot each joint separately
def smooth_curve(data, window_size=11):
"""Simple moving average filter"""
if window_size < 2:
return data
window = np.ones(int(window_size))/float(window_size)
# 'valid' mode will shorten the length, use 'edge' padding to keep the length unchanged
return np.convolve(data, window, mode='same')
def calc_numeric_velocity(time_list, position_list):
dt = np.diff(time_list)
dtheta = np.diff(position_list)
dt[dt == 0] = 0.005
vel = dtheta / dt
t_mid = (time_list[:-1] + time_list[1:]) / 2
return t_mid, vel
def plot_data(filename):
# 1. Read data
with h5py.File(f'{filename}', 'r') as f:
command_time_list = f['command_time_list'][:]
command_val_list = f['command_val_list'][:]
motion_name = f['motion_name'][()].decode('utf-8') # Get motion name
current_time = f['current_time'][()].decode('utf-8') # Get current time string
joint_time_list_left = f['robot1/joint_time_list'][:]
joint_val_list_left = f['robot1/joint_angle_list'][:] # shape: [N, 7]
joint_time_list_right = f['robot2/joint_time_list'][:]
joint_val_list_right = f['robot2/joint_angle_list'][:] # shape: [N, 7]
joint_velocity_left = f['robot1/joint_velocity_list'][:]
joint_current_left = f['robot1/joint_current_list'][:]
joint_temperature_left = f['robot1/joint_temperature_list'][:]
joint_velocity_right = f['robot2/joint_velocity_list'][:]
joint_current_right = f['robot2/joint_current_list'][:]
joint_temperature_right = f['robot2/joint_temperature_list'][:]
print(f"Loaded data: {len(command_time_list)} command points")
print(f"LeftArm joint data shape: {joint_val_list_left.shape}")
print(f"RightArm joint data shape: {joint_val_list_right.shape}")
print(f"LeftArm joint time points: {len(joint_time_list_left)}")
print(f"RightArm joint time points: {len(joint_time_list_right)}")
# 2. Generate save directory
parent_dir = os.path.abspath(os.path.dirname(__file__))
plot_data_dir = os.path.join(parent_dir, 'plot_data', motion_name + current_time)
os.makedirs(plot_data_dir, exist_ok=True)
print(f"saving images in: {plot_data_dir}")
if PLOT_SINGLE_JOINT:
# 3. Plot 14 images separately
for i in range(7):
# leftarm
plt.figure(figsize=(10, 5))
plt.plot(command_time_list, command_val_list[:, i], label='Command (LeftArm, rad)', color='b', linestyle='-')
plt.plot(joint_time_list_left, joint_val_list_left[:, i], label=f'LeftArm Joint {i+1} (rad)', color='r', linestyle='--')
plt.xlabel('Elapsed Time (s)')
plt.ylabel('Angle (rad)')
plt.title(f'Command vs LeftArm Joint {i+1} (rad)')
plt.legend(loc='best', fontsize=10)
plt.grid(True)
plt.tight_layout()
save_path = os.path.join(plot_data_dir, f'leftarm_joint_{i+1}.png')
plt.savefig(save_path)
plt.close()
print(f"image saved: {save_path}")
# rightarm
plt.figure(figsize=(10, 5))
plt.plot(command_time_list, command_val_list[:, i+7], label='Command (RightArm, rad)', color='b', linestyle='-')
plt.plot(joint_time_list_right, joint_val_list_right[:, i], label=f'RightArm Joint {i+1} (rad)', color='g', linestyle='--')
plt.xlabel('Elapsed Time (s)')
plt.ylabel('Angle (rad)')
plt.title(f'Command vs RightArm Joint {i+1} (rad)')
plt.legend(loc='best', fontsize=10)
plt.grid(True)
plt.tight_layout()
save_path = os.path.join(plot_data_dir, f'rightarm_joint_{i+1}.png')
plt.savefig(save_path)
plt.close()
print(f"image saved: {save_path}")
# 4. alldata.png: 14 subplots (7 left + 7 right)
fig, axs = plt.subplots(14, 1, figsize=(14, 32), sharex=True)
for i in range(7):
axs[i].plot(command_time_list, command_val_list[:, i], label='Command (LeftArm, rad)', color='b', linestyle='-')
axs[i].plot(joint_time_list_left, joint_val_list_left[:, i], label=f'LeftArm Joint {i+1} (rad)', color='r', linestyle='--')
axs[i].set_ylabel('Angle (rad)')
axs[i].set_title(f'LeftArm Joint {i+1}')
axs[i].legend(loc='best', fontsize=9)
axs[i].grid(True)
for i in range(7):
axs[i+7].plot(command_time_list, command_val_list[:, i+7], label='Command (RightArm, rad)', color='b', linestyle='-')
axs[i+7].plot(joint_time_list_right, joint_val_list_right[:, i], label=f'RightArm Joint {i+1} (rad)', color='g', linestyle='--')
axs[i+7].set_ylabel('Angle (rad)')
axs[i+7].set_title(f'RightArm Joint {i+1}')
axs[i+7].legend(loc='best', fontsize=9)
axs[i+7].grid(True)
axs[-1].set_xlabel('Elapsed Time (s)')
fig.suptitle(f'Command and Actual Angle || {motion_name}', fontsize=18)
plt.tight_layout(rect=[0, 0, 1, 0.97])
alldata_path = os.path.join(plot_data_dir, 'alldata.png')
plt.savefig(alldata_path)
plt.close()
print(f"all joints plot saved: {alldata_path}")
# ==== Plot "raw velocity" ====
fig, axs = plt.subplots(14, 1, figsize=(14, 32), sharex=True)
for i in range(7):
orig_vel_left = joint_velocity_left[:, i]
axs[i].plot(joint_time_list_left, orig_vel_left, label=f'LeftArm Joint {i+1} (deg/s)', color='r')
axs[i].set_ylabel('Velocity (deg/s)')
axs[i].set_title(f'LeftArm Joint {i+1}')
axs[i].legend(loc='best', fontsize=9)
axs[i].grid(True)
for i in range(7):
orig_vel_right = joint_velocity_right[:, i]
axs[i+7].plot(joint_time_list_right, orig_vel_right, label=f'RightArm Joint {i+1} (deg/s)', color='g')
axs[i+7].set_ylabel('Velocity (deg/s)')
axs[i+7].set_title(f'RightArm Joint {i+1}')
axs[i+7].legend(loc='best', fontsize=9)
axs[i+7].grid(True)
axs[-1].set_xlabel('Elapsed Time (s)')
fig.suptitle(f'Raw Joint Velocity (deg/s) || {motion_name}', fontsize=18)
plt.tight_layout(rect=[0, 0, 1, 0.97])
raw_vel_path = os.path.join(plot_data_dir, 'alldata_velocity_raw.png')
plt.savefig(raw_vel_path)
plt.close()
print(f"raw velocity plot saved: {raw_vel_path}")
# ==== Plot compare: numerical diff & smoothing vs raw velocity ====
fig, axs = plt.subplots(14, 1, figsize=(14, 32), sharex=True)
for i in range(7):
t_left, num_vel_left = calc_numeric_velocity(joint_time_list_left, joint_val_list_left[:, i])
num_vel_left_deg = num_vel_left
num_vel_left_smooth = smooth_curve(num_vel_left_deg, window_size=11)
orig_vel_left = joint_velocity_left[:, i]
axs[i].plot(t_left, num_vel_left_smooth, label=f'NumDiff Smoothed (deg/s)', color='orange', linestyle='-')
axs[i].plot(joint_time_list_left, orig_vel_left, label=f'Raw (deg/s)', color='r', linestyle='--')
axs[i].set_ylabel('Velocity (deg/s)')
axs[i].set_title(f'LeftArm Joint {i+1}')
axs[i].legend(loc='best', fontsize=9)
axs[i].grid(True)
for i in range(7):
t_right, num_vel_right = calc_numeric_velocity(joint_time_list_right, joint_val_list_right[:, i])
num_vel_right_deg = num_vel_right
num_vel_right_smooth = smooth_curve(num_vel_right_deg, window_size=11)
orig_vel_right = joint_velocity_right[:, i]
axs[i+7].plot(t_right, num_vel_right_smooth, label=f'NumDiff Smoothed (deg/s)', color='orange', linestyle='-')
axs[i+7].plot(joint_time_list_right, orig_vel_right, label=f'Raw (deg/s)', color='g', linestyle='--')
axs[i+7].set_ylabel('Velocity (deg/s)')
axs[i+7].set_title(f'RightArm Joint {i+1}')
axs[i+7].legend(loc='best', fontsize=9)
axs[i+7].grid(True)
axs[-1].set_xlabel('Elapsed Time (s)')
fig.suptitle(f'Velocity Comparison (NumDiff Smoothed vs Raw) || {motion_name}', fontsize=18)
plt.tight_layout(rect=[0, 0, 1, 0.97])
vel_compare_path = os.path.join(plot_data_dir, 'alldata_velocity_compare.png')
plt.savefig(vel_compare_path)
plt.close()
print(f"velocity compare plot saved: {vel_compare_path}")
# ==== Plot current ====
fig, axs = plt.subplots(14, 1, figsize=(14, 32), sharex=True)
for i in range(7):
axs[i].plot(joint_time_list_left, joint_current_left[:, i], label=f'LeftArm Joint {i+1} current (A)', color='r')
axs[i].set_ylabel('Current (A)')
axs[i].set_title(f'LeftArm Joint {i+1}')
axs[i].legend(loc='best', fontsize=9)
axs[i].grid(True)
for i in range(7):
axs[i+7].plot(joint_time_list_right, joint_current_right[:, i], label=f'RightArm Joint {i+1} current (A)', color='g')
axs[i+7].set_ylabel('Current (A)')
axs[i+7].set_title(f'RightArm Joint {i+1}')
axs[i+7].legend(loc='best', fontsize=9)
axs[i+7].grid(True)
axs[-1].set_xlabel('Elapsed Time (s)')
fig.suptitle(f'Joint Current || {motion_name}', fontsize=18)
plt.tight_layout(rect=[0, 0, 1, 0.97])
cur_img_path = os.path.join(plot_data_dir, 'alldata_current.png')
plt.savefig(cur_img_path)
plt.close()
print(f"current plot saved: {cur_img_path}")
# ==== Plot temperature ====
fig, axs = plt.subplots(14, 1, figsize=(14, 32), sharex=True)
for i in range(7):
axs[i].plot(joint_time_list_left, joint_temperature_left[:, i], label=f'LeftArm Joint {i+1} temperature (°C)', color='r')
axs[i].set_ylabel('Temp (°C)')
axs[i].set_title(f'LeftArm Joint {i+1}')
axs[i].legend(loc='best', fontsize=9)
axs[i].grid(True)
for i in range(7):
axs[i+7].plot(joint_time_list_right, joint_temperature_right[:, i], label=f'RightArm Joint {i+1} temperature (°C)', color='g')
axs[i+7].set_ylabel('Temp (°C)')
axs[i+7].set_title(f'RightArm Joint {i+1}')
axs[i+7].legend(loc='best', fontsize=9)
axs[i+7].grid(True)
axs[-1].set_xlabel('Elapsed Time (s)')
fig.suptitle(f'Joint Temperature || {motion_name}', fontsize=18)
plt.tight_layout(rect=[0, 0, 1, 0.97])
temp_img_path = os.path.join(plot_data_dir, 'alldata_temperature.png')
plt.savefig(temp_img_path)
plt.close()
print(f"temperature plot saved: {temp_img_path}")
if __name__ == "__main__":
run_dir = 'robot1/robot1_0kg'
files = [f for f in os.listdir(run_dir) if os.path.isfile(os.path.join(run_dir, f))]
print(f"Found {len(files)} files in {run_dir}:")
for filename in files:
print(f"Plotting {filename} ...")
plot_data(run_dir + "/" + filename)
print("All plotting completed.")