Advertisement
Guest User

ps6

a guest
Jun 14th, 2013
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.27 KB | None | 0 0
  1. # Problem Set 6: Simulating robots
  2. # Name:
  3. # Collaborators:
  4. # Time:
  5.  
  6. import math
  7. import random
  8.  
  9. import ps6_visualize
  10. import pylab
  11.  
  12. # === Provided classes
  13.  
  14. class Position(object):
  15.     """
  16.    A Position represents a location in a two-dimensional room.
  17.    """
  18.     def __init__(self, x, y):
  19.         """
  20.        Initializes a position with coordinates (x, y).
  21.        """
  22.         self.x = x
  23.         self.y = y
  24.     def getX(self):
  25.         return self.x
  26.     def getY(self):
  27.         return self.y
  28.     def getNewPosition(self, angle, speed):
  29.         """
  30.        Computes and returns the new Position after a single clock-tick has
  31.        passed, with this object as the current position, and with the
  32.        specified angle and speed.
  33.  
  34.        Does NOT test whether the returned position fits inside the room.
  35.  
  36.        angle: float representing angle in degrees, 0 <= angle < 360
  37.        speed: positive float representing speed
  38.  
  39.        Returns: a Position object representing the new position.
  40.        """
  41.         old_x, old_y = self.getX(), self.getY()
  42.         # Compute the change in position
  43.         delta_y = speed * math.cos(math.radians(angle))
  44.         delta_x = speed * math.sin(math.radians(angle))
  45.         # Add that to the existing position
  46.         new_x = old_x + delta_x
  47.         new_y = old_y + delta_y
  48.         return Position(new_x, new_y)
  49.  
  50. # === Problems 1
  51.  
  52. class RectangularRoom(object):
  53.     """
  54.    A RectangularRoom represents a rectangular region containing clean or dirty
  55.    tiles.
  56.  
  57.    A room has a width and a height and contains (width * height) tiles. At any
  58.    particular time, each of these tiles is either clean or dirty.
  59.    """
  60.     def __init__(self, width, height):
  61.         """
  62.        Initializes a rectangular room with the specified width and height.
  63.  
  64.        Initially, no tiles in the room have been cleaned.
  65.  
  66.        width: an integer > 0
  67.        height: an integer > 0
  68.        """
  69.         if width < 1 or height < 1:
  70.             raise "width or height must be > 0"
  71.  
  72.         if type(width) is not int and type(height) is not int :
  73.             raise "width and height must be integers"
  74.        
  75.         self.width = width
  76.         self.height = height
  77.         self.cleaned = []
  78.         return None
  79.    
  80.     def cleanTileAtPosition(self, pos):
  81.         """
  82.        Mark the tile under the position POS as cleaned.
  83.  
  84.        Assumes that POS represents a valid position inside this room.
  85.  
  86.        pos: a Position
  87.        """
  88.         self.position_int = math.floor(pos.getX()), math.floor(pos.getY())
  89.  
  90.         if not self.isTileCleaned(self,self.position_int):
  91.             self.cleaned.append(self.position_int)
  92.        
  93.        
  94.         pass
  95.  
  96.     def isTileCleaned(self, m, n):
  97.         """
  98.        Return True if the tile (m, n) has been cleaned.
  99.  
  100.        Assumes that (m, n) represents a valid tile inside the room.
  101.  
  102.        m: an integer
  103.        n: an integer
  104.        returns: True if (m, n) is cleaned, False otherwise
  105.        """
  106.         self.tile = m,n
  107.        
  108.         if self.tile in self.cleaned:
  109.             return True
  110.         else:
  111.             return False
  112.    
  113.         raise NotImplementedError
  114.    
  115.     def getNumTiles(self):
  116.         """
  117.        Return the total number of tiles in the room.
  118.  
  119.        returns: an integer
  120.        """
  121.         return (self.width )* (self.height )
  122.         raise NotImplementedError
  123.  
  124.     def getNumCleanedTiles(self):
  125.         """
  126.        Return the total number of clean tiles in the room.
  127.  
  128.        returns: an integer
  129.        """
  130.         return len(self.cleaned)
  131.    
  132.         raise NotImplementedError
  133.  
  134.     def getRandomPosition(self):
  135.         """
  136.        Return a random position inside the room.
  137.  
  138.        returns: a Position object.
  139.        """
  140.  
  141.         return Position(random.uniform(0,self.width), random.uniform(0,self.height))
  142.        
  143.         raise NotImplementedError
  144.  
  145.     def isPositionInRoom(self, pos):
  146.         """
  147.        Return True if pos is inside the room.
  148.  
  149.        pos: a Position object.
  150.        returns: True if pos is in the room, False otherwise.
  151.        """
  152.        
  153.         if 0 <= pos.getX() <= self.width and 0 <= pos.getY() <= self.height:
  154.             return True
  155.         else:
  156.             return False
  157.        
  158.         raise NotImplementedError
  159.  
  160.  
  161. class Robot(object):
  162.     """
  163.    Represents a robot cleaning a particular room.
  164.  
  165.    At all times the robot has a particular position and direction in the room.
  166.    The robot also has a fixed speed.
  167.  
  168.    Subclasses of Robot should provide movement strategies by implementing
  169.    updatePositionAndClean(), which simulates a single time-step.
  170.    """
  171.     def __init__(self, room, speed):
  172.         """
  173.        Initializes a Robot with the given speed in the specified room. The
  174.        robot initially has a random direction and a random position in the
  175.        room. The robot cleans the tile it is on.
  176.        
  177.        room:  a RectangularRoom object.
  178.        speed: a float (speed > 0)
  179.        """
  180.         self.setRobotPosition(room.getRandomPosition())
  181.         self.speed = speed
  182.         self.room = room
  183.         self.setRobotDirection(self.getRandomDirection())
  184.         self.room.cleanTileAtPosition(self.position)
  185.         print "initialised"
  186.         pass
  187.  
  188.     def getRandomDirection(self):
  189.  
  190.         return random.uniform(0,360)
  191.    
  192.     def getRobotPosition(self):
  193.         """
  194.        Return the position of the robot.
  195.  
  196.        returns: a Position object giving the robot's position.
  197.        """
  198.         return self.position
  199.         raise NotImplementedError
  200.    
  201.     def getRobotDirection(self):
  202.         """
  203.        Return the direction of the robot.
  204.  
  205.        returns: an integer d giving the direction of the robot as an angle in
  206.        degrees, 0 <= d < 360.
  207.        """
  208.         return self.direction
  209.         raise NotImplementedError
  210.  
  211.     def setRobotPosition(self, position):
  212.         """
  213.        Set the position of the robot to POSITION.
  214.  
  215.        position: a Position object.
  216.        """
  217.         self.position = position
  218.         print position.getX(),position.getY()
  219.         pass
  220.  
  221.     def setRobotDirection(self, direction):
  222.         """
  223.        Set the direction of the robot to DIRECTION.
  224.  
  225.        direction: integer representing an angle in degrees
  226.        """
  227.         self.direction = direction
  228.         pass
  229.  
  230.     def updatePositionAndClean(self):
  231.         """
  232.        Simulate the raise passage of a single time-step.
  233.  
  234.        Move the robot to a new position and mark the tile it is on as having
  235.        been cleaned.
  236.        """
  237.         print "default updateclean called"
  238.         self.setRobotPosition(self.position.getNewPosition(self.getRobotDirection(),self.speed))
  239.         self.room.cleanTileAtPosition(getRobotDirection())
  240.         pass
  241.  
  242. # === Problem 2
  243. class StandardRobot(Robot):
  244.     """
  245.    A StandardRobot is a Robot with the standard movement strategy.
  246.  
  247.    At each time-step, a StandardRobot attempts to move in its current direction; when
  248.    it hits a wall, it chooses a new direction randomly.
  249.    """
  250.     def updatePositionAndClean(self):
  251.         """
  252.        Simulate the passage of a single time-step.
  253.  
  254.        Move the robot to a new position and mark the tile it is on as having
  255.        been cleaned.
  256.        """
  257.  
  258.         self.potential_move = self.position.getNewPosition(self.direction,self.speed)
  259.         if self.room.isPositionInRoom(self.potential_move):
  260.             self.setRobotPosition(self.potential_move)
  261.            
  262.             self.room.cleanTileAtPosition(self.position)
  263.         else:
  264.             self.setRobotDirection(self.getRandomDirection())
  265.             print "new direction", self.direction
  266.  
  267.         pass
  268.  
  269. # === Problem 3
  270.  
  271. def runSimulation(num_robots, speed, width, height, min_coverage, num_trials,
  272.                   robot_type):
  273.     """
  274.    Runs NUM_TRIALS trials of the simulation and returns the mean number of
  275.    time-steps needed to clean the fraction MIN_COVERAGE of the room.
  276.  
  277.    The simulation is run with NUM_ROBOTS robots of type ROBOT_TYPE, each with
  278.    speed SPEED, in a room of dimensions WIDTH x HEIGHT.
  279.  
  280.    num_robots: an int (num_robots > 0)
  281.    speed: a float (speed > 0)
  282.    width: an int (width > 0)
  283.    height: an int (height > 0)
  284.    min_coverage: a float (0 <= min_coverage <= 1.0)
  285.    num_trials: an int (num_trials > 0)
  286.    robot_type: class of robot to be instantiated (e.g. Robot or
  287.                RandomWalkRobot)
  288.    """
  289.    
  290.    
  291.     bots = []
  292.     timestep = 0
  293.     times = []
  294.     time_sum = 0
  295.    
  296.  
  297.    
  298.     for i in range(0,num_trials):
  299.         room = RectangularRoom( width, height )
  300.         NumTiles = room.getNumTiles()
  301.         bots = []
  302.         timestep = 1
  303.         for bot in range(0,num_robots):
  304.             bots.append(StandardRobot( room, speed))
  305.         while ( room.getNumCleanedTiles() / NumTiles ) < min_coverage :
  306.             print "cleaned tiles", room.getNumCleanedTiles()
  307.             for bot in range(0,(num_robots)):
  308.                 bots[bot].updatePositionAndClean()
  309.             timestep = timestep + 1
  310.         times.append(timestep)
  311.     for i in times:
  312.         time_sum = time_sum + i
  313.  
  314.     time_av = time_sum / len(times)
  315.     return time_av
  316.        
  317.  
  318.  
  319. # === Problem 4
  320. #
  321. # 1) How long does it take to clean 80% of a 20×20 room with each of 1-10 robots?
  322. #
  323. # 2) How long does it take two robots to clean 80% of rooms with dimensions
  324. #    20×20, 25×16, 40×10, 50×8, 80×5, and 100×4?
  325.  
  326. def showPlot1():
  327.     """
  328.    Produces a plot showing dependence of cleaning time on number of robots.
  329.    """
  330.     raise NotImplementedError
  331.  
  332. def showPlot2():
  333.     """
  334.    Produces a plot showing dependence of cleaning time on room shape.
  335.    """
  336.     raise NotImplementedError
  337.  
  338. # === Problem 5
  339.  
  340. class RandomWalkRobot(Robot):
  341.     """
  342.    A RandomWalkRobot is a robot with the "random walk" movement strategy: it
  343.    chooses a new direction at random after each time-step.
  344.    """
  345.     raise NotImplementedError
  346.  
  347.  
  348. # === Problem 6
  349.  
  350. # For the parameters tested below (cleaning 80% of a 20x20 square room),
  351. # RandomWalkRobots take approximately twice as long to clean the same room as
  352. # StandardRobots do.
  353. def showPlot3():
  354.     """
  355.    Produces a plot comparing the two robot strategies.
  356.    """
  357.     raise NotImplementedError
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement