示例#1
0
def search_BSF_solution(connections, init_state, solution):
    solved = False
    visited_nodes = []
    frontrs_nodes = []

    init_node = Node(init_state)
    frontrs_nodes.append(init_node)
    while (not solved) and len(frontrs_nodes) != 0:
        node = frontrs_nodes[0]
        # extraer nodo y añadirlo a visitados
        visited_nodes.append(frontrs_nodes.pop(0))
        if node.get_data() == solution:
            solved = True
            return node
        else:
            # expandir nodos hijo - ciudades con conexion
            node_data = node.get_data()
            child_list = []
            for chld in connections[node_data]:
                child = Node(chld)
                child_list.append(child)
                if not child.on_list(visited_nodes) and not child.on_list(
                        frontrs_nodes):
                    frontrs_nodes.append(child)

            node.set_child(child_list)
示例#2
0
    def mctsNormal(self, board):
        root = Node(None, None, None, self.opponent.color)
        # set initial child layer
        initial_moves = board.getAllValidMoves(self.pieces)
        if initial_moves == []:
            return None
        for move in initial_moves:
            #consider using piece size as first play urgency as initialVal
            child = Node(move,
                         root,
                         self.color,
                         initialVal=move[0].size() * 10)
            root.addChild(child)

        num_simulations = 0
        startTime = time.perf_counter()
        while (self.resourcesAvailable(startTime)):
            #selection phase
            currentNode = Node.getMctsLeaf(root)
            #make board accurate for current state
            board.makeMovesInStack(currentNode.moveStack)

            #expansion phase
            useable_pieces = []
            if currentNode.turnColor == self.color:
                # opponents turn, use their pieces
                useable_pieces = self.opponent.getPiecesNotIn(
                    currentNode.moveStack)

            else:
                #our turn, use our pieces
                useable_pieces = self.getPiecesNotIn(currentNode.moveStack)

            valid_moves = board.getAllValidMoves(useable_pieces)
            if valid_moves == []:
                #game in terminal moveStack for this player
                pass
            else:
                # add all substates
                for move in valid_moves:
                    child = Node(move,
                                 currentNode,
                                 move[0].color,
                                 initialVal=move[0].size() * 10)
                    currentNode.addChild(child)

            #simulation phase
            res = self.playoutRandomGame(currentNode, board)
            num_simulations += 1
            #board is returned to initial state

            #backpropogate
            currentNode.backpropogate(res)

        #select highest val node
        node = Node.getMaxFirstLayer(root)
        #Node.delTree(root)
        #print(num_simulations, " simulations executed")
        return node.move
示例#3
0
def built_binary_tree():
    node = Node(1)
    ret_tree = BinaryTree(node)
    two_node = Node(2)
    three_node = Node(3)
    ret_tree.insert(ret_tree.root, two_node)
    ret_tree.insert(ret_tree.root, three_node)
    return ret_tree
示例#4
0
def built_tree():
    node = Node(1)
    ret_tree = Tree(node)
    one_node = Node(1)
    two_node = Node(2)
    ret_tree.insert(one_node)
    ret_tree.insert(two_node)
    return ret_tree
示例#5
0
def getNodes(parent, label, value, l):
    nodes = []
    for node in parent:
        if type(node) is nltk.Tree:
            nd = Node(node.label())
            nd.next = getNodes(node, label, value, node.label())
            nodes.append(nd)
        else:
            nodes.append(Node(node))
    return nodes
示例#6
0
    def insert_rec(self, n: Node, val: int):
        if val > n.val:
            if n.right is None:
                n.right = Node(val)
                return
            self.insert_rec(n.right, val)
        if val < n.val:
            if n.left is None:
                n.left = Node(val)
                return

            self.insert_rec(n.right, val)
示例#7
0
 def Deeper(N):
     if N.Left is not None:
         N.Left = Deeper(N.Left)
     if N.Right is not None:
         N.Right = Deeper(N.Right)
     if N.Left is None and N.Right is None:
         if N.One is True:
             N.Left = Node(one=False, value=5 / 36)
             N.Right = Node(one=True, value=5 / 6)
         else:
             N.One = True
     return N
示例#8
0
def test_Tree():
    node0 = Node("apple")
    node1 = Node("banana")
    node2 = Node("orange")

    assert node0.has_left_child() == False, 'Fail'
    assert node0.has_right_child() == False, 'Fail'

    node0.set_left_child(node1)
    node0.set_right_child(node2)

    assert node0.has_left_child(), 'Fail'
    assert node0.has_right_child(), 'Fail'
示例#9
0
def makeTree(dataset, deleteRows, label, InfoD, parentNode, edgeNum,
             deleteCols, dataRow):
    # node = getNode(dataset,deleteRows,label,InfoD,deleteCols)
    # Tree.add_node(node)
    # Tree.add_edge(parentNode,node,weight=edgeNum)

    nodeNum = getNode(dataset, deleteRows, label, InfoD, deleteCols)
    node = Node(nodeNum, parentNode)
    edge = {"edgeNum": edgeNum, "node": node}
    parentNode.genChildren(edge)
    parentNode = node

    elements = []
    for x in dataset[nodeNum]:
        if x not in elements:
            elements.append(x)
    deleteRows = []
    if nodeNum not in deleteCols:
        deleteCols.append(nodeNum)
    if len(deleteCols) is len(dataset):
        for element in elements:
            dataRow[nodeNum] = element
            flag = False
            store = 0
            for idx, x in enumerate(dataset.T):
                if np.array_equal(dataRow, x):
                    flag = True
                    store = idx
                    break
            if not flag:
                store = random.randint(0, len(dataset[0]) - 2)
            # store label[store] in node now
            temp_node = Node(-2, parentNode)
            edge = {
                "edgeNum": element,
                "node": temp_node,
                "answer": label[store]
            }
            parentNode.genChildren(edge)

        return 0

    for x in elements:
        dataRow[nodeNum] = x
        for i in range(len(dataset[nodeNum])):
            if x != dataset[nodeNum][i]:
                deleteRows.append(i)
        makeTree(dataset, deleteRows, label, InfoD, parentNode, x,
                 deleteCols[:], dataRow[:])
示例#10
0
文件: views.py 项目: seidelj/milgrim
def node(request, tree, event):
    event = int(event)
    treeObj = Node(tree, event)
    children = []
    path = Path.objects.get(name=tree)
    for c in treeObj.children:
        children.append(Node(tree, c))
    context = {
        'parent': treeObj,
        'parentMeters': path.get_parent_meters(event),
        'meters': path.get_meters(event),
        'children': children,
    }

    return render(request, "nodes/node.html", context)
示例#11
0
    def Start(self):
        currentPlayer = self.player
        maxPlayer = True
        depth = self.maxDepth
        print self.state.boardState
        if currentPlayer == 'Star':
            isStar = True
        else:
            isStar = False
        if self.algorithm == 'MINIMAX':
            root = Node(self.state, None, self.player)
            score = self.Minimax(root, 0, maxPlayer, isStar)
            bestMove, score, farSightScore, numNodes = root.TermEvaluation(
                score, depth, isStar)
            print bestMove, score, farSightScore, numNodes
            with open('output.txt', 'w') as openFile:
                openFile.write(bestMove + '\n')
                openFile.write(str(score) + '\n')
                openFile.write(str(farSightScore) + '\n')
                openFile.write(str(numNodes))

        elif self.algorithm == 'ALPHABETA':
            root = ABNode(self.state, None, self.player)
            alpha = -float("inf")
            beta = float("inf")
            score = self.AlphaBeta(root, 0, maxPlayer, isStar, alpha, beta)
            bestMove, score, farSightScore, numNodes = root.TermEvaluation(
                score, self.maxDepth, isStar)
            print bestMove, score, farSightScore, numNodes
示例#12
0
    def Minimax(self, node, depth, maxPlayer, isStar):
        pieces = self.pieces

        if depth == self.maxDepth:
            node.score = node.ScoreEvaluation()
            return node.score

        else:
            endFlag = node.checkEnd()
            moves, childLocation = node.state.getMoves(isStar, pieces, endFlag)
            if maxPlayer:
                score = -float("inf")
            else:
                score = float("inf")

            if len(childLocation) == 0:
                node.score = node.ScoreEvaluation()
                return node.score
            for index in range(len(childLocation)):
                childState, move = childLocation[index], moves[index]
                childNode = Node(childState, move, isStar)
                node.addChild(childNode)
                childScore = self.Minimax(childNode, depth + 1, not maxPlayer,
                                          not isStar)
                if maxPlayer:
                    score = max(score, childScore)
                else:
                    score = min(score, childScore)
            #node.score = score
            return score
示例#13
0
def make_tree(filename):
    fid = open(filename + ".txt", 'r')
    node = Node('0', None)
    node.add_left(Edge(None, None))
    t = {}
    stack = [node]
    return build_tree(fid, stack, t)
示例#14
0
    def theory(self):
        from Tree import Node
        sum = 2 / 27

        def Deeper(N):
            if N.Left is not None:
                N.Left = Deeper(N.Left)
            if N.Right is not None:
                N.Right = Deeper(N.Right)
            if N.Left is None and N.Right is None:
                if N.One is True:
                    N.Left = Node(one=False, value=5 / 36)
                    N.Right = Node(one=True, value=5 / 6)
                else:
                    N.One = True
            return N

        def Calculate(N):
            if N.Left is not None and N.Right is not None:
                if N.Left.Left is not None:
                    N.Left = Calculate(N.Left)
                if N.Right.Right is not None:
                    N.Right = Calculate(N.Right)
                N.Value = N.Value * (N.Left.Value + N.Right.Value)
            return N

        root = Node(one=True, value=5 / 216)
        for each in range(5, self.TH - 1):
            root = Deeper(root)
            sum += Calculate(root).Value
        return round(1 - sum, 6)
示例#15
0
def DepthFirstSearch():
    dataTable,mapPoints = marios.CreateMapDataTable(fileName)

    openSet = []
    visitedNodes = set()
    metaNodes = set()

    root,goal = Node(mapPoints['p']),mapPoints['g']

    openSet.append(root)
    metaNodes.add(root)

    while openSet:
        subRoot = openSet.pop()
        meta = subRoot

        if(subRoot.data==goal):
            t= FindPath(meta,root)
            print("Lisi Depth First!")
            marios.PrintFinishedMap(dataTable,t)
            return visitedNodes
        for (action,child) in marios.ClosebyDataPoints(subRoot,dataTable).items():
            if(child in visitedNodes):
                continue

            if(child not in openSet):
                    openSet.append(child)
                    meta.AddChild(child)
        visitedNodes.add(subRoot)

    return visitedNodes
示例#16
0
def stringToTree(s, loc):
    #print s[loc[0]:]
    #print loc[0]
    if loc[0] >= len(s):
        return None

    ind = 0
    while loc[0] + ind < len(s) and (s[loc[0] + ind] != '('
                                     and s[loc[0] + ind] != ')'):
        ind += 1
    #print ind
    #print s[loc[0]:(loc[0]+ind)]
    res = Node(s[loc[0]:(loc[0] + ind)])
    loc[0] = loc[0] + ind

    if s[loc[0]] == '(':
        loc[0] = loc[0] + 1
        res.left = stringToTree(s, loc)
        loc[0] = loc[0] + 1

    if s[loc[0]] == '(':
        loc[0] = loc[0] + 1
        res.right = stringToTree(s, loc)
        loc[0] = loc[0] + 1

    return res
示例#17
0
def BreadthFirstSearch():
    dataTable, mapPoints = marios.CreateMapDataTable(fileName)

    openSet = Queue()
    openSetCopy = {}

    visitedNodes = set()

    root, goal = Node(mapPoints['p']), mapPoints['g']
    meta = {}
    meta[root] = (None)

    openSet.put(root)
    openSetCopy[root] = None

    while not openSet.empty():

        subRoot = openSet.get()
        openSetCopy = RemoveDictonaryKey(openSetCopy, subRoot)

        if (subRoot.data == goal):
            #return CreatePath()
            #for i,x in meta.items():
            #    print(i.data,x.data)
            #print(mapPoints['g'],"yolo")
            #print(goal,"patatatata")
            print(root.data)
            print(goal)

            t = CreatePath(subRoot, meta, Node(goal))
            t.append(goal)
            marios.PrintFinishedMap(dataTable, t)
            return t

        for (action, child) in marios.ClosebyDataPoints(subRoot,
                                                        dataTable).items():

            if (child in visitedNodes):
                continue

            if (child not in openSetCopy):
                meta[child] = subRoot
                print(child.data, subRoot.data, "abga aglias")

                openSet.put(child)
                openSetCopy[child] = child
        visitedNodes.add(subRoot)
示例#18
0
def decisionTreeClassifier(dataset, label):
    InfoD = calculateInfoD(label)
    root = Node(-1, None)
    dataRow = []
    for x in range(len(dataset)):
        dataRow.append(-1)
    makeTree(dataset, [], label, InfoD, root, 0, [], dataRow[:])
    return root
示例#19
0
 def __init__(self, byte_seq):
     range = (0, 255)
     self.range_size = abs(range[0] - range[1]) + 1
     self.current_num = self.range_size * 2 - 1
     self.byte_seq = byte_seq
     self.tree = Node(0,self.current_num, data=NYT)
     self.all_nodes = [self.tree]
     self.nyt = self.tree
示例#20
0
def rebuild_tree(forward_list, in_list):

    if len(forward_list) == 0 or len(in_list) == 0:
        return None
    elif len(forward_list) == 1 and len(in_list) == 1:
        return Node(forward_list[0])

    in_list_index = in_list.index(forward_list[0])
    left_lenth = in_list_index

    tree = Node(forward_list[0])
    tree.lchild = rebuild_tree(forward_list[1:left_lenth + 1],
                               in_list[0:left_lenth])
    tree.rchild = rebuild_tree(forward_list[left_lenth + 1:],
                               in_list[left_lenth + 1:])

    return tree
示例#21
0
def _simpleTest(canv):
  from Tree import TreeNode as Node
  root = Node(None,'r',label='r')
  c1 = root.AddChild('l1_1',label='l1_1')
  c2 = root.AddChild('l1_2',isTerminal=1,label=1)
  c3 = c1.AddChild('l2_1',isTerminal=1,label=0)
  c4 = c1.AddChild('l2_2',isTerminal=1,label=1)

  DrawTreeNode(root,(150,visOpts.vertOffset),canv)  
示例#22
0
 def generateNode(self, lb_list):
     idx = len(self.nodeList)
     if len(lb_list) > self.maxLabelsInLeaf:
         child_node = Node(idx, lb_list)
         print('Node#%d Generated!' % (idx))
     else:
         child_node = Leaf(idx, lb_list)
         print('Leaf#%d Generated!' % (idx))
     self.nodeList.append(child_node)
     return child_node, idx
示例#23
0
def breadthFirstSearch(problem, verbose=False):
	""" Perform a Breadth-First search on the given problem and return a solution.
		NOTE: This is a graph based implementation of the algorithm, please be aware of the memory overhead."""
	start = Node(problem, state = problem.initialState())
	solution = Solution(verbose)

	if problem.goalTest(start.state()): return solution.setGoalNode(start)
	frontier = Queue(items=[start])
	explored = set()
	
	while True:
		solution.trackProgress(frontier, explored)
		if frontier.isEmpty(): raise NoSolutionFoundError()
		node = frontier.dequeue()
		explored.add(node.state())
		for action in problem.applicableActions(node.state()):
			child = Node(problem, node, action)
			if child not in frontier and child.state() not in explored:
				if problem.goalTest(child.state()): return solution.setGoalNode(child)
				else: frontier.enqueue(child)
示例#24
0
def read_text(filepath):
    trees = []
    with open(filepath) as tree_file:
        for line in tree_file:
            line = line.split()
            nodes = format_line(line[0])
            possible_edges = format_line(line[1])
            edges = []
            nodes = [
                Node(data, True) if (val == 'MAX') else Node(data, False)
                for (data, val) in nodes
            ]
            for parent, child in possible_edges:
                if child.isnumeric(
                ):  # The leaf nodes are the only ones that are numeric and aren't in the node list already
                    child = float(child)
                    nodes.append(Node(child, None, True))
                edges.append((parent, child))
            trees.append(create_tree(nodes, edges))
    return trees
示例#25
0
def search_BFS_solution(init_state, solution):
    solved = False
    visited_nodes = []
    frontrs_nodes = []

    initNode = Node(init_state)
    frontrs_nodes.append(initNode)
    while (not solved) and len(frontrs_nodes) != 0:
        node = frontrs_nodes.pop(0)
        # extraer nodo y añadirlo a visitados
        visited_nodes.append(node)
        if node.get_data() == solution:
            # solucion encontrada
            solved = True
            return node
        else:
            # expandir nodos hijo
            node_data = node.get_data()

            # operador izquierdo
            child = [node_data[1], node_data[0], node_data[2], node_data[3]]
            left_child = Node(child)
            if not left_child.on_list(
                    visited_nodes) and not left_child.on_list(frontrs_nodes):
                frontrs_nodes.append(left_child)

            # operador central
            child = [node_data[0], node_data[2], node_data[1], node_data[3]]
            center_child = Node(child)
            if not center_child.on_list(
                    visited_nodes) and not center_child.on_list(frontrs_nodes):
                frontrs_nodes.append(center_child)

            # operador derecho
            child = [node_data[0], node_data[1], node_data[3], node_data[2]]
            right_child = Node(child)
            if not right_child.on_list(
                    visited_nodes) and not right_child.on_list(frontrs_nodes):
                frontrs_nodes.append(right_child)

            node.set_child([left_child, center_child, right_child])
示例#26
0
    def update(self, data, is_first):
        def find_node(data):
            for node in self.all_nodes:
                if node.data == data:
                    return node
            raise KeyError(f'Cannot find the target node given {data}.')
        current_node = None
        while True:
            if is_first:
                current_node = self.nyt
                self.current_num -= 1
                new_external = Node(1, self.current_num, data=data)
                current_node.right = new_external
                self.all_nodes.append(new_external)

                self.current_num -= 1
                self.nyt = Node(0,self.current_num, data=NYT)
                current_node.left = self.nyt
                self.all_nodes.append(self.nyt)

                current_node.weight += 1
                current_node.data = None
                self.nyt = current_node.left
            else:
                if not current_node:
                    current_node = find_node(data)
                node_max_num = max(
                    (
                        n for n in self.all_nodes
                        if n.weight == current_node.weight
                    ),
                    key=operator.attrgetter('num')
                )
                if node_max_num not in (current_node, current_node.parent):
                    exchange(node_max_num,current_node)
                    current_node = node_max_num
                current_node.weight += 1
            if not current_node.parent:
                break
            current_node = current_node.parent
            is_first = False
示例#27
0
 def second_level(self, node):
     self.level2_pn.reset(Node(node.node_type, node.state, None, depth=0))
     x = self.level1_dfpn.TT.size()
     # logistic growth
     # fraction = 1/(1+(a-x)/b)
     #self.level2_pn.set_limit(min(self.max_nodes-x,int(x*(1/(1+e**((self.a-x)/self.b))))))
     self.level2_pn.set_limit(min(self.max_nodes - x, x + 1))
     res = self.level2_pn.perform_search()
     self.eval_count += self.level2_pn.get_node_count()
     if self.eval_count > self.max_evaluations:
         self.level1_dfpn.terminate()
     return res
示例#28
0
 def _make_tree(self):
     symbols = []
     for item in self._freq_map:
         symbols.append(Leaf(item[0], item[1]))
     for i in range(len(self._freq_map)):
         symbols = sorted(symbols, key=lambda symbol: symbol.weight)
         symbol_to_add = Node(symbols[1].value + symbols[0].value,
                              symbols[1].weight + symbols[0].weight,
                              symbols[1], symbols[0])
         if len(symbols) == 2:
             return symbol_to_add
         symbols = [symbol_to_add] + symbols[2:]
示例#29
0
 def setUp(self):
     self.t = Tree(Node("root"))
     self.t.add(Node("A"))
     self.t.add(Node("B"))
     self.t.add(Node("Aa"), self.t.root.children[0])
     self.t.add(Node("Ab"), self.t.root.children[0])
     self.t.add(Node("Ba"), self.t.root.children[1])
示例#30
0
def search_solution_DFS_R(init_node, solution, visited):
    visited.append(init_node.get_data())
    if init_node.get_data() == solution:
        return init_node
    else:
        # Expandir nodos sucesores (hijos)
        node_data = init_node.get_data()
        son = [node_data[1], node_data[0], node_data[2], node_data[3]]
        left_son = Node(son)
        son = [node_data[0], node_data[2], node_data[1], node_data[3]]
        central_son = Node(son)
        son = [node_data[0], node_data[1], node_data[3], node_data[2]]
        right_son = Node(son)
        init_node.set_child([left_son, central_son, right_son])

        for node_son in init_node.get_child():
            if not node_son.get_data() in visited:
                # Llamada Recursiva
                Solution = search_solution_DFS_R(node_son, solution, visited)
                if Solution is not None:
                    return Solution
        return None