def breadthFirstSearch(problem): """ Search the shallowest nodes in the search tree first. """ "*** YOUR CODE HERE ***" #util.raiseNotDefined() import GraphSearch return GraphSearch.graphSearch(problem, util.Queue())
def run_search_exhaustive(self): self.statusConsole.clear() msgFormat = 'Run {}: {} -> {}, Cost: {:.2f}, Time Elapsed: {:.2f}ms\n' coordinates = extract_coordinates() counter = 0 benchmark = list() final_cost = list() for i in coordinates: for j in coordinates: if (i != j): counter = counter+1 t0 = time.perf_counter() total_cost = 0 #print('Computing, {} to {}'.format(i, j)) try: result = GraphSearch.GraphSearch(i, j,'path') except: print('Failed {} to {}'.format(i,j)) t1 = time.perf_counter() for node in result: cost = node.stepCost total_cost += cost print('Computing, {} to {}'.format(i, j)) try: result = GraphSearch.GraphSearch(i, j,'path') except: print('Failed {} to {}'.format(i,j)) t1 = time.perf_counter() for node in result: cost = node.stepCost total_cost += cost final_cost.append(total_cost) benchmark.append((t1-t0)*1000) self.statusConsole.insertPlainText( msgFormat.format(counter, i, j, total_cost, (t1 - t0)*1000)) msgFormat = '\nBenchmarks:\nMean Cost: {:.2f}\nAvg Time: {:.2f}ms\nMin Time: {:.2f}ms\nMax Time: {:.2f}ms' self.statusConsole.insertPlainText(msgFormat.format( statistics.mean(final_cost), statistics.mean(benchmark), min(benchmark), max(benchmark)))
def __init__(self,G): """Search for strongly connected components of graph G.""" # set up data structures for DFS self._components = [] self._dfsnumber = {} self._activelen = {} self._active = [] self._low = {} self._biglow = len(G) self._graph = G # perform the Depth First Search GraphSearch.Searcher.__init__(self,G,GraphSearch.dfs()) # clean up now-useless data structures del self._dfsnumber, self._activelen, self._active, self._low
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 ***" #util.raiseNotDefined() import GraphSearch return GraphSearch.graphSearch(problem, util.Stack())
def Forest(G): #check H = G.to_undirected() if G.number_of_edges() != H.number_of_edges(): return (False) #check to see if the undirected graph of G has any cycles nodes = H.nodes() #evaluate each component until either a cycle is found or all components are checked while (G.nodes()): #generate components starting in unexplored vertex H = G.subgraph(GraphSearch(G, nodes[0], 0)[0]) #if a connected undirected graph has more than n - 1 edges it has a cycle if H.number_of_edges() > H.number_of_nodes() - 1: return (False) else: #remove all nodes in the component containing node[0] and update nodes for element in H.nodes(): G.remove_node(element) #all possibilities have been checked, so the graph must be a forest return (True)
def run_search(self): start = str(self.sourceEdit.text()) destination = str(self.dstEdit.text()) start_coord = re.findall(r'\d+', start) destination_coord = re.findall(r'\d+', destination) result = GraphSearch.GraphSearch((int(start_coord[0]), int(start_coord[1])), (int(destination_coord[0]), int(destination_coord[1])),'path') self.map.mark_paths(result) self.statusConsole.clear() street_string_info = "\n".join(str(a) for a in self.street_info) self.statusConsole.insertPlainText(street_string_info) self.statusConsole.insertPlainText('\n\nDirections...\n\n') total_cost = 0 for node in result: cost = node.stepCost total_cost += cost msgFormat = 'Walk from {} through {} to get to {}, Cost: {:.2f}\n' self.statusConsole.insertPlainText(msgFormat.format(node.Parent, get_street_name( node.Parent, node.State, self.street_info), node.State, cost)) self.statusConsole.insertPlainText( '\nTotal Cost: {:.2f}'.format(total_cost) + '\n') self.statusConsole.insertPlainText( '\nRaw Result\n' + str(result) + '\n')
from EightPuzzle import * from GraphSearch import * from BFS import * from DFS import * from IDS import * # create the problem model eight_puzzle = EightPuzzle((1, 2, 3, 4, 5, 6, 0, 7, 8)) # requires 2 moves # other examples of creating an 8-puzzle problem #eight_puzzle = EightPuzzle((1, 2, 3, 4, 5, 7, 8, 6, 0)) #requires 12 moves #eight_puzzle = EightPuzzle((1, 2, 3, 4, 5, 6, 7, 8, 0)) #start with solution # eight_puzzle.shuffle(10) # make 10 moves to ensure the puzzle is in a solvable state, but mixed up a bit # search using Graph Search myGraphSearch = GraphSearch(eight_puzzle) result_node = myGraphSearch.search() print("GRAPH SEARCH") if (result_node is None): print("No path found using graph search!") else: print("Path:", result_node.path()) print("Path Cost:", result_node.path_cost) print("Solution:", result_node.solution()) print("Nodes searched with graph search:", myGraphSearch.nodesSearched) print("Time Spent with graph search:", myGraphSearch.timeSpent) print("==============")
def BFTIterLinkedList(graph): gs = GraphSearch.GraphSearch() gs.BFTIter(graph)
def BFTRecLinkedList(graph): gs = GraphSearch.GraphSearch() gs.BFTRec(graph)
from copy import deepcopy from GraphUtils import * from GraphSearch import * KB = readPaths('KB2.txt') KB = parseKB(KB) simpleKB = simplifyKB( KB) #Turns the parsed KB into [A,B,...],[C,D,...] : A list of clauses print(simpleKB) thesis = ['R'] # What we are trying to prove bu and e toProve = negateList( deepcopy(thesis)) # Proof by contradiction -> not bu or not e RULES = simpleKB # The Rules we have RULES.append(toProve) # We append the negated thesis to it y = Resolution(deepcopy(RULES)) # One step of the resolution algorithm initialState = RULES # Our initial state will be the rules goalState = [] # Our goal state is the empty clause SOLUTION = GraphSearch(deepcopy(initialState), deepcopy(goalState), 'logic') if SOLUTION != 'FAIL!': print('Step ', 1, ': ', SOLUTION[0].State) for i in range(0, len(SOLUTION)): print('Step ', i + 2, ': ', SOLUTION[i].State) else: print(SOLUTION)
from State import * from Noeud import * from GraphSearch import * numberOfCannibals = 3 numberOfMissionairies = 3 boatSize = 2 start = Object(State(numberOfCannibals,numberOfMissionairies,0,0,True), None) temp=GraphSearch(start,2) for i in range(len(temp)): print(temp[i]) if(i+1!=len(temp)): print("______Next______")