How to use the simpleai.search.astar function in simpleai

To help you get started, we’ve selected a few simpleai examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github PacktPublishing / Artificial-Intelligence-with-Python / Chapter 7 / code / puzzle.py View on Github external
4-5-6
7-8-e'''

# Starting point
INITIAL = '''1-e-2
6-3-4
7-5-8'''

# Create a cache for the goal position of each piece
goal_positions = {}
rows_goal = string_to_list(GOAL)
for number in '12345678e':
    goal_positions[number] = get_location(rows_goal, number)

# Create the solver object
result = astar(PuzzleSolver(INITIAL))

# Print the results
for i, (action, state) in enumerate(result.path()):
    print()
    if action == None:
        print('Initial configuration')
    elif i == len(result.path()) - 1:
        print('After moving', action, 'into the empty space. Goal achieved!')
    else:
        print('After moving', action, 'into the empty space')

    print(state)
github simpleai-team / simpleai / samples / search / hello_world.py View on Github external
def result(self, state, action):
        return state + action

    def is_goal(self, state):
        return state == GOAL

    def heuristic(self, state):
        # how far are we from the goal?
        wrong = sum([1 if state[i] != GOAL[i] else 0
                    for i in range(len(state))])
        missing = len(GOAL) - len(state)
        return wrong + missing

problem = HelloProblem(initial_state='')
result = astar(problem)

print result.state
print result.path()
github simpleai-team / simpleai / samples / search / missioners.py View on Github external
else:
            return (s[0] + a[1][0], s[1] + a[1][1], 0)

    def is_goal(self, state):
        return state == (0, 0, 1)

    def heuristic(self, state):
        return (state[0] + state[1]) / 2

    def value(self, state):
        return 6 - state[0] - state[1]


problem = MissionersProblem()

result = astar(problem)
print result.path()
github machinalis / yalign / yalign / sequencealigner.py View on Github external
the sum of weights as given by the `weight` function and the
        `gap_penalty`.
        The aligment format is a list of tuples `(i, j, cost)` such that:
            `i` and `j` are indexes of elements in `xs` and `ys` respectively.
            The alignment weight is sum(cost for i, j, cost in alignment).
            if `i == None` then `j` is not aligned to anything (is a gap).
            if `j == None` then `i` is not aligned to anything (is a gap).
        If `minimize` is `True` this function minimizes the sum of the weights
        instead.
        """
        if score is None:
            score = self.score
        if penalty is None:
            penalty = self.penalty
        problem = SequenceAlignmentSearchProblem(xs, ys, score, penalty)
        node = astar(problem, graph_search=True)
        path = [action for action, node in node.path()[1:]]
        return path
github simpleai-team / simpleai / samples / search / eight_puzzle.py View on Github external
We are using the manhattan distance.
        '''
        rows = string_to_list(state)

        distance = 0

        for number in '12345678e':
            row_n, col_n = find_location(rows, number)
            row_n_goal, col_n_goal = goal_positions[number]

            distance += abs(row_n - row_n_goal) + abs(col_n - col_n_goal)

        return distance


result = astar(EigthPuzzleProblem(INITIAL))
# if you want to use the visual debugger, use this instead:
# result = astar(EigthPuzzleProblem(INITIAL), viewer=WebViewer())

for action, state in result.path():
    print 'Move number', action
    print state
github machinalis / yalign / yalign / sequencealigner.py View on Github external
the sum of weights as given by the `score` function and the
        `gap_penalty`.
        The aligment format is a list of tuples `(i, j, cost)` such that:
            `i` and `j` are indexes of elements in `xs` and `ys` respectively.
            The alignment weight is sum(cost for i, j, cost in alignment).
            if `i == None` then `j` is not aligned to anything (is a gap).
            if `j == None` then `i` is not aligned to anything (is a gap).
        If `minimize` is `True` this function minimizes the sum of the weights
        instead.
        """
        if score is None:
            score = self.score
        if penalty is None:
            penalty = self.penalty
        problem = SequenceAlignmentSearchProblem(xs, ys, score, penalty)
        node = astar(problem, graph_search=True)
        path = [action for action, node in node.path()[1:]]
        return path
github PacktPublishing / Artificial-Intelligence-with-Python / Chapter 7 / code / maze.py View on Github external
COSTS = {
        "up": cost_regular,
        "down": cost_regular,
        "left": cost_regular,
        "right": cost_regular,
        "up left": cost_diagonal,
        "up right": cost_diagonal,
        "down left": cost_diagonal,
        "down right": cost_diagonal,
    }

    # Create maze solver object
    problem = MazeSolver(MAP)

    # Run the solver
    result = astar(problem, graph_search=True)

    # Extract the path
    path = [x[1] for x in result.path()]

    # Print the result
    print()
    for y in range(len(MAP)):
        for x in range(len(MAP[y])):
            if (x, y) == problem.initial:
                print('o', end='')
            elif (x, y) == problem.goal:
                print('x', end='')
            elif (x, y) in path:
                print('·', end='')
            else:
                print(MAP[y][x], end='')
github simpleai-team / simpleai / samples / search / game_walk.py View on Github external
def main():
    problem = GameWalkPuzzle(MAP)
    result = astar(problem, graph_search=True)
    path = [x[1] for x in result.path()]

    for y in xrange(len(MAP)):
        for x in xrange(len(MAP[y])):
            if (x, y) == problem.initial:
                print "o",
            elif (x, y) == problem.goal:
                print "x",
            elif (x, y) in path:
                print "·",
            else:
                print MAP[y][x],
        print
github simpleai-team / simpleai / samples / search / make_report.py View on Github external
from dotsearch import report
import argparse
parser = argparse.ArgumentParser(description="Runs graph search "
"algorithms over a .dot graph file.")
parser.add_argument("dotfile", action="store")
cfg = parser.parse_args()


from simpleai.search import breadth_first, astar, beam, simulated_annealing


print "Running algorithms and writting report.html..."
report(infile=cfg.dotfile,
       algorithms=[
            breadth_first,
            astar,
            beam,
            simulated_annealing,
           ],
       outfile="report.html",
       with_images=True)