Esempio n. 1
0
def connected_components(X):
    """Find all connected nonzero components in a 3d array X

    Returns a list of lists of indices of connected components
    """
    visited = np.zeros_like(X, dtype="bool")
    components = []
    current_component = set()

    def _fn(p):
        if X[p]:
            current_component.add(p)
            return True

    for i in range(visited.shape[0]):
        for j in range(visited.shape[1]):
            for k in range(visited.shape[2]):
                if visited[i, j, k]:
                    continue
                visited[i, j, k] = True
                if not X[i, j, k]:
                    continue
                # found a new component
                pos = (i, j, k)
                visited |= depth_first_search(X, pos, _fn, util.diag_adjacent)
                components.append(list(current_component))
                current_component.clear()

    return components
Esempio n. 2
0
def connected_components(X, unique_idm=False):
    """Find all connected nonzero components in a array X.
    X is either rank 3 (volume) or rank 4 (volume-idm)
    If unique_idm == True, different block types are different 
    components

    Returns a list of lists of indices of connected components
    """

    visited = np.zeros((X.shape[0], X.shape[1], X.shape[2]), dtype="bool")
    components = []
    current_component = set()
    diag_adj = util.build_safe_diag_adjacent(
        [0, X.shape[0], 0, X.shape[1], 0, X.shape[2]])

    if len(X.shape) == 3:
        X = np.expand_dims(X, axis=3)

    def is_air(X, i, j, k):
        return X[i, j, k, 0] == 0

    if not unique_idm:

        def _build_fn(X, current_component, idm):
            def _fn(p):
                if X[p[0], p[1], p[2], 0]:
                    current_component.add(p)
                    return True

            return _fn

    else:

        def _build_fn(X, current_component, idm):
            def _fn(p):
                if tuple(X[p]) == idm:
                    current_component.add(p)
                    return True

            return _fn

    for i in range(visited.shape[0]):
        for j in range(visited.shape[1]):
            for k in range(visited.shape[2]):
                if visited[i, j, k]:
                    continue
                visited[i, j, k] = True
                if is_air(X, i, j, k):
                    continue
                # found a new component
                pos = (i, j, k)
                _fn = _build_fn(X, current_component, tuple(X[i, j, k, :]))
                visited |= depth_first_search(X.shape[:3], pos, _fn, diag_adj)
                components.append(list(current_component))
                current_component.clear()

    return components
Esempio n. 3
0
def accessible_interesting_blocks(blocks, pos):
    """Return a boolean mask of blocks that are accessible-interesting from pos.

    A block b is accessible-interesting if it is
    1. interesting, AND
    2. there exists a path from pos to b through only passable or interesting blocks
    """
    passable = np.isin(blocks, PASSABLE_BLOCKS)
    interesting = np.isin(blocks, BORING_BLOCKS, invert=True)
    passable_or_interesting = passable | interesting
    X = np.zeros_like(passable)

    def _fn(p):
        if passable_or_interesting[p]:
            X[p] = True
            return True
        return False

    depth_first_search(blocks, pos, _fn)
    return X & interesting
def main():
    print('Water Jugs: ')
    print(
        ' Tuples are in this format --> [<Node (litersOfWaterInPot1, litersOfWaterInPot2, litersOfWaterInPot3)>]'
    )
    goalState = (2, 2, 3)

    problem = Problem2(goalState)
    goal = depth_first_search(problem)
    print("\nPath = ", goal.path(), "\n\nPath cost = ", goal.path_cost)
    #print("      Steps = " + str(goal.path()), "\n      Cost = " + str(goal.path_cost))
    print()
Esempio n. 5
0
def main():
    print('Family Dilema: ')
    print(
        ' Tuples are in this format --> [<Node (isPoliceAcross, isThiefAcross, isMomAcross, isDadAcross, numberOfSonsAcross, numberOfGirlsAcross, isBoatAcross)>]'
    )
    goalState = (1, 1, 1, 1, 2, 2, 1)

    problem = Problem1(goalState)
    goal = depth_first_search(problem)
    print("\nPath = ", goal.path(), "\n\nPath cost = ", goal.path_cost)
    #print("      Steps = " + str(goal.path()), "\n      Cost = " + str(goal.path_cost))
    print()
Esempio n. 6
0
def get_component_of(x, incidents, n):
    """Returns the set of connected verticies associated to a particular vertex X from a
    dictionary of INCIDENTS for a graph of order N."""
    closed = set()
    for i in range(n):
        if i+1 in closed:
            continue
        problem = GraphSearchProblem(x, i+1, graph_path_goal_test, incidents)
        result = depth_first_search(problem)
        if result == -1:
           continue
        closed = closed.union(result[2])
    return closed
Esempio n. 7
0
def main():
    print('River Crossing: ')
    print(
        ' Tuples are in this format --> [<Node (leftThief, leftMom, leftDad, leftSons, leftDaughters, leftPolice, rightThief, rightMom, rightDad, rightSons, rightDaughters, rightPolice boatSide)>]'
    )
    goalState = (0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 1, 1)

    problem = Problem1(goalState)
    goal = depth_first_search(problem)

    print("\nPath = ", goal.path(), "\n\nPath cost = ", goal.path_cost)
    #print("      Steps = " + str(goal.path()), "\n      Cost = " + str(goal.path_cost))
    print()
def main():
    #Runs the Cannibals and Missionary problem, will provide a solution to getting all missionaries
    #and all cannibals to the other side, without missionaries ever being outnumbered by cannibals
    #on either side.
    print('Missionaries/Cannibals Problem: ')
    print(
        ' Tuples are in this format --> [<Node (leftMissionaries, rightMissionaries, leftCannibals, rightCannibals, boatSide)>]'
    )
    goalState = (3, 0, 3, 0, 0)

    problem = MCP(goalState)
    goal = depth_first_search(problem)
    print("\nPath = ", goal.path(), "\n\nPath cost = ", goal.path_cost)
    #print("      Steps = " + str(goal.path()), "\n      Cost = " + str(goal.path_cost))
    print()
Esempio n. 9
0
    def test_depth_first_search(self):
        print("Starting depth first search test")
        print("---------------------------------------------")
        puzzle = EightPuzzleState([1, 0, 2, 3, 4, 5, 6, 7, 8])
        problem = PuzzleSearchProblem(puzzle)
        path, step = search.depth_first_search(problem)
        print("Test DFS on:")
        print(puzzle)

        self.print_result("DFS", step, problem.get_costs(path), path)

        curr = puzzle
        for a in path:
            curr = curr.next_state(a)
        self.assertTrue(curr.is_goal(), "The final state is not goal test")
        print("=============================================")
Esempio n. 10
0
 def BuscaProfundidade(self):
     table = self.get_table()
     print(table)
     initial_state = StateNode(Game8(table), None, None, 0, 0)
     start = int(round(time.time() * 1000))
     path = depth_first_search(initial_state)
     end = int(round(time.time() * 1000))
     for state in path:
         self.depth_label['text'] = 'Profundidade: ' + str(state.depth)
         b = state.game.get_b_position()
         state.game.table[b[0]][b[1]] = ''
         self.set_table(state.game.table)
         state.game.show_table()
         time.sleep(1)
     self.generated_nodes_label['text'] = 'Nós gerados: ' + str(
         s.generated_nodes)
     self.execution_time['text'] = 'Tempo de execução (ms): ' + str(end -
                                                                    start)
    def test_depth_first_search(self):
        print("Starting depth first search test")
        print("---------------------------------------------")
        with TimeoutAlarm(
                30,
                error_message=
                "Depth First Search cannot find the solution within 30s"):
            puzzle = EightPuzzleState([1, 0, 2, 3, 4, 5, 6, 7, 8])
            problem = PuzzleSearchProblem(puzzle)
            path, step = search.depth_first_search(problem)
            print("Test DFS on:")
            print(puzzle)

            self.print_result("DFS", step, problem.get_costs(path), path)

            curr = puzzle
            for a in path:
                curr = curr.next_state(a)
            self.assertTrue(curr.is_goal(), "The final state is not goal test")
            print("=============================================")
Esempio n. 12
0
    print()
    print('=' * 50)
    print('=' * 50)
    print("Q1: FIVE QUEENS")
    print('=' * 50)
    print('=' * 50)

    fq = NQueensProblem(5)

    print()
    print('-' * 50)
    print("DEPTH-FIRST-TREE-SEARCH")
    print('-' * 50)

    dfts = depth_first_search(fq, search_type=uninformed_tree_search)

    print("Solution", dfts.solution())

    print()
    print('=' * 50)
    print('=' * 50)
    print("Q2-5: TRAVEL")
    print('=' * 50)
    print('=' * 50)

    city_map = CityMap()

    city_map.add_road('F', 'S', 5)
    city_map.add_one_way_road('S', 'A', 2)
    city_map.add_road('S', 'C', 6)
Esempio n. 13
0
from trees import Node
from search import (depth_first_search, breadth_first_search,
                    recursion_tree_traverse)

# Setup Tree
root = Node(0)
root.left = Node(1)
root.right = Node(2)
root.left.left = Node(3)
root.left.right = Node(4)
root.right.left = Node(5)
root.right.right = Node(6)

print('Depth First Search')
depth_first_search(root)
print('=' * 25)
print('Breadth First Search')
breadth_first_search(root)
print('Recursion Tree Traversal')
recursion_tree_traverse(root)
Esempio n. 14
0
       
    print
    print '=' * 50
    print '=' * 50
    print "N QUEENS PROBLEM"
    print '=' * 50
    print '=' * 50
      
    nq = NQueensProblem(8)
	
    print
    print '-' * 24 + '1' + '-' * 25
    print "Running DEPTH-FIRST-TREE-SEARCH"
    print '-' * 50
    	
    dfts = depth_first_search(nq, search_type=uninformed_tree_search)
    
    print "Solution", dfts.solution()
	
    print
    print '-' * 24 + '2' + '-' * 25
    print "Running BREADTH-FIRST-TREE-SEARCH"
    print '-' * 50
    	
    bfts = breadth_first_search(nq, search_type=uninformed_tree_search)
    
    print "Solution", bfts.solution()
    
		
    print
    print '=' * 50
    puzzle = EightPuzzleState(list(range(9)))
    for i in range(moves):
        puzzle = puzzle.next_state(random.sample(puzzle.legal_moves(), 1)[0])
    return puzzle


if __name__ == '__main__':
    # puzzle = createRandomEightPuzzle(30)
    puzzle = EightPuzzleState([3, 0, 5, 6, 2, 4, 7, 8, 1])

    print('A random puzzle:')
    print(puzzle)

    problem = PuzzleSearchProblem(puzzle)
    #path, step = search.uniform_cost_search(problem)
    #path, step = search.breadth_first_search(problem)
    path, step = search.depth_first_search(problem)
    #path, step = search.uniform_cost_search(problem)
    #path, step = search.a_start_search(problem)
    print(('BFS found a path of %d moves: %s by %d steps cost %d' %
           (len(path), str(path), step, problem.get_costs(path))))
    curr = puzzle
    i = 1
    for a in path:
        curr = curr.next_state(a)
        print(('After %d move%s: %s' % (i, ("", "s")[i > 1], a)))
        print(curr)

        input("Press return for the next state...")  # wait for key stroke
        i += 1
Esempio n. 16
0
import search
import token

fplay = token.playz()
# gives the choose function the start and goal and capacity and the flag
fplay.choose({'x': 5, 'y': 3, 'z': 0}, {'x': 4, 'y': 0, 'z': 4}, [5,3,8], 1)
print("Start position =>", fplay.start(),"\n", "Goal position =>", fplay.goaldiff)
# gives the token to the search
list = search.depth_first_search(fplay, fplay.start(), "")

# to print the steps
for node in list:
    x = node["x"]
    y = node["y"]
    z = node["z"]
    print(x, y, z)
print("\n \n")

fplay = token.playz()
fplay.choose({'x': 7, 'y': 0, 'z': 0,}, {'x': 2, 'y': 2, 'z': 3}, [7,4,3], 1)
print("Start position =>", fplay.start(),"\n", "Goal position =>", fplay.goaldiff)
list = search.depth_first_search(fplay, fplay.start(), "")


for node in list:
    x = node["x"]
    y = node["y"]
    z = node["z"]
    print(x, y, z)
print("\n \n")
Esempio n. 17
0
import search
from graph import Graph

if __name__ == "__main__":
    # Setting graph we initiated to search class...
    graph = Graph()
    search.graph = graph

    search.depth_first_search()
    search.breath_first_search()
    search.iterative_deepening_search()
    search.uniform_cost_search()
    search.greedy_best_first_search()
    search.a_star_search()