Advertisement
TDimovska

[AI] A trip through Germany

May 30th, 2019
274
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 22.26 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. import bisect
  3.  
  4. """
  5. Defining a class for the problem structure that we will solve with a search.
  6. The Problem class is an abstract class from which we make inheritance to define the basic
  7. characteristics of every problem we want to solve
  8. """
  9.  
  10.  
  11. class Problem:
  12.     def __init__(self, initial, goal=None):
  13.         self.initial = initial
  14.         self.goal = goal
  15.  
  16.     def successor(self, state):
  17.         """Given a state, return a dictionary of {action : state} pairs reachable
  18.        from this state. If there are many successors, consider an iterator
  19.        that yields the successors one at a time, rather than building them
  20.        all at once.
  21.  
  22.        :param state: given state
  23.        :return:  dictionary of {action : state} pairs reachable
  24.                  from this state
  25.        :rtype: dict
  26.        """
  27.         raise NotImplementedError
  28.  
  29.     def actions(self, state):
  30.         """Given a state, return a list of all actions possible
  31.        from that state
  32.  
  33.        :param state: given state
  34.        :return: list of actions
  35.        :rtype: list
  36.        """
  37.         raise NotImplementedError
  38.  
  39.     def result(self, state, action):
  40.         """Given a state and action, return the resulting state
  41.  
  42.        :param state: given state
  43.        :param action: given action
  44.        :return: resulting state
  45.        """
  46.         raise NotImplementedError
  47.  
  48.     def goal_test(self, state):
  49.         """Return True if the state is a goal. The default method compares
  50.        the state to self.goal, as specified in the constructor. Implement
  51.        this method if checking against a single self.goal is not enough.
  52.  
  53.        :param state: given state
  54.        :return: is the given state a goal state
  55.        :rtype: bool
  56.        """
  57.         return state == self.goal
  58.  
  59.     def path_cost(self, c, state1, action, state2):
  60.         """Return the cost of a solution path that arrives at state2 from state1
  61.        via action, assuming cost c to get up to state1. If the problem is such
  62.        that the path doesn't matter, this function will only look at state2. 
  63.        If the path does matter, it will consider c and maybe state1 and action.
  64.        The default method costs 1 for every step in the path.
  65.  
  66.        :param c: cost of the path to get up to state1
  67.        :param state1: given current state
  68.        :param action: action that needs to be done
  69.        :param state2: state to arrive to
  70.        :return: cost of the path after executing the action
  71.        :rtype: float
  72.        """
  73.         return c + 1
  74.  
  75.     def value(self):
  76.         """For optimization problems, each state has a value.
  77.        Hill-climbing and related algorithms try to maximize this value.
  78.  
  79.        :return: state value
  80.        :rtype: float
  81.        """
  82.         raise NotImplementedError
  83.  
  84.  
  85. """
  86. Definition of the class for node structure of the search.
  87. The class Node is not inherited
  88. """
  89.  
  90.  
  91. class Node:
  92.     def __init__(self, state, parent=None, action=None, path_cost=0):
  93.         """Create node from the search tree,  obtained from the parent by
  94.        taking the action
  95.  
  96.        :param state: current state
  97.        :param parent: parent state
  98.        :param action: action
  99.        :param path_cost: path cost
  100.        """
  101.         self.state = state
  102.         self.parent = parent
  103.         self.action = action
  104.         self.path_cost = path_cost
  105.         self.depth = 0  # search depth
  106.         if parent:
  107.             self.depth = parent.depth + 1
  108.  
  109.     def __repr__(self):
  110.         return "<Node %s>" % (self.state,)
  111.  
  112.     def __lt__(self, node):
  113.         return self.state < node.state
  114.  
  115.     def expand(self, problem):
  116.         """List the nodes reachable in one step from this node.
  117.  
  118.        :param problem: given problem
  119.        :return: list of available nodes in one step
  120.        :rtype: list(Node)
  121.        """
  122.         return [self.child_node(problem, action)
  123.                 for action in problem.actions(self.state)]
  124.  
  125.     def child_node(self, problem, action):
  126.         """Return a child node from this node
  127.  
  128.        :param problem: given problem
  129.        :param action: given action
  130.        :return: available node  according to the given action
  131.        :rtype: Node
  132.        """
  133.         next_state = problem.result(self.state, action)
  134.         return Node(next_state, self, action,
  135.                     problem.path_cost(self.path_cost, self.state,
  136.                                       action, next_state))
  137.  
  138.     def solution(self):
  139.         """Return the sequence of actions to go from the root to this node.
  140.  
  141.        :return: sequence of actions
  142.        :rtype: list
  143.        """
  144.         return [node.action for node in self.path()[1:]]
  145.  
  146.     def solve(self):
  147.         """Return the sequence of states to go from the root to this node.
  148.  
  149.        :return: list of states
  150.        :rtype: list
  151.        """
  152.         return [node.state for node in self.path()[0:]]
  153.  
  154.     def path(self):
  155.         """Return a list of nodes forming the path from the root to this node.
  156.  
  157.        :return: list of states from the path
  158.        :rtype: list(Node)
  159.        """
  160.         x, result = self, []
  161.         while x:
  162.             result.append(x)
  163.             x = x.parent
  164.         result.reverse()
  165.         return result
  166.  
  167.     """We want the queue of nodes at breadth_first_search or
  168.     astar_search to not contain states-duplicates, so the nodes that
  169.     contain the same condition we treat as the same. [Problem: this can
  170.     not be desirable in other situations.]"""
  171.  
  172.     def __eq__(self, other):
  173.         return isinstance(other, Node) and self.state == other.state
  174.  
  175.     def __hash__(self):
  176.         return hash(self.state)
  177.  
  178.  
  179. """
  180. Definitions of helper structures for storing the list of generated, but not checked nodes
  181. """
  182.  
  183.  
  184. class Queue:
  185.     """Queue is an abstract class/interface. There are three types:
  186.         Stack(): Last In First Out Queue (stack).
  187.         FIFOQueue(): First In First Out Queue.
  188.         PriorityQueue(order, f): QQueue in sorted order (default min-first).
  189.     """
  190.  
  191.     def __init__(self):
  192.         raise NotImplementedError
  193.  
  194.     def append(self, item):
  195.         """Adds the item into the queue
  196.  
  197.        :param item: given element
  198.        :return: None
  199.        """
  200.         raise NotImplementedError
  201.  
  202.     def extend(self, items):
  203.         """Adds the items into the queue
  204.  
  205.        :param items: given elements
  206.        :return: None
  207.        """
  208.         raise NotImplementedError
  209.  
  210.     def pop(self):
  211.         """Returns the first element of the queue
  212.  
  213.        :return: first element
  214.        """
  215.         raise NotImplementedError
  216.  
  217.     def __len__(self):
  218.         """Returns the number of elements in the queue
  219.  
  220.        :return: number of elements in the queue
  221.        :rtype: int
  222.        """
  223.         raise NotImplementedError
  224.  
  225.     def __contains__(self, item):
  226.         """Check if the queue contains the element item
  227.  
  228.        :param item: given element
  229.        :return: whether the queue contains the item
  230.        :rtype: bool
  231.        """
  232.         raise NotImplementedError
  233.  
  234.  
  235. class Stack(Queue):
  236.     """Last-In-First-Out Queue."""
  237.  
  238.     def __init__(self):
  239.         self.data = []
  240.  
  241.     def append(self, item):
  242.         self.data.append(item)
  243.  
  244.     def extend(self, items):
  245.         self.data.extend(items)
  246.  
  247.     def pop(self):
  248.         return self.data.pop()
  249.  
  250.     def __len__(self):
  251.         return len(self.data)
  252.  
  253.     def __contains__(self, item):
  254.         return item in self.data
  255.  
  256.  
  257. class FIFOQueue(Queue):
  258.     """First-In-First-Out Queue."""
  259.  
  260.     def __init__(self):
  261.         self.data = []
  262.  
  263.     def append(self, item):
  264.         self.data.append(item)
  265.  
  266.     def extend(self, items):
  267.         self.data.extend(items)
  268.  
  269.     def pop(self):
  270.         return self.data.pop(0)
  271.  
  272.     def __len__(self):
  273.         return len(self.data)
  274.  
  275.     def __contains__(self, item):
  276.         return item in self.data
  277.  
  278.  
  279. class PriorityQueue(Queue):
  280.     """A queue in which the minimum (or maximum) element is returned first
  281.      (as determined by f and order). This structure is used in
  282.      informed search"""
  283.  
  284.     def __init__(self, order=min, f=lambda x: x):
  285.         """
  286.        :param order: sorting function, if order is min, returns the element
  287.                       with minimal f (x); if the order is max, then returns the
  288.                      element with maximum f (x).
  289.        :param f: function f(x)
  290.        """
  291.         assert order in [min, max]
  292.         self.data = []
  293.         self.order = order
  294.         self.f = f
  295.  
  296.     def append(self, item):
  297.         bisect.insort_right(self.data, (self.f(item), item))
  298.  
  299.     def extend(self, items):
  300.         for item in items:
  301.             bisect.insort_right(self.data, (self.f(item), item))
  302.  
  303.     def pop(self):
  304.         if self.order == min:
  305.             return self.data.pop(0)[1]
  306.         return self.data.pop()[1]
  307.  
  308.     def __len__(self):
  309.         return len(self.data)
  310.  
  311.     def __contains__(self, item):
  312.         return any(item == pair[1] for pair in self.data)
  313.  
  314.     def __getitem__(self, key):
  315.         for _, item in self.data:
  316.             if item == key:
  317.                 return item
  318.  
  319.     def __delitem__(self, key):
  320.         for i, (value, item) in enumerate(self.data):
  321.             if item == key:
  322.                 self.data.pop(i)
  323.  
  324.  
  325. import sys
  326.  
  327. """
  328. Uninformed tree search.
  329. Within the tree we do not solve the loops.
  330. """
  331.  
  332.  
  333. def tree_search(problem, fringe):
  334.     """Search through the successors of a problem to find a goal.
  335.  
  336.    :param problem: given problem
  337.    :param fringe:  empty queue
  338.    :return: Node
  339.    """
  340.     fringe.append(Node(problem.initial))
  341.     while fringe:
  342.         node = fringe.pop()
  343.         print(node.state)
  344.         if problem.goal_test(node.state):
  345.             return node
  346.         fringe.extend(node.expand(problem))
  347.     return None
  348.  
  349.  
  350. def breadth_first_tree_search(problem):
  351.     """Search the shallowest nodes in the search tree first.
  352.  
  353.    :param problem: given problem
  354.    :return: Node
  355.    """
  356.     return tree_search(problem, FIFOQueue())
  357.  
  358.  
  359. def depth_first_tree_search(problem):
  360.     """Search the deepest nodes in the search tree first.
  361.  
  362.    :param problem: given problem
  363.    :return: Node
  364.    """
  365.     return tree_search(problem, Stack())
  366.  
  367.  
  368. """
  369. Uninformed graph search
  370. The main difference is that here we do not allow loops,
  371. i.e. repetition of states
  372. """
  373.  
  374.  
  375. def graph_search(problem, fringe):
  376.     """Search through the successors of a problem to find a goal.
  377.      If two paths reach a state, only use the best one.
  378.  
  379.    :param problem: given problem
  380.    :param fringe: empty queue
  381.    :return: Node
  382.    """
  383.     closed = set()
  384.     fringe.append(Node(problem.initial))
  385.     while fringe:
  386.         node = fringe.pop()
  387.         if problem.goal_test(node.state):
  388.             return node
  389.         if node.state not in closed:
  390.             closed.add(node.state)
  391.             fringe.extend(node.expand(problem))
  392.     return None
  393.  
  394.  
  395. def breadth_first_graph_search(problem):
  396.     """Search the shallowest nodes in the search tree first.
  397.  
  398.    :param problem: given problem
  399.    :return: Node
  400.    """
  401.     return graph_search(problem, FIFOQueue())
  402.  
  403.  
  404. def depth_first_graph_search(problem):
  405.     """Search the deepest nodes in the search tree first.
  406.  
  407.    :param problem: given problem
  408.    :return: Node
  409.    """
  410.     return graph_search(problem, Stack())
  411.  
  412.  
  413. def depth_limited_search(problem, limit=50):
  414.     def recursive_dls(node, problem, limit):
  415.         """Helper function for depth limited"""
  416.         cutoff_occurred = False
  417.         if problem.goal_test(node.state):
  418.             return node
  419.         elif node.depth == limit:
  420.             return 'cutoff'
  421.         else:
  422.             for successor in node.expand(problem):
  423.                 result = recursive_dls(successor, problem, limit)
  424.                 if result == 'cutoff':
  425.                     cutoff_occurred = True
  426.                 elif result is not None:
  427.                     return result
  428.         if cutoff_occurred:
  429.             return 'cutoff'
  430.         return None
  431.  
  432.     return recursive_dls(Node(problem.initial), problem, limit)
  433.  
  434.  
  435. def iterative_deepening_search(problem):
  436.     for depth in range(sys.maxsize):
  437.         result = depth_limited_search(problem, depth)
  438.         if result is not 'cutoff':
  439.             return result
  440.  
  441.  
  442. def uniform_cost_search(problem):
  443.     """Search the nodes in the search tree with lowest cost first."""
  444.     return graph_search(problem, PriorityQueue(min, lambda a: a.path_cost))
  445.  
  446.  
  447. from sys import maxsize as infinity
  448.  
  449. """
  450. Informed graph search.
  451. """
  452.  
  453.  
  454. def memoize(fn, slot=None):
  455.     """ Store the calculated value for any arguments list. If a
  456.    slot is specified, store the result in that slot in the first
  457.    argument. If slot is false, store the results in a dictionary.
  458.  
  459.    :param fn: given function
  460.    :param slot: name of the attribute for saving the function results
  461.    :return: modified function for storing the results
  462.    """
  463.     if slot:
  464.         def memoized_fn(obj, *args):
  465.             if hasattr(obj, slot):
  466.                 return getattr(obj, slot)
  467.             else:
  468.                 val = fn(obj, *args)
  469.                 setattr(obj, slot, val)
  470.                 return val
  471.     else:
  472.         def memoized_fn(*args):
  473.             if args not in memoized_fn.cache:
  474.                 memoized_fn.cache[args] = fn(*args)
  475.             return memoized_fn.cache[args]
  476.  
  477.         memoized_fn.cache = {}
  478.     return memoized_fn
  479.  
  480.  
  481. def best_first_graph_search(problem, f):
  482.     """The idea of Best First Search is to use an evaluation function
  483.    to decide which adjacent is most promising and then explore.
  484.  
  485.    :param problem: given problem
  486.    :param f: given heuristic function
  487.    :return: Node or None
  488.    """
  489.     f = memoize(f, 'f')
  490.     node = Node(problem.initial)
  491.     if problem.goal_test(node.state):
  492.         return node
  493.     frontier = PriorityQueue(min, f)
  494.     frontier.append(node)
  495.     explored = set()
  496.     while frontier:
  497.         node = frontier.pop()
  498.         if problem.goal_test(node.state):
  499.             return node
  500.         explored.add(node.state)
  501.         for child in node.expand(problem):
  502.             if child.state not in explored and child not in frontier:
  503.                 frontier.append(child)
  504.             elif child in frontier:
  505.                 incumbent = frontier[child]
  506.                 if f(child) < f(incumbent):
  507.                     del frontier[incumbent]
  508.                     frontier.append(child)
  509.     return None
  510.  
  511.  
  512. def greedy_best_first_graph_search(problem, h=None):
  513.     """ Greedy best-first search is implemented with f(n) = h(n).
  514.  
  515.    :param problem: given problem
  516.    :param h: given heuristic function
  517.    :return: Node or None
  518.    """
  519.     h = memoize(h or problem.h, 'h')
  520.     return best_first_graph_search(problem, h)
  521.  
  522.  
  523. def astar_search(problem, h=None):
  524.     """ A* search is best-first graph search where f(n) = g(n) + h(n).
  525.  
  526.    :param problem: given problem
  527.    :param h: given heuristic function
  528.    :return: Node or None
  529.    """
  530.     h = memoize(h or problem.h, 'h')
  531.     return best_first_graph_search(problem, lambda n: n.path_cost + h(n))
  532.  
  533.  
  534. def recursive_best_first_search(problem, h=None):
  535.     """ Recursive best first search - limits recursion by
  536.    keeping track of the f-value of the best alternative
  537.    path from any ancestor node (one step look-ahead).
  538.  
  539.    :param problem: given problem
  540.    :param h: given heuristic function
  541.    :return: Node or None
  542.    """
  543.     h = memoize(h or problem.h, 'h')
  544.  
  545.     def RBFS(problem, node, flimit):
  546.         if problem.goal_test(node.state):
  547.             return node, 0  # (the second value is not important)
  548.         successors = node.expand(problem)
  549.         if len(successors) == 0:
  550.             return None, infinity
  551.         for s in successors:
  552.             s.f = max(s.path_cost + h(s), node.f)
  553.         while True:
  554.             # Sort them according to the lowest f value
  555.             successors.sort(key=lambda x: x.f)
  556.             best = successors[0]
  557.             if best.f > flimit:
  558.                 return None, best.f
  559.             if len(successors) > 1:
  560.                 alternative = successors[1].f
  561.             else:
  562.                 alternative = infinity
  563.             result, best.f = RBFS(problem, best, min(flimit, alternative))
  564.             if result is not None:
  565.                 return result, best.f
  566.  
  567.     node = Node(problem.initial)
  568.     node.f = h(node)
  569.     result, bestf = RBFS(problem, node, infinity)
  570.     return result
  571.  
  572.  
  573. import math
  574. import random
  575.  
  576.  
  577. def distance(a, b):
  578.     """The distance between two (x, y) points."""
  579.     return math.hypot((a[0] - b[0]), (a[1] - b[1]))
  580.  
  581.  
  582. class Graph:
  583.     """A graph connects nodes (verticies) by edges (links).  Each edge can also
  584.    have a length associated with it.  The constructor call is something like:
  585.        g = Graph({'A': {'B': 1, 'C': 2})
  586.    this makes a graph with 3 nodes, A, B, and C, with an edge of length 1 from
  587.    A to B,  and an edge of length 2 from A to C.  You can also do:
  588.        g = Graph({'A': {'B': 1, 'C': 2}, directed=False)
  589.    This makes an undirected graph, so inverse links are also added. The graph
  590.    stays undirected; if you add more links with g.connect('B', 'C', 3), then
  591.    inverse link is also added.  You can use g.nodes() to get a list of nodes,
  592.    g.get('A') to get a dict of links out of A, and g.get('A', 'B') to get the
  593.    length of the link from A to B.  'Lengths' can actually be any object at
  594.    all, and nodes can be any hashable object."""
  595.  
  596.     def __init__(self, dictionary=None, directed=True):
  597.         self.dict = dictionary or {}
  598.         self.directed = directed
  599.         if not directed:
  600.             self.make_undirected()
  601.         else:
  602.             # add empty edges dictionary for those nodes that do not
  603.             # have edges and are not included in the dictionary as keys
  604.             nodes_no_edges = list({y for x in self.dict.values()
  605.                                    for y in x if y not in self.dict})
  606.             for node in nodes_no_edges:
  607.                 self.dict[node] = {}
  608.  
  609.     def make_undirected(self):
  610.         """Make a digraph into an undirected graph by adding symmetric edges."""
  611.         for a in list(self.dict.keys()):
  612.             for (b, dist) in self.dict[a].items():
  613.                 self.connect1(b, a, dist)
  614.  
  615.     def connect(self, node_a, node_b, distance_val=1):
  616.         """Add a link from node_a and node_b of given distance_val, and also add the inverse
  617.        link if the graph is undirected."""
  618.         self.connect1(node_a, node_b, distance_val)
  619.         if not self.directed:
  620.             self.connect1(node_b, node_a, distance_val)
  621.  
  622.     def connect1(self, node_a, node_b, distance_val):
  623.         """Add a link from node_a to node_b of given distance_val, in one direction only."""
  624.         self.dict.setdefault(node_a, {})[node_b] = distance_val
  625.  
  626.     def get(self, a, b=None):
  627.         """Return a link distance or a dict of {node: distance} entries.
  628.        .get(a,b) returns the distance or None;
  629.        .get(a) returns a dict of {node: distance} entries, possibly {}."""
  630.         links = self.dict.get(a)
  631.         if b is None:
  632.             return links
  633.         else:
  634.             return links.get(b)
  635.  
  636.     def nodes(self):
  637.         """Return a list of nodes in the graph."""
  638.         return list(self.dict.keys())
  639.  
  640.  
  641. def UndirectedGraph(dictionary=None):
  642.     """Build a Graph where every edge (including future ones) goes both ways."""
  643.     return Graph(dictionary=dictionary, directed=False)
  644.  
  645.  
  646. def RandomGraph(nodes=list(range(10)), min_links=2, width=400, height=300,
  647.                 curvature=lambda: random.uniform(1.1, 1.5)):
  648.     """Construct a random graph, with the specified nodes, and random links.
  649.    The nodes are laid out randomly on a (width x height) rectangle.
  650.    Then each node is connected to the min_links nearest neighbors.
  651.    Because inverse links are added, some nodes will have more connections.
  652.    The distance between nodes is the hypotenuse times curvature(),
  653.    where curvature() defaults to a random number between 1.1 and 1.5."""
  654.     g = UndirectedGraph()
  655.     g.locations = {}
  656.     # Build the cities
  657.     for node in nodes:
  658.         g.locations[node] = (random.randrange(width), random.randrange(height))
  659.     # Build roads from each city to at least min_links nearest neighbors.
  660.     for i in range(min_links):
  661.         for node in nodes:
  662.             if len(g.get(node)) < min_links:
  663.                 here = g.locations[node]
  664.  
  665.                 def distance_to_node(n):
  666.                     if n is node or g.get(node, n):
  667.                         return math.inf
  668.                     return distance(g.locations[n], here)
  669.  
  670.                 neighbor = nodes.index(min(nodes, key=distance_to_node))
  671.                 d = distance(g.locations[neighbor], here) * curvature()
  672.                 g.connect(node, neighbor, int(d))
  673.     return g
  674.  
  675.  
  676. class GraphProblem(Problem):
  677.     """The problem of searching a graph from one node to another."""
  678.  
  679.     def __init__(self, initial, goal, graph):
  680.         Problem.__init__(self, initial, goal)
  681.         self.graph = graph
  682.  
  683.     def actions(self, state):
  684.         """The actions at a graph node are just its neighbors."""
  685.         return list(self.graph.get(state).keys())
  686.  
  687.     def result(self, state, action):
  688.         """The result of going to a neighbor is just that neighbor."""
  689.         return action
  690.  
  691.     def path_cost(self, c, state1, action, state2):
  692.         return c + (self.graph.get(state1, state2) or math.inf)
  693.  
  694.     def h(self, node):
  695.         state = node.state
  696.         current = state
  697.         kraj = self.goal
  698.         grapf = self.graph
  699.  
  700.         graphh = GraphProblem(current, kraj, grapf)
  701.  
  702.         return uniform_cost_search(graphh).path_cost
  703.  
  704.  
  705. if __name__ == '__main__':
  706.     Pocetok = input()
  707.     Kraj = input()
  708.  
  709.     graph_map = UndirectedGraph(dict(
  710.         Frankfurt=dict(Mannheim=85, Wurzburg=217, Kassel=173),
  711.         Mannheim=dict(Karlsruhe=80),
  712.         Wurzburg=dict(Erfurt=186, Nurnberg=103),
  713.         Stuttgart=dict(Nurnberg=183),
  714.         Kassel=dict(Munchen=502),
  715.         Karlsruhe=dict(Augsburg=250),
  716.         Erfurt=dict(),
  717.         Nurnberg=dict(Munchen=167),
  718.         Augsburg=dict(Munchen=84),
  719.         Munchen=dict()
  720.     ))
  721.  
  722.  
  723.  
  724.     graph1 = GraphProblem(Pocetok, Kraj, graph_map)
  725.  
  726.     answer = astar_search(graph1)
  727.     print(answer.path_cost)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement