Ejemplo n.º 1
0
def depthFirstSearch(problem):
    print 'This is DFS'
    from searchAgents import direction_list
    from spade import pyxf
    import os
    """
    Building the XSB PROLOG query
    """
    myXsb = pyxf.xsb("/home/vishal/Downloads/xsb/XSB/bin/xsb")
    myXsb.load(os.getcwd() + '/maze.P')
    myXsb.load(os.getcwd() + '/dfs.P')
    q_result = myXsb.query("dfs(start,X)")
    result =  q_result[0]['X']
    result = result[1:]
    result = result[:-1]
    result = result.split(',')
    result.reverse()
    result = result[1:]
    result_list = list()
    result_list.append(direction_list[('start', result[0])])
    """
    Converting the list of actions returned by prolog into appropriate directions to be returned
    """
    for x in range(len(result) - 1):
        result_list.append(direction_list[(result[x], result[x + 1])])
    return result_list
Ejemplo n.º 2
0
def depthFirstSearch(problem):
  """
  Search the deepest nodes in the search tree first [p 85].
  
  Your search algorithm needs to return a list of actions that reaches
  the goal.  Make sure to implement a graph search algorithm [Fig. 3.7].
  
  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 ***"

  from spade import pyxf

  myXSB = pyxf.xsb("/home/raghu/ai/XSB/bin/xsb")
  myXSB.load("maze1.P")
  myXSB.load("dfs.P")
  result = myXSB.query("dfs(start,[],P).")
  #print result
  path = result[0]['P']
  #print path
  #print type(path)
  path_no_null = path[6:-6]
  #print path_no_null
  path_list = path_no_null.split(",")
  #print path_list
  path_upper_list = [word[:1].upper() + word[1:] for word in path_list]
  #print path_upper_list
  return path_upper_list
Ejemplo n.º 3
0
def breadthFirstSearch(problem):
  "Search the shallowest nodes in the search tree first. [p 81]"
  "*** YOUR CODE HERE ***"
  from spade import pyxf

  myXSB = pyxf.xsb("/home/raghu/ai/XSB/bin/xsb")

  myXSB.load("maze1.P")
  myXSB.load("bfs.P")
  result1 = myXSB.query("bfs([[start]],P).")
  #print result1
  path = result1[0]['P']
  #print path
  #print type(path)
  path_no_null = path[6:-12]
  #print path_no_null
  path_list = path_no_null.split(",")
  #print path_list
  path_dir = path_list[1::2]
  #print "path_dir " + str(path_dir)
  path_upper_list = [word[:1].upper() + word[1:] for word in path_dir]
  #print path_upper_list
  path_reverse = path_upper_list[::-1]
  print path_reverse
  return path_reverse
Ejemplo n.º 4
0
def aStarSearch(problem, heuristic=nullHeuristic):
  "Search the node that has the lowest combined cost and heuristic first."
  "*** YOUR CODE HERE ***"
  from spade import pyxf

  myXSB = pyxf.xsb("/home/raghu/ai/XSB/bin/xsb")
  myXSB.load("maze_astar.P")
  myXSB.load("astar2.P")
  result1 = myXSB.query("astar1([[start]],P).")
  #print result1
  path = result1[0]['P']
  print path
  #print type(path)
  #path_no_null = path[:-12]
  print path
  path_list = path.split(",")
  print path_list
  path_dir = path_list[1::3]
  print "path_dir " + str(path_dir)
  path_no_null = path_dir[:-1]
  path_upper_list = [word[:1].upper() + word[1:] for word in path_no_null]
  #print path_upper_list
  path_reverse = path_upper_list[::-1]
  #print path_reverse
  return path_reverse

  util.raiseNotDefined()
Ejemplo n.º 5
0
def depthFirstSearch(problem):
    print 'This is DFS'
    from searchAgents import direction_list
    from spade import pyxf
    import os
    """
    Building the XSB PROLOG query
    """
    myXsb = pyxf.xsb("/home/vishal/Downloads/xsb/XSB/bin/xsb")
    myXsb.load(os.getcwd() + '/maze.P')
    myXsb.load(os.getcwd() + '/dfs.P')
    q_result = myXsb.query("dfs(start,X)")
    result = q_result[0]['X']
    result = result[1:]
    result = result[:-1]
    result = result.split(',')
    result.reverse()
    result = result[1:]
    result_list = list()
    result_list.append(direction_list[('start', result[0])])
    """
    Converting the list of actions returned by prolog into appropriate directions to be returned
    """
    for x in range(len(result) - 1):
        result_list.append(direction_list[(result[x], result[x + 1])])
    return result_list
Ejemplo n.º 6
0
def breadthFirstSearch(problem):
    "Search the shallowest nodes in the search tree first. [p 81]"

    "*** YOUR CODE HERE ***"
    startTime = time.clock()
    mazeFilePath = './maze.P'
    foodList = getFoodStatus(mazeFilePath)
    permutationList = getPermutations(foodList)                 # get all the 24 permutations of food list

    file = open(mazeFilePath)
    lines = file.readlines()

    pathLists = []
    xsb = pyxf.xsb('/Users/zephyrYin/Documents/tools/XSB/bin/xsb')
    for i in range(len(permutationList)):
        reviseMazeFile(mazeFilePath, lines, permutationList[i])
        xsb.load(mazeFilePath)
        xsb.load('./bfs.P')
        result = xsb.query('solve(F).')
        fullPath = result[0]['F']
        tempList = fullPath[1:-1].split(',')
        pathList = [int(x) for x in tempList]
        print pathList
        pathLists.append(pathList)
    shortestPath = getShortest(pathLists)                       # find a shortest path
    print 'time cost:'
    print time.clock() - startTime
    return path2Action(shortestPath)
Ejemplo n.º 7
0
def depthFirstSearch(problem):
    """
    Search the deepest nodes in the search tree first [p 85].

    Your search algorithm needs to return a list of actions that reaches
    the goal.  Make sure to implement a graph search algorithm [Fig. 3.7].

    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 ***"
    xsb = pyxf.xsb('/Users/zephyrYin/Documents/tools/XSB/bin/xsb')
    xsb.load('./maze.P')
    xsb.load('./dfs.P')
    startTime = time.clock()
    result = xsb.query('solve(X).')
    print time.clock() - startTime
    print result
    path = result[0]['X']
    tempList = path[1:-1].split(',')
    pathList = [int(x) for x in tempList]

    return path2Action(pathList)
Ejemplo n.º 8
0
def breadthFirstSearch(problem):
  "Search the shallowest nodes in the search tree first. [p 81]"
  "*** YOUR CODE HERE ***"
  myXsb=  pyxf.xsb("/Users/muthukumarsuresh/Downloads/XSB/bin/xsb")
  myXsb.load('mazeeee.P')
  myXsb.load('bfs2.P')
  time.sleep(5)
  result = myXsb.query('planPathbfs(X)')
  while(result == False):
      result = myXsb.query('planPathbfs(X)')
  returnstr = result[0]['X']
  returnstr = returnstr[1:len(returnstr)-1]
  returnList = returnstr.split(',')
  s =Directions.SOUTH
  w = Directions.WEST
  e = Directions.EAST
  n = Directions.NORTH
  retList = []
  for element in returnList:
      if element == 's':
          retList.append(s)
      if element == 'e':
          retList.append(e)
      if element == 'w':
          retList.append(w)
      if element == 'n':
          retList.append(n)
  # returnList = returnList.reverse()
  return retList
Ejemplo n.º 9
0
def aStarSearch(problem, heuristic=nullHeuristic):
    "Search the node that has the lowest combined cost and heuristic first."

    from game import Directions
    from spade import pyxf
    import time

   # Creates an instance and makes a query to XSB using SPADE interface
    myXsb = pyxf.xsb('C:/XSB/config/x86-pc-windows/bin/xsb.exe')
    myXsb.load('D:/Tmp/maze.P')
    myXsb.load('D:/Tmp/astar.P')

    # print ('Starting to search!')

    time.sleep(2)
    result = myXsb.query("astar(start,finish,Direction).")

    finalDirections = []
    res = []

    # Choose the shortest path from all results available.
    # XSB is unstable from time to time, so we print something when it goes wrong.
    # print ('Retrieving results!')
    # print result

    # Choose the shortest path from all results available.
    if isinstance(result,bool):
        print "Catches XSB Problem!"

    else:
        cnt = 99999
        for dict in result:
            if len(dict['Direction']) < cnt:
                cnt = len(dict['Direction'])
                res = dict['Direction']
                res = res.split(",")
                print res
                break

        # print ('Final processing')
        # Perform final step to return real directions to Pacman
        for direction in res:
            if direction=="s":
                finalDirections.append(Directions.SOUTH)
            if direction=="w":
                finalDirections.append(Directions.WEST)
            if direction=="n":
                finalDirections.append(Directions.NORTH)
            if direction=="e":
                finalDirections.append(Directions.EAST)

        print finalDirections

    return finalDirections

    # We didn't find a solution, such assert
    # calls generalErrorDefined() and exit
    util.generalErrorDefined()
Ejemplo n.º 10
0
def depthFirstSearch(problem):
    """
  Search the deepest nodes in the search tree first [p 85].
  
  Your search algorithm needs to return a list of actions that reaches
  the goal.  Make sure to implement a graph search algorithm [Fig. 3.7].
  
  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 ***"
    f = open('maze.P', 'r')
    for line in f:
        if "goal" in line:
            g = line
    last = line
    print "lastline", last
    print "goal", g
    f.close()
    refine = last.split("(")
    refine2 = refine[1].split(")")
    startPac = refine2[0]
    myXSB = pyxf.xsb("/home/nikhil/Downloads/XSB/bin/xsb")
    myXSB.load("maze.P")
    myXSB.load("dfs.P")

    result = myXSB.query("depthFirstSearch(" + startPac + ", Path,Direction).")
    print result
    x = result[0]['Path']
    f1 = x.split("[")
    neededDir = f1[1].split(",")
    gg = g.split("(")
    g2 = gg[1].split(")")
    ls = []
    f2 = open('maze.P', 'r')
    for i in xrange(len(neededDir)):
        f2 = open('maze.P', 'r')
        for line1 in f2:
            if i + 1 < len(neededDir):
                stri = neededDir[i] + "," + neededDir[i + 1]
                if i + 1 < len(neededDir) and stri in line1:
                    j = line1.split(",")
                    k = j[2].split(").")
                    print line1, neededDir[i], neededDir[i + 1], k[0]
                    if g2[0] == neededDir[i + 1]:
                        exit

                    ls.append(str(k[0]))
                    continue
        f2.close()

    return ls
    """for x in xrange(len(array)):
def breadthFirstSearch(problem):
  "Search the shallowest nodes in the search tree first. [p 81]"
  "*** YOUR CODE HERE ***"
  f = open('maze.P','r')
  for line in f:
    pass
  last = line
  refine = last.split("(")
  refine2 = refine[1].split(")")
  startPac = refine2[0]
  myXSB = pyxf.xsb("/home/nikhil/Downloads/XSB/bin/xsb")
  myXSB.load("maze.P")
  myXSB.load("bfs.P")
  if sys.argv=="CornersProblem":
      myXSB = pyxf.xsb("/home/nikhil/Downloads/XSB/bin/xsb")
      myXSB.load("maze.P")
      myXSB.load("CornersProblem.P")
      result = myXSB.query("breadthFirstSearch("+startPac+",Path,Direction).")
      print result
  else:
      result = myXSB.query("breadthFirstSearch("+startPac+",Path,Direction).")
      print result
Ejemplo n.º 12
0
def depthFirstSearch(problem):
  """
  Search the deepest nodes in the search tree first [p 85].
  
  Your search algorithm needs to return a list of actions that reaches
  the goal.  Make sure to implement a graph search algorithm [Fig. 3.7].
  
  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 ***"
  """
  This function makes a generic implementation of DFS.Following variables are mainly used -
  1. state_stack - It is the stack class imported from util class. It keeps track of the nodes to be expanded and pops the nodes depth first.
  2. parents - It is used to backtrack the path of the node after it reaches the goal.
  3. direction - This is also used to backtrack the path of the node once it reaches goal. It gives the exact direction to trace back.
  4. visited - This keeps track of visited nodes so as to avoid a deadlock.
  5. path - This is used to return the path to the main function
  """
  from game import Directions
  from spade import pyxf
  south = Directions.SOUTH
  west = Directions.WEST
  north = Directions.NORTH
  east = Directions.EAST
  
  myXSB = pyxf.xsb("/home/dushyant/Downloads/XSB/bin/xsb")
  myXSB.load("maze.P")
  myXSB.load("dfs.P")
  result = myXSB.query("connected(start, A,D).")
  print result
  result1 = myXSB.query("dfs(start,[],P,D).")
  print result1
  #print result1[0]['P']
  #print result1[0]['D']
  #print result1[0].values
  path = result1[0]['D']
  #print path, len(path)
  path2 = path[1:-6]
  #print path2
  import re
  path3 = re.split(',',path2)
  #print path3
  path4 = [word[:1].upper() + word[1:] for word in path3]
  print path4
  print "Sending the path"
  return path4
Ejemplo n.º 13
0
def depthFirstSearch(problem):

    from spade import pyxf

    myXsb = pyxf.xsb("/home/prasidh/Downloads/XSB/bin/xsb")
    myXsb.load("/home/prasidh/Downloads/search-source1/search/dfs.P")
    myXsb.load("/home/prasidh/Downloads/search-source1/search/maze.P")
    param = "dfs1(c" + str(problem.startState[0]) + "_" + str(problem.startState[1]) + ",goal,Solution)"
    # param calls the prolog query that returns the dfs path
    result1 = myXsb.query(param)
    # print result1
    x = []
    x.append(result1[0])
    xy1 = [0]
    xy2 = [0]
    moves = []
    # Parse the values obtained from the dfs.P file and return the directions
    for i in x:
        # print i
        x = i.values()
        # print x
        z = x[0]
        # print z
        t = z.replace("[", "")
        t = t.replace("]", "")
        t = t.replace("c", "")
        t = t.split(",")
        # print t
        for i in t:
            i = i.split("_")
            xy1.append(i[0])
            xy2.append(i[1])
            # print i[0]
            # print i[1]
            # print xy1
            # print xy2
            # print xy1
            # print xy2
    length = len(xy1) - 1

    for i in range(1, length):
        if int(xy1[i + 1]) - int(xy1[i]) == 1:
            moves.append("East")
        if int(xy2[i + 1]) - int(xy2[i]) == 1:
            moves.append("North")
        if int(xy1[i + 1]) - int(xy1[i]) == -1:
            moves.append("West")
        if int(xy2[i + 1]) - int(xy2[i]) == -1:
            moves.append("South")
    return moves
Ejemplo n.º 14
0
def breadthFirstSearch(problem):
    "Search the shallowest nodes in the search tree first. [p 81]"
    "*** YOUR CODE HERE ***"
    f = open('maze.P', 'r')
    for line in f:
        pass
    last = line
    refine = last.split("(")
    refine2 = refine[1].split(")")
    startPac = refine2[0]
    myXSB = pyxf.xsb("/home/nikhil/Downloads/XSB/bin/xsb")
    myXSB.load("maze.P")
    myXSB.load("bfs.P")
    if sys.argv == "CornersProblem":
        myXSB = pyxf.xsb("/home/nikhil/Downloads/XSB/bin/xsb")
        myXSB.load("maze.P")
        myXSB.load("CornersProblem.P")
        result = myXSB.query("breadthFirstSearch(" + startPac +
                             ",Path,Direction).")
        print result
    else:
        result = myXSB.query("breadthFirstSearch(" + startPac +
                             ",Path,Direction).")
        print result
def aStarSearch(problem, heuristic=nullHeuristic):
  "Search the node that has the lowest combined cost and heuristic first."
  "*** YOUR CODE HERE ***"
  f = open('maze.P','r')
  for line in f:
    pass
  last = line
  refine = last.split("(")
  refine2 = refine[1].split(")")
  startPac = refine2[0]
  myXSB = pyxf.xsb("/home/nikhil/Downloads/XSB/bin/xsb")
  myXSB.load("maze.P")
  myXSB.load("AStar.P")
  
  result = myXSB.query("AStarAlgorithm("+startPac+",Path,Direction).")
  print result
Ejemplo n.º 16
0
def aStarSearch(problem, heuristic=nullHeuristic):
    "Search the node that has the lowest combined cost and heuristic first."
    "*** YOUR CODE HERE ***"
    f = open('maze.P', 'r')
    for line in f:
        pass
    last = line
    refine = last.split("(")
    refine2 = refine[1].split(")")
    startPac = refine2[0]
    myXSB = pyxf.xsb("/home/nikhil/Downloads/XSB/bin/xsb")
    myXSB.load("maze.P")
    myXSB.load("AStar.P")

    result = myXSB.query("AStarAlgorithm(" + startPac + ",Path,Direction).")
    print result
Ejemplo n.º 17
0
def aStarSearch(problem, heuristic=nullHeuristic):
    "Search the node that has the lowest combined cost and heuristic first."
    "*** YOUR CODE HERE ***"
    mazeFile = 'maze.P'
    heuFile = 'heu.P'
    createHeuFile(problem, heuristic, heuFile)
    xsb = pyxf.xsb('/Users/zephyrYin/Documents/tools/XSB/bin/xsb')
    xsb.load('./maze.P')
    xsb.load('./heu.P')
    xsb.load('./astar.P')
    startTime = time.clock()
    result = xsb.query('solve(P/C).')
    print time.clock() - startTime
    path = result[0]['P']
    tempList = path[1:-1].split(',')
    pathList = [int(x) for x in tempList]
    print pathList
    return path2Action(pathList)
Ejemplo n.º 18
0
def depthFirstSearch(problem):
  """
  Search the deepest nodes in the search tree first [p 85].
  
  Your search algorithm needs to return a list of actions that reaches
  the goal.  Make sure to implement a graph search algorithm [Fig. 3.7].
  
  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 ***"

  myXsb=  pyxf.xsb("/Users/muthukumarsuresh/Downloads/XSB/bin/xsb")
  myXsb.load('mazeeee.P')
  myXsb.load('dfs2.P')
  time.sleep(5)
  result = myXsb.query('planPath(X)')

  while(result == False):
      result = myXsb.query('planPath(X)')
  returnstr = result[0]['X']
  returnstr = returnstr[1:len(returnstr)-1]
  returnList = returnstr.split(',')
  s =Directions.SOUTH
  w = Directions.WEST
  e = Directions.EAST
  n = Directions.NORTH
  retList = []
  for element in returnList:
      if element == 's':
          retList.append(s)
      if element == 'e':
          retList.append(e)
      if element == 'w':
          retList.append(w)
      if element == 'n':
          retList.append(n)
  # returnList = returnList.reverse()
  return retList
Ejemplo n.º 19
0
def breadthFirstSearch(problem):
  "Search the shallowest nodes in the search tree first. [p 81]"
  "*** YOUR CODE HERE ***"

  """
  This function makes a generic implementation of DFS.Following variables are mainly used -
  1. state_queue - It is the queue class imported from util class. It keeps track of the nodes to be expanded and pops the nodes breadth first.
  2. parents - It is used to backtrack the path of the node after it reaches the goal.
  3. direction - This is also used to backtrack the path of the node once it reaches goal. It gives the exact direction to trace back.
  4. visited - This keeps track of visited nodes so as to avoid a deadlock.
  5. path - This is used to return the path to the main function
  """
  from game import Directions
  from spade import pyxf
  south = Directions.SOUTH
  west = Directions.WEST
  north = Directions.NORTH
  east = Directions.EAST
  
  myXSB = pyxf.xsb("/home/dushyant/Downloads/XSB/bin/xsb")
  myXSB.load("maze.P")
  myXSB.load("bfs.P")
  result = myXSB.query("connected(start, A,D).")
  print result
  result1 = myXSB.query("solve(start,D).")
  print result1
  print result1[0]['D']
  path = result1[0]['D']
  print path, len(path)
  path2 = path[1:-7]
  print path2
  import re
  path3 = re.split(',',path2)
  print path3
  path4 = [word[:1].upper() + word[1:] for word in path3]
  print path4
  path5 = path4[1:][::2]
  path6 = path5[::-1]
  print path5, path6
  print path[0]
  print "Sending the path"
  return path6
Ejemplo n.º 20
0
def aStarSearch(problem, heuristic=nullHeuristic):
  "Search the node that has the lowest combined cost and heuristic first."
  "*** YOUR CODE HERE ***"
  """
  This function makes a generic implementation of UCS.Following variables are mainly used -
  1. state_queue - It is the priority queue class imported from util class. It keeps track of the nodes to be expanded and pops the nodes in order of their priotiy.
  2. parents - It is used to backtrack the path of the node after it reaches the goal.
  3. direction - This is also used to backtrack the path of the node once it reaches goal. It gives the exact direction to trace back.
  4. visited - This keeps track of visited nodes so as to avoid a deadlock.
  5. cost - this keeps track of the cost of the nodes and adds them to the child if needed.
  6. path - This is used to return the path to the main function
  """
  from game import Directions
  from spade import pyxf
  south = Directions.SOUTH
  west = Directions.WEST
  north = Directions.NORTH
  east = Directions.EAST
  
  myXSB = pyxf.xsb("/home/dushyant/Downloads/XSB/bin/xsb")
  myXSB.load("mazeastar.P")
  myXSB.load("astar.P")
  #result = myXSB.query("connected(start#A#D#E#F).")
  result1 = myXSB.query("solve(start, D).")
  print "Result is -"
  print result1
  path = result1[0]['D']
  path2 = path[1:-1]
  import re
  path3 = re.split(',',path2)
  final_path = []
  i=1
  for it in path3:
    temp = re.split('#',it.replace(" ",""))
    final_path.append(temp[1])

  del final_path[-1]
  path4 = [word[:1].upper() + word[1:] for word in final_path]
  path6 = path4[::-1]
  print "Sending the path"
  return path6
Ejemplo n.º 21
0
def aStarSearch(problem, heuristic=nullHeuristic):
  "Search the node that has the lowest combined cost and heuristic first."
  "*** YOUR CODE HERE ***"

  myXsb=  pyxf.xsb("/Users/muthukumarsuresh/Downloads/XSB/bin/xsb")
  myXsb.load('mazeeee.P')

  myXsb.load('heuristic.P')

  myXsb.load('astar.P')
  time.sleep(5)
  result = myXsb.query('planPathbfs(X)')

  if result is False:
      print(result)
      result = myXsb.query('planPathbfs(X)')
  print("hello", result)
  returnstr = result[0]['X']
  returnstr = returnstr[1:len(returnstr)-1]
  returnList = returnstr.split(',')
  s =Directions.SOUTH
  w = Directions.WEST
  e = Directions.EAST
  n = Directions.NORTH
  retList = []
  for element in returnList:
      if element == 's':
          retList.append(s)
      if element == 'e':
          retList.append(e)
      if element == 'w':
          retList.append(w)
      if element == 'n':
          retList.append(n)
  print retList
  # returnList = returnList.reverse()
  return retList
def aStarSearch(problem, heuristic=nullHeuristic):
  print "***************************astarSearch Start***************************"
  south = Directions.SOUTH
  west = Directions.WEST
  north = Directions.NORTH
  east = Directions.EAST
  myXSB = pyxf.xsb("/home/gp/Downloads/XSB/bin/xsb")
  myXSB.load("mazeastar.P")
  myXSB.load("astar.P")
  result1 = myXSB.query("astar_search(start, D).")
  path = result1[0]['D']
  path2 = path[1:-1]
  path3 = re.split(',',path2)
  final_path = []
  i=1
  for it in path3:
    temp = re.split('#',it.replace(" ",""))
    final_path.append(temp[1])

  del final_path[-1]
  path4 = [word[:1].upper() + word[1:] for word in final_path]
  path6 = path4[::-1]
  print "***************************astarSearch End***************************"
  return path6
def aStarSearch(problem, heuristic=nullHeuristic):
    print "***************************astarSearch Start***************************"
    south = Directions.SOUTH
    west = Directions.WEST
    north = Directions.NORTH
    east = Directions.EAST
    myXSB = pyxf.xsb("/home/gp/Downloads/XSB/bin/xsb")
    myXSB.load("mazeastar.P")
    myXSB.load("astar.P")
    result1 = myXSB.query("astar_search(start, D).")
    path = result1[0]['D']
    path2 = path[1:-1]
    path3 = re.split(',', path2)
    final_path = []
    i = 1
    for it in path3:
        temp = re.split('#', it.replace(" ", ""))
        final_path.append(temp[1])

    del final_path[-1]
    path4 = [word[:1].upper() + word[1:] for word in final_path]
    path6 = path4[::-1]
    print "***************************astarSearch End***************************"
    return path6
Ejemplo n.º 24
0
def aStarSearch(problem, heuristic=nullHeuristic):
    print 'This is A*!'
    from game import Directions
    """
    A separate file consisting of heuristic values based on argument is populated for future use by the query.
    """
    f = open('astar_heuristic.P', 'w')
    sx, sy = problem.startState
    start = sx + (problem.walls.width - 2) * (problem.walls.height - 2 - sy)
    gx, gy = problem.goal
    goal = gx + (problem.walls.width - 2) * (problem.walls.height - 2 - gy)
    for x in range(problem.walls.width):
        for y in range(problem.walls.height):
            """
            Avoiding the boundary frames
            """
            if x != 0 and y != 0 and x != problem.walls.width - 1 and y != problem.walls.height - 1:
                if problem.walls[x][y] is False:
                    curr = x + (problem.walls.width -
                                2) * (problem.walls.height - 2 - y)
                    if curr == goal:
                        u = 'finish'
                    elif curr == start:
                        u = 'start'
                    else:
                        u = 'c' + str(curr)
                    v = ''
                    temp = 0
                    """
                    Processing the left of the node
                    """
                    if problem.walls[x - 1][y] is False:
                        temp = x - 1 + (problem.walls.width -
                                        2) * (problem.walls.height - 2 - y)
                        if temp == goal:
                            v = 'finish'
                        elif temp == start:
                            v = 'start'
                        else:
                            v = 'c' + str(temp)
                        """
                        Adding the manhattan heuristic value to the clause file.
                        """
                        man_d = heuristic((x - 1, y), problem, {})
                        f.write('manhattan_distance_heuristic(' + v + ',' +
                                str(man_d) + ').\n')
                    """
                    Processing the right of the node
                    """
                    if problem.walls[x + 1][y] is False:
                        temp = x + 1 + (problem.walls.width -
                                        2) * (problem.walls.height - 2 - y)
                        if temp == goal:
                            v = 'finish'
                        elif temp == start:
                            v = 'start'
                        else:
                            v = 'c' + str(temp)
                        """
                        Adding the manhattan heuristic value to the clause file.
                        """
                        man_d = heuristic((x + 1, y), problem, {})
                        f.write('manhattan_distance_heuristic(' + v + ',' +
                                str(man_d) + ').\n')
                    """
                    Processing left of the node
                    """
                    if problem.walls[x][y - 1] is False:
                        temp = x + (problem.walls.width -
                                    2) * (problem.walls.height - 2 - (y - 1))
                        if temp == goal:
                            v = 'finish'
                        elif temp == start:
                            v = 'start'
                        else:
                            v = 'c' + str(temp)
                        """
                        Adding the manhattan heuristic value to the clause file.
                        """
                        man_d = heuristic((x, y - 1), problem, {})
                        f.write('manhattan_distance_heuristic(' + v + ',' +
                                str(man_d) + ').\n')
                    """
                    Processing right of the node
                    """
                    if problem.walls[x][y + 1] is False:
                        temp = x + (problem.walls.width -
                                    2) * (problem.walls.height - 2 - (y + 1))
                        if temp == goal:
                            v = 'finish'
                        elif temp == start:
                            v = 'start'
                        else:
                            v = 'c' + str(temp)
                        """
                        Adding the manhattan heuristic value to the clause file.
                        """
                        man_d = heuristic((x, y + 1), problem, {})
                        f.write('manhattan_distance_heuristic(' + v + ',' +
                                str(man_d) + ').\n')

    f.close()
    from searchAgents import direction_list
    from spade import pyxf
    import os
    """
    Building the XSB PROLOG Query
    """
    myXsb = pyxf.xsb("/home/vishal/Downloads/xsb/XSB/bin/xsb")
    myXsb.load(os.getcwd() + '/maze.P')
    myXsb.load(os.getcwd() + '/astar.P')
    myXsb.load(os.getcwd() + '/astar_heuristic.P')
    q_result = myXsb.query("astar(start,X)")
    result = q_result[0]['X']
    result = result[1:]
    result = result[:-1]
    result = result.split(',')
    result = result[1:]
    result_list = list()
    result_list.append(direction_list[('start', result[0])])
    """
    Converting the list of actions returned by prolog into appropriate directions to be returned
    """
    for x in range(len(result) - 1):
        result_list.append(direction_list[(result[x], result[x + 1])])
    return result_list
Ejemplo n.º 25
0
def depthFirstSearch(problem):
    """
    Search the deepest nodes in the search tree first [p 85].

    Your search algorithm needs to return a list of actions that reaches
    the goal.  Make sure to implement a graph search algorithm [Fig. 3.7].

    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())
    """
    from game import Directions
    from spade import pyxf
    import time

    # Creates an instance and makes a query to XSB using SPADE interface
    myXsb = pyxf.xsb('C:/XSB/config/x86-pc-windows/bin/xsb.exe')
    myXsb.load('D:/Tmp/maze.P')
    myXsb.load('D:/Tmp/dfs.P')

    # print ('Starting to search!')

    time.sleep(2)
    result = myXsb.query("dfs(finish,[start],Direction).")

    finalDirections = []
    res = []

    # print ('Retrieving results!')

    # Choose the shortest path from all results available.
    # XSB is unstable from time to time, so we print something when it goes wrong.
    if isinstance(result,bool):
        print "Catches XSB Problem!"
    else:
        cnt = 99999
        for dict in result:
            if len(dict['Direction']) < cnt:
                cnt = len(dict['Direction'])
                res = dict['Direction']
                res = res.split(",")
                print res
                break

        # print ('Final processing')
        # Final step to return real direction to Pacman

        for direction in res:
            if direction=="s":
                finalDirections.append(Directions.SOUTH)
            if direction=="w":
                finalDirections.append(Directions.WEST)
            if direction=="n":
                finalDirections.append(Directions.NORTH)
            if direction=="e":
                finalDirections.append(Directions.EAST)

        print finalDirections

    return finalDirections

    # We didn't find a solution, such assert
    # calls generalErrorDefined() and exit
    util.generalErrorDefined()
Ejemplo n.º 26
0
def breadthFirstSearch(problem):
    print 'This is BFS!'
    if problem.problemType is 'Position':
        from searchAgents import direction_list
        from spade import pyxf
        import os
        """
        Building the XSB PROLOG query
        """
        myXsb = pyxf.xsb("/home/vishal/Downloads/xsb/XSB/bin/xsb")
        myXsb.load(os.getcwd() + '/maze.P')
        myXsb.load(os.getcwd() + '/bfs.P')
        q_result = myXsb.query("bfs(start,X)")
        result = q_result[0]['X']
        result = result[1:]
        result = result[:-1]
        result = result.split(',')
        result.reverse()
        result = result[1:]
        result_list = list()
        result_list.append(direction_list[('start', result[0])])
        """
        Converting the list of actions returned by prolog into appropriate directions to be returned
        """
        for x in range(len(result) - 1):
            result_list.append(direction_list[(result[x], result[x + 1])])
        return result_list
    elif problem.problemType is 'Corners':
        from searchAgents import direction_list
        from spade import pyxf
        import os
        merged_result = []
        """
        Building the XSB PROLOG query
        """
        myXsb = pyxf.xsb("/home/vishal/Downloads/xsb/XSB/bin/xsb")
        myXsb.load(os.getcwd() + '/maze.P')
        myXsb.load(os.getcwd() + '/bfs.P')
        myXsb.load(os.getcwd() + '/corner4.P')
        q_result = myXsb.query("bfs(start,X)")
        result = q_result[0]['X']
        result = result[1:]
        result = result[:-1]
        result = result.split(',')
        merged_result.extend(result[1:])
        """
        Building the XSB PROLOG query
        """
        myXsb = pyxf.xsb("/home/vishal/Downloads/xsb/XSB/bin/xsb")
        myXsb.load(os.getcwd() + '/maze.P')
        myXsb.load(os.getcwd() + '/bfs.P')
        myXsb.load(os.getcwd() + '/corner3.P')
        q_result = myXsb.query("bfs(" + str(result[0]) + ",X)")
        result = q_result[0]['X']
        result = result[1:]
        result = result[:-1]
        result = result.split(',')

        temp = result[1:]
        temp.extend(merged_result)
        merged_result = temp
        """
        Building the XSB PROLOG query
        """
        myXsb = pyxf.xsb("/home/vishal/Downloads/xsb/XSB/bin/xsb")
        myXsb.load(os.getcwd() + '/maze.P')
        myXsb.load(os.getcwd() + '/bfs.P')
        myXsb.load(os.getcwd() + '/corner2.P')
        q_result = myXsb.query("bfs(" + str(result[0]) + ",X)")
        result = q_result[0]['X']
        result = result[1:]
        result = result[:-1]
        result = result.split(',')

        temp = result[1:]
        temp.extend(merged_result)
        merged_result = temp
        """
        Building the XSB PROLOG query
        """
        myXsb = pyxf.xsb("/home/vishal/Downloads/xsb/XSB/bin/xsb")
        myXsb.load(os.getcwd() + '/maze.P')
        myXsb.load(os.getcwd() + '/bfs.P')
        myXsb.load(os.getcwd() + '/corner1.P')
        q_result = myXsb.query("bfs(" + str(result[0]) + ",X)")
        result = q_result[0]['X']
        result = result[1:]
        result = result[:-1]
        result = result.split(',')

        temp = result
        temp.extend(merged_result)
        merged_result = temp

        result = merged_result
        result.reverse()
        result = result[1:]
        result_list = list()
        result_list.append(direction_list[('start', result[0])])
        """
        Converting the list of actions returned by prolog into appropriate directions to be returned
        """
        for x in range(len(result) - 1):
            result_list.append(direction_list[(result[x], result[x + 1])])
        return result_list
Ejemplo n.º 27
0
from spade import pyxf
myXsb=  pyxf.xsb("/Users/muthukumarsuresh/Downloads/XSB/bin/xsb")
myXsb.load('program.P')
myXsb.load('program2.P')
result = myXsb.query('q(X)')
print(result)
Ejemplo n.º 28
0
def aStarSearch(problem, heuristic=nullHeuristic):
  "Search the node that has the lowest combined cost and heuristic first."


  "*** YOUR CODE HERE ***"
#get map's outline

  w = problem.walls.width
  h = problem.walls.height
  sx, sy = problem.getStartState()
  goalx,goaly = problem.goal

 #define the notion to each position in map: (1,1) --> cell01

  notion = []
  t=0
  for i in range(0,w):
    notion.append([])
  for i in range(0,w):
    for j in range(0,h):
        notion[i].append(t)
        t=t+1

 #prolog file contains connection between cell
  fname = 'connection.P'
  from game import Directions
  dict ={}
  with open(fname, 'w') as fout:

    fout.write('\n')
    for i in range(0,w):
        for j in range(0,h):
            if not problem.walls[i][j]:
                if i+1 <= w :
                    if not problem.walls[i+1][j]:
                        fout.write('connect(cell'+ notion[i][j].__str__() +',cell'+ notion[i+1][j].__str__()+ ').')
                        fout.write('\n')
                        word = 'cell'+ notion[i][j].__str__()+'cell'+ notion[i+1][j].__str__()
                        dict[word] = Directions.EAST                #dictionary translating from strings "cellXcellY" to the real direction in game
                if i-1 >= 0 :
                    if not problem.walls[i-1][j]:
                        fout.write('connect(cell'+ notion[i][j].__str__() +',cell'+ notion[i-1][j].__str__()+ ').')
                        fout.write('\n')
                        word = 'cell'+ notion[i][j].__str__()+'cell'+ notion[i-1][j].__str__()
                        dict[word] = Directions.WEST
                if j+1 <= h :
                    if not problem.walls[i][j+1]:
                        fout.write('connect(cell'+ notion[i][j].__str__() +',cell'+ notion[i][j+1].__str__()+ ').')
                        fout.write('\n')
                        word = 'cell'+ notion[i][j].__str__()+'cell'+ notion[i][j+1].__str__()
                        dict[word] = Directions.NORTH
                if j-1 >= 0 :
                    if not problem.walls[i][j-1]:
                        fout.write('connect(cell'+ notion[i][j].__str__() +',cell'+ notion[i][j-1].__str__()+ ').')
                        fout.write('\n')
                        word = 'cell'+ notion[i][j].__str__()+'cell'+ notion[i][j-1].__str__()
                        dict[word] = Directions.SOUTH

    fout.close()

    global hname
    hname = 'heuristicvalues.P'
    with open(hname, 'w') as fout:
        for i in range(0,w):
            for j in range(0,h):
                if not problem.walls[i][j]:
                    distant=abs(i - goalx) + abs(j - goaly)
                    fout.write('h(cell'+ notion[i][j].__str__()+ ','+ distant.__str__() + ').')
                    fout.write('\n')

    fout.close()
 #load prolog fact
  from spade import pyxf
  brain = pyxf.xsb('/home/hieule/Downloads/XSB/bin/xsb')
  brain.load(fname)
  brain.load(hname)

  brain.load('astar.P')
  goal = 'cell'+notion[goalx][goaly].__str__()
  start = 'cell'+notion[sx][sy].__str__()
  #feedback = brain.query('dfs('+start+',['+start+'],'+goal+',X).')
  feedback = brain.query('solve2('+start+','+goal+',X).')
  path=feedback[0].__str__()


  path = path[8:len(path)-3]
  path = path.split(',', 9999)
  #reverse the path
  path= path[::-1]
  #translate the path using dictionary
  path_translated=[]
  for i in range(0,len(path)-1):
      path_translated.append(dict[path[i]+path[i+1]])

  return path_translated
Ejemplo n.º 29
0
def breadthFirstSearch(problem):

    from spade import pyxf

    myXsb = pyxf.xsb("/home/prasidh/Downloads/XSB/bin/xsb")
    myXsb.load("/home/prasidh/Downloads/search-source1/search/bfs2.P")
    myXsb.load("/home/prasidh/Downloads/search-source1/search/maze.P")
    param = "bfs(c" + str(problem.startState[0]) + "_" + str(problem.startState[1]) + ",Solution)."
    # param calls the prolog query that returns the bfs path
    result1 = myXsb.query(param)
    # print result1
    length = len(result1)
    # print length
    list = []
    m = 0
    y = "inf"
    minlist = 0
    # Find the shortest path that bfs returns
    for i in range(0, length):
        list.append(result1[i])
        # print list
        for j in list:
            l = j.values()
            # print l
            z = l[0]
            m = z.count("_")
            # print m
            if m < y:
                y = m
                minlist = i
                # print index
                # print list
        list = []

    x = []
    x.append(result1[minlist])
    xy1 = [0]
    xy2 = [0]
    moves = []
    # Parse the solution to return the moves for Breadth First Search
    for i in x:
        # print i
        x = i.values()
        # print x
        z = x[0]
        # print z
        t = z.replace("[", "")
        t = t.replace("]", "")
        t = t.replace("c", "")
        t = t.split(",")

        # print t
        for i in t:
            i = i.split("_")
            xy1.append(i[0])
            xy2.append(i[1])
            # print i[0]
            # print i[1]
            # print xy1
            # print xy2
            # print xy1
            # print xy2
    length = len(xy1) - 1
    for i in range(1, length):
        if int(xy1[i + 1]) - int(xy1[i]) == 1:
            moves.append("West")
        if int(xy2[i + 1]) - int(xy2[i]) == 1:
            moves.append("South")
        if int(xy1[i + 1]) - int(xy1[i]) == -1:
            moves.append("East")
        if int(xy2[i + 1]) - int(xy2[i]) == -1:
            moves.append("North")

            # print int(xy2[i+1])-int(xy2[i])
            # print moves
    moves.reverse()
    # print moves
    return moves
Ejemplo n.º 30
0
from spade import pyxf

#print spade.__file__
myXsb = pyxf.xsb('/home/adrian/Applications/XSB/bin/xsb')
myXsb.load("/home/adrian/project/cse537-project/project_4/search/prolog_scripts/maze.P")
myXsb.load("/home/adrian/project/cse537-project/project_4/search/prolog_scripts/bfs.P")
#result = myXsb.query("member(cell23,[cell23|start]).")
#print result
result = myXsb.query("append([a,b,c],[1,2,3],[a,b,c,1,2,3]).")
print result
Ejemplo n.º 31
0
def breadthFirstSearch(problem):
    print 'This is BFS!'
    if problem.problemType is 'Position':
        from searchAgents import direction_list
        from spade import pyxf
        import os
        """
        Building the XSB PROLOG query
        """
        myXsb = pyxf.xsb("/home/vishal/Downloads/xsb/XSB/bin/xsb")
        myXsb.load(os.getcwd() + '/maze.P')
        myXsb.load(os.getcwd() + '/bfs.P')
        q_result = myXsb.query("bfs(start,X)")
        result =  q_result[0]['X']
        result = result[1:]
        result = result[:-1]
        result = result.split(',')
        result.reverse()
        result = result[1:]
        result_list = list()
        result_list.append(direction_list[('start', result[0])])
        """
        Converting the list of actions returned by prolog into appropriate directions to be returned
        """
        for x in range(len(result) - 1):
            result_list.append(direction_list[(result[x], result[x + 1])])
        return result_list
    elif problem.problemType is 'Corners':
        from searchAgents import direction_list
        from spade import pyxf
        import os
        merged_result = []

        """
        Building the XSB PROLOG query
        """
        myXsb = pyxf.xsb("/home/vishal/Downloads/xsb/XSB/bin/xsb")
        myXsb.load(os.getcwd() + '/maze.P')
        myXsb.load(os.getcwd() + '/bfs.P')
        myXsb.load(os.getcwd() + '/corner4.P')
        q_result = myXsb.query("bfs(start,X)")
        result =  q_result[0]['X']
        result = result[1:]
        result = result[:-1]
        result = result.split(',')
        merged_result.extend(result[1:])

        """
        Building the XSB PROLOG query
        """
        myXsb = pyxf.xsb("/home/vishal/Downloads/xsb/XSB/bin/xsb")
        myXsb.load(os.getcwd() + '/maze.P')
        myXsb.load(os.getcwd() + '/bfs.P')
        myXsb.load(os.getcwd() + '/corner3.P')
        q_result = myXsb.query("bfs("+str(result[0])+",X)")
        result =  q_result[0]['X']
        result = result[1:]
        result = result[:-1]
        result = result.split(',')

        temp = result[1:]
        temp.extend(merged_result)
        merged_result = temp

        """
        Building the XSB PROLOG query
        """
        myXsb = pyxf.xsb("/home/vishal/Downloads/xsb/XSB/bin/xsb")
        myXsb.load(os.getcwd() + '/maze.P')
        myXsb.load(os.getcwd() + '/bfs.P')
        myXsb.load(os.getcwd() + '/corner2.P')
        q_result = myXsb.query("bfs("+str(result[0])+",X)")
        result =  q_result[0]['X']
        result = result[1:]
        result = result[:-1]
        result = result.split(',')
        
        temp = result[1:]
        temp.extend(merged_result)
        merged_result = temp

        """
        Building the XSB PROLOG query
        """
        myXsb = pyxf.xsb("/home/vishal/Downloads/xsb/XSB/bin/xsb")
        myXsb.load(os.getcwd() + '/maze.P')
        myXsb.load(os.getcwd() + '/bfs.P')
        myXsb.load(os.getcwd() + '/corner1.P')
        q_result = myXsb.query("bfs("+str(result[0])+",X)")
        result =  q_result[0]['X']
        result = result[1:]
        result = result[:-1]
        result = result.split(',')

        temp = result
        temp.extend(merged_result)
        merged_result = temp

        result = merged_result
        result.reverse()
        result = result[1:]
        result_list = list()
        result_list.append(direction_list[('start', result[0])])
        """
        Converting the list of actions returned by prolog into appropriate directions to be returned
        """
        for x in range(len(result) - 1):
            result_list.append(direction_list[(result[x], result[x + 1])])
        return result_list
Ejemplo n.º 32
0
def depthFirstSearch(problem):

  #get map's outline

  w = problem.walls.width
  h = problem.walls.height
  sx, sy = problem.getStartState()
  goalx,goaly = problem.goal

 #define the notion to each position in map: (1,1) --> cell01

  notion = []
  t=0
  for i in range(0,w):
    notion.append([])
  for i in range(0,w):
    for j in range(0,h):
        notion[i].append(t)
        t=t+1

 #prolog file contains connection between cell
  fname = 'connection.P'
  from game import Directions
  dict ={}
  with open(fname, 'w') as fout:

    fout.write('\n')
    for i in range(0,w):
        for j in range(0,h):
            if not problem.walls[i][j]:
                if i+1 <= w :
                    if not problem.walls[i+1][j]:
                        fout.write('connect(cell'+ notion[i][j].__str__() +',cell'+ notion[i+1][j].__str__()+ ').')
                        fout.write('\n')
                        word = 'cell'+ notion[i][j].__str__()+'cell'+ notion[i+1][j].__str__()
                        dict[word] = Directions.EAST                #dictionary translating from strings "cellXcellY" to the real direction in game
                if i-1 >= 0 :
                    if not problem.walls[i-1][j]:
                        fout.write('connect(cell'+ notion[i][j].__str__() +',cell'+ notion[i-1][j].__str__()+ ').')
                        fout.write('\n')
                        word = 'cell'+ notion[i][j].__str__()+'cell'+ notion[i-1][j].__str__()
                        dict[word] = Directions.WEST
                if j+1 <= h :
                    if not problem.walls[i][j+1]:
                        fout.write('connect(cell'+ notion[i][j].__str__() +',cell'+ notion[i][j+1].__str__()+ ').')
                        fout.write('\n')
                        word = 'cell'+ notion[i][j].__str__()+'cell'+ notion[i][j+1].__str__()
                        dict[word] = Directions.NORTH
                if j-1 >= 0 :
                    if not problem.walls[i][j-1]:
                        fout.write('connect(cell'+ notion[i][j].__str__() +',cell'+ notion[i][j-1].__str__()+ ').')
                        fout.write('\n')
                        word = 'cell'+ notion[i][j].__str__()+'cell'+ notion[i][j-1].__str__()
                        dict[word] = Directions.SOUTH

    fout.close()

 #load prolog fact
  from spade import pyxf
  brain = pyxf.xsb('/home/hieule/Downloads/XSB/bin/xsb')
  brain.load(fname)
  brain.load('dfs.P')
  goal = 'cell'+notion[goalx][goaly].__str__()
  start = 'cell'+notion[sx][sy].__str__()
  feedback = brain.query('dfs('+start+',['+start+'],'+goal+',X).')
  #feedback = brain.query('solve2('+start+','+goal+',X).')
  path=feedback[0].__str__()


  path = path[8:len(path)-3]
  path = path.split(',', 9999)
  #translate the path using dictionary
  path_translated=[]
  for i in range(0,len(path)-1):
      path_translated.append(dict[path[i]+path[i+1]])

  return path_translated
Ejemplo n.º 33
0
import types
from spade import pyxf 

# load xsb from your computer - have to be installed
# go to Flora-2 download, unzip and ./runflora after that 
# run command 'xsb'. If xsb working then change path 
# in line below
xsb = pyxf.xsb('/home/stella/Flora-2/XSB/bin/xsb')
xsb.load('osobe.P')

def getMyFriends(user):
    # define path to xsb
    results = xsb.query('all_friends(%s, X)' % user) 

    return parseResultToArray(results)

def getMySuggestions(user):
    results = xsb.query('all_suggestions(%s, X)' % user)
    return parseResultToArray(results)

def addNewFriend(user, friend):
    query = "asserta(friends('%s', '%s'))." % (user, friend)
    xsb.query(query)


def parseResultToArray(dictData):
    if type(dictData) == type(True) or type(dictData) == type(False):
        return []

    result = dictData[0]["X"]
    result = result.replace('[', '').replace(']', '')
def depthFirstSearch(problem):
  """
  Search the deepest nodes in the search tree first [p 85].
  
  Your search algorithm needs to return a list of actions that reaches
  the goal.  Make sure to implement a graph search algorithm [Fig. 3.7].
  
  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 ***"
  f = open('maze.P','r')
  for line in f:
      if "goal" in line:
          g = line
  last = line
  print "lastline",last
  print "goal",g
  f.close()
  refine = last.split("(")
  refine2 = refine[1].split(")")
  startPac = refine2[0]
  myXSB = pyxf.xsb("/home/nikhil/Downloads/XSB/bin/xsb")
  myXSB.load("maze.P")
  myXSB.load("dfs.P")
  
  result = myXSB.query("depthFirstSearch("+startPac+", Path,Direction).")
  print result
  x = result[0]['Path']
  f1 = x.split("[")
  neededDir = f1[1].split(",")
  gg = g.split("(")
  g2 = gg[1].split(")")
  ls = []
  f2 = open('maze.P','r')
  for i in xrange(len(neededDir)):
      f2 = open('maze.P','r')
      for line1 in f2:
          if i+1<len(neededDir):
              stri = neededDir[i] + "," + neededDir[i+1]
              if i+1<len(neededDir) and stri in line1:
                  j = line1.split(",")
                  k = j[2].split(").")
                  print line1,neededDir[i],neededDir[i+1],k[0]
                  if g2[0]==neededDir[i+1]:
                      exit
                      
                  ls.append(str(k[0]))
                  continue
      f2.close()
      
  return ls

  
  

  
      
  """for x in xrange(len(array)):
Ejemplo n.º 35
0
from spade import pyxf

myXsb=pyxf.xsb("/home/prasidh/Downloads/XSB/bin/xsb")

myXsb.load("/home/prasidh/Downloads/search-source1/search/dfs.P")
myXsb.load("/home/prasidh/Downloads/search-source1/search/maze.P")


result1=myXsb.query("dfs_start(c35_1,goal,Path).")


print result1
Ejemplo n.º 36
0
def aStarSearch(problem, heuristic=nullHeuristic):
    print 'This is A*!'
    from game import Directions
    """
    A separate file consisting of heuristic values based on argument is populated for future use by the query.
    """
    f = open('astar_heuristic.P', 'w')
    sx, sy = problem.startState
    start = sx + (problem.walls.width - 2) * (problem.walls.height- 2 - sy)
    gx, gy = problem.goal
    goal = gx + (problem.walls.width - 2) * (problem.walls.height - 2 - gy)
    for x in range(problem.walls.width):
        for y in range(problem.walls.height):
            """
            Avoiding the boundary frames
            """
            if x != 0 and y != 0 and x != problem.walls.width - 1 and y != problem.walls.height - 1:
                if problem.walls[x][y] is False:
                    curr = x + (problem.walls.width - 2) * (problem.walls.height - 2 - y)
                    if curr == goal:
                        u = 'finish'
                    elif curr == start:
                        u = 'start'
                    else:
                        u = 'c' + str(curr)
                    v = ''
                    temp = 0
                    """
                    Processing the left of the node
                    """
                    if problem.walls[x - 1][y] is False:
                        temp = x - 1 + (problem.walls.width - 2) * (problem.walls.height - 2 - y)
                        if temp == goal:
                            v = 'finish'
                        elif temp == start:
                            v = 'start'
                        else:
                            v = 'c' + str(temp)
                        """
                        Adding the manhattan heuristic value to the clause file.
                        """
                        man_d = heuristic((x-1,y),problem,{})
                        f.write('manhattan_distance_heuristic(' + v + ',' + str(man_d) + ').\n')
                    """
                    Processing the right of the node
                    """
                    if problem.walls[x + 1][y] is False:
                        temp = x + 1 + (problem.walls.width - 2) * (problem.walls.height - 2 - y)
                        if temp == goal:
                            v = 'finish'
                        elif temp == start:
                            v = 'start'
                        else:
                            v = 'c' + str(temp)
                        """
                        Adding the manhattan heuristic value to the clause file.
                        """
                        man_d = heuristic((x+1,y),problem,{})
                        f.write('manhattan_distance_heuristic(' + v + ',' + str(man_d) + ').\n')
                    """
                    Processing left of the node
                    """
                    if problem.walls[x][y - 1] is False:
                        temp = x + (problem.walls.width - 2) * (problem.walls.height - 2 - (y - 1))
                        if temp == goal:
                            v = 'finish'
                        elif temp == start:
                            v = 'start'
                        else:
                            v = 'c' + str(temp)
                        """
                        Adding the manhattan heuristic value to the clause file.
                        """
                        man_d = heuristic((x,y-1),problem,{})
                        f.write('manhattan_distance_heuristic(' + v + ',' + str(man_d) + ').\n')
                    """
                    Processing right of the node
                    """
                    if problem.walls[x][y + 1] is False:
                        temp = x + (problem.walls.width - 2) * (problem.walls.height - 2 - (y + 1))
                        if temp == goal:
                            v = 'finish'
                        elif temp == start:
                            v = 'start'
                        else:
                            v = 'c' + str(temp)
                        """
                        Adding the manhattan heuristic value to the clause file.
                        """
                        man_d = heuristic((x,y+1),problem,{})
                        f.write('manhattan_distance_heuristic(' + v + ',' + str(man_d) + ').\n')

    f.close()
    from searchAgents import direction_list
    from spade import pyxf
    import os
    """
    Building the XSB PROLOG Query
    """
    myXsb = pyxf.xsb("/home/vishal/Downloads/xsb/XSB/bin/xsb")
    myXsb.load(os.getcwd() + '/maze.P')
    myXsb.load(os.getcwd() + '/astar.P')
    myXsb.load(os.getcwd() + '/astar_heuristic.P')
    q_result = myXsb.query("astar(start,X)")
    result =  q_result[0]['X']
    result = result[1:]
    result = result[:-1]
    result = result.split(',')
    result = result[1:]
    result_list = list()
    result_list.append(direction_list[('start', result[0])])
    """
    Converting the list of actions returned by prolog into appropriate directions to be returned
    """
    for x in range(len(result) - 1):
        result_list.append(direction_list[(result[x], result[x + 1])])
    return result_list