-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathutils.py
196 lines (161 loc) · 6.73 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 1 09:50:39 2022
@author: suhail
"""
from scipy.ndimage import uniform_filter1d
import pickle
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import colorsys
from MR_env import MR_Env, save_frames_as_gif
import numpy as np
import matplotlib.cm as cm
#helper function to read some existing data
def readfile(filename):
#extract the data
with open(filename, 'rb') as f:
data = pickle.load(f)
dataset = data[0]
params = dataset['Track_Params(frame,error,current_pos,target_pos,alpha,time)']
freq = data[2]
X = []
Y = []
alpha = []
time = []
for i in range(0, len(params)):
row = params[i]
X.append(row[2][0])
Y.append(row[2][1])
alpha.append(row[4])
time.append(row[5])
print('Finished loading pickle file\n')
X = np.array(X)
Y = np.array(Y)
alpha = np.array(alpha)
time = np.array(time)
return X,Y,alpha,time,freq
def run_sim(actions,init_pos=None,noise_var = 1,a0 =1, is_mismatched = False):
state_prime = np.empty((0,2))
states = np.empty((0,2))
env = MR_Env()
state = env.reset(init = init_pos,noise_var = noise_var,a0=a0, is_mismatched = is_mismatched)
# init
# states = np.append(states, env.last_pos, axis=0)
# state_prime = np.append(state_prime, np.array([0,0]), axis=0)
for action in actions:
env.step(action)
states = np.append(states, np.array([env.last_pos]), axis=0)
state_prime = np.append(state_prime, np.array([env.state_prime]), axis=0)
X = states[:,0]
Y = states[:,1]
alpha = actions[:,1]
freq = actions[:,0]
time = np.linspace(0, (len(X) - 1)/30.0, len(X)) # (np.arange(len(X))) / 30.0 #timestep is 1/30
return X,Y,alpha,time,freq
def plot_xy(xys, legends=[""],fig_title=[""], savefile_name=''):
fig, ax = plt.subplots()
count = 0
for (X,Y),legend in zip(xys,legends):
if count is 0:
ax.plot(X,Y, '--', label=legend)
else:
ax.plot(X,Y, label=legend)
count = count + 1
ax.legend(loc='upper left',
shadow=True, fontsize='x-small')
if savefile_name:
plt.savefig(savefile_name, bbox_inches='tight')
plt.show()
def plot_bounded_curves(curves, bounds, legends=[""], fig_title=[""], savefile_name='', nn=[]):
fig, ax = plt.subplots()
for (t, lb, ub) in bounds:
ax.fill_between(t, lb, ub)
colors = cm.Set1(np.linspace(0, 1, len(curves)))
for (X,Y),legend,c in zip(curves,legends,colors):
ax.plot(X,Y, color='k', label=legend)
if nn:
for (t, v) in nn:
ax.plot(t, v, color='r');
ax.legend(loc='upper left',
shadow=True, fontsize='x-small')
fig.suptitle(fig_title[0])
plt.xlabel('time (s)')
plt.ylabel('velocity error (microns/s)')
if savefile_name:
plt.savefig(savefile_name, bbox_inches='tight')
plt.show()
def plot_curve(y, xlabel, ylabel,savefile_name=''):
fig, ax = plt.subplots()
ax.plot(y)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
if savefile_name:
plt.savefig(savefile_name, bbox_inches='tight')
plt.show()
def plot_traj(xts, legends=[""],fig_title=[""]):
fig, ax = plt.subplots()
for (times,xs),legend in zip(xts,legends):
ax.plot(times,xs,label=legend)
ax.legend(loc='upper left', shadow=True, fontsize='x-small')
fig.suptitle(fig_title[0])
plt.show()
def plot_vel(vxys, legends=[""],fig_title=[""]):
fig, ax = plt.subplots()
figy, ay = plt.subplots()
handles =[]
N = int(3*len(vxys))
HSV_tuples = [(x*1.0/N, 0.5, 0.5) for x in range(N)]
colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), HSV_tuples))
if N==3:
colors =['k','b','r']
for index,((v_desired,v_error,v_stdv,vx,vy),legend) in enumerate(zip(vxys,legends)):
time = np.arange(len(vx))
ax.fill_between(time, v_desired[:,0] + v_error[:,0] - 2*v_stdv[:,0],
v_desired[:,0] + v_error[:,0] + 2*v_stdv[:,0])
ax.fill_between(time, v_desired[:,0] + v_error[:,0] - v_stdv[:,0],
v_desired[:,0] + v_error[:,0] + v_stdv[:,0])
ax.plot(time, vx, colors[3*index+0]) #data (real from sim)
ax.plot(time, v_desired[:,0], colors[3*index+1]) #desired (ideal=> no noise)
ax.plot(time, v_desired[:,0] + v_error[:,0], colors[3*index+2]) #learned (predicted from )
ay.fill_between(time, v_desired[:,1] + v_error[:,1] - 2*v_stdv[:,1],
v_desired[:,1] + v_error[:,1] + 2*v_stdv[:,1])
ay.fill_between(time, v_desired[:,1] + v_error[:,1] - v_stdv[:,1],
v_desired[:,1] + v_error[:,1] + v_stdv[:,1])
ay.plot(time, vy, colors[3*index+0]) #data (real from sim)
ay.plot(time, v_desired[:,1], colors[3*index+1]) #desired (ideal=> no noise)
ay.plot(time, v_desired[:,1] + v_error[:,1], colors[3*index+2]) #learned (predicted from )
#proxy artists for figures
h1 = mpatches.Patch(color= colors[3*index+0], label='Data_'+legend)
h2 = mpatches.Patch(color= colors[3*index+1], label='Desired_'+legend)
h3 = mpatches.Patch(color= colors[3*index+2], label='Learned_'+legend)
handles.append(h1)
handles.append(h2)
handles.append(h3)
fig.legend(handles=handles), figy.legend(handles=handles)
fig.suptitle(fig_title[0]+'_X') ,figy.suptitle(fig_title[0]+'_Y')
fig.legend(loc='upper left',
shadow=True, fontsize='x-small')
figy.legend(loc='upper left',
shadow=True, fontsize='x-small')
plt.show()
def test_gp(gp,X,Y,a0,alpha,freq,time):
#pretend this is happening real-time in a while loop
v_desired = np.zeros( (len(time), 2) )
v_error = np.zeros( (len(time), 2) )
v_stdv = np.zeros( (len(time), 2) )
alpha_pred = np.zeros( (len(time), 1) )
for i in range(0, len(time)):
print(a0,freq,np.cos(alpha[i]),np.sin(alpha[i]),a0*freq*np.cos(alpha[i]))
v_desired[i,0] = a0*freq*np.cos(alpha[i])
v_desired[i,1] = a0*freq*np.sin(alpha[i])
alpha_t,muX, muY, sigX, sigY = gp.predict(v_desired[i,:])
v_error[i,0] = muX
v_error[i,1] = muY
v_stdv[i,0] = sigX
v_stdv[i,1] = sigY
alpha_pred[i] = alpha_t
return alpha_pred,(v_desired,v_error,v_stdv,vx,vy)
def find_alpha_corrected(v_desired,gp):
alpha_corrected,muX, muY, sigX, sigY = gp.predict(v_desired)
return alpha_corrected,muX, muY, sigX, sigY