Ejemplo n.º 1
0
def createClassDefine(id):
    classDefine, className, classMap = createClassDefineCore(id)

    settingsMap = tree.Node("map")
    settingsPair = createPair("settings", settingsMap)

    variantsMap = tree.Node("map")
    variantsPair = createPair("variants", variantsMap)

    propertiesMap = tree.Node("map")
    propertiesPair = createPair("properties", propertiesMap)

    membersMap = tree.Node("map")
    membersPair = createPair("members", membersMap)

    staticsMap = tree.Node("map")
    staticsPair = createPair("statics", staticsMap)

    propertiesPair.addChild(createBlockComment("properties"))
    membersPair.addChild(createBlockComment("members"))
    staticsPair.addChild(createBlockComment("statics"))
    settingsPair.addChild(createBlockComment("settings"))
    variantsPair.addChild(createBlockComment("variants"))

    classMap.addChild(staticsPair)
    classMap.addChild(propertiesPair)
    classMap.addChild(membersPair)
    classMap.addChild(settingsPair)
    classMap.addChild(variantsPair)

    return classDefine, className, classMap, settingsMap, variantsMap, propertiesMap, membersMap, staticsMap
Ejemplo n.º 2
0
def p_declaracao_funcao(p):
    '''declaracao_funcao : tipo cabecalho
                         | cabecalho'''
    if len(p) > 2:
        p[0] = tree.Node(parser.get_next_id(), 'declaracao_funcao', p[1:])
    else:
        p[0] = tree.Node(parser.get_next_id(), 'declaracao_funcao', ['vazio', p[1]])
Ejemplo n.º 3
0
def p_corpo(p):
    '''corpo : corpo acao
             | empty'''
    if(p[1] != None):
        p[0] = tree.Node(parser.get_next_id(), 'corpo', p[1:])
    else:
        p[0] = tree.Node(parser.get_next_id(), 'corpo')
Ejemplo n.º 4
0
def DTL(examples, attributes, default):
    if not examples:
        return t.Node(dist=default, gain=0)

    elif sameclass(examples):
        return t.Node(dist=DISTRIBUTION(examples), gain=0)

    else:
        best_attribute, best_threshold, max_gain = choose_attribute(
            examples, attributes)
        tree = t.Node(best_attribute=best_attribute,
                      best_threshold=best_threshold,
                      gain=max_gain)
        examples_left, examples_right = separate(examples, best_attribute,
                                                 best_threshold)
        # Pruning
        if len(examples_left) < 50 or len(examples_right) < 50:
            tree.dist = DISTRIBUTION(examples)
            tree.best_threshold = -1
            tree.best_attribute = -1
            tree.gain = 0

        else:
            tree.left_child = DTL(examples_left, attributes,
                                  DISTRIBUTION(examples))
            tree.right_child = DTL(examples_right, attributes,
                                   DISTRIBUTION(examples))

        return tree
def build_tree(back, table, words):
    q = []
    i = 0
    j = len(words)
    label = 'TOP'
    top = tree.Node(label, [])
    count = 0
    q.append((top, i, j))
    while len(q) > 0:
        tuple_pop = q.pop()
        node = tuple_pop[0]
        i = tuple_pop[1]
        j = tuple_pop[2]
        back_tuple = back[(i, j, node.label)]
        if back_tuple:
            count += 1
            k = back_tuple[0]
            left = tree.Node(back_tuple[1], [])
            node.append_child(left)
            q.append((left, i, k))
            if back_tuple[2] is not '':
                right = tree.Node(back_tuple[2], [])
                node.append_child(right)
                q.append((right, k, j))
    t = tree.Tree(top)
    # print t.__str__()
    # # Q2
    # print "Output for the first line:"
    # print t.__str__()
    # print "Probability; ", table[(0, len(words), 'TOP')]
    if count > 0:
        return t.__str__()
    return ''
Ejemplo n.º 6
0
        def _makeTree(bitstream):
            """
            recursively construct a huffman tree from the encoding bit stream
            based on the schema specified in schema.py

            Time Complexity: O(m) where m is the no of individual unique chars
            used in the data. Note that indivdual number of chars are typically much
            smaller than total no of chars encoded or decoded. For example, the
            value of m will be 127 to decode any size of ascii data.
            """
            try:
                b = next(bitstream)
                if b == str(schema.LEAF_NODE):
                    n = next(bitstream)
                    return tree.Node(int(n,2))

                nodeleft = _makeTree(bitstream)
                noderight = _makeTree(bitstream)
                if noderight == None:
                    return  nodeleft

                node = tree.Node('*')
                node.add_left_child(nodeleft)
                node.add_right_child(noderight)
                return node
            except StopIteration:
                return None
Ejemplo n.º 7
0
    def setUp(self):
        self.child1 = tree.Node('child1')
        self.parent = tree.Node('parent')
        self.child2 = tree.Node('child2')

        self.child1.parent = self.parent
        self.child2.parent = self.parent
Ejemplo n.º 8
0
def p_lista_parametros(p):
    '''lista_parametros : lista_parametros VIRGULA parametro
                        | parametro
                        | empty'''
    if(p[1] != None):
        p[0] = tree.Node(parser.get_next_id(), 'lista_parametros', p[1:])
    else:
        p[0] = tree.Node(parser.get_next_id(), 'lista_parametros')
Ejemplo n.º 9
0
def p_lista_argumentos(p):
    '''lista_argumentos : lista_argumentos VIRGULA expressao
                        | expressao
                        | empty '''
    if(p[1] != None):
        p[0] = tree.Node(parser.get_next_id(), 'lista_argumentos', p[1:])
    else:
        p[0] = tree.Node(parser.get_next_id(), 'lista_argumentos')
Ejemplo n.º 10
0
 def _fake_tree_helper(lhs, rhs, antvalues):
     children = []
     for x in rhs:
         if sym.isvar(x):
             children.append(antvalues[sym.getindex(x) - 1])
         else:
             children.append(tree.Node(sym.tostring(x), []))
     return tree.Node(sym.totag(lhs), children)
Ejemplo n.º 11
0
 def _fake_tree_helper(lhs, rhs, antvalues):
     children = []
     for x in rhs:
         if isinstance(x, rule.Nonterminal):
             children.append(antvalues[x.getindex() - 1])
         else:
             children.append(tree.Node(x, []))
     return tree.Node(lhs.cat, children)
Ejemplo n.º 12
0
 def build_decision_tree(self):
     info = self.num_classes_in_data(self.data)
     d_tree = tree.Node(str(info[1][0]), 1.0)
     if (info[0] > 1):
         d_tree = self.build_decision_tree_r(self.data, tree.Node("", 1))
     else:
         d_tree = tree.Node(str(info[1][0]), 1.0)
     return d_tree
Ejemplo n.º 13
0
    def test_should_pass_None_to_the_child_parent(self):
        with patch('tree.Node.parent', new_callable=PropertyMock) as mock_prop:
            parent = tree.Node('parent')
            child = tree.Node('child')
            parent._children.append(child)
            child._parent = parent

            parent.remove_child(child)
            mock_prop.assert_called_with(None)
Ejemplo n.º 14
0
def createVariable(l):
    var = tree.Node("variable")

    for name in l:
        iden = tree.Node("identifier")
        iden.set("name", name)
        var.addChild(iden)

    return var
Ejemplo n.º 15
0
 def test_is_sub_tree(self):
     n1 = tree.Node(2)
     n2 = tree.Node(2)
     n3 = tree.Node(2)
     t = tree.Node(0, tree.Node(1, n1), n2)
     t.build_parents()
     n3.build_parents()
     self.assertTrue(ex10.is_sub_tree(t, n1))
     self.assertTrue(ex10.is_sub_tree(t, n2))
     self.assertFalse(ex10.is_sub_tree(t, n3))
Ejemplo n.º 16
0
def q_append_non_leaf(node, q):
    """This method will append null node children to the given node. (Step 2)
    
    When adding null nodes to a non-leaf node, the null nodes should exist on
    both side of the real children. This is why the first of each pair of
    children added sets the flag 'before=True', ensuring that on the left and
    right (or start and end) of the list of children a node is added."""
    for i in range(q-1):
        node.addkid(tree.Node("*"), before=True)
        node.addkid(tree.Node("*"))
Ejemplo n.º 17
0
def createPair(key, value, commentParent=None):
    par = tree.Node("keyvalue")
    sub = tree.Node("value")

    par.set("key", key)
    par.addChild(sub)
    sub.addChild(value)

    if commentParent and commentParent.hasChild("commentsBefore"):
        par.addChild(commentParent.getChild("commentsBefore"))

    return par
Ejemplo n.º 18
0
def grow():
    ct = tree.RBTree()
    ct.root = tree.Node(3)
    ct.root.left = tree.Node(1, ct.root)
    ct.root.right = tree.Node(5, ct.root)
    ct.root.left.left = tree.Node(0, ct.root.left)
    ct.root.left.right = tree.Node(2, ct.root.left)
    ct.root.right.left = tree.Node(4, ct.root.right)
    ct.root.right.right = tree.Node(7, ct.root.right)
    ct.root.right.right.left = tree.Node(6, ct.root.right.right)
    ct.root.right.right.right = tree.Node(8, ct.root.right.right)
    ct.root.right.right.right.right = tree.Node(9, ct.root.right.right.right)
    return ct
Ejemplo n.º 19
0
def traverse(t):
    """
    traverses the nltk tree
    """
    try:
        t.label()
    except AttributeError:
        return tree.Node(t[1])
    else:
        some_root = tree.Node(t.label())
        for child in t:
            some_root.addkid(traverse(child))
        return some_root
Ejemplo n.º 20
0
def inlineIfStatement(ifNode, conditionValue):
    """
    Inline an if statement assuming that the condition of the if
    statement evaluates to "conditionValue" (True/False")
    """

    if ifNode.type != "loop" or ifNode.get("loopType") != "IF":
        raise tree.NodeAccessException("Expected a the LOOP node of an if statement!", mapNode)

    replacement = []
    newDefinitions = []
    reovedDefinitions = []

    if ifNode.getChild("elseStatement", False):
        if conditionValue:
            reovedDefinitions = getDefinitions(ifNode.getChild("elseStatement"))
            newDefinitions = getDefinitions(ifNode.getChild("statement"))
            replacement = ifNode.getChild("statement").children
        else:
            reovedDefinitions = getDefinitions(ifNode.getChild("statement"))
            newDefinitions = getDefinitions(ifNode.getChild("elseStatement"))
            replacement = ifNode.getChild("elseStatement").children
    else:
        if conditionValue:
            newDefinitions = getDefinitions(ifNode.getChild("statement"))
            replacement = ifNode.getChild("statement").children
        else:
            reovedDefinitions = getDefinitions(ifNode.getChild("statement"))

    newDefinitions = map(lambda x: x.get("identifier"), newDefinitions)
    definitions = []
    for definition in reovedDefinitions:
        if not definition.get("identifier") in newDefinitions:
            definitions.append(definition)

    if len(definitions) > 0:
        defList = tree.Node("definitionList")
        defList.set("line", ifNode.get("line"))
        for definition in definitions:
            if definition.hasChildren():
                del definition.children
            defList.addChild(definition)
        replacement.append(defList)

    if replacement != []:
        replaceChildWithNodes(ifNode.parent, ifNode, replacement)
    else:
        emptyBlock = tree.Node("block");
        emptyBlock.set("line", ifNode.get("line"))
        ifNode.parent.replaceChild(ifNode, emptyBlock)
Ejemplo n.º 21
0
def randtree(depth=2, alpha='abcdefghijklmnopqrstuvwxyz', repeat=2, width=2):
    labels = [''.join(x) for x in itertools.product(alpha, repeat=repeat)]
    random.shuffle(labels)
    labels = (x for x in labels)
    root = tree.Node("root")
    p = [root]
    c = list()
    for x in xrange(depth - 1):
        for y in p:
            for z in xrange(random.randint(1, 1 + width)):
                n = tree.Node(labels.next())
                y.addkid(n)
                c.append(n)
        p = c
        c = list()
    return root
Ejemplo n.º 22
0
def parsefile(root_dir, filename, globals=[]):
    node = tree.Node(parsed_file.ParsedFile(root_dir, filename))
    fullpath = os.path.join(root_dir, filename)
    if os.path.exists(fullpath):
        #TODO add some info if file coudn't be opened
        #TODO handle circular includes
        with open(fullpath) as fp:
            for line in fp:
                match = BRACKET_INCLUDE_PATTERN.match(line)
                if match:
                    result = process_global_include(match.group("path"), globals)
                    if result is None:
                        result = process_local_include(match.group("path"), root_dir)
                    if result is None:
                        result=os.path.join("UNDETERMINED_PATH", match.group("path"))
                match = QUOTES_INCLUDE_PATTERN.match(line)
                if match:
                    result = process_local_include(match.group("path"), root_dir)
                    if result is None:
                        result = process_global_include(match.group("path"), globals)
                    if result is None:
                        result=os.path.join("UNDETERMINED_PATH", match.group("path"))
                if result is not None:
                    file_dir = os.path.dirname(result)
                    file_name = os.path.basename(result)
                    node.add_child(parsefile(file_dir, file_name, globals))

    return node
Ejemplo n.º 23
0
def makeForest(dataset, n, header):
    #print(" === Função makeForest")
    list_trees = []
    bootstrap_list = []

    #print("Dataset:")
    #print (*dataset,sep="\n")

    for i in range(n):
        #print("Criando Bootrap")
        bootstrap_list.append(bootstrap.bootstrap(dataset, len(dataset)))
        #print("Bootstrap criado")
        new_tree = tree.Node()
        bootstrap_list[i] = header.getHeader(bootstrap_list[i])
        #print(" ======== Conteudo do bootstrap list ========")
        #print (*bootstrap_list,sep="\n")
        #print("===============================================")

        makeTree(bootstrap_list[i], new_tree)

        #print("Arvore Criada")

        list_trees.append(new_tree)

    return list_trees
Ejemplo n.º 24
0
 def program(self):
     # root = t.Node("root"," ","r",True,True)
     temp = t.Node("root", " ", "r", False, False)
     root = self.stmt_sequence(temp)
     # program = Node(node)
     self.out.write("Program Found\n")
     return root
Ejemplo n.º 25
0
def createClassDefineCore(id):
    call = tree.Node("call")
    oper = tree.Node("operand")
    para = tree.Node("params")
    con = createConstant("string", id)
    args = tree.Node("map")

    call.addChild(oper)
    call.addChild(para)

    oper.addChild(createVariable(["qx", "Class", "define"]))

    para.addChild(con)
    para.addChild(args)

    return call, con, args
Ejemplo n.º 26
0
def zad4():
    tree_1 = tree.Node(d=tree.Data(4, str(4)))
    add_left(tree_1, tree.Data(3, str(3)))
    add_right(tree_1, tree.Data(6, str(6)))
    print_node(tree_minimum(tree_1))
    print_node(tree_maximum(tree_1))
    print_node(tree_successor(tree_1))
Ejemplo n.º 27
0
 def __init__(self):
     self.moves_num = 0
     self.mcts_batch = None
     self.current_node = tree.Node(tree.FakeNode(), 0, config.black,
                                   board.Board())
     self.current_node.is_game_root = True
     self.current_node.is_search_root = True
Ejemplo n.º 28
0
 def setUp(self):
     self.nodes = [tree.Node(i) for i in "abcdefg"]
     parent_index = 0
     for index, child in enumerate(self.nodes):
         if index == 0: continue
         child.parent = self.nodes[parent_index]
         parent_index += 1 if index % 2 == 0 else 0
Ejemplo n.º 29
0
    def _grow_tree(self, X, y, depth=0):
        """Build a decision tree by recursively finding the best split."""
        # Population for each class in current node. The predicted class is the one with
        # largest population.
        num_samples_per_class = [
            np.sum(y == i) for i in range(self.n_classes_)
        ]
        predicted_class = np.argmax(num_samples_per_class)
        node = tree.Node(
            gini=self._gini(y),
            num_samples=y.size,
            num_samples_per_class=num_samples_per_class,
            predicted_class=predicted_class,
        )

        # Split recursively until maximum depth is reached.
        if depth < self.max_depth:
            idx, thr = self._best_split(X, y)
            if idx is not None:
                indices_left = X[:, idx] < thr
                X_left, y_left = X[indices_left], y[indices_left]
                X_right, y_right = X[~indices_left], y[~indices_left]
                node.feature_index = idx
                node.threshold = thr
                node.left = self._grow_tree(X_left, y_left, depth + 1)
                node.right = self._grow_tree(X_right, y_right, depth + 1)
        return node
Ejemplo n.º 30
0
 def insert_helper(self, node, value):
     if node.data == value:
         return
     elif node.data > value:
         if not node.left:
             node.left = tree.Node(value)
             node.left.parent = node
         else:
             self.insert_helper(node.left, value)
     else:
         if not node.right:
             node.right = tree.Node(value)
             node.right.parent = node
         else:
             self.insert_helper(node.right, value)
     return