Esempio n. 1
0
def main():
    # Example graph generation with dimension and probability
    g = map.generateMap(150, 0.2)
    manhattanPath = aStar(g, manhattanH)
    euclideanPath = aStar(g, euclideanH)
    bfsPath = bfs(g)
    dfsPath = dfs(g)
    bidirectionalBFSPath = bidirectionalBfs(g)

    # Example for visualizing path for graph g
    map.visualize(manhattanPath, g)
    map.visualize(euclideanPath, g)
    map.visualize(bfsPath, g)
    map.visualize(dfsPath, g)
    map.visualize(bidirectionalBFSPath, g)

    # Part 3 calls with visualization
    path, graph, og_path, og_graph = GenerateHardMaze.generateHardMazePathLength(
    )
    map.visualize(og_path, og_graph)
    map.visualize(path, graph)

    path2, graph2, og_path2, og_graph2 = GenerateHardMaze.generateHardMazeFringeSize(
    )
    map.visualize(og_path2, og_graph2)
    map.visualize(path2, graph2)

    path3, graph3, og_path3, og_graph3 = GenerateHardMaze.generateHardMazeNumberOfNodes(
    )
    map.visualize(og_path3, og_graph3)
    map.visualize(path3, graph3)

    # Example fire graph generation with dimension and probability
    fireG = map.generateFireMap(100, 0.3)

    # Strategies with Flammability rate q
    q = 0.1
    result1 = fire.strategy1(fireG, q)
    result2 = fire.strategy2(fireG, q)

    map.printPath(result1[0], result1[1])
    print("")
    map.printPath(result2[0], result2[1])

    # Example for visualizing path for fire graph g where the first element
    # in the result tuple is the path and second element is the final graph.
    map.visualizeFireMap(result1[0], result1[1])
    map.visualizeFireMap(result2[0], result2[1])
Esempio n. 2
0
def main():
    # Example graph generation with dimension and probability
    g = map.generateMap(150, 0.2)
    path = aStar(g, euclideanH)
    bfsPath = bfs(g)

    map.printPath(path, g)
    print(" ")
    map.printPath(bfsPath, g)
    print(" ")
    print(len(path), len(bfsPath))
Esempio n. 3
0
def main():
    print(
        "=========================================================================================="
    )
    print(" ")
    print("\t\t\tWelcome to Transport Suggester")
    print(" ")
    print(
        "=========================================================================================="
    )
    print()
    print("Please enter source and destination")
    print()
    print("As of now you have 20 choices: ")
    print("Ahmedabad\tBangalore\tBhopal\t\tChennai\t\tDelhi")
    print("Hyderabad\tIndore\t\tJaipur\t\tKanpur\t\tKolkata")
    print("Lucknow\t\tLudhiana\tMumbai\t\tNagpur\t\tPatna")
    print("Pune\t\tSurat\t\tThane\t\tVadodara\tVisakhapatnam")
    print()
    src = str(input("Source: ").strip())
    print()
    dst = str(input("Destination: ").strip())
    print()
    print("Would you like to keep things environment-friendly?")
    print("\t For Yes, enter '1'")
    print("\t For No, enter '0'")
    env_conscious = int(input("Answer: ").strip())
    print()
    print("Want it cheap?")
    print("\t For Yes, enter '1'")
    print("\t For No, enter '0'")
    budget_conscious = int(input("Answer: ").strip())
    print()
    print("Is there anything you would like to avoid?")
    print("\t Avoid the roads: enter '0'")
    print("\t Avoid travel by air: enter '1'")
    print("\t Avoid railways: enter '2'")
    avoid = int(input("Answer: ").strip())

    util.Createcsv()

    dist = search.aStar(src, dst, "PrintDetails")
    airTravel.getAirDetails(src, dst)
    railTravel.getRailDetails(src, dst)
    print()
    dtree.predictDtree(dist, env_conscious, budget_conscious, avoid)
    print()
    print(
        "=========================================================================================="
    )
    print("\t\t\tHave a safe trip !!")
    print()
Esempio n. 4
0
def isadmissible():
    with open("./Data/RoadData.csv", "r") as csvfile:
        reader = csv.reader(csvfile)
        for row in reader:
            start = row[0]
            end = row[1]
            details = search.aStar(start, end, "CheckHeuristic")

            if details[0].get(end) >= util.getHeuristic(start, details[1]):
                adm = True
            else:
                adm = False

    print("Admissible: " + str(adm))
Esempio n. 5
0
def strategy1(graph, q):
    # Get shortest path on graph
    path = search.aStar(graph, search.euclideanH)

    # Iterate over the path which represents moving over the shortest path
    for x in range(1, len(path)):
        i = path[x][0]
        j = path[x][1]

        # Spread the fire everytime we move on the path
        graph = fireTimeStep(graph, q)

        # Check if the current cell we are on is on fire
        if graph[i][j] == 2:
            return "Failure: No Path"

    return path, graph
Esempio n. 6
0
def isConsistent():
    with open("./Data/RoadData.csv", "r") as csvfile:
        reader = csv.reader(csvfile)
        for row in reader:
            start = row[0]
            end = row[1]
            details = search.aStar(start, end, "CheckHeuristic")
            finalpath = details[2]
            distance = details[0]
            for i in range(len(details[2]) - 1):
                if distance[finalpath[i + 1]] - distance[
                        finalpath[i]] >= util.getHeuristic(
                            finalpath[i + 1], details[1]) - util.getHeuristic(
                                finalpath[i], details[1]):
                    cons = True
                else:
                    cons = False
                    break

    print("Consistent: " + str(cons))
Esempio n. 7
0
def main():
    args = parse_args()
    if not args.gpu:
        os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
    gameState = game.GameState.fromFile(args.file)
    if not args.search:
        playing = game.Game(gameState, game.Game.actionFromPlayer())
    else:
        problem = problems.LevelProblem(gameState)
        if args.search == 'astar':
            searchFunction = search.aStar(search.distanceHeuristic)
        elif args.search == 'qlearning':
            qAgent = reinforcement.QAgent(alpha=0.9, gamma=0.6, epsilon=0.2)
            qAgent.fit(problem, args.trials)
            searchFunction = qAgent.search
        elif args.search == 'deepq':
            _, startState = problem.getStartState()
            model = reinforcement.getModel((len(startState), len(startState[0]), 4))
            if os.path.exists(args.load):
                model.load_weights(args.load)
            model.compile(loss = 'mse', optimizer = 'adam')
            deepQ = reinforcement.DeepQAgent(model, alpha=1.0, gamma=0.8, epsilon=0.3)
            if args.directory:
                trainingSet = problems.ProblemSet.fromDirectory(args.directory)
                deepQ.fitProblemSet(trainingSet, args.trials)
                deepQ.searchAll(trainingSet, record=True)
            else:
                deepQ.fit(problem, args.trials)
            deepQ.save(args.load)
            searchFunction = deepQ.search
        else:
            searchFunction = getattr(search, args.search)
        solution = searchFunction(problem)
        playing = game.Game(gameState, game.Game.actionFromList(solution))
    playing.run(pause=args.pause)
    if args.search:
        print('Nodes expanded: ', problem.expanded)
    def __init__(self, bzrc, algorithm):
        self.bzrc = bzrc
        self.algorithm = algorithm
        self.constants = self.bzrc.get_constants()
        self.commands = []
        bases = self.bzrc.get_bases()
        for base in bases:
            if base.color == self.constants['team']:
                self.base = Answer()
                self.base.x = (base.corner1_x + base.corner3_x) / 2
                self.base.y = (base.corner1_y + base.corner3_y) / 2
        self.update()
        self.past_position = {}
        self.goals = {}
        self.stuck = {}
        for tank in self.mytanks:
            self.past_position[tank.index] = tank.x, tank.y
            self.goals[tank.index] = None
            self.stuck[tank.index] = 0
        self.set_flag_goals()

        self.vertex_positions = []
        self.vertex_positions.append((self.base.x, self.base.y))
        self.obstacles = self.bzrc.get_obstacles()
        for obstacle in self.obstacles:
            for i in range(len(obstacle)):
                x = obstacle[i][0] - obstacle[(i + 2) % 4][0]
                y = obstacle[i][1] - obstacle[(i + 2) % 4][1]
                dist = math.sqrt(x**2 + y**2)
                self.vertex_positions.append((obstacle[i][0] + x / dist * 0,
                                              obstacle[i][1] + y / dist * 0))
        self.vertex_positions.append(self.goals[0])

        #print "self.vertex_positions = " + str(self.vertex_positions)

        self.adjacency_matrix = numpy.zeros(
            [len(self.vertex_positions),
             len(self.vertex_positions)])

        for i in range(len(self.obstacles)):
            for j in range(4):
                index = i * 4 + j + 1
                if j < 3:
                    self.adjacency_matrix[index][
                        index + 1] = self.adjacency_matrix[
                            index + 1][index] = math.sqrt(
                                (self.vertex_positions[index][0] -
                                 self.vertex_positions[index + 1][0])**2 +
                                (self.vertex_positions[index][1] -
                                 self.vertex_positions[index + 1][1])**2)
                else:
                    first_corner = i * 4 + 1
                    self.adjacency_matrix[index][
                        first_corner] = self.adjacency_matrix[first_corner][
                            index] = math.sqrt(
                                (self.vertex_positions[index][0] -
                                 self.vertex_positions[first_corner][0])**2 +
                                (self.vertex_positions[index][1] -
                                 self.vertex_positions[first_corner][1])**2)

        for i in range(len(self.vertex_positions)):
            for j in range(i + 1, len(self.vertex_positions)):
                if i == 0 or j == len(self.vertex_positions) - 1 or (
                        i - 1) / 4 != (j - 1) / 4:
                    #print "i = " + str(i)
                    #print "j = " + str(j)
                    xa = self.vertex_positions[i][0]
                    ya = self.vertex_positions[i][1]
                    xb = self.vertex_positions[j][0]
                    yb = self.vertex_positions[j][1]
                    #print "a = (" + str(xa) + ", " + str(ya) + ")"
                    #print "b = (" + str(xb) + ", " + str(yb) + ")"
                    intersect = False

                    for m in range(len(self.obstacles)):
                        if intersect:
                            break
                        for n in range(4):
                            index = m * 4 + n + 1
                            if index == i or index == j:
                                continue
                            xc = self.vertex_positions[index][0]
                            yc = self.vertex_positions[index][1]
                            #print "c = (" + str(xc) + ", " + str(yc) + ")"
                            if n < 3:
                                if index + 1 == i or index + 1 == j:
                                    continue
                                xd = self.vertex_positions[index + 1][0]
                                yd = self.vertex_positions[index + 1][1]
                            else:
                                first_corner = m * 4 + 1
                                if first_corner == i or first_corner == j:
                                    continue
                                xd = self.vertex_positions[first_corner][0]
                                yd = self.vertex_positions[first_corner][1]
                            #print "d = (" + str(xd) + ", " + str(yd) + ")"
                            if self.segments_intersect(xa, ya, xb, yb, xc, yc,
                                                       xd, yd):
                                #print "intersection"
                                #print "a = (" + str(xa) + ", " + str(ya) + ")"
                                #print "b = (" + str(xb) + ", " + str(yb) + ")"
                                #print "c = (" + str(xc) + ", " + str(yc) + ")"
                                #print "d = (" + str(xd) + ", " + str(yd) + ")"
                                intersect = True
                                break

                    if intersect:
                        self.adjacency_matrix[i][j] = self.adjacency_matrix[j][
                            i] = 0
                    else:
                        self.adjacency_matrix[i][j] = self.adjacency_matrix[j][
                            i] = math.sqrt((self.vertex_positions[i][0] -
                                            self.vertex_positions[j][0])**2 +
                                           (self.vertex_positions[i][1] -
                                            self.vertex_positions[j][1])**2)

        half_worldsize = int(self.constants['worldsize']) / 2
        tanklength = int(self.constants['tanklength'])
        for i in range(1, len(self.vertex_positions) - 1):
            if half_worldsize - self.vertex_positions[i][
                    0] < tanklength or half_worldsize + self.vertex_positions[i][
                        0] < tanklength or half_worldsize - self.vertex_positions[
                            i][1] < tanklength or half_worldsize + self.vertex_positions[
                                i][1] < tanklength:
                for j in range(len(self.vertex_positions)):
                    self.adjacency_matrix[i][j] = self.adjacency_matrix[j][
                        i] = 0

        numpy.set_printoptions(threshold=numpy.nan)
        #print "self.adjacency_matrix = " + str(self.adjacency_matrix)
        self.updateGraph()
        if self.algorithm == 'dfs':
            self.path = search.dfs(self.graph, 0,
                                   len(self.vertex_positions) - 1,
                                   self.obstacles, self.vertex_positions)
        elif self.algorithm == 'bfs':
            self.path = search.bfs(self.graph, 0,
                                   len(self.vertex_positions) - 1,
                                   self.obstacles, self.vertex_positions)
        else:
            self.path = search.aStar(self.graph, self.adjacency_matrix,
                                     self.vertex_positions, 0,
                                     len(self.vertex_positions) - 1,
                                     self.obstacles)
        self.plot_visibility_graph()

        for i in range(len(self.obstacles)):
            obstacle = self.obstacles[i]
            for j in range(len(obstacle)):
                x1 = obstacle[j][0] - obstacle[(j + 1) % 4][0]
                y1 = obstacle[j][1] - obstacle[(j + 1) % 4][1]
                dist1 = math.sqrt(x1**2 + y1**2)
                x1 /= dist1
                y1 /= dist1
                x2 = obstacle[j][0] - obstacle[(j + 3) % 4][0]
                y2 = obstacle[j][1] - obstacle[(j + 3) % 4][1]
                dist2 = math.sqrt(x2**2 + y2**2)
                x2 /= dist2
                y2 /= dist2
                self.vertex_positions[i * 4 + j +
                                      1] = ((obstacle[j][0] + (x1 + x2) * 10,
                                             obstacle[j][1] + (y1 + y2) * 10))

        self.current_goal_index = 1
        self.goals[0] = self.vertex_positions[self.path[
            self.current_goal_index]]
 def __init__(self, bzrc, algorithm):
     self.bzrc = bzrc
     self.algorithm = algorithm
     self.constants = self.bzrc.get_constants()
     self.commands = []
     bases = self.bzrc.get_bases()
     for base in bases:
         if base.color == self.constants['team']:
             self.base = Answer()
             self.base.x = (base.corner1_x+base.corner3_x)/2
             self.base.y = (base.corner1_y+base.corner3_y)/2
     self.update()
     self.past_position = {}
     self.goals = {}
     self.stuck = {}
     for tank in self.mytanks:
         self.past_position[tank.index] = tank.x, tank.y
         self.goals[tank.index] = None
         self.stuck[tank.index] = 0
     self.set_flag_goals()
     
     self.vertex_positions = []
     self.vertex_positions.append((self.base.x, self.base.y))
     self.obstacles = self.bzrc.get_obstacles()
     for obstacle in self.obstacles:
         for i in range(len(obstacle)):
             x = obstacle[i][0] - obstacle[(i + 2) % 4][0]
             y = obstacle[i][1] - obstacle[(i + 2) % 4][1]
             dist = math.sqrt(x ** 2 + y ** 2)
             self.vertex_positions.append((obstacle[i][0] + x / dist * 0, obstacle[i][1] + y / dist * 0))
     self.vertex_positions.append(self.goals[0])
     
     #print "self.vertex_positions = " + str(self.vertex_positions)
     
     self.adjacency_matrix = numpy.zeros([len(self.vertex_positions), len(self.vertex_positions)])
     
     for i in range(len(self.obstacles)):
         for j in range(4):
             index = i * 4 + j + 1
             if j < 3:
                 self.adjacency_matrix[index][index + 1] = self.adjacency_matrix[index + 1][index] = math.sqrt((self.vertex_positions[index][0] - self.vertex_positions[index + 1][0]) ** 2 + (self.vertex_positions[index][1] - self.vertex_positions[index + 1][1]) ** 2)
             else:
                 first_corner = i * 4 + 1
                 self.adjacency_matrix[index][first_corner] = self.adjacency_matrix[first_corner][index] = math.sqrt((self.vertex_positions[index][0] - self.vertex_positions[first_corner][0]) ** 2 + (self.vertex_positions[index][1] - self.vertex_positions[first_corner][1]) ** 2)
     
     for i in range(len(self.vertex_positions)):
         for j in range(i + 1, len(self.vertex_positions)):
             if i == 0 or j == len(self.vertex_positions) - 1 or (i - 1) / 4 != (j - 1) / 4:
                 #print "i = " + str(i)
                 #print "j = " + str(j)
                 xa = self.vertex_positions[i][0]
                 ya = self.vertex_positions[i][1]
                 xb = self.vertex_positions[j][0]
                 yb = self.vertex_positions[j][1]
                 #print "a = (" + str(xa) + ", " + str(ya) + ")"
                 #print "b = (" + str(xb) + ", " + str(yb) + ")"
                 intersect = False
                 
                 for m in range(len(self.obstacles)):
                     if intersect:
                         break
                     for n in range(4):
                         index = m * 4 + n + 1
                         if index == i or index == j:
                             continue
                         xc = self.vertex_positions[index][0]
                         yc = self.vertex_positions[index][1]
                         #print "c = (" + str(xc) + ", " + str(yc) + ")"
                         if n < 3:
                             if index + 1 == i or index + 1 == j:
                                 continue
                             xd = self.vertex_positions[index + 1][0]
                             yd = self.vertex_positions[index + 1][1]
                         else:
                             first_corner = m * 4 + 1
                             if first_corner == i or first_corner == j:
                                 continue
                             xd = self.vertex_positions[first_corner][0]
                             yd = self.vertex_positions[first_corner][1]
                         #print "d = (" + str(xd) + ", " + str(yd) + ")"
                         if self.segments_intersect(xa, ya, xb, yb, xc, yc, xd, yd):
                             #print "intersection"
                             #print "a = (" + str(xa) + ", " + str(ya) + ")"
                             #print "b = (" + str(xb) + ", " + str(yb) + ")"
                             #print "c = (" + str(xc) + ", " + str(yc) + ")"
                             #print "d = (" + str(xd) + ", " + str(yd) + ")"
                             intersect = True
                             break
                 
                 if intersect:
                     self.adjacency_matrix[i][j] = self.adjacency_matrix[j][i] = 0
                 else:
                     self.adjacency_matrix[i][j] = self.adjacency_matrix[j][i] = math.sqrt((self.vertex_positions[i][0] - self.vertex_positions[j][0]) ** 2 + (self.vertex_positions[i][1] - self.vertex_positions[j][1]) ** 2)
     
     half_worldsize = int(self.constants['worldsize']) / 2
     tanklength = int(self.constants['tanklength'])
     for i in range(1, len(self.vertex_positions) - 1):
         if half_worldsize - self.vertex_positions[i][0] < tanklength or half_worldsize + self.vertex_positions[i][0] < tanklength or half_worldsize - self.vertex_positions[i][1] < tanklength or half_worldsize + self.vertex_positions[i][1] < tanklength:
             for j in range(len(self.vertex_positions)):
                 self.adjacency_matrix[i][j] = self.adjacency_matrix[j][i] = 0
     
     numpy.set_printoptions(threshold=numpy.nan)
     #print "self.adjacency_matrix = " + str(self.adjacency_matrix)
     self.updateGraph()
     if self.algorithm == 'dfs':
         self.path = search.dfs(self.graph,0,len(self.vertex_positions) - 1,self.obstacles,self.vertex_positions)
     elif self.algorithm == 'bfs':
         self.path = search.bfs(self.graph,0,len(self.vertex_positions) - 1,self.obstacles,self.vertex_positions)
     else:
         self.path = search.aStar(self.graph,self.adjacency_matrix,self.vertex_positions,0,len(self.vertex_positions) - 1,self.obstacles)
     self.plot_visibility_graph()
             
     for i in range(len(self.obstacles)):
         obstacle = self.obstacles[i]
         for j in range(len(obstacle)):
             x1 = obstacle[j][0] - obstacle[(j + 1) % 4][0]
             y1 = obstacle[j][1] - obstacle[(j + 1) % 4][1]
             dist1 = math.sqrt(x1 ** 2 + y1 ** 2)
             x1 /= dist1
             y1 /= dist1
             x2 = obstacle[j][0] - obstacle[(j + 3) % 4][0]
             y2 = obstacle[j][1] - obstacle[(j + 3) % 4][1]
             dist2 = math.sqrt(x2 ** 2 + y2 ** 2)
             x2 /= dist2
             y2 /= dist2
             self.vertex_positions[i * 4 + j + 1] = ((obstacle[j][0] + (x1 + x2) * 10, obstacle[j][1] + (y1 + y2) * 10))
     
     self.current_goal_index = 1
     self.goals[0] = self.vertex_positions[self.path[self.current_goal_index]]