You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

177 lines
8.7 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. # Creating robot behaviors with Python generators
  2. *Posted 2007-05-02.*
  3. [Generators](https://en.wikipedia.org/wiki/Generator_(computer_programming)) are a [powerful feature](https://docs.python.org/2.7/reference/simple_stmts.html#the-yield-statement) of the Python programming language. In a nutshell, generators let you write a function that behaves like an iterator. The standard approach to programming robot behaviors is based on state machines. However, robotics code is *full* of special cases, so a complex behavior will typically end up with a lot of bookkeeping cruft. Generators let us simplify the bookkeeping and express the desired behavior in a straightforward manner.
  4. (Idea originally due to [Jim Bruce](http://www.cs.cmu.edu/~jbruce/).)
  5. I've worked for several years on [RoboCup](https://robocup.org), the international robot soccer competition. [Our software](http://www.cs.cmu.edu/~robosoccer/legged/) is written in a mixture of C++ (for low-level localization and vision algorithms) and Python (for high-level behaviors). Let's say we want to write a simple goalkeeper for a robot soccer team. Our keeper will be pretty simple; here's a list of the requirements:
  6. 1. If the ball is far away, stand in place.
  7. 2. If the ball is near by, dive to block it. Dive to the left if the ball is to the left; dive to the right if the ball is to the right.
  8. 3. If we choose a "dive" action, then "stand" on the next frame, nothing will happen. (Well, maybe the robot will twitch briefly....) So when we choose to dive, we need to commit to sending the same dive command for some time (let's say one second).
  9. The usual approach to robot behavior design relies on hierarchical state machines. Specifically, we might be in a "standing" state while the ball is far away; when the ball becomes close, we enter a "diving" state that persists for one second. Because of requirement 3, this solution will have a few warts: we need to keep track of how much time we've spent in the dive state. Every time we add a special case like this, we need to keep some extra state information around. Since robotics code is full of special cases, we tend to end up with a lot of bookkeeping cruft. In contrast, generators will let us clearly express the desired behavior.
  10. On to the state-machine approach. First, we'll have a class called Features that abstracts the robot's raw sensor data. For this example, we only care whether the ball is near/far and left/right, so Features will just contain two boolean variables:
  11. ```python
  12. class Features(object):
  13. ballFar = True
  14. ballOnLeft = True
  15. ```
  16. Next, we make the goalkeeper. The keeper's behavior is specified by the `next()` function, which is called thirty times per second by the robot's main event loop (every time the on-board camera produces a new image). The `next()` function returns one of three actions: `"stand"`, `"diveLeft"`, or `"diveRight"`, based on the current values of the Features object. For now, let's pretend that requirement 3 doesn't exist.
  17. ```python
  18. class Goalkeeper(object):
  19. def __init__(self, features):
  20. self.features = features
  21. def next(self):
  22. features = self.features
  23. if features.ballFar:
  24. return 'stand'
  25. else:
  26. if features.ballOnLeft:
  27. return 'diveLeft'
  28. else:
  29. return 'diveRight'
  30. ```
  31. That was simple enough. The constructor takes in the `Features` object; the `next()` method checks the current `Features` values and returns the correct action. Now, how about satisfying requirement 3? When we choose to dive, we need to keep track of two things: how long we need to stay in the `"dive"` state and which direction we dove. We'll do this by adding a couple of instance variables (`self.diveFramesRemaining` and `self.lastDiveCommand`) to the Goalkeeper class. These variables are set when we initiate the dive. At the top of the `next()` function, we check if `self.diveFramesRemaining` is positive; if so, we can immediately return `self.lastDiveCommand` without consulting the `Features`. Here's the code:
  32. ```python
  33. class Goalkeeper(object):
  34. def __init__(self, features):
  35. self.features = features
  36. self.diveFramesRemaining = 0
  37. self.lastDiveCommand = None
  38. def next(self):
  39. features = self.features
  40. if self.diveFramesRemaining > 0:
  41. self.diveFramesRemaining -= 1
  42. return self.lastDiveCommand
  43. else:
  44. if features.ballFar:
  45. return 'stand'
  46. else:
  47. if features.ballOnLeft:
  48. command = 'diveLeft'
  49. else:
  50. command = 'diveRight'
  51. self.lastDiveCommand = command
  52. self.diveFramesRemaining = 29
  53. return command
  54. ```
  55. This satisfies all the requirements, but it's ugly. We've added a couple of bookkeeping variables to the Goalkeeper class. Code to properly maintain these variables is sprinkled all over the `next()` function. Even worse, the structure of the code no longer accurately represents the programmer's intent: the top-level if-statement depends on the state of the robot rather than the state of the world. The intent of the original `next()` function is much easier to discern. (In real code, we could use a state-machine class to tidy things up a bit, but the end result would still be ugly when compared to our original `next()` function.)
  56. With generators, we can preserve the form of the original `next()` function and keep the bookkeeping only where it's needed. If you're not familiar with generators, you can think of them as a special kind of function. The `yield` keyword is essentially equivalent to `return`, but the next time the generator is called, *execution continues from the point of the last `yield`*, preserving the state of all local variables. With `yield`, we can use a `for` loop to "return" the same dive command the next 30 times the function is called! Lines 11-16 of the below code show the magic:
  57. ```python
  58. class GoalkeeperWithGenerator(object):
  59. def __init__(self, features):
  60. self.features = features
  61. def behavior(self):
  62. while True:
  63. features = self.features
  64. if features.ballFar:
  65. yield 'stand'
  66. else:
  67. if features.ballOnLeft:
  68. command = 'diveLeft'
  69. else:
  70. command = 'diveRight'
  71. for i in xrange(30):
  72. yield command
  73. ```
  74. Here's a simple driver script that shows how to use our goalkeepers:
  75. ```python
  76. import random
  77. f = Features()
  78. g1 = Goalkeeper(f)
  79. g2 = GoalkeeperWithGenerator(f).behavior()
  80. for i in xrange(10000):
  81. f.ballFar = random.random() > 0.1
  82. f.ballOnLeft = random.random() < 0.5
  83. g1action = g1.next()
  84. g2action = g2.next()
  85. print "%s\t%s\t%s\t%s" % (
  86. f.ballFar, f.ballOnLeft, g1action, g2action)
  87. assert(g1action == g2action)
  88. ```
  89. ... and we're done! I hope you'll agree that the generator-based keeper is much easier to understand and maintain than the state-machine-based keeper. You can grab the full source code below and take a look for yourself.
  90. ```python
  91. #!/usr/bin/env python
  92. class Features(object):
  93. ballFar = True
  94. ballOnLeft = True
  95. class Goalkeeper(object):
  96. def __init__(self, features):
  97. self.features = features
  98. self.diveFramesRemaining = 0
  99. self.lastDiveCommand = None
  100. def next(self):
  101. features = self.features
  102. if self.diveFramesRemaining:
  103. self.diveFramesRemaining -= 1
  104. return self.lastDiveCommand
  105. else:
  106. if features.ballFar:
  107. return 'stand'
  108. else:
  109. if features.ballOnLeft:
  110. command = 'diveLeft'
  111. else:
  112. command = 'diveRight'
  113. self.lastDiveCommand = command
  114. self.diveFramesRemaining = 29
  115. return command
  116. class GoalkeeperWithGenerator(object):
  117. def __init__(self, features):
  118. self.features = features
  119. def behavior(self):
  120. while True:
  121. features = self.features
  122. if features.ballFar:
  123. yield 'stand'
  124. else:
  125. if features.ballOnLeft:
  126. command = 'diveLeft'
  127. else:
  128. command = 'diveRight'
  129. for i in xrange(30):
  130. yield command
  131. import random
  132. f = Features()
  133. g1 = Goalkeeper(f)
  134. g2 = GoalkeeperWithGenerator(f).behavior()
  135. for i in xrange(10000):
  136. f.ballFar = random.random() > 0.1
  137. f.ballOnLeft = random.random() < 0.5
  138. g1action = g1.next()
  139. g2action = g2.next()
  140. print "%s\t%s\t%s\t%s" % (
  141. f.ballFar, f.ballOnLeft, g1action, g2action)
  142. assert(g1action == g2action)
  143. ```