示例#1
0
 def test_add_child_connected(self):
     tp = Node(label="TP")
     dp = Node(label="DP")
     tp.add_child(dp)
     tp2 = Node(label="TP")
     with self.assertRaises(AssertionError):
         tp2.add_child(dp)
示例#2
0
 def test_to_dict_simple(self):
     tp = Node(label="TP")
     dp = Node(label="DP")
     tbar = Node(label="T<bar/>")
     tp.add_child(dp)
     tp.add_child(tbar)
     self.assertEqual(tp.to_dict(), TestNode.SIMPLE_TREE_DICT)
示例#3
0
def grow_tree(records, attributes, default = ''):
	if stopping_condition(records, attributes):
		label = classify(records)

		if label is None:
			label = default

		return Node(label = label)

	else:
		i, condition = find_best_split(records, attributes)
		default = classify(records)

		attributes[-1], attributes[i] = attributes[i], attributes[-1]
		name, v, values = attributes.pop()

		if v != False:
			root = Node(label = name + '<=' + str(v), test = condition)
			values = [True, False]
		
		else:
			root = Node(label = name, test = condition)

		for value in values:
			new_records = filter(lambda r: condition(r) == value, records)
			child = grow_tree(new_records, attributes, default)
			root.add_branch(value)
			root.add_child(child)

		attributes.append( (name, v, values) )
		attributes[-1], attributes[i] = attributes[i], attributes[-1]

		return root
示例#4
0
 def test_add_child(self):
     tp = Node()
     dp = Node()
     tp.label = "TP"
     dp.label = "DP"
     tp.add_child(dp)
     self.assertIn(dp, tp.children)
     self.assertEqual(dp.parent, tp)
示例#5
0
 def test_add_parent(self):
     dp = Node(label="DP")
     d = Node(label="D", value="the")
     dp.add_child(d)
     n = Node(label="N", value="cactus")
     dp.add_child(n)
     np = Node(label="NP")
     n.add_parent(np)
     self.assertIn(np, dp.children)
     self.assertEqual(np, n.parent)
     self.assertNotIn(n, dp.children)
示例#6
0
    def build_game_tree(self, depth, board, is_max, number):
        cpy = copy.deepcopy(board)
        r = Node(cpy, is_max, None)

        if depth == 0 :
            return r

        el_moves = self.get_eligible_for_board(cpy, number)
        for move in el_moves:
            new_board, free_move = self.board._dummy_move_stones(number, move, cpy)
            r_num = number if free_move else self.flip_number(number)
            ci = self.build_game_tree(depth-1, new_board, (is_max if free_move else not is_max), r_num)
            ci.set_move(move)
            r.add_child(ci)       

        return r
示例#7
0
class TestNodeMethods(unittest.TestCase):
    
    def setUp(self):
        # create test objects
        self.n = Node('node1')
        self.n2 = Node('node2', '2')
        self.n3 = Node('node3', '3')
        self.n4 = Node('node4', '4')
        self.n5 = Node('node5', '5')
        self.n6 = Node('node6', '6')
        self.n7 = Node('node7', '7')

    def tearDown(self):
        # set objects to none or delete stuff
        self.n = None
        self.n2 = None

    def test_get_id_where_no_id(self):
        self.assertEqual(self.n.get_id(), None)
        
    def test_get_id_and_title_n_n2(self):
        self.assertEqual(self.n.get_title(), 'node1')
        self.assertEqual(self.n2.get_title(), 'node2')
        self.assertEqual(self.n2.get_id(), '2')
    
    def test_string_repr(self):
        self.assertEqual(self.n.__str__(), 'node1')
        self.assertEqual(self.n2.__str__(), 'node2')

    def test_adding_2_children(self):
        self.n.add_child(self.n2)
        self.n.add_child(self.n3)
        children = Set()
        children.add(self.n2)
        children.add(self.n3)
        self.assertEqual(self.n.get_children(), children)

    def test_parent_id(self):
        n = Node(id='6', parent_id='1')
        self.assertEqual(n.get_parent_id(), '1')

    def test_set_and_get_parent_id(self):
        n = Node(id='1')
        n.set_parent_id(0)
        id = n.get_parent_id()
        self.assertEqual(0, id)
示例#8
0
class TestNode(unittest.TestCase):

    def setUp(self) -> None:
        self.node1 = Node('node1')
        self.node2 = Node('node2')
        self.node1.add_child(self.node2)

    def test_add_child(self):
        self.assertEqual(self.node2.parent, self.node1)
        self.assertIn(self.node2, self.node1.children)

    def test_id(self):
        self.assertEqual(self.node1.id, 'node1')
        self.assertEqual(self.node2.id, 'node1.node2')

    def test_get(self):
        node2 = self.node1.get('node2')
        self.assertEqual(self.node2, node2)
示例#9
0
 def test_delete(self):
     dp = Node(label="DP")
     d = Node(label="D", value="the")
     dp.add_child(d)
     np = Node(label="NP")
     dp.add_child(np)
     n = Node(label="N", value="cactus")
     np.add_child(n)
     np.delete()
     self.assertNotIn(np, dp.children)
     self.assertNotIn(n, dp.children)
n = Node('taste',5)
p = Node('var',6)
q = Node('var',7)
r = Node('var',8)
s = Node('name',9)

myTree.add_node(n,myTree.get_root())
print("Traversing the tree after adding 1 node")
myTree.print_tree(myTree.get_root(),0)

myTree.add_node(p,myTree.search_node(myTree.get_root(),n.feature,n.value))
print("Traversing the tree after adding 2 nodes")
myTree.print_tree(myTree.get_root(),0)
myTree.add_node(q,myTree.search_node(myTree.get_root(),n.feature,n.value))
myTree.add_node(r,myTree.search_node(myTree.get_root(),q.feature,q.value))

print("Traversing the tree after adding 4 nodes")
myTree.print_tree(myTree.get_root(),0)
myTree.add_node(s,myTree.search_node(myTree.get_root(),r.feature,r.value))

"""
n.add_child(p)
n.add_child(q)
n.add_child(r)
r.add_child(s)
"""

print("Traversing the tree after adding 5 nodes")
myTree.print_tree(myTree.root,0)
示例#11
0
def simulate_one_tree(n, pop_size):
    """ Simulates trees according to the Kingman coalescent model.

    inputs: number of available_nodes, n; effective population size, pop_size
    output: coalescent tree with n available_nodes.
    """
    from itertools import combinations
    from random import choice

    # each pair of lineages coalesces at rate 1/pop_size
    # given k lineages, total rate of coalescence is combination(k, 2)/pop_size

    k = n   # setting lineages to n
    t = 0

    # Initialising node labels, heights to zero, and matrix
    node_count = n

    available_nodes = [Node(str(i)) for i in range(n)]
    for node in available_nodes:
        node.set_height(0)
    # matrix = {available_nodes[i]: {available_nodes[j]: matrix[i][j] for j in range(n)} for i in range(n)}

    while k > 1:
        # updating time, t
        rate = ncr(k, 2)/pop_size
        # print(rate)
        t_k = np.random.exponential(1/rate)
        t = t + t_k

        # new node m, with height t, and random children from available_nodes and popping them
        m = Node(str(node_count))
        node_count += 1
        m.set_height(t)

        # Gets the combinations of 2 different nodes and their indices (pairs) from the available_nodes
        # Then setting into a list
        pairs = combinations(enumerate(available_nodes), 2)
        pairs = [(i[0], i[1]) for i in pairs]
        # At this point each node in a pair is a tuple -> (available_nodes index, node object)

        # Selecting a random pair (by index) and setting as children of m
        # Note: index [0] is the index from available nodes | [1] is the node object
        pairs_index = choice(range(len(pairs)))
        left_child = pairs[pairs_index][0]
        right_child = pairs[pairs_index][1]
        m.add_child(left_child[1])
        m.add_child(right_child[1])

        # Removing added children from list of available_nodes
        # Popping right child first to maintain index integrity of available_nodes
        index_to_pop = right_child[0]
        available_nodes.pop(index_to_pop)
        index_to_pop = left_child[0]
        available_nodes.pop(index_to_pop)

        # adding m to set of available_nodes
        available_nodes.append(m)

        # one less lineage
        k -= 1

        # ----- End of While Loop -----

    root_node = m
    return Tree(root_node)
from tree import Node

Bob = Node("Bob")
Marni = Node("Marni")
Declan = Node("Declan")

Bob.add_child(Marni)
Bob.add_child(Declan)

Declan.parent = Bob
Declan.parent = Marni

print('Bob\'s children:  ', Bob.children)
print('Marni\'s parent:  ', Marni.parent)
print('Marni\'s children:  ', Marni.children)
print('Declan\'s parent:  ', Declan.parent)
print('Declan\'s children:  ', Declan.children)
def test_Node_add_child_2():
    _node = Node(1)
    _node.add_child(2)
    _node.add_child(3)
    assert _node.children[1].data == 3
def test_Node_add_child_1():
    _node = Node(1)
    _node.add_child(2)
    assert _node.children[0].data == 2
示例#15
0
def action_reconstruct(current, **kwargs):

    if current.visited:
        return False, current
    current.visited = True
    handle_exits = kwargs.get('handle_exits', True)
    if current.S[current.I.names['p']] == 1:
        return False, current
    """

    :type current: class Node
    """

    from tree import Node
    if not current.parent:  # maybe Init process
        return False, current

    # 2 1 1

    if current.S[current.I.names['g']] == current.parent.S[current.parent.I.names['g']] and \
       current.S[current.I.names['s']] == current.parent.S[current.parent.I.names['s']]:
        current.I.act = 'fork' + '(' + str(
            current.S[current.I.names['pp']]) + ')'
        if 'check_fds' in kwargs:
            pass

    # 2 2 2
    # setsid
    elif current.S[current.I.names['p']] == current.S[
            current.I.names['g']] == current.S[current.I.names['s']]:
        new_state = Node(data=(None, default_inh, None, [
            current.S[current.I.names['p']],
            current.parent.S[current.parent.I.names['g']],
            current.parent.S[current.parent.I.names['s']],
            current.S[current.I.names['pp']], current.S[4], current.S[5],
            current.S[6], current.S[7]
        ]),
                         parent=current.parent,
                         visited=True)
        current.parent.add_child(new_state)
        current.parent.delete_child(index=current.index)
        new_state.parent = current.parent
        current.parent = new_state
        new_state.I.act = 'fork' + '(' + str(
            new_state.S[new_state.I.names['pp']]) + ')'
        current.I.act = 'setsid()'
        new_state.add_child(current)

    # 1 2 1
    # setsid(self)
    if current.S[current.I.names['p']] == current.S[current.I.names['g']] and \
            current.S[current.I.names['g']] != current.S[current.I.names['s']]:
        new_state = Node(data=(None, default_inh, None, [
            current.S[current.I.names['p']],
            current.parent.S[current.parent.I.names['g']],
            current.parent.S[current.parent.I.names['s']],
            current.S[current.I.names['pp']], current.S[4], current.S[5],
            current.S[6], current.S[7]
        ]),
                         parent=current.parent)

        current.parent.add_child(new_state)
        current.parent.delete_child(index=current.index)
        current.parent = new_state

        new_state.I.act = 'fork' + '(' + str(
            new_state.S[new_state.I.names['pp']]) + ')'
        current.I.act = 'setpgid' + '(self:' + str(
            new_state.S[new_state.I.names['p']]) + ')'
        new_state.add_child(current)

    # check cs:
    # correct_session_picker
    # pass this elif or not - think after sleep :)
    elif handle_exits and current.parent.S[current.parent.I.names['p']] == 1:
        res = False
        current.parent.delete_child(current.index)
        # see the tree in previous articles
        res, target = current.parent.dfs(
            action=action_check_attr_eq,
            name='g',
            val=current.S[current.I.names['g']])  # if Ex group
        if res:
            res, target = current.parent.dfs(
                action=action_check_attr_eq,
                name='s',
                val=current.S[current.I.names['s']])
            if res:
                node = Node(
                    data=(
                        None,
                        default_inh,
                        'fork(' + str(target.S[target.I.names['p']]) +
                        '),exit()',
                        [
                            current.S[current.I.names['p']],  # refill this
                            current.S[current.I.names['g']],
                            current.S[current.I.names['s']],
                            target.S[target.I.names['p']],
                            current.S[4],
                            current.S[5],
                            current.S[6],
                            current.S[7]
                        ]),
                    parent=target,
                    visited=True)
                target.add_child(node)
                current.parent.delete_child(current.index)
                node.add_child(current)
                #current.parent = node
                current.S[current.I.names['pp']] = current.parent.S[
                    current.parent.I.names['p']]
                current.I.act = 'fork' + '(' + str(
                    current.parent.S[current.I.names['pp']]) + ')'
            else:
                print('parsing error')
                import sys
                sys.exit(-1)
        else:
            res, target = current.parent.dfs(
                action=action_check_attr_eq,
                name='s',
                val=current.S[current.I.names['s']])  # if Ex session
            if res:
                node_par = Node(
                    data=(
                        None,
                        default_inh,
                        'fork(' + str(target.S[target.I.names['p']]) + ')',
                        [
                            current.S[current.I.names['g']],  # refill this
                            current.S[target.I.names['g']],
                            current.S[target.I.names['s']],
                            target.S[target.I.names['p']],
                            current.S[4],
                            current.S[5],
                            current.S[6],
                            current.S[7]
                        ]),
                    parent=current.parent,
                    visited=True)
                node_ch = Node(
                    data=(
                        None,
                        default_inh,
                        'setpgid(' + str(current.S[current.I.names['g']]) +
                        '),exit()',
                        [
                            current.S[current.I.names['g']],  # refill this
                            current.S[current.I.names['g']],
                            current.S[target.I.names['s']],
                            target.S[node_par.I.names['p']],
                            current.S[4],
                            current.S[5],
                            current.S[6],
                            current.S[7]
                        ]),
                    parent=node_par,
                    visited=True)
                node_par.add_child(node_ch)
                target.add_child(node_par)
                current.parent.delete_child(current.index)
                node_ch.add_child(current)
                current.S[current.I.names['pp']] = current.parent.S[
                    current.parent.I.names['p']]
            else:
                node_par = Node(
                    data=(
                        None,
                        default_inh,
                        'fork(' +
                        str(current.parent.S[current.parent.I.names['p']]) +
                        ')',
                        [
                            current.S[current.I.names['s']],  # refill this
                            current.parent.S[current.parent.I.names['g']],
                            current.parent.S[current.parent.I.names['s']],
                            current.parent.S[current.parent.I.names['p']],
                            current.S[4],
                            current.S[5],
                            current.S[6],
                            current.S[7]
                        ]),
                    parent=current.parent,
                    visited=True)
                node_ch = Node(data=(None, default_inh, 'setsid(), exit()', [
                    current.S[current.I.names['s']],
                    current.S[current.I.names['s']],
                    current.S[current.I.names['s']],
                    node_par.S[node_par.I.names['p']], current.S[4],
                    current.S[5], current.S[6], current.S[7]
                ]),
                               parent=node_par,
                               visited=True)

                node_br = Node(
                    data=(None, default_inh,
                          'fork(' + str(node_ch.S[node_ch.I.names['p']]) + ')',
                          [
                              current.S[current.I.names['g']],
                              current.S[current.I.names['s']],
                              current.S[current.I.names['s']],
                              node_ch.S[node_ch.I.names['p']], current.S[4],
                              current.S[5], current.S[6], current.S[7]
                          ]),
                    parent=node_ch,
                    visited=True)

                node_br2 = Node(
                    data=(None, default_inh, 'setpgid(self,' +
                          str(current.S[current.I.names['g']]) + '), exit()', [
                              current.S[current.I.names['g']],
                              current.S[current.I.names['g']],
                              current.S[current.I.names['s']],
                              node_br.S[node_br.I.names['p']], current.S[4],
                              current.S[5], current.S[6], current.S[7]
                          ]),
                    parent=node_br,
                    visited=True)

                node_par.add_child(node_ch)
                current.parent.add_child(node_par)
                current.parent.delete_child(current.index)
                node_ch.add_child(node_br)
                node_br.add_child(node_br2)
                node_br2.add_child(current)
                current.S[current.I.names['pp']] = node_ch.S[
                    node_ch.I.names['p']]

    else:
        res = False
        if current.parent.I.act == 'setsid()':
            # triple - see article - up of current's parent is reconstructed, which parent is target value
            res, _ = current.parent.parent.parent.upbranch(
                action=action_check_attr_eq,
                name='p',
                val=current.S[current.I.names['s']])
        elif 'setpgid' in current.parent.I.act:
            res, _ = current.parent.parent.parent.upbranch(
                action=action_check_attr_eq,
                name='p',
                val=current.S[current.I.names['s']])
        if res:
            #            current.parent.children = current.parent.delete_child(current.index)
            current.parent.delete_child(
                current.index
            )  # redundancy - needs dynamic refilling of children list!
            current.parent = current.parent.parent

            current.parent.add_child(current)

            # look for group if not id is not suitable
            if current.S[current.I.names['g']] != current.parent.S[
                    current.parent.I.names['g']]:  ##loc_group(noself)
                print('starting upbranch')
                resg, root = current.upbranch(
                    action=action_check_attr_eq,
                    name='p',
                    val=current.S[current.I.names['s']])
                print('upbranch is ok')
                if resg:
                    print('resg')
                    r, _ = root.dfs(action=action_check_attr_eq,
                                    name='p',
                                    name2='g',
                                    val=current.S[current.I.names['g']])
                    if r:
                        print('recons')
                        new_state = Node(data=(None, default_inh, None, [
                            current.S[current.I.names['p']],
                            current.parent.S[current.parent.I.names['g']],
                            current.parent.S[current.parent.I.names['s']],
                            current.S[current.I.names['pp']], current.S[4],
                            current.S[5], current.S[6], current.S[7]
                        ]),
                                         parent=current.parent)
                        current.parent.add_child(new_state)
                        current.parent.delete_child(index=current.index)
                        current.parent = new_state
                        new_state.I.act = 'fork' + '(' + str(
                            new_state.S[new_state.I.names['pp']]) + ')'
                        current.I.act = 'setpgid' + '(' + str(
                            new_state.S[new_state.I.names['p']]) + ';' + str(
                                current.S[current.I.names['g']]) + ')'
                        new_state.add_child(current)

            else:
                print('forku')
                current.I.act = 'fork' + ' (' + str(
                    current.S[current.I.names['pp']]) + ')'

    return False, current