def findPathToClosestDot(self, gameState): """ Returns a path (a list of actions) to the closest dot, starting from gameState. """ # Here are some useful elements of the startState startPosition = gameState.getPacmanPosition() food = gameState.getFood() walls = gameState.getWalls() problem = AnyFoodSearchProblem(gameState) "*** YOUR CODE HERE ***" bfs = GraphSearch(GraphSearchType.BFS) return bfs.solve(problem)
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print("Start:", problem.getStartState()) print("Is the start a goal?", problem.isGoalState(problem.getStartState())) print("Start's successors:", problem.getSuccessors(problem.getStartState())) """ "*** YOUR CODE HERE ***" dfs = GraphSearch(GraphSearchType.DFS) return dfs.solve(problem, nullHeuristic)
def batch_feature(folder_name): gs = GraphSearch() # TODO Remove all hard links. print(len(files)) feature_store = [] df = DeepFeatures(feature_type={ 'model': 'custom', 'input_layer': 'default', 'output_layer': 'fc2'}) # TODO Remove hardcoded value. file_indexes = np.random.choice(len(files), 25000) print(file_indexes.size) # TODO Move batchsize to properties file. batch_size = 128 image_batch = [] for idx, filenumber in enumerate(file_indexes): print(idx) image_decoded = scipy.ndimage.imread( files[filenumber], flatten=False, mode=None) # TODO Move hardcoded values to properties file. image_decoded = transform.resize(image_decoded, [224, 224, 3]) image_decoded = np.expand_dims(image_decoded, axis=0) if image_batch == []: image_batch = image_decoded else: image_batch = np.concatenate((image_batch, image_decoded), axis=0) if (not (idx) % (batch_size)) or (idx >= len(file_indexes) - 1): print(image_batch.shape) feature_store.extend(df.get_feature(image_batch)) image_batch = [] print('feature_store shape', np.array(feature_store).shape) gs.create_index(np.array(feature_store, np.float32), file_indexes) gs.save_index() query = gs.knn(feature_store[0]) print(query)
def single_feature(): gs = GraphSearch() # TODO Move to command line arguments folder_name = '/Users/midhun/Downloads/kagglecatsanddogs_3367a/PetImages' files = glob.glob(os.path.join(folder_name, '**/*.jpg')) print(len(files)) feature_store = [] df = DeepFeatures() file_indexes = np.random.choice(len(files), 10000) print(file_indexes.size) for idx, filenumber in enumerate(file_indexes): print(idx) image_decoded = scipy.ndimage.imread( files[filenumber], flatten=False, mode=None) image_decoded = transform.resize(image_decoded, [224, 224, 3]) image_decoded = np.expand_dims(image_decoded, axis=0) feature_store.append(df.get_feature(image_decoded).ravel()) print(np.array(feature_store).shape) gs.create_index(np.array(feature_store, np.float32), file_indexes) gs.save_index() query = gs.knn(feature_store[0]) print(query)
def breadthFirstSearch(problem): """Search the shallowest nodes in the search tree first.""" "*** YOUR CODE HERE ***" bfs = GraphSearch(GraphSearchType.BFS) return bfs.solve(problem, nullHeuristic)
def BFTRecLinkedList(node_count=10000): self = createLinkedList(node_count) return GraphSearch.BFTRec(self, 0)
def aStarSearch(problem, heuristic=nullHeuristic): """Search the node that has the lowest combined cost and heuristic first.""" "*** YOUR CODE HERE ***" aStar = GraphSearch(GraphSearchType.ASTAR) return aStar.solve(problem, heuristic)
def uniformCostSearch(problem): """Search the node of least total cost first.""" "*** YOUR CODE HERE ***" ucs = GraphSearch(GraphSearchType.UCS) return ucs.solve(problem, nullHeuristic)
def BFTIterLinkedList() -> List[Node]: graph = createLinkedList(10000) return GraphSearch.BFTIter(graph)
def BFTRecLinkedList() -> List[Node]: graph = createLinkedList(100) return GraphSearch.BFTRec(graph)
def pathCost(self, path): return len(path)-1 @lru_cache() def heuristic(self, state): x, y = state targetX, targetY = target[0] return min(map( lambda tgt: ((tgt[0]-x)**2 + (tgt[1]-y)**2)**0.5, target )) problemDescription = ProblemDescription(discreteMatrix, initial, target) graphSearch = GraphSearch(problemDescription) import scipy.misc scipy.misc.imsave('outfileAStar.jpg', outputMatrix) print("target", target) start = time.time() resultAStar = graphSearch.aStar() print("aStar time ", time.time()-start) if resultAStar: print("Solution found") for discreteSquare in resultAStar[1:-1]: xDiscrete, yDiscrete = discreteSquare for x in range(xDiscrete*discreteSquareSize, (xDiscrete+1)*discreteSquareSize): for y in range(yDiscrete*discreteSquareSize, (yDiscrete+1)*discreteSquareSize):
# Weighted Linked List: wll = createWeightedLinkedList(10, 2) print(wll) # Random unweighted graph: print("Random Unwighted graph:") graph = createRandomUnweightedGraphIter(200) print(graph) # Gridgraph: print("Grid Graph:") gGraph = createRandomGridGraph(8) print(gGraph) # Graph Traversals: print("Graph Searches:") GraphSearch.printResult(GraphSearch(), GraphSearch.BFTIter(graph, 0)) GraphSearch.printResult( GraphSearch(), GraphSearch.DFTIter(createRandomUnweightedGraphIter(200), 0)) # print(BFTRecLinkedList()) # Exceeds max recursion depth! GraphSearch.printResult(GraphSearch(), BFTIterLinkedList(100)) # BFT on a linked list GraphSearch.printResult(GraphSearch(), BFTRecLinkedList( 100)) # Exceeds recursion limit if node_count is too high! # GraphSearch.printResult(GraphSearch(), BFTIterLinkedList()) # Works great with default (10,000 nodes), spams the console! print("Main took:", f"{time.perf_counter()-start:.3}", "seconds") # Prints the time taken for main to run.
def BFTIterLinkedList(graph): from graphSearch import GraphSearch return GraphSearch.BFTIter(graph)
def BFTRecLinkedList(graph): from graphSearch import GraphSearch return GraphSearch.BFTRec(graph)
def BFTIterLinkedList(graph): iterativePath = GraphSearch() iterPath = iterativePath.BFTIter(graph) return iterPath
def BFTRecLinkedList(graph): recursivePath = GraphSearch() recPath = recursivePath.BFTRec(graph) return recPath
print("########################## START OF TEST FOR 3C ##########################") linkedList = createLinkedList(25) printGraph(linkedList) print("######################## START OF TEST FOR 3D, 3E ########################") a = GraphNode('A') b = GraphNode('B') c = GraphNode('C') d = GraphNode('D') e = GraphNode('E') f = GraphNode('F') # Unconnected node a.neighbors = [b, c] b.neighbors = [d, e, a] c.neighbors = [a] d.neighbors = [b] e.neighbors = [b] path = GraphSearch() dfsRec = path.DFSRec(a, e) dfsIter = path.DFSIter(a, e) print("Recursive DFS Traversal is: ") printTraversal(dfsRec) print("Iterative DFS Traversal is: ") printTraversal(dfsIter) print("######################## START OF TEST FOR 3F, 3G ########################") graph = Graph() g = GraphNode('G') graph.addNode(g.val) h = GraphNode('H') graph.addNode(h.val) i = GraphNode('I') graph.addNode(i.val)
def main(): graph = createRandomUnweightedGraphIter(10) nodes = graph.getAllNodes() listOfNodes = list(nodes) listOfNodes.sort(key=lambda x: x.nodeVal) dfs_rec_arr = GraphSearch.DFSRec(listOfNodes[3], listOfNodes[9]) dfs_iter_arr = GraphSearch.DFSIter(listOfNodes[3], listOfNodes[9]) bft_rec_arr = GraphSearch.BFTRec(graph) bft_iter_arr = GraphSearch.BFTIter(graph) print("--- Random Unweighted Graph ---") printGraph(graph) print("--- DFS-Rec ---") printList(dfs_rec_arr) print("\n--- DFS-Iter ---") printList(dfs_iter_arr) print("\n--- BFT-Rec ---") printList(bft_rec_arr) print("\n--- BFT-Iter ---") printList(bft_iter_arr) _graph = createLinkedList(10) _nodes = _graph.getAllNodes() _listOfNodes = list(_nodes) _listOfNodes.sort(key=lambda x: x.nodeVal) _dfs_rec_arr = GraphSearch.DFSRec(_listOfNodes[3], _listOfNodes[9]) _dfs_iter_arr = GraphSearch.DFSIter(_listOfNodes[3], _listOfNodes[9]) _bft_rec_arr = GraphSearch.BFTRec(_graph) _bft_iter_arr = GraphSearch.BFTIter(_graph) print("\n--- Linked List ---") printGraph(_graph) print("--- DFS-Rec ---") printList(_dfs_rec_arr) print("\n--- DFS-Iter ---") printList(_dfs_iter_arr) print("\n--- BFT-Rec ---") printList(_bft_rec_arr) print("\n--- BFT-Iter ---") printList(_bft_iter_arr) topSort_graph = createRandomDAGIter(1000) print("\n--- Random Directed Acyclic Graph ---") printGraph(topSort_graph) topSort_kahns = TopSort.Kahns(topSort_graph) print("--- Kahns Output---") printList(topSort_kahns) topSort_mDFS = TopSort.mDFS(topSort_graph) print("\n--- mDFS Output ---") printList(topSort_mDFS) dijkstras_graph = createRandomCompleteWeightedGraph(1000) print("\n--- Random Complete Weighted Graph ---") printGraph(dijkstras_graph) dijkstras_result = runDijkstras(dijkstras_graph, 2) print("--- Dijkstras Output ---") printDijkstras(dijkstras_result) astar_graph = createRandomGridGraph(100) print("--- Random Grid Graph ---") printGraph(astar_graph) astar_result = runAstar(astar_graph, 0, 9999) print("--- A* Output ---") printList(astar_result)
if num != 0: linkedGraph.addUndirectedEdge(num - 1, num) return linkedGraph @staticmethod def BFTRecLinkedList(graph): return graphSearch.BFTRec(graph) @staticmethod def BFTIterLinkedList(graph): return graphSearch.BFTIter(graph) if __name__ == "__main__": main = Main() graphSearch = GraphSearch() graph1 = main.createRandomUnweightedGraphIter(10) graph2 = main.createLinkedList(10) graphRec = main.createLinkedList(100) graphIter = main.createLinkedList(10000) graph3 = main.BFTRecLinkedList(graphRec) graph4 = main.BFTIterLinkedList(graphIter) print("-------------Unweighted Graph-------------" + "\n" "DFS-Rec: " + str(graphSearch.DFSRec(graph1, 4, 8)) + "\n" "DFS-Iter: " + str(graphSearch.DFSIter(graph1, 4, 8)) + "\n" "BFT-Rec: " + str(graphSearch.BFTRec(graph1)) + "\n" "BFT-Iter: " + str(graphSearch.BFTIter(graph1)) + "\n") print("---------------Linked List----------------" + "\n" "DFS-Rec: " + str(graphSearch.DFSRec(graph2, 4, 8)) + "\n"
def BFTIterLinkedList(node_count=10000): self = createLinkedList(node_count) print(self) return GraphSearch.BFTIter(self, 0)