| import pandas as pd
|
| import argparse
|
| import os
|
| import numpy as np
|
| from scipy.ndimage import gaussian_filter1d
|
| from sklearn.preprocessing import MinMaxScaler
|
|
|
|
|
|
|
|
|
| def angle_between_vectors(v1, v2):
|
| """Calculate the angle between two vectors."""
|
| v1 = v1 / np.linalg.norm(v1)
|
| v2 = v2 / np.linalg.norm(v2)
|
| u_minus_v = v1 - v2
|
| u_plus_v = v1 + v2
|
| angle = 2 * np.arctan2(np.linalg.norm(u_minus_v), np.linalg.norm(u_plus_v))
|
| return np.degrees(angle)
|
| def smooth_velocity(velocity, sigma=5):
|
| return gaussian_filter1d(velocity, sigma=sigma)
|
| def calculate_angular_velocity(forward_vectors, timestamps):
|
| """计算角速度"""
|
| angles = np.array(
|
| [angle_between_vectors(forward_vectors[i], forward_vectors[i + 1]) if i + 1 < len(forward_vectors) else 0 for i
|
| in range(len(forward_vectors) - 1)])
|
|
|
| times = np.diff(timestamps)/1000
|
|
|
| if len(times) > 0:
|
| angular_velocities = np.insert(angles / times, 0, 0)
|
| else:
|
| angular_velocities = np.array([0])
|
| return angular_velocities
|
| def calculate_linear_velocity(positions, timestamps):
|
| """计算线性速度"""
|
| distances = np.linalg.norm(np.diff(positions, axis=0), axis=1)
|
| times = np.diff(timestamps)/1000
|
| linear_velocities = np.insert(distances / times, 0,0)
|
| return linear_velocities
|
| def calculate_direction(start_position, current_position):
|
| """计算方向"""
|
| direction = current_position - start_position
|
| norm = np.linalg.norm(direction)
|
| return direction / norm if norm != 0 else np.zeros_like(direction)
|
| def calculate_acceleration(velocities, timestamps):
|
| """根据速度计算加速度"""
|
| accels = [0]
|
| for i in range(1, len(velocities)):
|
| accel = (velocities[i] - velocities[i-1]) / ((timestamps[i] - timestamps[i-1])/1000)
|
| accels.append(accel)
|
| return np.array(accels)
|
|
|
|
|
| def process_single_sequence(df):
|
| """处理groupBy之后的单个序列DataFrame,计算所有模态的角速度、线性速度、方向和旋转轴"""
|
|
|
| timestamps = df['TimeStamp'].values
|
|
|
| modalities = ['HMD', 'Hand', 'Leye']
|
| for modality in modalities:
|
|
|
| if all(f'{modality}ForwardV{i}' in df.columns for i in ['X', 'Y', 'Z']):
|
| forward_vectors = df[[f'{modality}ForwardVX', f'{modality}ForwardVY', f'{modality}ForwardVZ']].values
|
| initial_forward_vector = forward_vectors[0]
|
| df[f'{modality}A'] = [(angle_between_vectors(initial_forward_vector, fv)) for fv in forward_vectors]
|
| angular_velocity = calculate_angular_velocity(forward_vectors, timestamps)
|
| smoothed_angular_velocity = smooth_velocity(angular_velocity)
|
| df[f'{modality}AV'] = smoothed_angular_velocity
|
| df[f'{modality}AAcc'] = calculate_acceleration(smoothed_angular_velocity, timestamps)
|
|
|
| if modality == 'Hand':
|
| initial_forward_vector = forward_vectors[0]
|
| rotation_axes = np.array([np.cross(initial_forward_vector, fv) for fv in forward_vectors])
|
| rotation_axes_normalized = np.array(
|
| [axis / np.linalg.norm(axis) if np.linalg.norm(axis) != 0 else np.array([0.0, 0.0, 0.0]) for axis in
|
| rotation_axes]
|
| )
|
| df[f'{modality}RotationAxis_X'] = rotation_axes_normalized[:, 0]
|
| df[f'{modality}RotationAxis_Y'] = rotation_axes_normalized[:, 1]
|
| df[f'{modality}RotationAxis_Z'] = rotation_axes_normalized[:, 2]
|
|
|
|
|
| if modality in ['HMD', 'Hand'] and all(f'{modality}Position{i}' in df.columns for i in ['X', 'Y', 'Z']):
|
| positions = df[[f'{modality}PositionX', f'{modality}PositionY', f'{modality}PositionZ']].values
|
| initial_position = positions[0]
|
| linear_velocity = calculate_linear_velocity(positions, timestamps)
|
| df[f'{modality}L'] = [np.linalg.norm(pos-initial_position) for pos in positions]
|
| smoothed_velocity = smooth_velocity(linear_velocity)
|
| df[f'{modality}LV'] = smoothed_velocity
|
| df[f'{modality}LAcc'] = calculate_acceleration(smoothed_velocity, timestamps)
|
|
|
| if modality == 'Hand':
|
| start_position = positions[0]
|
| directions = np.array([calculate_direction(start_position, pos) for pos in positions])
|
| df[f'{modality}Direction_X'] = directions[:, 0]
|
| df[f'{modality}Direction_Y'] = directions[:, 1]
|
| df[f'{modality}Direction_Z'] = directions[:, 2]
|
|
|
| return df
|
|
|
|
|
| def label_trials_with_motion_metrics(df):
|
|
|
| def label_group(group):
|
|
|
| total_linear_distance = group['HandL'].iloc[-1]
|
| total_angular_distance = group['HandA'].iloc[-1]
|
|
|
| group['LLabel'] = total_linear_distance
|
| group['ALabel'] = total_angular_distance
|
| return group
|
|
|
| df_labeled = df.groupby(['ParticipantID', 'BlockID', 'TrialID'], group_keys=False).apply(label_group)
|
| return df_labeled
|
|
|
|
|
| def split_data_by_theta_grouped(df):
|
| grouped = df.groupby(['ParticipantID', 'BlockID', 'TrialID'])
|
| theta_groups = {}
|
|
|
| for _, group in grouped:
|
| theta_value = group['Theta'].iloc[0]
|
| if theta_value not in theta_groups:
|
| theta_groups[theta_value] = []
|
| theta_groups[theta_value].append(group)
|
| train_dfs = []
|
| test_dfs = []
|
| for theta_value, groups in theta_groups.items():
|
|
|
| n_train = int(len(groups) * 0.8)
|
|
|
| np.random.seed(1)
|
| train_indices = np.random.choice(len(groups), size=n_train, replace=False)
|
| train_groups = [groups[i] for i in train_indices]
|
|
|
| test_groups = [groups[i] for i in range(len(groups)) if i not in train_indices]
|
|
|
| train_df = pd.concat(train_groups)
|
| test_df = pd.concat(test_groups)
|
| train_dfs.append(train_df)
|
| test_dfs.append(test_df)
|
|
|
| final_train_df = pd.concat(train_dfs).sort_index()
|
| final_test_df = pd.concat(test_dfs).sort_index()
|
| return final_train_df, final_test_df
|
|
|
|
|
| def split_data_by_theta_grouped(df):
|
| grouped = df.groupby(['ParticipantID', 'BlockID', 'TrialID'])
|
| theta_groups = {}
|
|
|
| for _, group in grouped:
|
| theta_value = group['Theta'].iloc[0]
|
| if theta_value not in theta_groups:
|
| theta_groups[theta_value] = []
|
| theta_groups[theta_value].append(group)
|
| train_dfs = []
|
| test_dfs = []
|
| for theta_value, groups in theta_groups.items():
|
|
|
| n_train = int(len(groups) * 0.8)
|
|
|
| np.random.seed(1)
|
| train_indices = np.random.choice(len(groups), size=n_train, replace=False)
|
| train_groups = [groups[i] for i in train_indices]
|
|
|
| test_groups = [groups[i] for i in range(len(groups)) if i not in train_indices]
|
|
|
| train_df = pd.concat(train_groups)
|
| test_df = pd.concat(test_groups)
|
| train_dfs.append(train_df)
|
| test_dfs.append(test_df)
|
|
|
| final_train_df = pd.concat(train_dfs).sort_index()
|
| final_test_df = pd.concat(test_dfs).sort_index()
|
| return final_train_df, final_test_df
|
|
|
|
|
|
|
| def preprocess_features(train_df, test_df):
|
|
|
| negative_value_features = ['HandAAcc', 'HMDAAcc',"LeyeAAcc","HandLAcc","HMDLAcc"]
|
| other_features = ["HMDA", "HMDAV", "HandA", "HandAV", "LeyeA", "LeyeAV","HMDL", "HMDLV","HandL", "HandLV"]
|
|
|
| scaler_negatives = MinMaxScaler(feature_range=(-1, 1))
|
| scaler_others = MinMaxScaler(feature_range=(0, 1))
|
|
|
| train_df[negative_value_features] = scaler_negatives.fit_transform(train_df[negative_value_features])
|
| test_df[negative_value_features] = scaler_negatives.transform(test_df[negative_value_features])
|
| train_df[other_features] = scaler_others.fit_transform(train_df[other_features])
|
| test_df[other_features] = scaler_others.transform(test_df[other_features])
|
| return train_df, test_df
|
|
|
|
|
| def main(Participant_ID):
|
|
|
| input_file_path = f'../Data/Study2Evaluation/{Participant_ID}_Trajectory.csv'
|
| output_train_path = f'../Data/Study2Evaluation/Preprocessed/{Participant_ID}_train_data_preprocessed_evaluation.csv'
|
| output_test_path = f'../Data/Study2Evaluation/Preprocessed/{Participant_ID}_test_data_preprocessed_evaluation.csv'
|
|
|
| data=pd.read_csv(input_file_path)
|
| data_cleaned = data.loc[:, ~data.columns.str.contains('^Unnamed')]
|
| data_no_error = data_cleaned[data_cleaned['isError'] == False]
|
| final_data = data_no_error[(data_no_error['TrialID'] != 0) & (data_no_error['TrialID'] != 6) & (data_no_error['TrialID'] != 12)
|
| & (data_no_error['TrialID'] != 18) & (data_no_error['TrialID'] != 24) & (data_no_error['TrialID'] != 30) & (data_no_error['TrialID'] != 36)]
|
|
|
| processed_groups = final_data.groupby(['ParticipantID','BlockID', 'TrialID']).apply(process_single_sequence)
|
| processed_df = processed_groups.reset_index(drop=True)
|
|
|
|
|
| df_with_features_labelled = label_trials_with_motion_metrics(processed_df.copy())
|
| final_train_df, final_test_df = split_data_by_theta_grouped(df_with_features_labelled)
|
|
|
| final_train_df_preprocessed, final_test_df_preprocessed = preprocess_features(final_train_df.copy(), final_test_df.copy())
|
|
|
| final_train_df_preprocessed.to_csv(output_train_path, index=False)
|
| final_test_df_preprocessed.to_csv(output_test_path, index=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| if __name__ == '__main__':
|
| for i in range(79, 80):
|
| main(str(i))
|
|
|
|
|
|
|
|
|
|
|