def evaluationFunction(currentGameState): newPos = currentGameState.getPacmanPosition() newFood = currentGameState.getFood() newGhostStates = currentGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] """Calculate distance to the nearest food""" newFoodList = np.array(newFood.asList()) distanceToFood = [ util.euclideanDistance(newPos, food) for food in newFoodList ] min_food_distance = 0 if len(newFoodList) > 0: min_food_distance = distanceToFood[np.argmin(distanceToFood)] """Calculate the distance to nearest ghost""" ghostPositions = np.array(currentGameState.getGhostPositions()) if len(ghostPositions) > 0: distanceToGhost = [ util.manhattanDistance(newPos, ghost) for ghost in ghostPositions ] min_ghost_distance = distanceToGhost[np.argmin(distanceToGhost)] nearestGhostScaredTime = newScaredTimes[np.argmin(distanceToGhost)] # avoid certain death if min_ghost_distance <= 1 and nearestGhostScaredTime == 0: return -999999 # eat a scared ghost if min_ghost_distance <= 1 and nearestGhostScaredTime > 0: return 999999 return currentGameState.getScore() * 5 - min_food_distance
def checkDeath(state, agentIndex): toJump = [False] * 5 otherAgentIndex = state.getPacmanPosition() for index1 in range(1, len(state.data.agentStates)): for index2 in range(1, len(state.data.agentStates)): if index1 == index2: continue ghost1State = state.data.agentStates[index1] ghost2State = state.data.agentStates[index2] ghost1Position = ghost1State.configuration.getPosition() ghost2Position = ghost2State.configuration.getPosition() if util.euclideanDistance(ghost1Position, ghost2Position) < COLLISION_TOLERANCE: toJump[index1 - 1] = True toJump[index2 - 1] = True # @@#@@ for index in range(1, len(toJump) + 1): if toJump[index - 1]: ghostState = state.data.agentStates[index] GhostRules.placeGhost(state, ghostState) pacmanPosition = state.getPacmanPosition() if agentIndex == 0: # Pacman just moved; Anyone can kill him for index in range(1, len(state.data.agentStates)): ghostState = state.data.agentStates[index] ghostPosition = ghostState.configuration.getPosition() if GhostRules.canKill(pacmanPosition, ghostPosition): GhostRules.collide(state, ghostState, index) else: ghostState = state.data.agentStates[agentIndex] ghostPosition = ghostState.configuration.getPosition() if GhostRules.canKill(pacmanPosition, ghostPosition): GhostRules.collide(state, ghostState, agentIndex)
def checkDeath(state, agentIndex): toJump = [False] * 5 otherAgentIndex = state.getPacmanPosition() for index1 in range(1, len(state.data.agentStates)): for index2 in range(1, len(state.data.agentStates)): if index1 == index2: continue ghost1State = state.data.agentStates[index1] ghost2State = state.data.agentStates[index2] ghost1Position = ghost1State.configuration.getPosition() ghost2Position = ghost2State.configuration.getPosition() if util.euclideanDistance( ghost1Position, ghost2Position) < COLLISION_TOLERANCE: toJump[index1 - 1] = True toJump[index2 - 1] = True #@@#@@ for index in range(1, len(toJump) + 1): if toJump[index - 1]: ghostState = state.data.agentStates[index] GhostRules.placeGhost(state, ghostState) pacmanPosition = state.getPacmanPosition() if agentIndex == 0: # Pacman just moved; Anyone can kill him for index in range(1, len(state.data.agentStates)): ghostState = state.data.agentStates[index] ghostPosition = ghostState.configuration.getPosition() if GhostRules.canKill(pacmanPosition, ghostPosition): GhostRules.collide(state, ghostState, index) else: ghostState = state.data.agentStates[agentIndex] ghostPosition = ghostState.configuration.getPosition() if GhostRules.canKill(pacmanPosition, ghostPosition): GhostRules.collide(state, ghostState, agentIndex)
def classifyPts(eps, minPts): corePts = set() noisePts = set() neighborhood = dict() for i in range(size): temp = list() for j in range(size): distant = util.euclideanDistance(xCoord[i], yCoord[i], xCoord[j], yCoord[j]) if distant <= eps: temp.append(j) neighborhood[i] = temp for pt, neighbors in neighborhood.items(): if len(neighbors) >= minPts: corePts.add(pt) for pt, neighbors in neighborhood.items(): if pt not in corePts: isBorderPt = False for neighbor in neighbors: if neighbor in corePts: isBorderPt = True break if not isBorderPt: noisePts.add(pt) return corePts, noisePts, neighborhood
def getClusters(means, k): while True: tempMean = copy.deepcopy(means) cluster = list() for i in range(k): cluster.append(list()) for i in range(size): closestD = float('inf') suitableCusterId = -1 for j in range(k): distant = util.euclideanDistance(xCoord[i], yCoord[i], means[j][0], means[j][1]) if distant < closestD: closestD = distant suitableCusterId = j cluster[suitableCusterId].append(i) for i in range(k): means[i][0] = 0 means[i][1] = 0 for j in cluster[i]: means[i][0] += xCoord[j] means[i][1] += yCoord[j] clusterSize = len(cluster[i]) means[i][0] /= clusterSize means[i][1] /= clusterSize if means == tempMean: return cluster
class Cluster: def __init__(self): """ self.clusters will be a dictionary where self.clusters[coordinate] = cluster :param k: k clusters :param addresses: list of addresses to parse, for now just lat/lon coordinates """ ## self.clusters[cluster] = list of coordinates self.clusters = {} ## self.centroids[cluster] = centroid self.centroids = {} def euclideanDistance(self, (x1, y1), (x2, y2)): return util.euclideanDistance((x1, y1), (x2, y2))
def cornersHeuristic(state, problem): """ Q2.2 A heuristic for the CornersProblem that you defined. state: The current search state (a data structure you chose in your search problem) problem: The CornersProblem instance for this layout. This function should always return a number that is a lower bound on the shortest path from the state to a goal of the problem; i.e. it should be admissible (as well as consistent). """ corners = problem.corners # These are the corner coordinates # These are the walls of the maze, as a Grid (game.py) walls = problem.walls "*** YOUR CODE HERE ***" "*** we will use euclidean distance as a heuristic for this problem ***" # initialize current node with starting position currentNode = state[0] # list of min distances for all univisted corners minDistances = [] # list of unvisited corners unvisitedNodes = [corner for corner in corners if corner not in state[1]] while unvisitedNodes: dists = [] # append both node and its corresponding minimum distance for node in unvisitedNodes: dists.append((util.euclideanDistance(currentNode, node), node)) minDist = min(dists) minDistances.append(minDist[0]) # move on to the next corner which gave the min distance currentNode = minDist[1] # we don't want to re-explore the nodes unvisitedNodes.pop(unvisitedNodes.index(minDist[1])) return sum(minDistances)
def findNeighbors(self, training, point, k): """ calculates the neighbor points """ dim = len(training[0]) - 1 distance = [] neighbor = [] for i in range(0, len(training)): x = euclideanDistance(training[i][1:], point[1:], dim) distance.append((training[i][0], x)) distance = sorted(distance, key=lambda tup: tup[1]) for i in range(0, k): neighbor.append(distance[i]) return neighbor
def allCustomersConsidered(customerServed): for val in customerServed.values(): if val == False: return False return True # refer link - http://ieeexplore.ieee.org/document/7784340/?reload=true #Step 1 distanceDict = dict() for i in range(pointsLen): for j in range(i+1,pointsLen): distanceDict[(customerPositions[i], customerPositions[j])] = util.euclideanDistance(customerPositions[i], customerPositions[j]) #Step 2 for i in range(pointsLen): for j in range(i+1,pointsLen): savings[(customerPositions[i], customerPositions[j])] = computeSaving(depot,customerPositions[i], customerPositions[j]) savings = sorted(savings.items(),key=operator.itemgetter(1),reverse=True) l = len(savings) cust_pairs = list() for i in range(l): cust_pairs.append(savings[i][0]) #initially none of the customers have been isServed customerServed = dict() for c in customerPositions: customerServed[c] = False
def isGoalState(self, state): return util.euclideanDistance(state, self.goal) < 0.9
def canKill(pacmanPosition, ghostPosition): return util.euclideanDistance(ghostPosition, pacmanPosition) <= COLLISION_TOLERANCE
def euclideanDistanceHeuristic(state, problem): """ Returns the Euclidean distance from current state's position to goal """ return util.euclideanDistance(state, problem.goal)
def isGoalState(self, state): return util.euclideanDistance(state, self.goal ) < 0.9
def foodHeuristic(state, problem): """ Your heuristic for the FoodSearchProblem goes here. This heuristic must be consistent to ensure correctness. First, try to come up with an admissible heuristic; almost all admissible heuristics will be consistent as well. If using A* ever finds a solution that is worse uniform cost search finds, your heuristic is *not* consistent, and probably not admissible! On the other hand, inadmissible or inconsistent heuristics may find optimal solutions, so be careful. The state is a tuple ( pacmanPosition, foodGrid ) where foodGrid is a Grid (see game.py) of either True or False. You can call foodGrid.asList() to get a list of food coordinates instead. If you want access to info like walls, capsules, etc., you can query the problem. For example, problem.walls gives you a Grid of where the walls are. If you want to *store* information to be reused in other calls to the heuristic, there is a dictionary called problem.heuristicInfo that you can use. For example, if you only want to count the walls once and store that value, try: problem.heuristicInfo['wallCount'] = problem.walls.count() Subsequent calls to this heuristic can access problem.heuristicInfo['wallCount'] """ location, foodGrid = state # print "position", location, "Foods:", foodGrid.asList() from util import PriorityQueue from util import euclideanDistance from util import manhattanDistance foodList = foodGrid.asList() # These are the corner coordinates walls = problem.walls # These are the walls of the maze, as a Grid (game.py) points = () for food in foodList: points = points + (food, ) edgeList = [] if (location not in points): # print "add location" points = points + (location, ) if len(points) == 1: if points[0] != location: points = points + (location, ) else: return 0 #no food left to find if (len(points) == 0): return 0 edges = PriorityQueue() count = 0 for pointA in points: for pointB in points: if pointA != pointB: if (pointA, pointB) not in edgeList: edges.push( (pointA, pointB, euclideanDistance(pointA, pointB)), euclideanDistance(pointA, pointB)) count += 1 edgeList.append((pointA, pointB)) edgeList.append((pointB, pointA)) if len(edgeList) == 0: return 0 edgeCount = 0 totalDistance = 0 # construct tree visited = [] #visited.append() while (edgeCount != (len(points) - 1)): start, end, distance = edges.pop() # print "start", start, "end", end cycle = False added = False for group in visited: #print "group:", group if end in group and start in group: cycle = True if start in group: if end not in group: group.append(end) added = True if end in group: if start not in group: group.append(start) added = True if (added == False and cycle == False): # create new group visited.append([start, end]) added = True if (added and cycle == False): #print "add edge", start, end, distance edgeCount += 1 totalDistance += distance return totalDistance
def cornersHeuristic(state, problem): """ A heuristic for the CornersProblem that you defined. state: The current search state (a data structure you chose in your search problem) problem: The CornersProblem instance for this layout. This function should always return a number that is a lower bound on the shortest path from the state to a goal of the problem; i.e. it should be admissible (as well as consistent). """ from util import manhattanDistance from util import PriorityQueue from util import euclideanDistance corners = problem.corners # These are the corner coordinates walls = problem.walls # These are the walls of the maze, as a Grid (game.py) cornersVisited = state[1] points = () for corner in corners: if corner not in cornersVisited: #find remaining corners points = points + (corner, ) location = state[0] edgeList = [] if (location not in points): #print "add location" points = points + (location, ) if len(points) == 1: if points[0] != location: points = points + (location, ) else: #print "returned 0, points was 1" return 0 if (len(points) == 0): #print "returned 0" return 0 edges = PriorityQueue() count = 0 for pointA in points: for pointB in points: if pointA != pointB: if (pointA, pointB) not in edgeList: edges.push( (pointA, pointB, euclideanDistance(pointA, pointB)), euclideanDistance(pointA, pointB)) count += 1 edgeList.append((pointA, pointB)) edgeList.append((pointB, pointA)) if len(edgeList) == 0: return 0 edgeCount = 0 totalDistance = 0 # construct tree visited = [] visited.append(()) while (edgeCount != (len(points) - 1)): start, end, distance = edges.pop() cycle = False added = False for group in visited: if end in group and start in group: cycle = True if start in group: if end not in group: group = group + (end, ) added = True if end in group: if start not in group: group = group + (start, ) added = True if (added == False and cycle == False): #create new group visited.append((start, end)) added = True if (added): edgeCount += 1 totalDistance += distance return totalDistance