def graphHelper():
    dictionary = {}
    dictionary = readFile(openFile(), dictionary)
    start = tuple(dictionary.pop('start'))
    goal = tuple(dictionary.pop('finish'))

    dictionary = createNeighbors(dictionary)
    return (start, goal, UndirectedGraph(dictionary))
Ejemplo n.º 2
0
def get_graphs(file_name="graphs.txt", verbose=False):
    f = open(file_name)
    lines = [
        line.strip('\n').strip('\r').split(' ') for line in f.readlines()
        if line != '\n'
    ]
    f.close()

    graphs = {}
    g = None
    heuristicDict = None
    recordingHeuristic = False

    for line in lines:
        label = line[0]
        if label == '' or label == 'edges' or label[0] == '#':
            continue
        if recordingHeuristic:
            if label == 'heuristic-end':
                g.set_heuristic(heuristicDict)
                heuristicDict = None
                recordingHeuristic = False
            else:  #add entry to heuristicDict
                innerDict = {}
                for kvPair in line[1:]:
                    [key, value] = kvPair.split('-')
                    innerDict[key] = float(value)
                heuristicDict[label] = innerDict
        elif label == 'graph':
            if len(line) != 2:
                raise Exception(
                    "invalid graph line. Expected syntax: 'graph graphName'")
            g = UndirectedGraph()
            graphs[line[1]] = g
        elif label == 'nodes':
            if g.nodes != []:
                raise Exception("graph already has nodes list: \n" + str(g))
            g.nodes = line[1:]
        elif label == 'heuristic-start':
            recordingHeuristic = True
            heuristicDict = {}
        else:  #assume edge
            if len(line) == 2:  #unweighted edge
                g.join(line[0], line[1])
            elif len(line) == 3:  #weighted edge
                g.join(line[0], line[1], float(line[2]))
            else:
                raise Exception(
                    "invalid edge. Expected syntax: 'startNode endNode'" +
                    "OR 'startNode endNode edgeLength'")
        if verbose:
            print line

    if verbose:
        for graphName in sorted(graphs.keys()):
            print graphName, ":", graphs[graphName]

    return graphs
Ejemplo n.º 3
0
def readMazeFromFile(fileName):
    matrix = {}
    i = 0
    start = (0, 0)
    goal = (0, 0)
    with open(fileName) as f:
        start = tuple(map(int, f.readline().rstrip('\n').strip('()').split(',')))
        goal = tuple(map(int, f.readline().rstrip('\n').strip('()').split(',')))
        for line in f.readlines():
            line = line.rstrip('\n')
            j = 0
            for cost in line:
                if int(cost) != 0:
                    matrix[(j, i)] = int(cost)
                j = j + 1
            i = i + 1
    graph = Dict()
    for point in matrix.keys():
        entry = {point: {}}
        child1 = None
        child2 = None
        try:
            child1 = {(point[0], point[1] + 1): matrix[(point[0], point[1] + 1)]}
        except KeyError:
            pass
        try:
            child2 = {(point[0] + 1, point[1]): matrix[(point[0] + 1, point[1])]}
        except KeyError:
            pass
        if child1 is not None:
            entry[point].update(child1)
        if child2 is not None:
            entry[point].update(child2)

        graph.update(entry)
    undirGraph = UndirectedGraph(graph)
    undirGraph.locations = Dict()
    for i in undirGraph.nodes():
        undirGraph.locations.update({i: i})
    graphProblem = ManhattenGraphProblem(start, goal, undirGraph)
    return graphProblem
Ejemplo n.º 4
0
def get_graphs(file_name="graphs.txt", verbose=False):
    f = open(file_name)
    lines = [line.strip('\n').strip('\r').split(' ')
             for line in f.readlines() if line != '\n']
    f.close()

    graphs = {}
    g = None
    heuristicDict = None
    recordingHeuristic = False

    for line in lines:
        label = line[0]
        if label == '' or label == 'edges' or label[0] == '#':
            continue
        if recordingHeuristic:
            if label == 'heuristic-end':
                g.set_heuristic(heuristicDict)
                heuristicDict = None
                recordingHeuristic = False
            else: #add entry to heuristicDict
                innerDict = {}
                for kvPair in line[1:]:
                    [key, value] = kvPair.split('-')
                    innerDict[key] = float(value)
                heuristicDict[label] = innerDict
        elif label == 'graph':
            if len(line) != 2:
                raise Exception("invalid graph line. Expected syntax: 'graph graphName'")
            g = UndirectedGraph()
            graphs[line[1]] = g
        elif label == 'nodes':
            if g.nodes != []:
                raise Exception("graph already has nodes list: \n" + str(g))
            g.nodes = line[1:]
        elif label == 'heuristic-start':
            recordingHeuristic = True
            heuristicDict = {}
        else: #assume edge
            if len(line) == 2: #unweighted edge
                g.join(line[0], line[1])
            elif len(line) == 3: #weighted edge
                g.join(line[0], line[1], float(line[2]))
            else:
                raise Exception("invalid edge. Expected syntax: 'startNode endNode'"
                                + "OR 'startNode endNode edgeLength'")        
        if verbose:
            print line

    if verbose:
        for graphName in sorted(graphs.keys()):
            print graphName, ":", graphs[graphName]

    return graphs
 def __init__(self, env):
     """
     Constructor to initialise the environment for the simple agent
     """
     # Use the parser to get the location in state space,
     # the set of actions in each state, the initial starting
     # state and the terminal (goal) state
     w_1, x_1, y_1, z_1 = env2statespace(env)
     self.state_space_locations = w_1
     self.state_space_actions = x_1
     self.state_initial_id = y_1
     self.state_goal_id = z_1
     self.map = UndirectedGraph(self.state_space_actions)
     # Create a new GraphProblem instance to specify the problem in a format
     # in which it can be sovled
     self.problem = GraphProblem('{0}'.format(self.state_initial_id),
                                 '{0}'.format(self.state_goal_id), self.map)
Ejemplo n.º 6
0
    testanswer=lambda val, original_val=None: val == extensions_test2_answer,
    expected_val=extensions_test2_answer,
    name='extensions')

extensions_test3_answer = [['S', 'A', 'C', 'E',
                            'D'], ['S', 'A', 'C', 'E', 'F'],
                           ['S', 'A', 'C', 'E', 'G']]
make_test(
    type='FUNCTION',  #TEST 10
    getargs=[GRAPH_2, ['S', 'A', 'C', 'E']],
    testanswer=lambda val, original_val=None: val == extensions_test3_answer,
    expected_val=extensions_test3_answer,
    name='extensions')

# Checks intentionally-unordered neighbors in extensions
extensions_test4_graph = UndirectedGraph(
    list("abcdefgh"), edges=[Edge("a", l, 0) for l in "hgfebcd"])
extensions_test4_answer = [["a", l] for l in "bcdefgh"]
make_test(
    type='FUNCTION',  #TEST 11
    getargs=[extensions_test4_graph, ["a"]],
    testanswer=lambda val, original_val=None: val == extensions_test4_answer,
    expected_val=extensions_test4_answer,
    name='extensions')

sortby_test1_answer = ['c', 'a', 'b', 'd']
make_test(
    type='FUNCTION',  #TEST 12
    getargs=[GRAPH_1, 'c', ['d', 'a', 'b', 'c']],
    testanswer=lambda val, original_val=None: val == sortby_test1_answer,
    expected_val=sortby_test1_answer,
    name='sort_by_heuristic')
Ejemplo n.º 7
0
import search 
from search import UndirectedGraph, breadth_first_graph_search, greedy_best_first_graph_search

from search import * #semua kelas keambil

romania_map = UndirectedGraph(dict(										#jarak kota yang saling adjacent
    Arad=dict(Zerind=75, Sibiu=140, Timisoara=118),
    Bucharest=dict(Urziceni=85, Pitesti=101, Giurgiu=90, Fagaras=211),
    Craiova=dict(Drobeta=120, Rimnicu=146, Pitesti=138),
    Drobeta=dict(Mehadia=75),
    Eforie=dict(Hirsova=86),
    Fagaras=dict(Sibiu=99),
    Hirsova=dict(Urziceni=98),
    Iasi=dict(Vaslui=92, Neamt=87),
    Lugoj=dict(Timisoara=111, Mehadia=70),
    Oradea=dict(Zerind=71, Sibiu=151),
    Pitesti=dict(Rimnicu=97),
    Rimnicu=dict(Sibiu=80),
    Urziceni=dict(Vaslui=142)))
	
romania_map.locations = dict(
    Arad=(91, 492), Bucharest=(400, 327), Craiova=(253, 288),
    Drobeta=(165, 299), Eforie=(562, 293), Fagaras=(305, 449),
    Giurgiu=(375, 270), Hirsova=(534, 350), Iasi=(473, 506),
    Lugoj=(165, 379), Mehadia=(168, 339), Neamt=(406, 537),
    Oradea=(131, 571), Pitesti=(320, 368), Rimnicu=(233, 410),
    Sibiu=(207, 457), Timisoara=(94, 410), Urziceni=(456, 350),
    Vaslui=(509, 444), Zerind=(108, 531))
    
    
romania_problem = GraphProblem('Arad', 'Bucharest', romania_map)	#romania map jalur efektif dari state awal ke state akhir
Ejemplo n.º 8
0
def get_graphs(file_name="graphs.txt", verbose=False):
    with open('/Users/ddandhh/Desktop/AI6034/lab2/' + file_name, 'r') as f:
        line_strings = [
            line.strip('\n').strip('\r') for line in f.readlines()
            if (line != '\n' and line[0] != '#')
        ]
    lines = []
    for line_str in line_strings:
        if '#' not in line_str:
            lines.append(line_str.split(' '))
        else:
            i = line_str.find('#')
            lines.append(line_str[:i].split(' '))

    graphs = {}
    g = None
    heuristicDict = None
    recordingHeuristic = False

    for line in lines:
        label = line[0]
        if label == '' or label == 'edges':
            continue
        if recordingHeuristic:
            if label == 'heuristic-end':
                g.set_heuristic(heuristicDict)
                heuristicDict = None
                recordingHeuristic = False
            else:  #add entry to heuristicDict
                innerDict = {}
                for kvPair in line[1:]:
                    [key, value] = kvPair.split('-')
                    innerDict[key] = float(value)
                heuristicDict[label] = innerDict
        elif label == 'graph':
            if len(line) != 2:
                raise Exception(
                    "invalid graph line. Expected syntax: 'graph graphName'")
            g = UndirectedGraph()
            graphs[line[1]] = g
        elif label == 'nodes':
            if g.nodes != []:
                raise Exception("graph already has nodes list: \n" + str(g))
            g.nodes = line[1:]
        elif label == 'heuristic-start':
            recordingHeuristic = True
            heuristicDict = {}
        else:  #assume edge
            try:
                if len(line) == 2:  #unweighted edge
                    g.join(line[0], line[1])
                elif len(line) == 3:  #weighted edge
                    g.join(line[0], line[1], float(line[2]))
            except:
                raise Exception(
                    "invalid edge. Expected syntax: 'startNode endNode' " +
                    "OR 'startNode endNode edgeLength'")
        if verbose:
            print(line)

    if verbose:
        for graphName in sorted(graphs.keys()):
            print(graphName, ":", graphs[graphName])

    return graphs
Ejemplo n.º 9
0
import search
from search import UndirectedGraph, breadth_first_graph_search, greedy_best_first_graph_search

from search import *  #semua kelas keambil

romania_map = UndirectedGraph(
    dict(  #jarak kota yang saling adjacent
        Manchester=dict(Liverpool=30, Sheffield=40),
        Liverpool=dict(Nottingham=110, Shrewsbury=70),
        Sheffield=dict(Nottingham=40),
        Shrewsbury=dict(Bham=50, Aberystwyth=80, Cardiff=110),
        Nottingham=dict(Bham=50, Oxford=100),
        Bham=dict(Oxford=70, Bristol=90),
        Aberystwyth=dict(Cardiff=120),
        Oxford=dict(Southampton=70),
        Cardif=dict(Bristol=50),
        Bristol=dict(Southampton=80)))

romania_problem = GraphProblem(
    'Manchester', 'Southampton',
    romania_map)  #romania map jalur efektif dari state awal ke state akhir

#mau pake bfs
a = [node.state for node in breadth_first_graph_search(romania_problem).path()]
print(a)

#mau pake dfs
a = [node.state for node in depth_first_graph_search(romania_problem).path()]
print(a)

#kalo inform kita tau jarak pasti di petanya
Ejemplo n.º 10
0
from search import UndirectedGraph, GraphProblem, Graph
from search import InstrumentedProblem, compare_searchers
from search import uniform_cost_search, greedy_best_first_graph_search, astar_search
from utils import Dict, euclidean

#______________________________________________________________________________
#Define the Romania problem by simply creating the graph data structure directly

#edge or g costs based on actual travel distances
romania = UndirectedGraph(
    Dict(A=Dict(Z=75, S=140, T=118),
         B=Dict(U=85, P=101, G=90, F=211),
         C=Dict(D=120, R=146, P=138),
         D=Dict(M=75),
         E=Dict(H=86),
         F=Dict(S=99),
         H=Dict(U=98),
         I=Dict(V=92, N=87),
         L=Dict(T=111, M=70),
         O=Dict(Z=71, S=151),
         P=Dict(R=97),
         R=Dict(S=80),
         U=Dict(V=142)))

#heuristic or h costs based on straight-line distance
romania.locations = Dict(A=(91, 492),
                         B=(400, 327),
                         C=(253, 288),
                         D=(165, 299),
                         E=(562, 293),
                         F=(305, 449),
                         G=(375, 270),
Ejemplo n.º 11
0
Archivo: tsp.py Proyecto: bff3/cs344
    for i in range(len(vertexstring) - 1):
        vertex_dict = {}
        for k in vertexstring[i + 1:]:
            vertex_dict[k] = rnd.randint(1, maxdist)
        graph_dict[vertexstring[i]] = vertex_dict
    return graph_dict

if __name__ == '__main__':

    # invalid_it = ['C','D','B','A']
    # valid_it = ['C','A','B','D']
    # simpleTSP = TSP(invalid_it, simple_map)
    # print(hill_climbing(simpleTSP))
    graph_dict = gen_graph(vertexstring='ABCDEFGHIJKLMNOPQRSTUVWXYZ')
    print(graph_dict)
    myGraph = UndirectedGraph(graph_dict)
    myTSP = TSP(get_city_list(myGraph), myGraph)
    values = []
    for _ in range(1000):
        hill_climbing_solution = hill_climbing(myTSP)
        values.append(myTSP.value(hill_climbing_solution))
        # print(hill_climbing_solution)
        # print(myTSP.value(hill_climbing_solution))
    print(max(values))

    annealing_solution = simulated_annealing(myTSP, exp_schedule(k=20, lam=0.005, limit=100000))
    print(annealing_solution)
    print(myTSP.value(annealing_solution))


Ejemplo n.º 12
0
"""
This implements a travelling salesperson problem, which is solved using local search,
    with both AIMA hill-climbing and simulated annealing

Created by: Tyler Poel, for CS344, Homework01, at Calvin University
Date: February 25, 2020
"""

from search import UndirectedGraph, Problem, hill_climbing, simulated_annealing, exp_schedule
import random

# Uses an undirected graph to create the "world" in which our problem resides.
TSP_world = UndirectedGraph(
    dict(A=dict(B=1, C=7, D=3, E=6, F=22),
         B=dict(C=5, D=2, E=14, F=3),
         C=dict(D=8, E=12, F=15),
         D=dict(E=10, F=25),
         E=dict(F=20)))

romania = UndirectedGraph(
    dict(arad=dict(zerind=75, sibiu=140, timisoara=118),
         bucharest=dict(urziceni=85, pitesti=101, giurgiu=90, fagaras=211),
         craiova=dict(dobreta=120, rimnicuvilcea=146, pitesti=138),
         dobreta=dict(mehadia=75),
         eforie=dict(hirsova=86),
         fagaras=dict(sibiu=99),
         hirsova=dict(urziceni=98),
         iasi=dict(vaslui=92, neamt=87),
         lugoj=dict(timisoara=111, mehadia=70),
         oradea=dict(zerind=71, sibiu=151),
         pitesti=dict(rimnicuvilcea=97),
Ejemplo n.º 13
0
    def value(self, state):
        oldLocation = self.locations.get(self.currentState)
        newLocation = self.locations.get(state)
        value = self.cost - self.calculate_distance(oldLocation, newLocation)
        return value


if __name__ == '__main__':
    romania = UndirectedGraph(
        dict(arad=dict(zerind=75, sibiu=140, timisoara=118),
             bucharest=dict(urziceni=85, pitesti=101, giurgiu=90, fagaras=211),
             craiova=dict(dobreta=120, rimnicuvilcea=146, pitesti=138),
             dobreta=dict(mehadia=75),
             eforie=dict(hirsova=86),
             fagaras=dict(sibiu=99),
             hirsova=dict(urziceni=98),
             iasi=dict(vaslui=92, neamt=87),
             lugoj=dict(timisoara=111, mehadia=70),
             oradea=dict(zerind=71, sibiu=151),
             pitesti=dict(rimnicuvilcea=97),
             rimnicuvilcea=dict(sibiu=80),
             urziceni=dict(vaslui=142)))

    locations = dict(arad=(91, 492),
                     bucharest=(400, 327),
                     craiova=(253, 288),
                     dobreta=(165, 299),
                     eforie=(562, 293),
                     fagaras=(305, 449),
                     giurgiu=(375, 270),
                     hirsova=(534, 350),