Example #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)
Example #2
0
    def __init__(self, parent_node, id, collapsed_icon, x, y,
                 parent_widget=None, expanded_icon=None, label=None,
                 expandable_flag=0, draw=True):
        """overridden method (Node)"""

        # Call the constructor of Node
        Node.__init__(self, parent_node, id, collapsed_icon, x, y,
                 parent_widget, expanded_icon, label, expandable_flag)

        # Add additional functionality to Node to allow selection of nodes and their subtrees
        self.x = x
        self.y = y

        self.selected = False

        sw = self.widget

        self.checkUncheckImage = sw.create_image(x - sw.realDistX, y, image=sw.uncheckedIcon)
        sw.tag_bind(self.checkUncheckImage, '<1>', self._selectNode)
        sw.tag_bind(self.checkUncheckImage, '<3>', self._selectNode2)

        sw.tag_bind(self.symbol, '<1>', self._onNodeSelect)
        sw.tag_bind(self.label, '<1>', self._onNodeSelect)

        self.toBeExpanded = False
Example #3
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
Example #4
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
Example #5
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)
Example #6
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
Example #7
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
Example #8
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
Example #9
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
Example #10
0
    def delete(self, meToo=1):
        """overridden method (Node)"""

        # First clean up what additional stuff was added
        if meToo:
            print ("MultiSelectNode deleting checkUncheckImage")
            self.widget.delete(self.checkUncheckImage)

        # Then call the parent class' method
        Node.delete(self, meToo)
Example #11
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)
Example #12
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
Example #13
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'
Example #14
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
Example #15
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[:])
Example #16
0
    def buildStumpNode(self, now_root):
        now_counts = self.getCount(now_root.data_index)
        if now_counts == None or len(now_counts) == 0:
            return
        if len(now_root.data_index) <= self.max_leaf_data or len(now_counts) == 1:
            now_root.is_leaf = True
            self.setClassfy(now_root, now_counts)
            return

        best_value, best_sub_data_indexs = self.getSubIndex(now_root.data_index, self.tree_divide_feature_index)
        for i in range(len(best_sub_data_indexs)):
            new_son = Node(best_sub_data_indexs[i])
            new_son.setDivideFeatureAndValue(self.tree_divide_feature_index, best_value[0] + best_value[1] * (i + 1))
            self.buildStumpNode(new_son)
            now_root.son.append(new_son)
Example #17
0
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)
Example #18
0
def get_consensus_edges(nwkFittestTrees):
    N = len(nwkFittestTrees)
    Edges = {}  # track edge appearance across fittest trees
    cEdges = []  # edges labeled with fraction of times they appear
    for nwkTree in nwkFittestTrees:
        tree = Node.from_newick(nwkTree)
        tree.update_descendants()
        edges = tree.get_pairs()
        for edge in edges:
            if edge not in Edges.keys():
                Edges[edge] = 0
            Edges[edge] += 1

    # sort edges by value if they are numeric
    clusterLabels = list(set(zip(*Edges.keys())[0] + \
                             zip(*Edges.keys())[1]))
    # if cluster IDs are numeric, sort
    if sum([x.isdigit() for x in clusterLabels]) == len(clusterLabels):
        edgeKeys = sorted(Edges.keys(), \
                          key = lambda x: (int(x[0]),int(x[1])))
    else:
        edgeKeys = sorted(Edges.keys())

    # prepare to return edges labeled with frequency information
    for edge in edgeKeys:
        cEdges.append('\t'.join(map(str, edge) +\
                                [str(float(Edges[edge])/N),\
                                str(Edges[edge]) + '/' + str(N)]))

    return cEdges
Example #19
0
def get_consensus_edges(nwkFittestTrees):
    N = len(nwkFittestTrees)
    Edges = {} # track edge appearance across fittest trees
    cEdges = [] # edges labeled with fraction of times they appear
    for nwkTree in nwkFittestTrees:
        tree = Node.from_newick(nwkTree)
        tree.update_descendants()
        edges = tree.get_pairs()
        for edge in edges:
            if edge not in Edges.keys():
                Edges[edge] = 0
            Edges[edge]+=1

    # sort edges by value if they are numeric
    clusterLabels = list(set(zip(*Edges.keys())[0] + \
                             zip(*Edges.keys())[1]))
    # if cluster IDs are numeric, sort
    if sum([x.isdigit() for x in clusterLabels]) == len(clusterLabels):
        edgeKeys = sorted(Edges.keys(), \
                          key = lambda x: (int(x[0]),int(x[1])))
    else:
        edgeKeys = sorted(Edges.keys())

    # prepare to return edges labeled with frequency information
    for edge in edgeKeys:
         cEdges.append('\t'.join(map(str, edge) +\
                                 [str(float(Edges[edge])/N),\
                                 str(Edges[edge]) + '/' + str(N)]))

    return cEdges
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
Example #21
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)
Example #22
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
Example #23
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)
Example #24
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
Example #25
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
Example #26
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)  
Example #27
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
Example #28
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
Example #29
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
Example #30
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
Example #31
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:]
 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])
Example #33
0
    def __create_node__(self, parent_node, parent_attribute_val, xs, ys,
                        attributes, level):

        if level >= self.max_depth:
            val = self.__get_most_frequent_value__(ys)
            return Leaf(parent_attribute_val, val)

        distinct_ys = set(ys)
        if len(distinct_ys) == 1:
            return Leaf(parent_attribute_val, ys[0])

        best_attribute_name = self.__find_best_attribute__(
            attributes, parent_node.attribute_name, parent_attribute_val, xs,
            ys)
        new_node = Node(best_attribute_name, parent_attribute_val, parent_node,
                        self.fn_attribute_val_extractor)

        # Pivot by value to segment dataset for children
        xs_by_val, ys_by_val = self.__partition_by_attribute__(
            best_attribute_name, parent_node.attribute_name,
            parent_attribute_val, xs, ys)

        # If only one grouping, no further attributes are useful, take majority vote for class
        if len(ys_by_val) == 1:
            val = self.__get_most_frequent_value__(ys)
            return Leaf(parent_attribute_val, val)

        # Remove matched attribute
        remaining_attributes = [
            a for a in attributes if a != best_attribute_name
        ]
        for attr_val in xs_by_val.keys():
            xs4val = xs_by_val[attr_val]
            ys4val = ys_by_val[attr_val]

            child_node = self.__create_node__(new_node, attr_val, xs4val,
                                              ys4val, remaining_attributes,
                                              level + 1)
            new_node.add_child(child_node)
        return new_node
Example #34
0
 def expand(self):
     Node.expand(self)
     self._fixExpandedChildren()