Ejemplo n.º 1
0
    def setWeights(self, weights):
        """
        Plot the linear regression line for given weights; assuming h_w(x) = weights[0]*x + weights[1].

        This will draw on the existing pacman window with the existing points

        weights: array or list of 2 values (or if just one value, the bias weight is assumed to be zero). If None,
            no line is drawn. Default: None
        """
        weights = np.array(weights)

        if weights.size >= 2:
            w = weights[0]
            b = weights[1]
        else:
            w = float(weights)
            b = 0


#         xmin = min(x)
#         xmax = max(x)
#
#         ymin = w*xmin + b
#         ymax = w*xmax + b
#
#         point1 = (xmin+self.xShift, ymin+self.yShift)
#         point2 = (xmax+self.xShift, ymax+self.yShift)

        (point1, point2) = plotUtil.lineBoxIntersection(
            w, -1, b, 1 - self.xShift, 1 - self.yShift,
            self.width - 2 - self.xShift, self.height - 2 - self.yShift)

        if point1 is not None and point2 is not None:
            point1 = (point1[0] + self.xShift, point1[1] + self.yShift)
            point2 = (point2[0] + self.xShift, point2[1] + self.yShift)

            dx = point2[0] - point1[0]
            dy = point2[1] - point1[1]
            if dx == 0:
                angle = 90 + 180 * dy * 1.0 / abs(dy)
            else:
                angle = math.atan(dy * 1.0 / dx) * 180.0 / math.pi

            if self.line is not None:
                graphicsUtils.remove_from_screen(self.line)
            self.line = graphicsUtils.polygon(
                [self.to_screen(point1),
                 self.to_screen(point2)],
                LINE_COLOR,
                filled=0,
                behind=0)

            if self.addPacmanToLineStart is True and len(self.agentImages) > 0:
                # Bring pacman to front of display
                graphicsUtils._canvas.tag_raise(self.agentImages[0][1][0])

                # Put pacman at beginning of line
                self.movePacman(point1, angle, self.agentImages[0][1])

            graphicsUtils.refresh()
Ejemplo n.º 2
0
    def setWeights(self, weights):
        """
        Plot the logistic regression line for given weights
        
        This will draw on the existing pacman window with the existing points
        
        weights: array or list of 2 values (or if just one value, the bias weight is assumed to be zero). If None,
            no line is drawn. Default: None
        """
        weights = np.array(weights)

        if weights.size >= 2:
            w = weights[0]
            b = weights[1]
        else:
            w = float(weights)
            b = 0

        xmin = 1 - self.xShift
        xmax = self.width - 2 - self.xShift

        x = np.linspace(xmin, xmax, 30)
        y = 1.0 / (1 + np.exp(-(w * x + b)))
        x += self.xShift
        y += self.yShift

        if self.line is not None:
            for obj in self.line:
                graphicsUtils.remove_from_screen(obj)

        self.line = []

        prevPoint = self.to_screen((x[0], y[0]))
        for i in xrange(1, len(x)):
            point = self.to_screen((x[i], y[i]))
            self.line.append(graphicsUtils.line(prevPoint, point, LINE_COLOR))
            prevPoint = point


#         prevPoint = self.to_screen((x[0],y[0]))
#         for i in xrange(1,len(x)):
#             point = self.to_screen((x[i],y[i]))
#             line.append(graphicsUtils.line(prevPoint, point, LINE_COLOR, filled=0, behind=0)
#
#             prevPoint = point

        if self.addPacmanToLineStart is True and len(self.agentImages) > 0:
            # Bring pacman to front of display
            graphicsUtils._canvas.tag_raise(self.agentImages[0][1][0])

            # Put pacman at beginning of line
            if w >= 0:
                self.movePacman((x[0] - 0.5, y[0]), Directions.EAST,
                                self.agentImages[0][1])
            else:
                self.movePacman((x[-1] + 0.5, y[-1]), Directions.WEST,
                                self.agentImages[0][1])

        graphicsUtils.refresh()
        graphicsUtils.sleep(1)
Ejemplo n.º 3
0
    def updateDistributions(self, distributions):
        "Draws an agent's belief distributions"
        # copy all distributions so we don't change their state
        distributions = [x.copy() for x in distributions]
        if self.distributionImages is None:
            self.drawDistributions(self.previousState)
        for x in range(len(self.distributionImages)):
            for y in range(len(self.distributionImages[0])):
                image = self.distributionImages[x][y]
                weights = [dist[(x, y)] for dist in distributions]

                if sum(weights) != 0:
                    pass
                # Fog of war
                color = [0.0, 0.0, 0.0]
                colors = GHOST_VEC_COLORS[1:]  # With Pacman
                if self.capture:
                    colors = GHOST_VEC_COLORS
                for weight, gcolor in zip(weights, colors):
                    color = [
                        min(1.0, c + 0.95 * g * weight**0.3)
                        for c, g in zip(color, gcolor)
                    ]
                changeColor(image, formatColor(*color))
        refresh()
Ejemplo n.º 4
0
    def drawWallandPositionBeliefs(self,
                                   known_map=None,
                                   possibleLocations=None,
                                   direction="North",
                                   visited_states_to_render=[],
                                   pacman_position=None):
        import random
        import __main__
        from graphicsUtils import draw_background, refresh
        known_walls, known_non_walls = self.get_known_walls_non_walls_from_known_map(
            known_map)
        wallGrid = Grid(self.problem.walls.width,
                        self.problem.walls.height,
                        initialValue=False)
        wallGrid.data = known_walls
        allTrueWallGrid = Grid(self.problem.walls.width,
                               self.problem.walls.height,
                               initialValue=True)

        # Recover list of non-wall coords:
        non_wall_coords = []
        for x in range(len(known_non_walls)):
            for y in range(len(known_non_walls[x])):
                if known_non_walls[x][y] == 1:
                    non_wall_coords.append((x, y))

        self.display.clearExpandedCells()  # Erase previous colors

        self.display.drawWalls(wallGrid, formatColor(.9, 0, 0),
                               allTrueWallGrid)
        self.display.colorCircleSquareCells(possibleLocations,
                                            square_cells=non_wall_coords,
                                            direction=direction,
                                            pacman_position=pacman_position)
        refresh()
Ejemplo n.º 5
0
    def setWeights(self, weights):
        """
        Plot the logistic regression line for given weights
        
        This will draw on the existing pacman window with the existing points
        
        weights: array or list of 2 values (or if just one value, the bias weight is assumed to be zero). If None,
            no line is drawn. Default: None
        """
        weights = np.array(weights)

        if weights.size >= 2:
            w = weights[0]
            b = weights[1]
        else:
            w = float(weights)
            b = 0
            
        xmin = 1 - self.xShift
        xmax = self.width-2 - self.xShift
    
        x = np.linspace(xmin, xmax,30)
        y = 1.0/(1+np.exp(-(w*x+b)))
        x += self.xShift
        y += self.yShift

        if self.line is not None:
            for obj in self.line:
                graphicsUtils.remove_from_screen(obj)
                 
        self.line = []
        
        prevPoint = self.to_screen((x[0],y[0]))
        for i in xrange(1,len(x)):
            point = self.to_screen((x[i],y[i]))
            self.line.append(graphicsUtils.line(prevPoint, point, LINE_COLOR))
            prevPoint = point
            
#         prevPoint = self.to_screen((x[0],y[0]))
#         for i in xrange(1,len(x)):
#             point = self.to_screen((x[i],y[i]))
#             line.append(graphicsUtils.line(prevPoint, point, LINE_COLOR, filled=0, behind=0)
#                         
#             prevPoint = point

            
        if self.addPacmanToLineStart is True and len(self.agentImages) > 0:
            # Bring pacman to front of display
            graphicsUtils._canvas.tag_raise(self.agentImages[0][1][0])
            
            # Put pacman at beginning of line
            if w >= 0:
                self.movePacman((x[0]-0.5,y[0]), Directions.EAST, self.agentImages[0][1])
            else:
                self.movePacman((x[-1]+0.5,y[-1]), Directions.WEST, self.agentImages[0][1])

        graphicsUtils.refresh()
Ejemplo n.º 6
0
 def drawAgentObjects(self, state):
     self.agentImages = []  # (agentState, image)
     for index, agent in enumerate(state.agentStates):
         if agent.isPacman:
             image = self.drawPacman(agent, index)
             self.agentImages.append((agent, image))
         else:
             image = self.drawGhost(agent, index)
             self.agentImages.append((agent, image))
     gU.refresh()
Ejemplo n.º 7
0
    def setWeights(self, weights):
        """
        Plot the linear regression line for given weights; assuming h_w(x) = weights[0]*x + weights[1].
        
        This will draw on the existing pacman window with the existing points
        
        weights: array or list of 2 values (or if just one value, the bias weight is assumed to be zero). If None,
            no line is drawn. Default: None
        """
        weights = np.array(weights)

        if weights.size >= 2:
            w = weights[0]
            b = weights[1]
        else:
            w = float(weights)
            b = 0
            
#         xmin = min(x)
#         xmax = max(x)
#         
#         ymin = w*xmin + b
#         ymax = w*xmax + b        
#         
#         point1 = (xmin+self.xShift, ymin+self.yShift)
#         point2 = (xmax+self.xShift, ymax+self.yShift)

        (point1, point2) = plotUtil.lineBoxIntersection(w, -1, b,
                                                        1-self.xShift, 1-self.yShift,
                                                        self.width-2-self.xShift, self.height-2-self.yShift)
        
        if point1 is not None and point2 is not None:
            point1 = (point1[0]+self.xShift, point1[1]+self.yShift)
            point2 = (point2[0]+self.xShift, point2[1]+self.yShift)
            
            dx = point2[0]-point1[0]
            dy = point2[1]-point1[1]
            if dx == 0:
                angle = 90 + 180*dy*1.0/abs(dy)
            else:
                angle = math.atan(dy*1.0/dx)*180.0/math.pi
                   
            if self.line is not None:
                graphicsUtils.remove_from_screen(self.line) 
            self.line = graphicsUtils.polygon([self.to_screen(point1), self.to_screen(point2)], LINE_COLOR, filled=0, behind=0)
                
            if self.addPacmanToLineStart is True and len(self.agentImages) > 0:
                # Bring pacman to front of display
                graphicsUtils._canvas.tag_raise(self.agentImages[0][1][0])
                
                # Put pacman at beginning of line
                self.movePacman(point1, angle, self.agentImages[0][1])

            graphicsUtils.refresh()
Ejemplo n.º 8
0
    def plot(self, x, y, weights=None, title='Linear Regression'):
        """
        Plot the input values x with their corresponding output values y (either true or predicted).
        Also, plot the linear regression line if weights are given; assuming h_w(x) = weights[0]*x + weights[1].
        
        This will draw on the existing pacman window (clearing it first) or create a new one if no window exists.
        
        x: array or list of N scalar values.
        y: array or list of N scalar values.
        weights: array or list of 2 values (or if just one value, the bias weight is assumed to be zero). If None,
            no line is drawn. Default: None
        """
        if np.array(x).size == 0:
            return

        if isinstance(x[0], np.ndarray):
            # Scrape the first element of each data point
            x = [data[0] for data in x]

        xmin = int(math.floor(min(x)))
        ymin = int(math.floor(min(y)))
        xmax = int(math.ceil(max(x)))
        ymax = int(math.ceil(max(y)))
        width = xmax - xmin + 3
        height = ymax - ymin + 3
        self.initPlot(xmin, ymin, width, height)

        gameState = self.blankGameState.deepCopy()

        gameState.agentStates = []

        # Put pacman in bottom left
        if self.addPacmanToLineStart is True:
            gameState.agentStates.append(
                AgentState(Configuration((1, 1), Directions.STOP), True))

        # Add ghost at each point
        for (px, py) in zip(x, y):
            point = (px + self.xShift, py + self.yShift)
            gameState.agentStates.append(
                AgentState(Configuration(point, Directions.STOP), False))

#         self.initialize(gameState)
        graphicsUtils.clear_screen()
        self.infoPane = InfoPane(gameState.layout, self.gridSize)
        self.drawStaticObjects(gameState)
        self.drawAgentObjects(gameState)

        graphicsUtils.changeText(self.infoPane.scoreText, title)
        graphicsUtils.refresh()
        graphicsUtils.sleep(1)

        if weights is not None:
            self.setWeights(weights)
Ejemplo n.º 9
0
    def setWeights(self, weights):
        """
        Plot the logistic regression line for given weights

        This will draw on the existing pacman window with the existing points

        weights: array or list of 2 values (or if just one value, the bias weight is assumed to be zero). If None,
            no line is drawn. Default: None
        """

        weights = np.array(weights)

        if self.prev_weights is not None:
            if np.allclose(self.prev_weights, weights):
                return False  # no line update
        self.prev_weights = weights.copy()

        w1 = weights[0]
        w2 = weights[1]
        if weights.size >= 3:
            b = weights[2]
        else:
            b = 0

        # Line functions
        # Line where w1*x1 + w2*x2 + b = 0
        # x2 = -(w1*x1 + b)/w2  or
        # x1 = -(w2*x2 + b)/w1

        # Figure out where line intersections bounding box around points
        if w1 == 0 and w2 == 0:
            return

        (point1, point2) = plotUtil.lineBoxIntersection(
            w1, w2, b, 1 - self.xShift, 1 - self.yShift,
            self.width - 2 - self.xShift, self.height - 2 - self.yShift)

        if point1 is not None and point2 is not None:
            point1 = (point1[0] + self.xShift, point1[1] + self.yShift)
            point2 = (point2[0] + self.xShift, point2[1] + self.yShift)

            if self.line is not None:
                graphicsUtils.remove_from_screen(self.line)
            self.line = graphicsUtils.polygon(
                [self.to_screen(point1),
                 self.to_screen(point2)],
                LINE_COLOR,
                filled=0,
                behind=0)

        graphicsUtils.refresh()
        return True  # updated line
Ejemplo n.º 10
0
    def plot(self, x, y, weights=None, title='Linear Regression'):
        """
        Plot the input values x with their corresponding output values y (either true or predicted).
        Also, plot the linear regression line if weights are given; assuming h_w(x) = weights[0]*x + weights[1].
        
        This will draw on the existing pacman window (clearing it first) or create a new one if no window exists.
        
        x: array or list of N scalar values.
        y: array or list of N scalar values.
        weights: array or list of 2 values (or if just one value, the bias weight is assumed to be zero). If None,
            no line is drawn. Default: None
        """
        if np.array(x).size == 0:
            return
        
        if isinstance(x[0], np.ndarray):
            # Scrape the first element of each data point
            x = [data[0] for data in x]
        
        xmin = int(math.floor(min(x)))
        ymin = int(math.floor(min(y)))
        xmax = int(math.ceil(max(x)))
        ymax = int(math.ceil(max(y)))
        width = xmax-xmin+3
        height = ymax-ymin+3
        self.initPlot(xmin, ymin, width, height)
        
        gameState = self.blankGameState.deepCopy()
                
        gameState.agentStates = []
        
        # Put pacman in bottom left
        if self.addPacmanToLineStart is True:
            gameState.agentStates.append( AgentState( Configuration( (1,1), Directions.STOP), True) )
            
        # Add ghost at each point
        for (px,py) in zip(x,y):
            point = (px+self.xShift, py+self.yShift)
            gameState.agentStates.append( AgentState( Configuration( point, Directions.STOP), False) )

#         self.initialize(gameState)
        graphicsUtils.clear_screen()
        self.infoPane = InfoPane(gameState.layout, self.gridSize)
        self.drawStaticObjects(gameState)
        self.drawAgentObjects(gameState)

        graphicsUtils.changeText(self.infoPane.scoreText, title)
        graphicsUtils.refresh()
        
        if weights is not None:
            self.setWeights(weights)
Ejemplo n.º 11
0
 def swapImages(self, agentIndex, newState):
     """
     Changes an image from a ghost to a pacman or vis versa (for capture)
     """
     prevState, prevImage = self.agentImages[agentIndex]
     for item in prevImage:
         gU.remove_from_screen(item)
     if newState.isPacman:
         image = self.drawPacman(newState, agentIndex)
         self.agentImages[agentIndex] = (newState, image)
     else:
         image = self.drawGhost(newState, agentIndex)
         self.agentImages[agentIndex] = (newState, image)
     gU.refresh()
Ejemplo n.º 12
0
    def setWeights(self, weights):
        """
        Plot the logistic regression line for given weights

        This will draw on the existing pacman window with the existing points

        weights: array or list of 2 values (or if just one value, the bias weight is assumed to be zero). If None,
            no line is drawn. Default: None
        """

        weights = np.array(weights)

        if self.prev_weights is not None:
            if np.allclose(self.prev_weights, weights):
                return False # no line update
        self.prev_weights = weights.copy()

        w1 = weights[0]
        w2 = weights[1]
        if weights.size >= 3:
            b = weights[2]
        else:
            b = 0

        # Line functions
        # Line where w1*x1 + w2*x2 + b = 0
        # x2 = -(w1*x1 + b)/w2  or
        # x1 = -(w2*x2 + b)/w1

        # Figure out where line intersections bounding box around points
        if w1 == 0 and w2 == 0:
            return

        (point1, point2) = plotUtil.lineBoxIntersection(w1, w2, b,
                                                        1-self.xShift, 1-self.yShift,
                                                        self.width-2-self.xShift, self.height-2-self.yShift)

        if point1 is not None and point2 is not None:
            point1 = (point1[0]+self.xShift, point1[1]+self.yShift)
            point2 = (point2[0]+self.xShift, point2[1]+self.yShift)

            if self.line is not None:
                graphicsUtils.remove_from_screen(self.line)
            self.line = graphicsUtils.polygon([self.to_screen(point1), self.to_screen(point2)], LINE_COLOR, filled=0, behind=0)

        graphicsUtils.refresh()
        return True # updated line
Ejemplo n.º 13
0
    def moveGhost(self, ghost, ghostIndex, prevGhost, ghostImageParts):
        old_x, old_y = self.to_screen(self.getPosition(prevGhost))
        new_x, new_y = self.to_screen(self.getPosition(ghost))
        delta = new_x - old_x, new_y - old_y

        for ghostImagePart in ghostImageParts:
            gU.move_by(ghostImagePart, delta)
        gU.refresh()

        if ghost.scaredTimer > 0:
            color = SCARED_COLOR
        else:
            color = GHOST_COLORS[ghostIndex]
        gU.edit(ghostImageParts[0], ('fill', color), ('outline', color))
        self.moveEyes(self.getPosition(ghost), self.getDirection(ghost),
                      ghostImageParts[-4:])
        gU.refresh()
Ejemplo n.º 14
0
    def initPlot(self, xmin, ymin, width, height):
        if graphicsUtils._canvas is not None:
            graphicsUtils.clear_screen()
        
        # Initialize GameStateData with blank board with axes    
        self.width = width
        self.height = height
        self.xShift = -(xmin-1)
        self.yShift = -(ymin-1)
        self.line = None

        self.zoom = min(30.0/self.width, 20.0/self.height)
        self.gridSize = graphicsDisplay.DEFAULT_GRID_SIZE * self.zoom


#         fullRow = ['%']*self.width
#         row = ((self.width-1)/2)*[' '] + ['%'] + ((self.width-1)/2)*[' ']
#         boardText = ((self.height-1)/2)*[row] + [fullRow] + ((self.height-1)/2)*[row]

        numSpaces = self.width-1
        numSpacesLeft = self.xShift
        numSpacesRight = numSpaces-numSpacesLeft

        numRows = self.height
        numRowsBelow = self.yShift
        numRowsAbove = numRows-1-numRowsBelow


        fullRow = ['%']*self.width
        if numSpacesLeft < 0:
            row = [' ']*self.width
        else:
            row = numSpacesLeft*[' '] + ['%'] + numSpacesRight*[' ']
        boardText = numRowsAbove*[row] + [fullRow] + numRowsBelow*[row]

        layout = Layout(boardText)
    
        self.blankGameState = GameStateData()
        self.blankGameState.initialize(layout, 0)
        self.initialize(self.blankGameState)
        title = 'Pacman Plot'
        graphicsUtils.changeText(self.infoPane.scoreText, title)
        graphicsUtils.refresh()
Ejemplo n.º 15
0
    def initPlot(self, xmin, ymin, width, height):
        if graphicsUtils._canvas is not None:
            graphicsUtils.clear_screen()

        # Initialize GameStateData with blank board with axes
        self.width = width
        self.height = height
        self.xShift = -(xmin-1)
        self.yShift = -(ymin-1)
        self.line = None

        self.zoom = min(30.0/self.width, 20.0/self.height)
        self.gridSize = graphicsDisplay.DEFAULT_GRID_SIZE * self.zoom


#         fullRow = ['%']*self.width
#         row = ((self.width-1)/2)*[' '] + ['%'] + ((self.width-1)/2)*[' ']
#         boardText = ((self.height-1)/2)*[row] + [fullRow] + ((self.height-1)/2)*[row]

        numSpaces = self.width-1
        numSpacesLeft = self.xShift
        numSpacesRight = numSpaces-numSpacesLeft

        numRows = self.height
        numRowsBelow = self.yShift
        numRowsAbove = numRows-1-numRowsBelow


        fullRow = ['%']*self.width
        if numSpacesLeft < 0:
            row = [' ']*self.width
        else:
            row = round(numSpacesLeft)*[' '] + ['%'] + round(numSpacesRight)*[' ']
        boardText = round(numRowsAbove)*[row] + [fullRow] + round(numRowsBelow)*[row]

        layout = Layout(boardText)

        self.blankGameState = GameStateData()
        self.blankGameState.initialize(layout, 0)
        self.initialize(self.blankGameState)
        title = 'Pacman Plot'
        graphicsUtils.changeText(self.infoPane.scoreText, title)
        graphicsUtils.refresh()
Ejemplo n.º 16
0
 def drawExpandedCells(self, cells):
     """
     Draws an overlay of expanded grid positions for search agents
     """
     n = float(len(cells))
     baseColor = [1.0, 0.0, 0.0]
     self.clearExpandedCells()
     self.expandedCells = []
     for k, cell in enumerate(cells):
         screenPos = self.to_screen(cell)
         cellColor = gU.formatColor(*[(n - k) * c * .5 / n + .25
                                      for c in baseColor])
         block = gU.square(screenPos,
                           0.5 * self.gridSize,
                           color=cellColor,
                           filled=1, behind=2)
         self.expandedCells.append(block)
         if self.frameTime < 0:
             gU.refresh()
Ejemplo n.º 17
0
 def drawWallBeliefs(self,
                     known_map=None,
                     direction="North",
                     visited_states_to_render=[]):
     import random
     import __main__
     from graphicsUtils import draw_background, refresh
     known_walls, known_non_walls = self.get_known_walls_non_walls_from_known_map(
         known_map)
     wallGrid = Grid(self.problem.walls.width,
                     self.problem.walls.height,
                     initialValue=False)
     wallGrid.data = known_walls
     allTrueWallGrid = Grid(self.problem.walls.width,
                            self.problem.walls.height,
                            initialValue=True)
     self.display.clearExpandedCells()  # Erase previous colors
     self.display.drawWalls(wallGrid, formatColor(.9, 0, 0),
                            allTrueWallGrid)
     refresh()
Ejemplo n.º 18
0
 def animatePacman(self, pacman, prevPacman, image):
     if self.frameTime < 0:
         print('Press any key to step forward, "q" to play')
         keys = gU.wait_for_keys()
         if 'q' in keys:
             self.frameTime = 0.1
     if self.frameTime > 0.01 or self.frameTime < 0:
         fx, fy = self.getPosition(prevPacman)
         px, py = self.getPosition(pacman)
         frames = 4.0
         for i in range(1, int(frames) + 1):
             pos = px * i / frames + fx * (frames - i) / frames, \
                 py * i / frames + fy * (frames - i) / frames
             self.movePacman(pos, self.getDirection(pacman), image)
             gU.refresh()
             gU.sleep(abs(self.frameTime) / frames)
     else:
         self.movePacman(self.getPosition(pacman),
                         self.getDirection(pacman), image)
     gU.refresh()
Ejemplo n.º 19
0
    def shadeCost(self, layout, constraints, costVector, feasiblePoints, xmin,
                  ymin, xmax, ymax):
        baseColor = [1.0, 0.0, 0.0]

        costs = [self.pointCost(costVector, point) for point in feasiblePoints]
        minCost = min(costs)
        maxCost = max(costs)
        costSpan = maxCost - minCost

        allFeasiblePoints = self.getFeasibleLayoutPoints(
            layout, constraints, xmin, ymin, xmax, ymax)

        # The feasible points themselves may have been gridded to infeasible grid points,
        # but we want to make sure they are shaded too.
        #cornerPoints = [self.cartesianToLayout(xmin, ymin, xmax, ymax, point) for point in feasiblePoints]
        cornerPoints = self.getLayoutPointsWithSymbol(layout, ('o', 'P'))

        gridPointsToShade = cornerPoints + allFeasiblePoints

        for gridPoint in gridPointsToShade:
            point = self.layoutToCartesian(xmin, ymin, xmax, ymax, gridPoint)

            relativeCost = (self.pointCost(costVector, point) -
                            minCost) * 1.0 / costSpan

            # Whoops our grid points are flipped top-bottom from what to_screen expects
            screenPos = self.to_screen(
                (gridPoint[0], len(layout) - gridPoint[1] - 1))

            cellColor = [
                0.25 + 0.5 * relativeCost * channel for channel in baseColor
            ]

            graphicsUtils.square(screenPos,
                                 0.5 * self.gridSize,
                                 color=graphicsUtils.formatColor(*cellColor),
                                 filled=1,
                                 behind=2)

        graphicsUtils.refresh()
        graphicsUtils.sleep(1)
Ejemplo n.º 20
0
    def updateDistributions(self, distributions):
        "Draws an agent's belief distributions"
        if self.distributionImages is None:
            self.drawDistributions(self.previousState)
        for x in range(len(self.distributionImages)):
            for y in range(len(self.distributionImages[0])):
                image = self.distributionImages[x][y]
                weights = [dist[(x, y)] for dist in distributions]

                if sum(weights) != 0:
                    pass
                # Fog of war
                color = [0.0, 0.0, 0.0]
                colors = GHOST_VEC_COLORS[1:]  # With Pacman
                if self.capture:
                    colors = GHOST_VEC_COLORS
                for weight, gcolor in zip(weights, colors):
                    color = [min(1.0, c + 0.95 * g * weight ** .3)
                             for c, g in zip(color, gcolor)]
                gU.changeColor(image, gU.formatColor(*color))
        gU.refresh()
Ejemplo n.º 21
0
    def plot(self, x, y, weights=None, title='Linear Classification'):
        """
        Plot the 2D input points, data[i], colored based on their corresponding labels (either true or predicted).
        Also, plot the linear separator line if weights are given.

        This will draw on the existing pacman window (clearing it first) or create a new one if no window exists.

        x: list of 2D points, where each 2D point in the list is a 2 element numpy.ndarray
        y: list of N labels, one for each point in data. Labels can be of any type that can be converted
            a string.
        weights: array of 3 values the first two are the weight on the data and the third value is the bias
        weight term. If there are only 2 values in weights, the bias term is assumed to be zero.  If None,
        no line is drawn. Default: None
        """
        if np.array(x).size == 0:
            return

        # Process data, sorting by label
        possibleLabels = list(set(y))
        sortedX1 = {}
        sortedX2 = {}
        for label in possibleLabels:
            sortedX1[label] = []
            sortedX2[label] = []

        for i in range(len(x)):
            sortedX1[y[i]].append(x[i][0])
            sortedX2[y[i]].append(x[i][1])

        x1min = float("inf")
        x1max = float("-inf")
        for x1Values in sortedX1.values():
            x1min = min(min(x1Values), x1min)
            x1max = max(max(x1Values), x1max)
        x2min = float("inf")
        x2max = float("-inf")
        for x2Values in sortedX2.values():
            x2min = min(min(x2Values), x2min)
            x2max = max(max(x2Values), x2max)

        x1min = int(math.floor(x1min))
        x1max = int(math.ceil(x1max))
        x2min = int(math.floor(x2min))
        x2max = int(math.ceil(x2max))

        width = x1max - x1min + 3
        height = x2max - x2min + 3
        self.initPlot(x1min, x2min, width, height)

        gameState = self.blankGameState.deepCopy()

        gameState.agentStates = []

        # Add ghost/pacman at each point
        for (labelIndex, label) in enumerate(possibleLabels):
            pointsX1 = sortedX1[label]
            pointsX2 = sortedX2[label]
            for (px, py) in zip(pointsX1, pointsX2):
                point = (px + self.xShift, py + self.yShift)
                agent = AgentState(Configuration(point, Directions.STOP),
                                   False)
                agent.isPacman = (labelIndex == 0)
                if labelIndex == 2:
                    agent.scaredTimer = 1
                gameState.agentStates.append(agent)


#         self.initialize(gameState)
        graphicsUtils.clear_screen()
        self.infoPane = InfoPane(gameState.layout, self.gridSize)
        self.drawStaticObjects(gameState)
        self.drawAgentObjects(gameState)

        graphicsUtils.changeText(self.infoPane.scoreText, title)
        graphicsUtils.refresh()

        if weights is not None:
            self.setWeights(weights)
Ejemplo n.º 22
0
    def plot(self, x, y, weights=None, title='Logistic Regression'):
        """
        Plot the 1D input points, data[i], colored based on their corresponding labels (either true or predicted).
        Also, plot the logistic function fit if weights are given.

        This will draw on the existing pacman window (clearing it first) or create a new one if no window exists.

        x: list of 1D points, where each 1D point in the list is a 1 element numpy.ndarray
        y: list of N labels, one for each point in data. Labels can be of any type that can be converted
            a string.
        weights: array of 2 values the first one is the weight on the data and the second value is the bias weight term.
        If there are only 1 values in weights,
            the bias term is assumed to be zero.  If None, no line is drawn. Default: None
        """
        if np.array(x).size == 0:
            return

        # Process data, sorting by label
        possibleLabels = list(set(y))
        sortedX = {}
        for label in possibleLabels:
            sortedX[label] = []

        for i in range(len(x)):
            sortedX[y[i]].append(x[i])

        xmin = int(math.floor(min(x)))
        xmax = int(math.ceil(max(x)))
        ymin = int(math.floor(0)) - 1
        ymax = int(math.ceil(1))
        width = xmax - xmin + 3
        height = ymax - ymin + 3
        self.initPlot(xmin, ymin, width, height)

        gameState = self.blankGameState.deepCopy()

        gameState.agentStates = []

        # Put pacman in bottom left
        if self.addPacmanToLineStart is True:
            gameState.agentStates.append(
                AgentState(Configuration((1, 1), Directions.STOP), True))

        # Add ghost at each point
        for (py, label) in enumerate(possibleLabels):
            pointsX = sortedX[label]
            for px in pointsX:
                point = (px + self.xShift, py + self.yShift)
                agent = AgentState(Configuration(point, Directions.STOP),
                                   False)
                agent.isPacman = 1 - py
                gameState.agentStates.append(agent)

#         self.initialize(gameState)
        graphicsUtils.clear_screen()
        self.infoPane = InfoPane(gameState.layout, self.gridSize)
        self.drawStaticObjects(gameState)
        self.drawAgentObjects(gameState)

        graphicsUtils.changeText(self.infoPane.scoreText, title)
        graphicsUtils.refresh()

        if weights is not None:
            self.setWeights(weights)
Ejemplo n.º 23
0
    def __init__(self,
                 constraints=[],
                 infeasiblePoints=[],
                 feasiblePoints=[],
                 optimalPoint=None,
                 costVector=None,
                 zoom=1.0,
                 frameTime=0.0):
        """
        Create and dispaly a pacman plot figure.
        
        This will draw on the existing pacman window (clearing it first) or create a new one if no window exists.
        
        constraints: list of inequality constraints, where each constraint w1*x + w2*y <= b is represented as a tuple ((w1, w2), b)
        infeasiblePoints (food): list of points where each point is a tuple (x, y)
        feasiblePoints (power): list of points where each point is a tuple (x, y)
        optimalPoint (pacman): optimal point as a tuple (x, y)
        costVector (shading): cost vector represented as a tuple (c1, c2), where cost is c1*x + c2*x
        """
        super(PacmanPlotLP, self).__init__(zoom, frameTime)

        xmin = 100000
        ymin = 100000
        xmax = -100000
        ymax = -100000

        for point in feasiblePoints:
            if point[0] < xmin:
                xmin = point[0]
            if point[0] > xmax:
                xmax = point[0]
            if point[1] < ymin:
                ymin = point[1]
            if point[1] > ymax:
                ymax = point[1]

        if len(feasiblePoints) == 0:
            for point in infeasiblePoints:
                if point[0] < xmin:
                    xmin = point[0]
                if point[0] > xmax:
                    xmax = point[0]
                if point[1] < ymin:
                    ymin = point[1]
                if point[1] > ymax:
                    ymax = point[1]

        xmin = int(math.floor(xmin)) - 3
        ymin = int(math.floor(ymin)) - 3
        xmax = int(math.ceil(xmax)) + 3
        ymax = int(math.ceil(ymax)) + 3
        width = xmax - xmin + 1
        height = ymax - ymin + 1

        #        p = feasiblePoints[2]
        #        print("p={}".format(p))
        #        print("feasible={}".format(self.pointFeasible(p, constraints)))
        #        g = self.cartesianToLayout(xmin, ymin, xmax, ymax, p)
        #        print("g={}".format(g))
        #        gr = (int(round(g[0])), int(round(g[1])))
        #        p2 = self.layoutToCartesian(xmin, ymin, xmax, ymax, gr)
        #        print("p2={}".format(p2))
        #        print("p2 feasible={}".format(self.pointFeasible(p2, constraints)))

        layoutLists = self.blankLayoutLists(width, height)

        self.addInfeasibleGhosts(layoutLists, constraints, xmin, ymin, xmax,
                                 ymax)

        layoutLists = self.changeBorderGhostsToWall(layoutLists)

        for point in infeasiblePoints:
            self.addCartesianPointToLayout(layoutLists, point, '.', xmin, ymin,
                                           xmax, ymax)

        for point in feasiblePoints:
            self.addCartesianPointToLayout(layoutLists, point, 'o', xmin, ymin,
                                           xmax, ymax)

        if optimalPoint is not None:
            self.addCartesianPointToLayout(layoutLists, optimalPoint, 'P',
                                           xmin, ymin, xmax, ymax)

        if graphicsUtils._canvas is not None:
            graphicsUtils.clear_screen()

        # Initialize GameStateData with blank board with axes
        self.width = width
        self.height = height

        self.zoom = min(30.0 / self.width, 20.0 / self.height)
        self.gridSize = graphicsDisplay.DEFAULT_GRID_SIZE * self.zoom

        maxNumGhosts = 10000
        layout = Layout(layoutLists)
        self.blankGameState = GameStateData()
        self.blankGameState.initialize(layout, maxNumGhosts)
        self.initialize(self.blankGameState)
        title = 'Pacman Plot LP'
        graphicsUtils.changeText(self.infoPane.scoreText, title)
        graphicsUtils.refresh()

        if costVector is not None:
            self.shadeCost(layoutLists, constraints, costVector,
                           feasiblePoints, xmin, ymin, xmax, ymax)
Ejemplo n.º 24
0
 def movePacman(self, position, direction, image):
     screenPosition = self.to_screen(position)
     endpoints = self.getEndpoints(direction, position)
     r = PACMAN_SCALE * self.gridSize
     gU.moveCircle(image[0], screenPosition, r, endpoints)
     gU.refresh()
Ejemplo n.º 25
0
    def plot(self, x, y, weights=None, title='Logistic Regression'):
        """
        Plot the 1D input points, data[i], colored based on their corresponding labels (either true or predicted).
        Also, plot the logistic function fit if weights are given.
    
        This will draw on the existing pacman window (clearing it first) or create a new one if no window exists.
    
        x: list of 1D points, where each 1D point in the list is a 1 element numpy.ndarray
        y: list of N labels, one for each point in data. Labels can be of any type that can be converted
            a string.
        weights: array of 2 values the first one is the weight on the data and the second value is the bias weight term.
        If there are only 1 values in weights,
            the bias term is assumed to be zero.  If None, no line is drawn. Default: None
        """
        if np.array(x).size == 0:
            return
        
        # Process data, sorting by label
        possibleLabels = list(set(y))
        sortedX = {}
        for label in possibleLabels:
            sortedX[label] = []
    
        for i in range(len(x)):
            sortedX[y[i]].append(x[i])
    
        xmin = int(math.floor(min(x)))
        xmax = int(math.ceil(max(x)))
        ymin = int(math.floor(0))-1
        ymax = int(math.ceil(1))
        width = xmax-xmin+3
        height = ymax-ymin+3
        self.initPlot(xmin, ymin, width, height)
        
        gameState = self.blankGameState.deepCopy()
                
        gameState.agentStates = []
        
        # Put pacman in bottom left
        if self.addPacmanToLineStart is True:
            gameState.agentStates.append( AgentState( Configuration( (1,1), Directions.STOP), True) )
            
        # Add ghost at each point
        for (py, label) in enumerate(possibleLabels):
            pointsX = sortedX[label]
            for px in pointsX:
                point = (px+self.xShift, py+self.yShift)
                agent = AgentState( Configuration( point, Directions.STOP), False)
                agent.isPacman = 1-py 
                gameState.agentStates.append(agent)

#         self.initialize(gameState)
        graphicsUtils.clear_screen()
        self.infoPane = InfoPane(gameState.layout, self.gridSize)
        self.drawStaticObjects(gameState)
        self.drawAgentObjects(gameState)

        graphicsUtils.changeText(self.infoPane.scoreText, title)
        graphicsUtils.refresh()
        
        if weights is not None:
            self.setWeights(weights)
Ejemplo n.º 26
0
    def plot(self, x, y, weights=None, title='Linear Classification'):
        """
        Plot the 2D input points, data[i], colored based on their corresponding labels (either true or predicted).
        Also, plot the linear separator line if weights are given.
    
        This will draw on the existing pacman window (clearing it first) or create a new one if no window exists.
    
        x: list of 2D points, where each 2D point in the list is a 2 element numpy.ndarray
        y: list of N labels, one for each point in data. Labels can be of any type that can be converted
            a string.
        weights: array of 3 values the first two are the weight on the data and the third value is the bias
        weight term. If there are only 2 values in weights, the bias term is assumed to be zero.  If None,
        no line is drawn. Default: None
        """
        if np.array(x).size == 0:
            return
        
        # Process data, sorting by label
        possibleLabels = list(set(y))
        sortedX1 = {}
        sortedX2 = {}
        for label in possibleLabels:
            sortedX1[label] = []
            sortedX2[label] = []
    
        for i in range(len(x)):
            sortedX1[y[i]].append(x[i][0])
            sortedX2[y[i]].append(x[i][1])
    
        x1min = float("inf")
        x1max = float("-inf")
        for x1Values in sortedX1.values():
            x1min = min(min(x1Values), x1min)
            x1max = max(max(x1Values), x1max)
        x2min = float("inf")
        x2max = float("-inf")
        for x2Values in sortedX2.values():
            x2min = min(min(x2Values), x2min)
            x2max = max(max(x2Values), x2max)

        x1min = int(math.floor(x1min))
        x1max = int(math.ceil(x1max))
        x2min = int(math.floor(x2min))
        x2max = int(math.ceil(x2max))

        width = x1max-x1min+3
        height = x2max-x2min+3
        self.initPlot(x1min, x2min, width, height)
        
        gameState = self.blankGameState.deepCopy()
                
        gameState.agentStates = []
        
        # Add ghost/pacman at each point
        for (labelIndex, label) in enumerate(possibleLabels):
            pointsX1 = sortedX1[label]
            pointsX2 = sortedX2[label]
            for (px, py) in zip(pointsX1, pointsX2):
                point = (px+self.xShift, py+self.yShift)
                agent = AgentState( Configuration( point, Directions.STOP), False)
                agent.isPacman = (labelIndex==0) 
                if labelIndex==2:
                    agent.scaredTimer = 1
                gameState.agentStates.append(agent)

#         self.initialize(gameState)
        graphicsUtils.clear_screen()
        self.infoPane = InfoPane(gameState.layout, self.gridSize)
        self.drawStaticObjects(gameState)
        self.drawAgentObjects(gameState)

        graphicsUtils.changeText(self.infoPane.scoreText, title)
        graphicsUtils.refresh()
        
        if weights is not None:
            self.setWeights(weights)
Ejemplo n.º 27
0
 def drawStaticObjects(self, state):
     layout = self.layout
     self.drawWalls(layout.walls)
     self.food = self.drawFood(layout.food)
     self.capsules = self.drawCapsules(layout.capsules)
     gU.refresh()