Skip to content
Snippets Groups Projects
Commit 7feb10d8 authored by Maximilian Gruber's avatar Maximilian Gruber
Browse files

Fix video functionality

- video is only produced _after_ simulation has ended
- simulation class more modularized
parent b3d61d52
No related branches found
No related tags found
No related merge requests found
......@@ -41,7 +41,7 @@ class Simulation:
return path
def simulate(self):
def run(self):
# define some path to drive along (will be extended during runtime, if it gets to short)
path_1 = self.random_path()
......@@ -50,11 +50,13 @@ class Simulation:
vehicle_1 = Vehicle(init_position=path_1.values[0])
floor = Floor(shape=(4,3), tile_length=1.0, broadcast=False, vehicles=[vehicle_1])
# run the simulation for 5 steps
print("Simulation is running. Press Ctrl+C to cancel.\n")
_, position_previous, _ = path_1.popleft()
floor_arrays = Buffer()
wheel_positions_1 = Buffer()
while True:
try:
# get timestamp, position an rotation from path
......@@ -69,9 +71,9 @@ class Simulation:
# update floor
floor.update(timestamp=timestamp)
# update plot objects
#vehicle_1.update_shape(shape)
#floor.update_floor_array(pc)
# buffer plot objects for later animation
floor_arrays.append(time=timestamp, value=floor.get_tile_values())
wheel_positions_1.append(time=timestamp, value=vehicle_1.get_wheel_positions(cyclic=True))
# prepare next cycle
position_previous = position
......@@ -82,17 +84,22 @@ class Simulation:
print("\nSimulation canceled. Now writing some results to disk.\n")
break
# plot sensors
# remove sensor agents
sensors = [tile["sensor"] for tile in floor.tiles.values()]
for sensor in sensors:
if sensor.agent_network:
sensor.remove_agent()
return floor, vehicle_1, sensors, floor_arrays, wheel_positions_1
def plot_sensor_timeseries(self, sensors):
fig, ax = plt.subplots(nrows=len(sensors), ncols=1, sharex=True, sharey=True)
for i, sensor in enumerate(sensors):
ax[i].step(sensor.output_buffer.timestamps, sensor.output_buffer.values, where="post")
ax[i].step(sensor.input_buffer.timestamps, sensor.input_buffer.values, where="post")
plt.show()
# write results to files
time_string = time.strftime("%Y-%m-%d__%H:%M:%S")
fig.show()
def write_sensor_timeseries(self, sensors, time_string):
_in = np.vstack([sensor.input_buffer.values for sensor in sensors]).T
_out = np.vstack([sensor.output_buffer.values for sensor in sensors]).T
df_input = pd.DataFrame(data=_in, index=sensors[0].input_buffer.timestamps)
......@@ -101,33 +108,36 @@ class Simulation:
df_input.to_csv("{TS}_input.csv".format(TS=time_string))
df_output.to_csv("{TS}_output.csv".format(TS=time_string))
## # update sensors on floor
## floor.update(timestamp=0.0)
## # init visualization
## ## init figure
## fig = plt.figure()
## ax = fig.add_subplot(111)
## ## draw floor
## fx, fy = floor.get_grid()
## fc = floor.get_tile_values()
## pc = ax.pcolormesh(fx, fy, fc, cmap="Greens", vmin=0, vmax=vehicle_1.mass)
## ## vehicle representation
## shape = vehicle_1.shape()
## shape_patch = ax.add_patch(shape)
## ## plot the scene
## ax.set_xlim(*floor.draw_limits[0])
## ax.set_ylim(*floor.draw_limits[1])
## ax.set_aspect("equal")
## anim = mpa.FuncAnimation(fig, animate, frames=path_1.timestamps, interval=self.dt*1000, repeat=False)
## anim.save("{TS}_movement.mpg".format(TS=time_string))
# remove sensor agents
for sensor in sensors:
if sensor.agent_network:
sensor.remove_agent()
def make_video(self, floor, vehicle_1, floor_arrays, wheel_positions_1, time_string):
# init figure
fig, ax = plt.subplots(nrows=1, ncols=1, sharex=True, sharey=True)
# draw floor
fx, fy = floor.get_grid()
timestamp, fc, _ = floor_arrays.popleft()
pc = ax.pcolormesh(fx, fy, fc, cmap="Greens", vmin=0, vmax=vehicle_1.mass)
# vehicle representation
_, wheel_position_1, _ = wheel_positions_1.popleft()
shape = mpl.patches.Polygon(wheel_position_1[:-1], fill=False)
shape_patch = ax.add_patch(shape)
# plot the scene
ax.set_xlim(*floor.draw_limits[0])
ax.set_ylim(*floor.draw_limits[1])
ax.set_aspect("equal")
# animation
def animate(frame):
_, fc, _ = floor_arrays.popleft()
_, wheel_position_1, _ = wheel_positions_1.popleft()
pc.set_array(fc.ravel())
shape.set_xy(wheel_position_1)
return pc, shape
anim = mpa.FuncAnimation(fig, animate, frames=range(len(floor_arrays.timestamps)-1), interval=self.dt*1000, repeat=False, blit=True)
# save to video
anim.save("{TS}_movement.mpg".format(TS=time_string))
class Vehicle:
......@@ -164,7 +174,6 @@ class Vehicle:
shape.set_xy(self.get_wheel_positions(cyclic=True))
class Floor():
def __init__(self, shape=(10,12), tile_length=0.5, vehicles=[], broadcast=False):
......@@ -209,9 +218,6 @@ class Floor():
return C
def update_floor_array(self, pc):
pc.set_array(self.get_tile_values().ravel())
def update(self, timestamp=None):
# reset every tile
for it, tile in self.tiles.items():
......@@ -266,7 +272,7 @@ class Floor():
class Buffer():
def __init__(self, maxlen):
def __init__(self, maxlen=1000):
self.timestamps = deque(maxlen=maxlen)
self.values = deque(maxlen=maxlen)
self.uncertainties = deque(maxlen=maxlen)
......@@ -292,8 +298,8 @@ class Sensor():
self.has_failure = False
# time series
self.input_buffer = Buffer(1000)
self.output_buffer = Buffer(1000)
self.input_buffer = Buffer()
self.output_buffer = Buffer()
# broadcast to network if wanted
self.agent = None
......@@ -417,5 +423,14 @@ class SensorAgent(Agent):
if __name__ == "__main__":
s = Simulation(dt=0.05)
s.simulate()
\ No newline at end of file
# init simulation
sim = Simulation(dt=0.05)
# run simulation infinitely
floor, vehicle_1, sensors, floor_arrays, wheel_positions_1 = sim.run()
# store results (only the values of limited buffers are written)
time_string = time.strftime("%Y-%m-%d__%H:%M:%S")
sim.plot_sensor_timeseries(sensors)
sim.write_sensor_timeseries(sensors, time_string)
sim.make_video(floor, vehicle_1, floor_arrays, wheel_positions_1, time_string)
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment