-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimulateTrajectories.py
More file actions
273 lines (175 loc) · 8.39 KB
/
SimulateTrajectories.py
File metadata and controls
273 lines (175 loc) · 8.39 KB
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import sys
rootpath = 'C:\\VENLAB data\\TrackMaker\\'
sys.path.append(rootpath)
import numpy as np
import matplotlib.pyplot as plt
import pdb
import pandas as pd
import io
import csv
import simTrackMaker
class vehicle:
def __init__(self, initialyaw, speed, dt, yawrate_readout, Course):
#self.pos = np.array([pos[0], pos[1]])
self.yawrate_readout = yawrate_readout
self.playback_length = len(yawrate_readout)
self.pos = np.array(Course[0])
self.yaw = initialyaw #heading angle, radians
self.speed = speed
self.dt = dt
self.midline = Course[1]
self.trackorigin = Course[2]
self.yawrate = 0
self.pos_history = []
self.yaw_history = []
self.yawrate_history = []
self.error_history = []
self.closestpt_history = []
self.Course = Course
self.currenterror, self.closestpt = self.calculatebias()
# self.save_history()
def calculatebias(self):
#TODO: cut down on processing but only selecting a window of points based on lastmidindex.
midlinedist = np.sqrt(
((self.pos[0]-self.midline[:,0])**2)
+((self.pos[1]-self.midline[:,1])**2)
) #get a 4000 array of distances from the midline
idx = np.argmin(abs(midlinedist)) #find smallest difference. This is the closest index on the midline.
closestpt = self.midline[idx,:] #xy of closest point
dist = midlinedist[idx] #distance from closest point
#Sign bias from assessing if the closest point on midline is closer to the track origin than the driver position. Since the track is an oval, closer = understeering, farther = oversteering.
middist_from_origin = np.sqrt(
((closestpt[0]-self.trackorigin[0])**2)
+((closestpt[1]-self.trackorigin[1])**2)
) #distance of midline to origin
pos_from_trackorigin = np.sqrt(
((self.pos[0]-self.trackorigin[0])**2)
+((self.pos[1]-self.trackorigin[1])**2)
) #distance of driver pos to origin
distdiff = middist_from_origin - pos_from_trackorigin #if driver distance is greater than closest point distance, steering position should be understeering
steeringbias = dist * np.sign(distdiff)
return steeringbias, closestpt
def move_vehicle(self, newyawrate):
"""update the position of the vehicle over timestep dt"""
self.yawrate = newyawrate
# self.yawrate = np.deg2rad(0.5) # np.random.normal(0, 0.001)
maxheadingval = np.deg2rad(35.0) #in rads per second
self.yawrate = np.clip(self.yawrate, -maxheadingval, maxheadingval)
# print(self.yawrate)
# self.yawrate = 0.0
self.yaw = self.yaw + self.yawrate * self.dt #+ np.random.normal(0, 0.005)
#zrnew = znew*cos(omegaH) + xnew*sin(omegaH);
#xrnew = xnew*cos(omegaH) - znew*sin(omegaH)
x_change = self.speed * self.dt * np.sin(self.yaw)
y_change = self.speed * self.dt * np.cos(self.yaw)
self.pos = self.pos + np.array([x_change, y_change])
self.currenterror, self.closestpt = self.calculatebias()
self.save_history()
def save_history(self):
self.pos_history.append(self.pos)
self.yaw_history.append(self.yaw)
self.yawrate_history.append(self.yawrate)
self.error_history.append(self.currenterror)
self.closestpt_history.append(self.closestpt)
def runSimulation(Course, yawrate_readout, yawrateoffset= 0, onsettime = 0):
"""run simulation and return RMS"""
#Sim params
fps = 60.0
speed = 8.0
yawrateoffset_rads = np.deg2rad(yawrateoffset)
# print ("speed; ", speed)
dt = 1.0 / fps
run_time = 15 #seconds
time = 0
Car = vehicle(0.0, speed, dt, yawrate_readout, Course)
i = 0
print ("playback lenght", Car.playback_length)
while (time < run_time) and (i < Car.playback_length):
#print i
time += dt
newyawrate = np.deg2rad(Car.yawrate_readout[i])
if time > onsettime:
newyawrate += yawrateoffset_rads
Car.move_vehicle(newyawrate)
i += 1
return Car
#RMS = np.sqrt(np.mean(steeringbias**2))
#print ("RMS: ", RMS)
def plotCar(plt, Car):
"""Plot results of simulations"""
positions = np.array(Car.pos_history)
steeringbias = np.array(Car.error_history)
if max(abs(steeringbias)) > 1.5:
plt.plot(positions[:,0], positions[:,1], 'ro', markersize=.2)
else:
plt.plot(positions[:,0], positions[:,1], 'go', markersize=.2)
def saveCar(OutputWriter, Car, radius, file, file_i, yr, onset):
"""save results of simulations"""
datacolumns = ('radius','AutoFile','AutoFile_i','steering_angle_bias', 'OnsetTime','UID','World_x','World_z','SteeringBias','WorldYaw','YawRate_radspersec')
UID = "{}_{}_{}_{}".format(radius,file_i, yr, onset)
positions = np.array(Car.pos_history)
World_x = positions[:,0]
World_z = positions[:,1]
steeringbias = np.array(Car.error_history)
yaw = np.array(Car.yaw_history)
yawrate = np.array(Car.yawrate_history)
for row in range(len(positions)):
output = (radius, file, file_i, yr, onset, UID,
World_x[row],World_z[row],
steeringbias[row],
yaw[row],
yawrate[row])
OutputWriter.writerow(output)
return(OutputWriter)
if __name__ == '__main__':
#onset pool times
OnsetTimePool = np.arange(5, 9.25, step = .25)
#yawrateoffsets = np.linspace(-10,10,200)
yawrateoffsets = [-.2, .15, -9, -1.5]
#radii
myrads = [40, 80]
datacolumns = ('radius','AutoFile','AutoFile_i','steering_angle_bias', 'OnsetTime','UID','World_x','World_z','SteeringBias','WorldYaw','YawRate_radspersec')
#dataframe
OutputFile = io.BytesIO()
OutputWriter = csv.writer(OutputFile)
OutputWriter.writerow(datacolumns) #write headers.
for rads_i, radius in enumerate(myrads):
L = 16#2sec.
myStraight = simTrackMaker.lineStraight(startpos = [0,0], length= 16)
#Create Bend
myBend = simTrackMaker.lineBend(startpos = myStraight.RoadEnd, rads = radius, x_dir = 1, road_width=3.0)
#midline and edges
Course_RoadStart = myStraight.RoadStart
Course_midline = np.vstack((myStraight.midline, myBend.midline))
Course_OutsideLine = np.vstack(
(myStraight.OutsideLine, myBend.OutsideLine)
)
Course_InsideLine = np.vstack((myStraight.InsideLine, myBend.InsideLine))
Course_CurveOrigin = myBend.CurveOrigin
#Temp HACK to store in list while I improve trackmaker.
Course = [
Course_RoadStart,
Course_midline, Course_CurveOrigin,
Course_OutsideLine, Course_InsideLine
]
#
#list of filenames
if radius == 40:
filename_list = ["Midline_40_0.csv","Midline_40_1.csv","Midline_40_2.csv","Midline_40_3.csv","Midline_40_4.csv","Midline_40_5.csv"]
elif radius == 80:
filename_list = ["Midline_80_0.csv","Midline_80_1.csv","Midline_80_2.csv","Midline_80_3.csv","Midline_80_4.csv","Midline_80_5.csv"]
else:
raise Exception('Unrecognised radius')
for file_i, file in enumerate(filename_list):
#loop through filename and onset times.
playbackdata = pd.read_csv("Data//"+file)
yawrate_readout = playbackdata.get("YawRate_seconds")
for yr_i,yr in enumerate(yawrateoffsets):
for onset_i, onset in enumerate(OnsetTimePool):
Car = runSimulation(Course, yawrate_readout, yr, onset)
#save results
OutputWriter = saveCar(OutputWriter, Car, radius, file, file_i, yr, onset)
OutputFile.seek(0)
df = pd.read_csv(OutputFile) #grab bytesIO object.
df.to_csv('Data//Untouched_Trajectories.csv') #save to file.
print ("Saved file")