예제 #1
0
    def fit(self, X, Y):
        b = self.b
        k = len(Y[0])
        p = len(X[0])
        n = len(Y)

        logf.info("Learning an EasyHeuristic classifier on " + str(n) + "examples")

        allNodes = []
        allScores = []
        for i in range(k):  # add k nodes to the top level
            curNode = Node()
            curNode.tagsSoFar = [i]
            children = []
            self.setPCCScore(X, Y, curNode)  # Fourth argument = none
            allNodes.append(curNode)
            allScores.append(curNode.getScore())

        selectedNodes = argsort(allScores[:])[::-1]
        snIter = iter(selectedNodes)
        tagOrdering = [allNodes[snIter.next()].tagsSoFar[0] for count in range(len(allNodes))]

        # Pick the best
        self.tagOrder = tagOrdering
        yReordered = reorder(Y, self.tagOrder)
        self.clf = FixedPCCClassifier(b=64)
        self.clf.fit(X, yReordered)
def find_astar_route(source, target):
    problem = RoutingProblem(source, target, MapData.get_instance())
    # Use best first graph search algorithm when function f defined as g (the path cost) + h (the heuristic function)
    # and return the solution path.
    return best_first_graph_search(
        problem,
        cost_function,
        f=lambda n: g(n) + heuristic_function(n, Node(problem.goal)))[0]
def leaf_pushing(node, interface):
    if (node.interface == None):
        inter = interface
    else:
        inter = node.interface
    if (node.left == None and node.right == None):
        if (node.interface == None):
            node.interface = inter
        return ()
    else:
        if (node.left == None):
            node.left = Node()
        if (node.right == None):
            node.right = Node()
        leaf_pushing(node.left, inter)
        leaf_pushing(node.right, inter)
        node.interface = None
def astar_runtime():
    arbitrary_solvable_problems = get_100_solvable_search_problems()
    for problem in arbitrary_solvable_problems:
        source = problem[0]
        target = problem[1]
        problem = RoutingProblem(source, target, MapData.get_instance())
        best_first_graph_search(
            problem,
            cost_function,
            f=lambda n: g(n) + heuristic_function(n, Node(problem.goal)))
def idastar_solution_for_5_problems():
    astar_results_file = open('results/IDAStarRuns.txt', "w")
    problems_list = load_data()
    for line in range(0, 5):
        source = problems_list[line][0]
        target = problems_list[line][1]
        problem = RoutingProblem(int(source), int(target),
                                 MapData.get_instance())
        path = idastar(problem)
        cost = 0
        for i in range(len(path) - 1):
            links = MapData.get_instance().get(path[i]).links
            for link in links:
                if link.target == path[i + 1]:
                    cost += cost_function(link)
                    break
        astar_results_file.write("heuristic cost: " + str(
            heuristic_function(Node(problem.start_state), Node(problem.goal)))
                                 + ", actual cost: " + str(cost) + "\n")
    astar_results_file.close()
def astar_solution_for_100_problems():
    astar_results_file = open('results/AStarRuns.txt', "w")
    problems_list = load_data()
    counter = 0
    for problem in problems_list:
        source = problem[0]
        target = problem[1]
        problem = RoutingProblem(int(source), int(target),
                                 MapData.get_instance())
        path, cost = best_first_graph_search(
            problem,
            cost_function,
            f=lambda n: g(n) + heuristic_function(n, Node(problem.goal)))
        astar_results_file.write("heuristic cost: " + str(
            heuristic_function(Node(problem.start_state), Node(problem.goal)))
                                 + ", actual cost: " + str(cost) + "\n")
        # We want to draw solution maps only for 10 problems as required.
        if counter < 10:
            draw_solution_map(path)
        counter += 1
    astar_results_file.close()
def best_first_graph_search(problem, cost_func, f):
    # Create the node of the initial state and set its cost function.
    node = Node(problem.start_state)
    node.set_cost_function(cost_func)
    frontier = PriorityQueue(
        f)  # The frontier is implemented as a Priority Queue.
    frontier.append(node)
    closed_list = set()  # Set a closed list to deal with loops.
    while frontier:  # As long as the frontier is not empty
        node = frontier.pop(
        )  # Retrieve and remove the head of the priority queue.
        # If the state of the current node is the goal state - return the solution (the path and cost).
        if problem.is_goal(node.state):
            return node.solution()
        closed_list.add(
            node.state.index)  # Add the current state to the closed list
        for child in node.expand(
                problem):  # Run over the children of the current node.
            child_item = frontier.__getitem__(child)
            # If the child is not in the frontier and also not in the closed list - insert it to the frontier.
            if child.state.index not in closed_list and child_item is None:
                frontier.append(child)
            # If the child is in the frontier and we have found a shorter path to it -
            # delete the longer path from the frontier and save the shorter path instead.
            elif child_item is not None and f(child) < child_item:
                del frontier[child]
                frontier.append(child)
    return None
def idastar(problem):
    # The initial limit is the evaluation of the heuristic function from the start state to the goal state.
    limit = heuristic_function(Node(problem.start_state), Node(problem.goal))
    path = [Node(problem.start_state)
            ]  # Set the start state as the first node of the path.
    cost = 0
    while limit < sys.maxsize:
        # An implementation of "DFScountour" - it gets the current limit and returns a new limit.
        t = depth_limited_search(
            path,
            cost,
            limit,
            problem,
            cost_function,
            f=lambda n: g(n) + heuristic_function(n, Node(problem.goal)))
        if t == "Found":
            path_indexes = [
            ]  # Create the list of the path indexes and return it.
            for junction in path:
                path_indexes.append(junction.state.index)
            return path_indexes
        if t == sys.maxsize:
            return "Not Found"
        limit = t  # Set the old limit to be the new limit.
예제 #9
0
파일: sa.py 프로젝트: GengWu-JLU/AIBigdata
 def read_data_from_file(file_path):
     """"读取坐标数据"""
     node_map = {}
     node_list = []
     index = 0
     with open(file_path, encoding='utf8') as f:
         for line in f.readlines():
             if not line:
                 continue
             line_items = line.split()
             assert len(line_items) == 3, "地图坐标数据格式错误:%s" % file_path
             pos = line_items[2].split(",")
             name = line_items[1]
             log = float(pos[0])
             lat = float(pos[1])
             node_map.setdefault(name, (log, lat))
             node_list.append(Node(index, name, Pos(log, lat)))
             index += 1
     return node_map, node_list
예제 #10
0
def main(input_file, output_file):

    # player 0: circular - even
    # player 1: rectangular - odd

    # creating the graph from this webpage: https://en.wikipedia.org/wiki/Parity_game

    even_nodes = []
    odd_nodes = []
    G = Graph()
    higher = -1
    number = None
    with open(input_file) as reader:
        data = reader.read().splitlines(True)
        number = data[0].split()
        number = number[1]
        number = number.replace(";", "")
        data = data[1:]
        for line in data:
            uuid, p, owner, edges, name = line.split()

            uuid = int(uuid)
            p = int(p)
            owner = int(owner)
            name = name.replace("\"", "")
            name = name.replace(";", "")
            node = Node(p, owner, uuid, name)

            edges = edges.split(',')
            G.insert_node(node)

            for edge in edges:
                edge = int(edge)
                G.insert_edge(uuid, edge)

            if owner % 2 == 0:
                even_nodes.append(uuid)
            else:
                odd_nodes.append(uuid)

            if p > higher:
                higher = p


    if higher % 2 == 1:
        higher = higher + 1

    WE = solveE(G, even_nodes, odd_nodes, higher)

    nodes = G.get_nodes()
    for node in WE:
        node.set_winner(0) # 0 means even player

    for node in nodes:
        if node.get_winner() == -1:
            node.set_winner(1) # 1 means odd player

    with open(output_file, 'w') as writter:

        writter.write("parity " + number + ";\n")
        for node in nodes:
            writter.write(str(node.get_uuid()) + " " + str(node.get_winner()) + ";\n")
예제 #11
0
def main(input_file, output_file):

    # player 0: circular - even
    # player 1: rectangular - odd

    even_nodes = []
    odd_nodes = []
    G = Graph()
    higher = -1
    number_nodes = None
    with open(input_file) as reader:
        data = reader.read().splitlines(True)
        number_nodes = data[0].split()
        number_nodes = number_nodes[1]
        number_nodes = number_nodes.replace(";", "")
        data = data[1:]
        for line in data:
            uuid, p, owner, edges, name = line.split()

            uuid = int(uuid)
            p = int(p)
            owner = int(owner)
            name = name.replace("\"", "")
            name = name.replace(";", "")
            node = Node(p, owner, uuid, name)

            edges = edges.split(',')
            G.insert_node(node)

            for edge in edges:
                edge = int(edge)
                G.insert_edge(uuid, edge)

            if owner % 2 == 0:
                even_nodes.append(uuid)
            else:
                odd_nodes.append(uuid)

            if p > higher:
                higher = p


    if higher % 2 == 1:
        higher = higher + 1

    # it's number_nodes + 1 because it's index in 0
    WE = solveE(G, even_nodes, odd_nodes, higher, int(number_nodes) + 1, int(number_nodes) + 1)

    nodes = G.get_nodes()
    for node in WE:
        node.set_winner(0) # 0 means even player

    for node in nodes:
        if node.get_winner() == -1:
            node.set_winner(1) # 1 means odd player

    with open(output_file, 'w') as writter:

        writter.write("parity " + number_nodes + ";\n")
        for node in nodes:
            writter.write(str(node.get_uuid()) + " " + str(node.get_winner()) + ";\n")
예제 #12
0
 def _add_node(self, data, label):
     value = None
     if 'value' in data:
         value = data['value']
     self.nodes.append(Node(label, data['type'], value))
예제 #13
0
        ret.insert(0, cur.val)
        if cur.left:
            stack.append(cur.left)
        if cur.right:
            stack.append(cur.right)
    return ret


def traversal_forward(root):
    ret = []

    def _helper(node, ret):
        if node:
            ret.append(node.val)
            _helper(node.left, ret)
            _helper(node.right, ret)

    cur = root
    _helper(cur, ret)
    return ret


if __name__ == "__main__":
    root = Node.generate([1, 2, 3, 4, 5, 6])
    # ret = solution.traverse_recursion(root)
    # ret = solution.traverse_iterative(root)
    # ret = solution.traversal_morris(root)
    # ret = traversal_backward(root)
    ret = traversal_forward(root)
    print(ret)
예제 #14
0
from ipaddress import ip_address

from net import PeerRoot, PeerClient
from tools import Node

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Create a peer')
    parser.add_argument('ip', help='ip of this peer', type=ip_address)
    parser.add_argument('port', help='port of this peer', type=int)
    
    parser.add_argument('--root', help='this peer is a root', dest='is_root', default=False, type=bool)
    
    parser.add_argument('--root-ip', help='ip of root peer', type=ip_address, dest='root_ip')
    parser.add_argument('--root-port', help='port of root peer', type=int, dest='root_port')
    
    args = parser.parse_args()

    address = Node.parse_address((str(args.ip), args.port))

    if args.is_root:
        peer = PeerRoot(address)
    else:
        if args.root_port is None or args.root_ip is None:
            print("Error: you should specify root-ip and root-port")
            exit(1)

        root_address = Node.parse_address((str(args.root_ip), args.root_port))
        peer = PeerClient(address, root_address)

    peer.run()