Guest User

Untitled

a guest
Nov 19th, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.45 KB | None | 0 0
  1. import numpy as np
  2. from matplotlib.animation import FuncAnimation
  3. from matplotlib import pyplot as plt
  4.  
  5. from mcl import Environment, MCL, Agent
  6.  
  7.  
  8. def particle_weight(particle_observation, agent_observation):
  9. return 1 if particle_observation == agent_observation else 0
  10.  
  11.  
  12. class Drawer(object):
  13. def __init__(self, ax,
  14. range_, doors, initial_location, controls,
  15. uncertaintity, covariance_ratio):
  16. environment = Environment(range_, doors, uncertaintity)
  17. self.mcl = MCL(range_, n_particles,
  18. environment.observe, particle_weight,
  19. covariance_ratio)
  20. self.agent = Agent(range_, initial_location, environment.observe)
  21.  
  22. self.agent_scatter = ax.scatter([], [])
  23.  
  24. self.particle_vlines = []
  25. for i in range(n_particles):
  26. vline = ax.axvline(ymin=0.2, ymax=0.8, color="cyan")
  27. self.particle_vlines.append(vline)
  28.  
  29. ax.set_xlim(environment.range)
  30. ax.set_ylim([-0.2, 1.2])
  31.  
  32. self.controls = controls
  33.  
  34. xs = np.linspace(*range_, 200)
  35. doors = [1 if environment.is_door(x) else None for x in xs]
  36. self.door_lines = ax.plot(xs, doors, linewidth=6, color="r")
  37.  
  38. def init(self):
  39. self.agent_scatter.set_offsets(np.c_[self.agent.location, 0])
  40.  
  41. for x, vline in zip(self.mcl.particles, self.particle_vlines):
  42. vline.set_xdata(x)
  43. return self.particle_vlines + [self.agent_scatter]
  44.  
  45. def __call__(self, i):
  46. control = self.controls[i]
  47. noise = np.random.normal(0, 0.3)
  48.  
  49. self.agent.move(control + noise)
  50.  
  51. particles = self.mcl.update_particles(control, self.agent.observation())
  52.  
  53. self.agent_scatter.set_offsets(np.c_[self.agent.location, 0])
  54.  
  55. for x, vline in zip(particles, self.particle_vlines):
  56. vline.set_xdata(x)
  57. return self.particle_vlines + [self.agent_scatter]
  58.  
  59.  
  60. n_particles = 400
  61. range_ = [-4, 24]
  62. doors = [[-2, -1], [3, 5], [8, 12], [18, 22]]
  63. initial_location = 2
  64. uncertaintity = 0.05
  65. covariance_ratio = 0.08
  66.  
  67. controls = [2, 5, -2, 1, 0, -3, -5, -2, 4, 2, 7, -3, -3, -4]
  68. controls = np.vstack((controls, controls)).flatten()
  69.  
  70. fig, ax = plt.subplots()
  71. drawer = Drawer(ax, range_, doors, initial_location, controls,
  72. uncertaintity, covariance_ratio)
  73. animation = FuncAnimation(
  74. fig, drawer,
  75. init_func=drawer.init,
  76. frames=np.arange(len(controls)),
  77. interval=1000,
  78. )
  79. animation.save("mcl.mp4", dpi=400)
Add Comment
Please, Sign In to add comment