Skip to content

Commit 3dd86d4

Browse files
committed
refresh all scripts
1 parent cbdcdf0 commit 3dd86d4

8 files changed

+105
-63
lines changed

scripts/feature_selection.py

+1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from sklearn.feature_selection import VarianceThreshold
1313
import matplotlib.pyplot as plt
1414

15+
1516
# the current file path
1617
file_path = os.path.dirname(__file__)
1718

scripts/hmm_based_state_estimation.py

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
#!/usr/bin/python
2+
import numpy as np
3+
from hmmlearn import hmm
4+
import os
5+
import ConfigParser
6+
from sklearn.externals import joblib
7+
from sklearn.mixture import GaussianMixture
8+
9+
# read the current file path
10+
file_path = os.path.dirname(__file__)
11+
# read model cfg file
12+
cp_models = ConfigParser.SafeConfigParser()
13+
cp_models.read(os.path.join(file_path, '../cfg/models.cfg'))
14+
datasets_path = os.path.join(file_path, cp_models.get('datasets', 'path'))
15+
16+
# load dataset
17+
datasets_raw = joblib.load(os.path.join(datasets_path, 'pkl/datasets_raw.pkl'))
18+
19+
# task name
20+
task_name = joblib.load(os.path.join(datasets_path, 'pkl/task_name_list.pkl'))
21+
22+
# joint number
23+
num_joints = cp_models.getint('datasets', 'num_joints')
24+
25+
26+
def main():
27+
states = task_name
28+
n_task = len(states)
29+
30+
# don't know the task prior here
31+
start_probability = np.array(([1.0/n_task]*n_task))
32+
33+
# don't know the task transition probability here
34+
transition_probability = np.array([1.0/n_task]*n_task*n_task).reshape([n_task, n_task])
35+
36+
gmm_model_full = [GaussianMixture(n_components = 3) for i in range(n_task)]
37+
38+
task_data_full = []
39+
for task_idx, task_data in enumerate(datasets_raw):
40+
demo_data_full = np.array([]).reshape(0, num_joints)
41+
for demo_data in task_data:
42+
h = np.hstack([demo_data['left_hand'], demo_data['left_joints']])
43+
demo_data_full = np.vstack([demo_data_full, h])
44+
task_data_full.append(demo_data_full)
45+
46+
for task_data, gmm_model in zip(task_data_full, gmm_model_full):
47+
gmm_model.fit(task_data)
48+
49+
# hmm_model = hmm.GMMHMM()
50+
# hmm_model.n_components = n_task
51+
# hmm_model.startprob_ = start_probability
52+
# hmm_model.transmat_ = transition_probability
53+
# hmm_model.means_ = gmm_model_full[0].means_
54+
55+
# testing
56+
hmm_model1 = hmm.GMMHMM()
57+
hmm_model1.n_components = 10
58+
hmm_model1.fit(task_data_full[0])
59+
print 1
60+
61+
if __name__ == '__main__':
62+
main()

scripts/ipromps_lib.py

-4
Original file line numberDiff line numberDiff line change
@@ -452,11 +452,7 @@ def __init__(self, num_joints=28, num_obs_joints=None, num_basis=11, sigma_basis
452452
:param num_alpha_candidate:
453453
"""
454454
# compute the obs noise after preprocessing
455-
# noise_cov_full = min_max_scaler.scale_.T * sigmay * min_max_scaler.scale_
456-
# noise_cov_full = np.diag(min_max_scaler.scale_, 0) * np.diag(min_max_scaler.scale_, 0) * sigmay
457-
# noise_cov_full = np.diag(min_max_scaler.scale_, 0) * sigmay
458455
noise_cov_full = sigmay
459-
460456
NDProMP.__init__(self, num_joints=num_joints, num_basis=num_basis,
461457
sigma_basis=sigma_basis, num_samples=num_samples, sigmay=noise_cov_full)
462458

scripts/load_data.py

+8-14
Original file line numberDiff line numberDiff line change
@@ -40,19 +40,18 @@ def main():
4040
datasets_raw = []
4141
for task_path in task_path_list:
4242
task_csv_path = os.path.join(task_path, 'csv')
43-
print('Loading data from ' + task_csv_path)
44-
demo_path_list = glob.glob(os.path.join(task_csv_path, '201*')) # the prefix of data, guarantee the right file
43+
print('Loading data from: ' + task_csv_path)
44+
demo_path_list = glob.glob(os.path.join(task_csv_path, '201*')) # the prefix of dataset file
4545
demo_temp = []
4646
for demo_path in demo_path_list:
4747
data_csv = pd.read_csv(os.path.join(demo_path, 'multiModal_states.csv')) # the file name of csv
48-
# the info of interest: convert the object to int / float
4948
demo_temp.append({
50-
'stamp': (data_csv.values[:, 2].astype(int)-data_csv.values[0, 2])*1e-9, # the time stamp
51-
'left_hand':np.hstack([
49+
'stamp': (data_csv.values[:, 2].astype(int)-data_csv.values[0, 2])*1e-9,
50+
'left_hand': np.hstack([
5251
data_csv.values[:, 207:210].astype(float), # human left hand position
5352
data_csv.values[:, 7:15].astype(float), # emg
5453
]),
55-
'left_joints': data_csv.values[:, 317:320].astype(float) # robot ee actually
54+
'left_joints': data_csv.values[:, 317:324].astype(float) # robot ee actually
5655
})
5756
datasets_raw.append(demo_temp)
5857

@@ -69,7 +68,6 @@ def main():
6968
# append them to list
7069
demo_norm_temp.append({
7170
'alpha': time_stamp[-1],
72-
# 'emg': emg_filtered,
7371
'left_hand': left_hand_filtered,
7472
'left_joints': left_joints_filtered
7573
})
@@ -87,13 +85,11 @@ def main():
8785
left_hand_filtered = gaussian_filter1d(demo_data['left_hand'].T, sigma=sigma).T
8886
left_joints_filtered = gaussian_filter1d(demo_data['left_joints'].T, sigma=sigma).T
8987
# normalize the datasets
90-
# emg_norm = griddata(time_stamp, emg_filtered, grid, method='linear')
9188
left_hand_norm = griddata(time_stamp, left_hand_filtered, grid, method='linear')
9289
left_joints_norm = griddata(time_stamp, left_joints_filtered, grid, method='linear')
9390
# append them to list
9491
demo_norm_temp.append({
9592
'alpha': time_stamp[-1],
96-
# 'emg': emg_norm,
9793
'left_hand': left_hand_norm,
9894
'left_joints': left_joints_norm
9995
})
@@ -106,7 +102,7 @@ def main():
106102
datasets4train.append(data)
107103
y_full = np.array([]).reshape(0, num_joints)
108104
for task_idx, task_data in enumerate(datasets4train):
109-
print('Preprocessing data of task: ' + task_name_list[task_idx])
105+
print('Preprocessing data for task: ' + task_name_list[task_idx])
110106
for demo_data in task_data:
111107
h = np.hstack([demo_data['left_hand'], demo_data['left_joints']])
112108
y_full = np.vstack([y_full, h])
@@ -120,11 +116,9 @@ def main():
120116
temp = datasets_norm_full[(task_idx * num_demo + demo_idx) * len_norm:
121117
(task_idx * num_demo + demo_idx) * len_norm + len_norm, :]
122118
datasets_temp.append({
123-
# 'left_hand': temp[:, 0:3],
124-
# 'left_joints': temp[:, 3:6],
125119
'left_hand': temp[:, 0:11],
126-
'left_joints': temp[:, 11:14],
127-
'alpha': datasets4train[task_idx][demo_idx]['alpha']})
120+
'left_joints': temp[:, 11:18],
121+
'alpha': datasets4train[task_idx][demo_idx]['alpha']})
128122
datasets_norm_preproc.append(datasets_temp)
129123

130124
# save all the datasets

scripts/noise_cov_cal.py

+9-5
Original file line numberDiff line numberDiff line change
@@ -20,16 +20,20 @@ def main():
2020
csv_path = os.path.join(datasets_path, 'info/noise/multiModal_states.csv')
2121
data = pd.read_csv(csv_path)
2222

23-
# extract the all signals data
23+
# # extract the all signals data
24+
# emg = data.values[:, 7:15].astype(float)
25+
# left_hand = data.values[:, 207:210].astype(float)
26+
# left_joints = data.values[:, 317:320].astype(float) # robot ee actually
27+
# # left_joints = data.values[:, 317:324].astype(float) # robot ee actually
28+
# # left_joints = data.values[:, 99:106].astype(float)
29+
30+
# extract the all signals data ORIENTATION
2431
emg = data.values[:, 7:15].astype(float)
2532
left_hand = data.values[:, 207:210].astype(float)
26-
left_joints = data.values[:, 317:320].astype(float) # robot ee actually
27-
# left_joints = data.values[:, 317:324].astype(float) # robot ee actually
28-
# left_joints = data.values[:, 99:106].astype(float)
33+
left_joints = data.values[:, 317:324].astype(float) # robot ee actually
2934

3035
# stack them as a big matrix
3136
full_data = np.hstack([left_hand, emg, left_joints])[1200:, :]
32-
# full_data = np.hstack([left_hand, left_joints])
3337
full_data = min_max_scaler.transform(full_data)
3438

3539
# compute the noise observation covariance matrix

scripts/test_data_gen.py

+4-5
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,8 @@
3333

3434
def main():
3535
task_id = 0
36-
test_index = 37
37-
obs_ratio = 0.5
36+
test_index = 25
37+
obs_ratio = 0.1
3838

3939
# read test data
4040
obs_data_dict = datasets_raw[task_id][test_index]
@@ -53,7 +53,7 @@ def main():
5353

5454
# choose the data
5555
num_obs = int(len(timestamp)*obs_ratio)
56-
num_obs = num_obs - num_obs%15
56+
num_obs -= num_obs % 15
5757
obs_data_post_arr = obs_data_post_arr[0:num_obs:15, :]
5858
timestamp = timestamp[0:num_obs:15]
5959
obs_data_post_arr = obs_data_post_arr
@@ -112,5 +112,4 @@ def main():
112112

113113

114114
if __name__ == '__main__':
115-
main()
116-
# visualization.main()
115+
main()

scripts/test_data_gen_orientation.py

+15-29
Original file line numberDiff line numberDiff line change
@@ -20,58 +20,55 @@
2020
sigma = cp_models.get('filter', 'sigma')
2121
ipromps_set = joblib.load(os.path.join(datasets_path, 'pkl/ipromps_set.pkl'))
2222
datasets_raw = joblib.load(os.path.join(datasets_path, 'pkl/datasets_raw.pkl'))
23-
test_index = cp_models.getint('visualization', 'test_index')
24-
2523

2624
# read datasets cfg file
2725
cp_datasets = ConfigParser.SafeConfigParser()
2826
cp_datasets.read(os.path.join(datasets_path, './info/cfg/datasets.cfg'))
27+
2928
# read datasets params
3029
data_index_sec = cp_datasets.items('index_17')
31-
# data_index_sec = cp_datasets.items('index_25')
3230
data_index = [map(int, task[1].split(',')) for task in data_index_sec]
3331

3432

3533
def main():
36-
task_id = 0
37-
test_index = 37
38-
obs_ratio = 0.35
34+
# super param
35+
task_id = 1
36+
test_index = 1
37+
obs_ratio = 0.5
3938

40-
# read test data
39+
# load test data
4140
obs_data_dict = datasets_raw[task_id][test_index]
42-
4341
left_hand = obs_data_dict['left_hand']
4442
left_joints = obs_data_dict['left_joints']
4543
obs_data = np.hstack([left_hand, left_joints])
4644
timestamp = obs_data_dict['stamp']
4745

48-
# filter the data
46+
# filter data and preprocessing data
4947
obs_data = gaussian_filter1d(obs_data.T, sigma=sigma).T
50-
# preprocessing for the data
51-
obs_data_post_arr = ipromps_set[0].min_max_scaler.transform(obs_data)
52-
# consider the unobserved info
53-
obs_data_post_arr[:, -7:] = 0.0
48+
obs_data_preproc = ipromps_set[0].min_max_scaler.transform(obs_data)
49+
# set unobserved info
50+
obs_data_preproc[:, -7:] = 0.0
5451

5552
# choose the data
5653
num_obs = int(len(timestamp)*obs_ratio)
57-
num_obs = num_obs - num_obs%15
58-
obs_data_post_arr = obs_data_post_arr[0:num_obs:15, :]
54+
num_obs -= num_obs % 15
55+
obs_data_preproc = obs_data_preproc[0:num_obs:15, :]
5956
timestamp = timestamp[0:num_obs:15]
6057

6158
# phase estimation
6259
print('Phase estimating...')
6360
alpha_max_list = []
6461
for ipromp in ipromps_set:
6562
alpha_temp = ipromp.alpha_candidate(num_alpha_candidate)
66-
idx_max = ipromp.estimate_alpha(alpha_temp, obs_data_post_arr, timestamp)
63+
idx_max = ipromp.estimate_alpha(alpha_temp, obs_data_preproc, timestamp)
6764
alpha_max_list.append(alpha_temp[idx_max]['candidate'])
6865
ipromp.set_alpha(alpha_temp[idx_max]['candidate'])
6966

7067
# task recognition
7168
print('Adding via points in each trained model...')
7269
for task_idx, ipromp in enumerate(ipromps_set):
7370
for idx in range(len(timestamp)):
74-
ipromp.add_viapoint(timestamp[idx] / alpha_max_list[task_idx], obs_data_post_arr[idx, :])
71+
ipromp.add_viapoint(timestamp[idx] / alpha_max_list[task_idx], obs_data_preproc[idx, :])
7572
ipromp.param_update(unit_update=True)
7673
print('Computing the likelihood for each model under observations...')
7774

@@ -83,25 +80,15 @@ def main():
8380
# idx_max_prob = 0 # a trick for testing
8481
print('The max fit model index is task %s' % task_name[idx_max_prob])
8582

86-
# # robot motion generation
87-
# [traj_time, traj] = ipromps_set[idx_max_prob].gen_real_traj(alpha_max_list[idx_max_prob])
88-
# traj = ipromps_set[idx_max_prob].min_max_scaler.inverse_transform(traj)
89-
# robot_traj = traj[:, -3:]
90-
9183
# robot motion generation
9284
traj_full = []
9385
for ipromp_id, ipromp in enumerate(ipromps_set):
9486
[traj_time, traj] = ipromp.gen_real_traj(alpha_max_list[ipromp_id])
9587
traj = ipromp.min_max_scaler.inverse_transform(traj)
9688
robot_traj = traj[:, -7:]
97-
human_traj= traj[:, 0:-7]
89+
human_traj = traj[:, 0:3]
9890
traj_full.append([human_traj, robot_traj])
9991

100-
# # test: robot motion generation for task2
101-
# [traj_time2, traj2] = ipromps_set[2].gen_real_traj(alpha_max_list[2])
102-
# traj2 = ipromps_set[2].min_max_scaler.inverse_transform(traj2)
103-
# robot_traj2 = traj2[:, -3:]
104-
10592
# save the conditional result
10693
print('Saving the post IProMPs...')
10794
joblib.dump(ipromps_set, os.path.join(datasets_path, 'pkl/ipromps_set_post_offline.pkl'))
@@ -112,4 +99,3 @@ def main():
11299

113100
if __name__ == '__main__':
114101
main()
115-
# visualization.main()

scripts/visualization.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,8 @@
2727
datasets_norm_preproc = joblib.load(os.path.join(datasets_path, 'pkl/datasets_norm_preproc.pkl'))
2828
task_name = joblib.load(os.path.join(datasets_path, 'pkl/task_name_list.pkl'))
2929
[robot_traj_offline, ground_truth, num_obs] = joblib.load(os.path.join(datasets_path, 'pkl/robot_traj_offline.pkl'))
30-
robot_traj_online = joblib.load(os.path.join(datasets_path, 'pkl/robot_traj_online.pkl'))
31-
obs_data_online = joblib.load(os.path.join(datasets_path, 'pkl/obs_data_online.pkl'))
30+
# robot_traj_online = joblib.load(os.path.join(datasets_path, 'pkl/robot_traj_online.pkl'))
31+
# obs_data_online = joblib.load(os.path.join(datasets_path, 'pkl/obs_data_online.pkl'))
3232

3333

3434
# read datasets cfg file
@@ -44,8 +44,8 @@
4444
# 'left_joints': [11, 14]
4545
# }
4646
info_n_idx = {
47-
'left_hand': [0, 3],
48-
'left_joints': [3, 6]
47+
'left_hand': [0, 11],
48+
'left_joints': [11, 18]
4949
}
5050
# the info to be plotted
5151
info = cp_models.get('visualization', 'info')
@@ -265,7 +265,7 @@ def plot_offline_3d_obs(num=0):
265265
ax.plot(data[:, 0], data[:, 1], data[:, 2],
266266
'-', linewidth=5, color='blue', label='Human trajectory ground truth', alpha = 1.0)
267267
data = ground_truth['left_joints']
268-
ax.plot(data[:, -3], data[:, -2], data[:, -1],
268+
ax.plot(data[:, -7], data[:, -6], data[:, -5],
269269
linewidth=5, linestyle='-', color='r', label='Robot trajectory ground Truth', alpha=1.0)
270270
ax.set_xlabel('X (m)')
271271
ax.set_ylabel('Y (m)')
@@ -298,7 +298,7 @@ def plot_gen_3d_offline_r_traj(num=0):
298298
fig = plt.figure(task_idx+num)
299299
ax = fig.gca(projection='3d')
300300
data = robot_traj_offline[task_idx][1]
301-
ax.plot(data[:, -3], data[:, -2], data[:, -1], 'r',
301+
ax.plot(data[:, -7], data[:, -6], data[:, -5], 'r',
302302
linewidth=5, linestyle='--', label='Predicted robot trajectory')
303303
data = robot_traj_offline[task_idx][0]
304304
ax.plot(data[:, 0], data[:, 1], data[:, 2], 'b',

0 commit comments

Comments
 (0)