コード例 #1
0
ファイル: cli.py プロジェクト: chwnam/lifemotif-diem
 def message_structure_recursively(cls, structure):
     if type(structure) == dict and 'parts' in structure:
         current_node = Tree(structure['content-type'])
         for part in structure['parts']:
             entry = cls.message_structure_recursively(part)
             current_node.addChild(entry)
         return current_node
     else:
         if ('file-name' in structure and structure['file-name']) and \
                 ('attachment-id' in structure and structure['attachment-id']):
             return Tree(structure)
         else:
             return Tree(structure['content-type'])
コード例 #2
0
ファイル: minimax.py プロジェクト: Bukkaraya/TicTacToe
def mini_max(board):
    tree_root = Tree(board)
    populateTree(tree_root, SELF_PIECE)
    children = tree_root.getChildren()
    temp_min = 10000
    next_move = None

    for child in children:
        if get_tree_depth(child) < temp_min:
            next_move = child
            temp_min = get_tree_depth(child)

    if (next_move is not None):
        return next_move.data

    return None
コード例 #3
0
ファイル: dtree.py プロジェクト: yoyzhou/dmP
 def __treeGrowth__(self, dataset, attributes, target):
     """
     Grows decision tree based on training set
     @param dataset: training set
     @param attributes: attribute set, which may contains target attribute
     @param target: target attribute   
     """
     
     #Target values
     tvals = [record[target] for record in dataset]
     
     default = self.datasource.majorityValue(dataset)
 
     # If the data set is empty or the attributes list is empty, return the
     # default value. 
     if not dataset or (len(attributes) - 1) <= 0:
         return Tree(DecisionNode(default))
     
     # If all the records in the data set have the same classification,
     # return that classification.
     elif tvals.count(tvals[0]) == len(tvals):
         return Tree(DecisionNode(tvals[0]))
     else:
         # Choose best attribute to best classify data
         best = self.splitmetric(dataset, attributes, target)
 
         # Create a new decision tree/node with the best attribute
         dtree = Tree(DecisionNode(best))
         
         #Attributes for next iterator, all attributes except already fitted `best` attribute
         attrs = [attr for attr in attributes if attr != best]
         
         # Create a new decision tree/sub-node for each of the values in the
         # best attribute field
         for val in self.datasource.uniqueValues(dataset, best):
             # Create a subtree for the current value under the "best" field
             subtree = self.__treeGrowth__(
                 self.datasource.subDataSet(dataset, best, val),
                 attrs, 
                 target)
 
             # Set decision condition, and add the new subtree
             subtree.data.condition = val  
             dtree.addChild( subtree)
             
 
         return dtree
コード例 #4
0
ファイル: minimax.py プロジェクト: Bukkaraya/TicTacToe
def populateTree(tree, piece):
    cur_board = tree.data
    indices = cur_board.get_none_indices()

    if indices == [] or cur_board.board_won(piece) or cur_board.board_won(
            piece_comp(piece)):
        return Board()

    for i in indices:
        child_board = copy.deepcopy(cur_board)
        child_board.insert_element(i[0], i[1], piece)
        child = Tree(child_board)
        tree.addChild(child)
        populateTree(child, piece_comp(piece))
コード例 #5
0
ファイル: testTree.py プロジェクト: pombredanne/pyTree
 def test_NewTreeMulti(self):
     child1 = Tree("C01")
     child2 = Tree("C02")
     root = Tree('Root', [child1, child2])
     self.assertEqual(root.data, "Root")
     self.assertEqual(root.getChildren()[1].data, "C02")
コード例 #6
0
ファイル: testTree.py プロジェクト: pombredanne/pyTree
 def test_NewTreeSingle(self):
     child1 = Tree("C01")
     root = Tree('Root', child1)
     self.assertEqual(root.data, "Root")
     self.assertEqual(root.getChildren()[0].data, "C01")
コード例 #7
0
ファイル: testTree.py プロジェクト: pombredanne/pyTree
 def test_NewTree(self):
     root = Tree("Root")
     child1 = Tree("C01")
     child2 = Tree("C02")
     child21 = Tree("C21")
     root.addChild(child1)
     root.addChild(child2)
     child2.addChild(child21)
     self.assertEqual(root.data, "Root")
     self.assertEqual(root.getChildren()[0].data, "C01")
コード例 #8
0
ファイル: testTree.py プロジェクト: pombredanne/pyTree
 def setUp(self):
     """
     Test Tree structure:
         Root
         |___ C01
         |     |___ C11
         |          |___ C111
         |          |___ C112
         |___ C02
         |___ C03
         |     |___ C31
     """
     self.root = Tree('Root')
     self.child01 = Tree('C01')
     self.child02 = Tree('C02')
     self.child03 = Tree('C03')
     self.child11 = Tree('C11')
     self.child31 = Tree('C31')
     self.child111 = Tree('C111')
     self.child112 = Tree('C112')
     self.root.addChildren([self.child01, self.child02, self.child03])
     self.child01.addChild(self.child11)
     self.child03.addChild(self.child31)
     self.child11.addChild(self.child111)
     self.child11.addChild(self.child112)
コード例 #9
0
ファイル: testTree.py プロジェクト: pombredanne/pyTree
 def test_PrintTree(self):
     root = Tree('root')
     t1 = Tree('1')
     t11 = Tree('11')
     t111 = Tree('111')
     t1111 = Tree('1111')
     t11111 = Tree('11111')
     t111111 = Tree('111111')
     t1111111 = Tree('1111111')
     root.addChild(t1)
     t1.addChild(t11)
     t11.addChild(t111)
     t111.addChild(t1111)
     t1111.addChild(t11111)
     t1111.addChild(Tree('44444'))
     t11111.addChild(t111111)
     t111111.addChild(t1111111)
     root.prettyTree()       
コード例 #10
0
ファイル: testTree.py プロジェクト: pombredanne/pyTree
class TestTree(unittest.TestCase):
    
    def setUp(self):
        """
        Test Tree structure:
            Root
            |___ C01
            |     |___ C11
            |          |___ C111
            |          |___ C112
            |___ C02
            |___ C03
            |     |___ C31
        """
        self.root = Tree('Root')
        self.child01 = Tree('C01')
        self.child02 = Tree('C02')
        self.child03 = Tree('C03')
        self.child11 = Tree('C11')
        self.child31 = Tree('C31')
        self.child111 = Tree('C111')
        self.child112 = Tree('C112')
        self.root.addChildren([self.child01, self.child02, self.child03])
        self.child01.addChild(self.child11)
        self.child03.addChild(self.child31)
        self.child11.addChild(self.child111)
        self.child11.addChild(self.child112)
        #self.root.printTree(T)
        
    def test_initialization(self):
        pass
    
    def test_NewTree(self):
        root = Tree("Root")
        child1 = Tree("C01")
        child2 = Tree("C02")
        child21 = Tree("C21")
        root.addChild(child1)
        root.addChild(child2)
        child2.addChild(child21)
        self.assertEqual(root.data, "Root")
        self.assertEqual(root.getChildren()[0].data, "C01")
        
    def test_NewTreeSingle(self):
        child1 = Tree("C01")
        root = Tree('Root', child1)
        self.assertEqual(root.data, "Root")
        self.assertEqual(root.getChildren()[0].data, "C01")
     
    def test_NewTreeMulti(self):
        child1 = Tree("C01")
        child2 = Tree("C02")
        root = Tree('Root', [child1, child2])
        self.assertEqual(root.data, "Root")
        self.assertEqual(root.getChildren()[1].data, "C02")
        
    def test_Parent(self):
        self.assertEqual(self.child01.getParent(),  self.root)
        self.assertEqual(self.child02.getParent(),  self.root)
        self.assertEqual(self.child03.getParent(),  self.root)
        self.assertEqual(self.child11.getParent(),  self.child01)
        self.assertEqual(self.child31.getParent(),  self.child03)    
        
    def test_IsRoot(self):
        self.assertTrue(self.root.isRoot())
        self.assertFalse(self.child01.isRoot())
        self.assertFalse(self.child31.isRoot())
    
    def test_IsBranch(self):
        self.assertFalse(self.root.isBranch())
        self.assertFalse(self.child01.isBranch())
        self.assertFalse(self.child03.isBranch())
        self.assertTrue(self.child02.isBranch())
        self.assertFalse(self.child11.isBranch())
        self.assertTrue(self.child31.isBranch())
    
    def test_ChildrendotAssign(self):

        #self.root.children = []
        with self.assertRaises(AttributeError) as excpt:
            self.root.children = []
            self.assertEqual(excpt.expection, AttributeError)

    def test_GetRoot(self):
        self.assertEqual(self.root.getRoot(), self.root);
        self.assertEqual(self.child01.getRoot(), self.root)
        self.assertEqual(self.child31.getRoot(), self.root)
        
    def test_GetChild(self):
        self.assertEqual(self.root.getChild(2), self.child03)
        self.assertEqual(self.child03.getChild(0), self.child31);
        
        
    def test_GetNode(self):
        self.assertEqual(self.root.getNode('C31'), self.child31)
        self.assertEqual(self.child11.getNode('C11'), self.child11)
        self.assertEqual(self.root.getNode('C41'), None)
    
    def test_DelChild(self):
        self.child11.delChild(0);
        #self.root.prettyTree()
        
     
    def test_DelNode(self):
        self.root.delNode('C03');
        #self.root.prettyTree()
      
            
    def test_PrintTree(self):
        root = Tree('root')
        t1 = Tree('1')
        t11 = Tree('11')
        t111 = Tree('111')
        t1111 = Tree('1111')
        t11111 = Tree('11111')
        t111111 = Tree('111111')
        t1111111 = Tree('1111111')
        root.addChild(t1)
        t1.addChild(t11)
        t11.addChild(t111)
        t111.addChild(t1111)
        t1111.addChild(t11111)
        t1111.addChild(Tree('44444'))
        t11111.addChild(t111111)
        t111111.addChild(t1111111)
        root.prettyTree()       
        #self.root.prettyTree()
        # self.root.nestedTree()
       
        
    def tearDown(self):
        del self.root
コード例 #11
0
def Weighted_A_Star_Search(maze, vis, Dtype, Weight):
    Start = helper.find_pos(maze, what="S")
    End = helper.find_pos(maze, what="G")
    Result = []
    MaxFrontier = 1
    MaxDepth = 1
    counter = 0  # a counter to identify paths with same distance
    if (Start == End):
        Result.append("Start is End")
        Result.append("Start is End")
        Result.append("Start is End")
        Result.append("Start is End")
        return Result

    q = [
    ]  # It's a sorted list with nodes (can be built as a path by tree) from shortest f(n) to largest f(n), like priority queue
    Root = Tree(Start)
    q.append([
        Find_Weightd_F_Distance(maze, Start, Root, Root, End, Dtype, Weight),
        Root, counter
    ])
    while (len(q) != 0):
        if (len(q) > MaxFrontier):
            MaxFrontier = len(q)
        tNode = q[0].copy()  # Pull out the node with smallest f(n)
        q.pop(0)

        NodeonTree = tNode[1]
        Node = NodeonTree.data

        depth = Find_Distance(NodeonTree, Root)
        if (MaxDepth < depth):  # Find the depth of the node
            MaxDepth = depth

        UpdateMaze(maze, NodeonTree, vis)  # Update maze with each new path

        if (Node == End):
            newTreeNode = Tree(Node)
            NodeonTree.addChild(newTreeNode)
            tempNode = newTreeNode.getParent()
            while (tempNode != Root):
                maze[tempNode.data[0]][tempNode.data[1]] = 'P'
                tempNode = tempNode.getParent()
            maze[End[0]][End[1]] = 'G'  # Remark Path and Destination's colors

            Result = getResult(maze)
            Result.append(MaxFrontier)
            Result.append(MaxDepth)
            return Result

        children = Find_A_Star_Children(
            maze, Node, Root, NodeonTree, End,
            Dtype)  # Get the children of the current path

        for e in children:
            counter = counter + 1  # Update counter to make diffferent identification for the node
            newchild = Tree(e)
            NodeonTree.addChild(newchild)
            newchildDistance = Find_Distance(NodeonTree, Root)
            UpdateMaze(maze, newchild, vis)

            newDistance = Find_Weightd_F_Distance(
                maze, e, Root, newchild, End, Dtype,
                Weight)  # Find the f(n) for that node

            find = False  # insert the new node into the sorted list
            index = -1
            has = False
            for a in range(len(q)):
                if (e == q[a][1].data
                    ):  # Find where the node is already in the container
                    if (newDistance < q[a][0]):
                        q[a] = [newDistance, newchild, counter]
                    has = True
            if (has == False):  # Insert it into the container
                for b in range(len(q)):
                    if (newDistance < q[a][0]):
                        q.insert(a, [newDistance, newchild, counter])
                        find = True
                        break
                    elif (newDistance == q[a][0]):
                        if (counter >= q[a][2]):
                            q.insert(a, [newDistance, newchild, counter])
                            find = True
                            break
                if (find == False):
                    q.append([newDistance, newchild, counter])
    Result.append("Path not found")
    Result.append("Path not found")
    Result.append("Path not found")
    Result.append("Path not found")
    return Result
コード例 #12
0
def BFS_Search(maze, vis):
    Start = helper.find_pos(maze, what="S")
    End = helper.find_pos(maze, what="G")  #   Set start point and end point
    Result = []
    MaxFrontier = 1
    MaxDepth = 1
    if (Start == End):  # If Start is End
        Result.append("Start is End")
        Result.append("Start is End")
        Result.append("Start is End")
        Result.append("Start is End")
        return Result
    q = Queue(maxsize=(len(maze) * len(maze[0])))  # It is a FIFO queue
    q.put(Start)

    Root = Tree(Start)  # Use a tree to store all the paths

    while (q.empty() == False):
        if (q.qsize() > MaxFrontier):
            MaxFrontier = q.qsize()

        Node = q.get()  # Get a node from queue
        NodeonTree = Root.getNode(Node)

        depth = Find_Distance(NodeonTree, Root)
        if (MaxDepth < depth):  # Find the depth of the node
            MaxDepth = depth

        children = Find_Children(maze, Node)
        if (vis == True):  # Show paths for each round
            if (Node != Start):
                maze[Node[0]][Node[1]] = 'P'
                helper.show_maze(maze)
                maze[Node[0]][Node[1]] = '.'
            else:
                helper.show_maze(maze)
        for e in children:
            if (e == End):
                newTreeNode = Tree(e)
                NodeonTree.addChild(newTreeNode)
                tempNode = newTreeNode.getParent()
                while (tempNode != Root):
                    maze[tempNode.data[0]][tempNode.data[1]] = 'P'
                    tempNode = tempNode.getParent(
                    )  # Rebuild the path based on the tree
                Result = getResult(maze)
                Result.append(MaxFrontier)
                Result.append(MaxDepth)
                return Result
            if (Root.getNode(e) == None):
                newTreeNode = Tree(e)
                maze[e[0]][e[1]] = '.'
                NodeonTree.addChild(
                    newTreeNode)  # Add child to the tree and to the queue
                q.put(e)

    Result.append("Path not found")
    Result.append("Path not found")  # If no path founded
    Result.append("Path not found")
    Result.append("Path not found")  # If no path founded
    return Result
コード例 #13
0
def DLS_Search(maze, vis, depth):
    Start = helper.find_pos(maze, what="S")
    End = helper.find_pos(maze, what="G")
    Result = []
    MaxFrontier = 1
    MaxDepth = 1  # The maximum number will always show with longest distance

    if (Start == End):
        Result.append("Start is End")
        Result.append("Start is End")
        Result.append("Start is End")
        Result.append("Start is End")
        return Result

    q = LifoQueue(maxsize=(len(maze) *
                           len(maze[0])))  # It is a LIFO queue like DFS
    Root = Tree(Start)
    q.put(Root)
    layer = 0

    while (q.empty() == False):
        if (q.qsize() > MaxFrontier):
            MaxFrontier = q.qsize()

        NodeonTree = q.get()
        Node = NodeonTree.data
        layer = Get_layer(NodeonTree, Root)

        if (layer > MaxDepth):
            MaxDepth = layer

        if (layer < depth):
            children = Find_DLS_Children(maze, Node, NodeonTree, Root)
            if (vis == True):
                if (Node != Start):
                    maze[Node[0]][Node[1]] = 'P'
                    helper.show_maze(maze)
                    maze[Node[0]][Node[1]] = '.'
                else:
                    helper.show_maze(maze)
            for e in children:
                if (e == End):
                    newTreeNode = Tree(e)
                    NodeonTree.addChild(newTreeNode)
                    tempNode = newTreeNode.getParent()
                    while (tempNode != Root):
                        maze[tempNode.data[0]][tempNode.data[1]] = 'P'
                        tempNode = tempNode.getParent(
                        )  # Rebuild the path based on the tree
                    Result = getResult(maze)
                    Result.append(MaxFrontier)
                    Result.append(MaxDepth)
                    return Result
                newTreeNode = Tree(e)
                maze[e[0]][e[1]] = '.'
                NodeonTree.addChild(
                    newTreeNode)  # Add child to the tree and to the queue
                q.put(newTreeNode)
    Result.append("Path not found")
    Result.append("Path not found")
    Result.append("Path not found")
    Result.append("Path not found")
    return Result