Example #1
0
    def search(self, b):
        # Create the root node
        root = node(None, self.start)

        # Initial explored set and frontier
        # Frontier: queue
        explorered_set = []
        frontier = queue.Queue(maxsize = -1)
        frontier.put(root)
        
        while not frontier.empty():
            # Expand shallowest unexpanded node
            cur_node = frontier.get()
            
            # Return when path is found
            if cur_node.position == self.goal:
                return path_list(cur_node)
            if cur_node.position in explorered_set:
                continue

            possible_moves = cur_node.position.available_moves(b)
            self.add_expanded_node()
            explorered_set.append(cur_node.position)

            for new_pos in possible_moves:
                # Create child node and append to parent
                child = node(cur_node, new_pos)
                cur_node.add_child(child)
                
                # Set frontier
                frontier.put(child)
        return []
Example #2
0
    def search(self, b):
        # Create the root node
        root = node(None, self.start)

        # Initial explored set and frontier
        # Frontier: stack
        explorered_set = []
        frontier = [root]
        
        while len(frontier):
            # Expand the deepest (most recent) unexpanded node
            cur_node = frontier.pop()

            # Return when path is found
            if cur_node.position == self.goal:
                return path_list(cur_node)
            if cur_node.position in explorered_set:
                continue
            
            possible_moves = cur_node.position.available_moves(b)
            self.add_expanded_node()
            explorered_set.append(cur_node.position)

            for new_pos in possible_moves:
                # Create child node and append to parent
                child = node(cur_node, new_pos)
                cur_node.add_child(child)
                
                # Set frontier
                frontier.append(child)
        return []
Example #3
0
    def search(self, b):
        # Create the root node
        root = node(None, self.start, 0)
        
        # Initial explored set and frontier
        # Frontier: priority queue
        explorered_set = []
        frontier = []
        pair = (estimated_cost(root.depth, root, self.goal), root)
        bisect.insort(frontier, pair)
        
        while len(frontier):
            # Expand the unexpanded node with the lowest
            # estimated total path cost
            cur_node = frontier.pop(0)[1]
            
            # Return when path is found
            if cur_node.position == self.goal:
                return path_list(cur_node)
            if cur_node.position in explorered_set:
                continue

            possible_moves = cur_node.position.available_moves(b)
            self.add_expanded_node()
            explorered_set.append(cur_node.position)

            for new_pos in possible_moves:
                # Create child node and append to parent
                child = node(cur_node, new_pos, cur_node.depth+1)
                cur_node.add_child(child)
                
                # Set frontier
                pair = (estimated_cost(child.depth, child, self.goal), child)
                bisect.insort(frontier, pair)
        return []
Example #4
0
def generate_random_tree(a):
    r = []
    for i in range(len(a)):
        r.append(i)
    # initialize the tree
    t = []
    for i in range(0, range(len(a))):
        # the id of the node is the actual value of the leaf
        # however, when referring to parents or children, we still use their actual index in the array
        t.append(node(a[i], -1, [], True))

    while len(r) >= 2:
        # continue drawing
        # every time draw a pair to merge together
        x = round(random.uniform(0, len(r) - 1))
        v_x = r[x]
        del r[x]
        y = round(random.uniform(0, len(r) - 1))
        v_y = r[y]
        del r[y]
        # replace with a new value and add to the tree
        v_p = len(t)
        r.append(v_p)
        # connect the new node v_p with v_x and v_y
        # here v_p in the index does not really matter
        t.append(node(v_p, -1, [v_x, v_y], False))
        t[v_x].parent = v_p
        t[v_y].parent = v_p

    return t
Example #5
0
def getMove(board, roll):

    validMoves = moveGen.getMoves(board, roll, 1)
    treeRoots = []
    #print validMoves
    for validMove in validMoves:
        root = tree.node()
        root.name = str(validMove)
        root.move = validMove
        newBoard = move(board, validMove[0][0], validMove[0][1], 1)
        newBoard = move(newBoard, validMove[1][0], validMove[1][1], 1)
        root.board = newBoard
        root.roll = roll
        treeRoots.append(root)

# What complete is essentaily the first max level
# So min first then max
# Each level should then consist of a call to the min max function
# Which will min then max
    highest = tree.node()
    for root in treeRoots:
        minMax(root)
        #print root.score
        #print root.name
        if root.score > highest.score:
            highest = root
    return highest.move
Example #6
0
def build_decision_tree(data, attributes, attributes_value, depth=0):
    root = tree.node()

    flag, label = is_finish(
        data, attributes)  #not empty, no attributes or data can't be seperated
    if flag:  # finish
        root.set_end(label)
        return root

    best_attribute, median = select_best_attribute(data, attributes)
    root.set_attributes(best_attribute, not attributes[best_attribute], median)
    #print( best_attribute , ' ', median )

    if attributes[best_attribute] == 0:  #distinct
        branch = tree.node()
        grouped = data.groupby(best_attribute)
        for value in attributes_value[best_attribute]:
            if value not in grouped.groups:  #数据集中该属性没有这个值
                branch.set_end(label)
                root.children[value] = branch
                continue
            group = grouped.get_group(value)  #get df for the group
            new_attributes = attributes.copy()
            del new_attributes[best_attribute]
            branch = build_decision_tree(group, new_attributes,
                                         attributes_value)
            root.children[value] = branch
    return root
Example #7
0
 def p_statements(p):
     """statements : statements statement
                   | statement"""
     if len(p) == 2:
         p[0] = node('statements', ch=[p[1]], no=p.lineno(1))
     else:
         p[0] = node('statements', ch=[p[1], p[2]], no=p.lineno(1))
def splitBDD(BDD,c1):
	if len(BDD.data) > c1-1:
		#print type(BDD),type(BDD.cutval),type(BDD.dimCutVal),type(BDD.data),type(BDD.n1),type(BDD.n2),type(BDD.LE),type(BDD.LEM)################
		cutVals = C2_criterion(BDD)
		BDD.n1 = tree.node(-1,-1,[],None,None,[],[])
		BDD.n2 = tree.node(-1,-1,[],None,None,[],[])
		for x in range(0,c1-1):
			if(BDD.data[x][cutVals[1]] <= cutVals[0]):
				BDD.n1.data.append(BDD.data[x])
			else:
				BDD.n2.data.append(BDD.data[x])
				pass
			pass
		BDD.cutval = cutVals[0]
		BDD.dimCutVal = cutVals[1]

		BDD.n1.LE = copy(BDD.LE)
		BDD.n1.LEM = copy(BDD.LEM)
		BDD.n2.LE = copy(BDD.LE)
		BDD.n2.LEM = copy(BDD.LEM)

		#supp de DATA LE et LEM du pere
		BDD.LE = []
		BDD.LEM = []
		BDD.data = []
	else:
		pass
Example #9
0
 def p_parameters(p):
     """parameters : parameters name
                   | name"""
     if len(p) == 2:
         p[0] = node('parameters', ch=[p[1]], no=p.lineno(1))
     elif len(p) == 3:
         p[0] = node('parameters', ch=[p[1], p[2]], no=p.lineno(1))
Example #10
0
def postpruning(root, data, attributes):
    if (root.is_a_leaf()):
        return root

    new_root = tree.node()
    new_root.set_attributes(root.get_attribute(), True)
    branchs = root.get_child_values()  #the branchs of this root node

    grouped = data.groupby(root.get_attribute())
    for branch in branchs:
        if branch in grouped.groups:  #the data have this attribute value
            child_data = grouped.get_group(
                branch)  #the data group with attribute values branch
            temp = root.get_child(branch)
            new_child = postpruning(temp, child_data, attributes)
            new_root.set_children(False, branch, new_child)
        else:  #the branch has no data to support it.
            new_child = tree.node()
            new_child.set_end(most_label(data))
            new_root.set_children(False, branch, new_child)

    no_split = tree.node()
    no_split.set_end(most_label(data))
    precision_pruning = model_test(no_split, data, attributes)

    precision_contrast = model_test(new_root, data, attributes)
    if precision_pruning >= precision_contrast:  #original is better
        return no_split
    return new_root
Example #11
0
def prepruning_DT(data, attributes, attributes_value, valid_data, depth=0):
    root = tree.node()

    flag, label = is_finish(
        data, attributes)  #not empty, no attributes or data can't be seperated
    if flag:  # finish
        root.set_end(label)
        return root

    best_attribute, median, flag = select_best_attribute_1(
        data, attributes, attributes_value, valid_data, label)
    if (not flag):  # flag means the split is ok
        root.set_end(label)
        return root
    root.set_attributes(best_attribute, not attributes[best_attribute], median)
    #print( best_attribute , ' ', median )

    if attributes[best_attribute] == 0:  #distinct
        branch = tree.node()
        grouped = data.groupby(best_attribute)
        for value in attributes_value[best_attribute]:
            if value not in grouped.groups:  #数据集中该属性没有这个值
                branch.set_end(label)
                root.children[value] = branch
                continue
            group = grouped.get_group(value)  #get df for the group
            new_attributes = attributes.copy()
            del new_attributes[best_attribute]
            branch = prepruning_DT(group, new_attributes, attributes_value,
                                   valid_data)
            root.children[value] = branch
    return root
def Low(father):
	global lookahead, token_list, node

	LOW = node()
	nt_init(father, LOW, "Low", [])

	if match("intc"):
		T_INTC = node()
		t_init(LOW, T_INTC, lookahead[1], [])
def Top(father):
	global lookahead, token_list, node

	TOP = node()
	nt_init(father, TOP, "Top", [])

	if match("intc"):
		T_INTC = node()
		t_init(TOP, T_INTC, lookahead[1], [])
def ProcName(father):
	global lookahead, token_list, node

	PROCNAME = node()
	nt_init(father, PROCNAME, "ProcName", [])

	if match("id"):
		T_ID = node()
		t_init(PROCNAME, T_ID, lookahead[1], [])
def Invar(father):
	global lookahead, token_list, node

	INVAR = node()
	nt_init(father, INVAR, "Invar", [])

	if match("id"):
		T_ID = node()
		t_init(INVAR, T_ID, lookahead[1], [])
def TypeId(father):
	global lookahead, token_list, node

	TYPEID = node()
	nt_init(father, TYPEID, "TypeId", [])

	if match("id"):
		T_ID = node()
		t_init(TYPEID, T_ID, lookahead[1], [])
def ReturnStm(father):
	global lookahead, token_list, node

	RETURNSTM = node()
	nt_init(father, RETURNSTM, "ReturnStm", [])

	if match("return"):
		T_RETURN = node()
		t_init(RETURNSTM, T_RETURN, "return", [])
def IdList(father):
	global lookahead, token_list, node

	IDLIST = node()
	nt_init(father, IDLIST, "IdList", [])

	if match("id"):
		T_ID = node()
		t_init(IDLIST, T_ID, lookahead[1], [])
	IdMore(IDLIST)
def VarDec(father):
	global lookahead, token_list, node

	VARDEC = node()
	nt_init(father, VARDEC, "VarDec", [])

	if match("var"):
		T_VAR = node()
		t_init(VARDEC, T_VAR, "var", [])
	VarDecList(VARDEC)
def VarIdList(father):
	global lookahead, token_list, node

	VARIDLIST = node()
	nt_init(father, VARIDLIST, "VarIdList", [])

	if match("id"):
		T_ID = node()
		t_init(VARIDLIST, T_ID, lookahead[1], [])
	VarIdMore(VARIDLIST)
def Variable(father):
	global lookahead, token_list, node

	VARIABLE = node()
	nt_init(father, VARIABLE, "Variable", [])

	if match("id"):
		T_ID = node()
		t_init(VARIABLE, T_ID, lookahead[1], [])
	VariMore(VARIABLE)
def FormList(father):
	global lookahead, token_list, node

	FORMLIST = node()
	nt_init(father, FORMLIST, "FormList", [])

	if match("id"):
		T_ID = node()
		t_init(FORMLIST, T_ID, lookahead[1], [])
	FidMore(FORMLIST)
def FieldVar(father):
	global lookahead, token_list, node

	FIELDVAR = node()
	nt_init(father, FIELDVAR, "FieldVar", [])

	if match("id"):
		T_ID = node()
		t_init(FIELDVAR, T_ID, lookahead[1], [])
	FieldVarMore(FIELDVAR)
Example #24
0
 def p_declaration(p):
     """declaration : type name EQUALS expression
                    | MAP name"""
     if len(p) == 3:
         p[0] = node('declaration', val=p[1], ch=p[2], no=p.lineno(1))
     else:
         p[0] = node('declaration',
                     val=p[1],
                     ch=[p[2], p[4]],
                     no=p.lineno(1))
def ProgramHead(father):
	global lookahead, token_list, node

	PROGRAMHEAD = node()
	nt_init(father, PROGRAMHEAD, "ProgramHead", [])

	if match("program"):
		T_PROGRAM = node()
		t_init(PROGRAMHEAD, T_PROGRAM, "program", [])
	ProgramName(PROGRAMHEAD)
Example #26
0
def get_url_path(starturl, target, limit=1):
    targetSubject = get_subjects([target])[0]
    startSubject = get_subjects([start])[0]

    # make a tree with start url as head
    head = node(starturl)
    t = tree(head)

    # queue of new nodes to try searching from
    searchOrder = queue()
    searchOrder.add(t.getHead(), subject_distance(startSubject, targetSubject))

    # set of all urls that have already been searched from
    allAdded = set()
    allAdded.add(t.getHead().getData())

    # LOOP:
    # set head to current node
    curr = searchOrder.pop()
    targetFound = False
    while not targetFound:
        # get child nodes/urls of current node
        currUrl = curr.getData()
        # print(f"getting article: {get_subjects([currUrl])[0]}")

        # if url is a valid article
        if valid_url(currUrl):
            childUrls = get_child_urls(currUrl)

            # check if target destination in children
            for url in childUrls:
                # add child urls to tree as child nodes of curr
                newNode = node(url)
                t.add(newNode, curr)

                currSubject = get_subjects([url])[0]
                currDist = subject_distance(currSubject, targetSubject)
                print(f"{currDist:.5f} - {currSubject}")

                # if target, then return path to this node
                if target.lower() == url.lower():
                    targetFound = True
                    fullPath = t.getPath(newNode)
                    return fullPath, len(allAdded)
                else:
                    # if not, then add children to tree and queue for bfs
                    if newNode.getData() not in allAdded:
                        searchOrder.add(newNode, currDist)
                        allAdded.add(newNode.getData())
        else:
            print("breaking because of invalid url ^")

        # change curr to next node in queue
        curr = searchOrder.pop()
def AssignmentRest(father):
	global lookahead, token_list, node

	ASSIGNMENTREST = node()
	nt_init(father, ASSIGNMENTREST, "AssignmentRest", [])

	VariMore(ASSIGNMENTREST)
	if match(":="):
		T_ASSIGNMENT = node()
		t_init(ASSIGNMENTREST, T_ASSIGNMENT, ":=", [])
	Exp(ASSIGNMENTREST)
def ProcDecMore(father):
	global lookahead, token_list, node

	PROCDECMORE = node()
	nt_init(father, PROCDECMORE, "ProcDecMore", [])

	if lookahead[1] == "procedure":
		ProcDec(PROCDECMORE)
	else:
		T_VOID = node()
		t_init(PROCDECMORE, T_VOID, "ε", [])
def VarDecPart(father):
	global lookahead, token_list, node

	VARDECPART = node()
	nt_init(father, VARDECPART, "VarDecPart", [])

	if lookahead[1] == "var":
		VarDec(VARDECPART)
	else:
		T_VOID = node()
		t_init(VARDECPART, T_VOID, "ε", [])
def ProcDecpart(father):
	global lookahead, token_list, node

	PROCDECPART = node()
	nt_init(father, PROCDECPART, "ProcDecpart", [])

	if lookahead[1] == "procedure":
		ProcDec(PROCDECPART)
	else:
		T_VOID = node()
		t_init(PROCDECPART, T_VOID, "ε", [])
def TypeDecMore(father):
	global lookahead, token_list, node

	TYPEDECMORE = node()
	nt_init(father, TYPEDECMORE, "TypeDecMore", [])

	if lookahead[2] == "id":
		TypeDecList(TYPEDECMORE)
	else:
		T_VOID = node()
		t_init(TYPEDECMORE, T_VOID, "ε", [])
def BaseType(father):
	global lookahead, token_list, node

	BASETYPE = node()
	nt_init(father, BASETYPE, "BaseType", [])

	if match("integer"):
		T_INTEGER = node()
		t_init(BASETYPE, T_INTEGER, "integer", [])
	elif match("char"):
		T_CHAR = node()
		t_init(BASETYPE, T_CHAR, "char", [])
def VarDecList(father):
	global lookahead, token_list, node

	VARDECLIST = node()
	nt_init(father, VARDECLIST, "VarDecList", [])

	TypeDef(VARDECLIST)
	VarIdList(VARDECLIST)
	if match(";"):
		T_SEMICOLON = node()
		t_init(VARDECLIST, T_SEMICOLON, ";", [])
	VarDecMore(VARDECLIST)
def OtherTerm(father):
	global lookahead, token_list, node

	OTHERTERM = node()
	nt_init(father, OTHERTERM, "OtherTerm", [])

	if lookahead[1] in ["+", "-"]:
		AddOp(OTHERTERM)
		Exp(OTHERTERM)
	else:
		T_VOID = node()
		t_init(OTHERTERM, T_VOID, "ε", [])
def OtherFactor(father):
	global lookahead, token_list, node

	OTHERFACTOR = node()
	nt_init(father, OTHERFACTOR, "OtherFactor", [])

	if lookahead[1] in ["*", "/"]:
		MultOp(OTHERFACTOR)
		Term(OTHERFACTOR)
	else:
		T_VOID = node()
		t_init(OTHERFACTOR, T_VOID, "ε", [])
def RecType(father):
	global lookahead, token_list, node

	RECTYPE = node()
	nt_init(father, RECTYPE, RecType, [])

	if match("record"):
		T_RECORD = node()
		t_init(RECTYPE, T_RECORD, "record", [])
	FieldDecList(RECTYPE)
	if match("end"):
		T_END = node()
		t_init(RECTYPE, T_END, "end", [])
def CallStmRest(father):
	global lookahead, token_list, node

	CALLSTMTREST = node()
	nt_init(father, CALLSTMTREST, "CallStmTRest", [])

	if match("("):
		T_LEFT_SM_COL = node()
		t_init(CALLSTMTREST, T_LEFT_SM_COL, "(", [])
	ActParamList(CALLSTMTREST)
	if match(")"):
		T_RIGHT_SM_COL = node()
		t_init(CALLSTMTREST, T_RIGHT_SM_COL, ")", [])
def FieldDecMore(father):
	global lookahead, token_list, node

	FIELDDECMORE = node()
	nt_init(father, FIELDDECMORE, "FieldDecList", [])

	if lookahead[1] == "integer":
		FieldDecList(FIELDDECMORE)
	elif lookahead[1] == "char":
		FieldDecList(FIELDDECMORE)
	else:
		T_VOID = node()
		t_init(FIELDDECMORE, T_VOID, "ε", [])
def VarDecMore(father):
	global lookahead, token_list, node

	VARDECMORE = node()
	nt_init(father, VARDECMORE, "VarDecMore", [])

	if lookahead[2] == "id":
		VarDecList(VARDECMORE)
	elif lookahead[1] in ["integer", "array", "char"]:
		VarDecList(VARDECMORE)
	else:
		T_VOID = node()
		t_init(VARDECMORE, T_VOID, "ε", [])
Example #40
0
 def p_logic_expression(p):
     """logic_expression : LT expression expression
                        | GT expression expression
                        | NOT expression
                        | NOT call
                        | OR or_arg or_arg"""
     if len(p) == 4:
         p[0] = node('math_expression',
                     p[1],
                     ch=[p[2], p[3]],
                     no=p.lineno(1))
     else:
         p[0] = node('math_expression', p[1], ch=p[2], no=p.lineno(1))
def ParamList(father):
	global lookahead, token_list, node

	PARAMLIST = node()
	nt_init(father, PARAMLIST, "ParamList", [])

	if lookahead[2] == "id":
		ParamDecList(PARAMLIST)
	elif lookahead[1] in ["char", "integer", "array"]:
		ParamDecList(PARAMLIST)
	else:
		T_VOID = node()
		t_init(PARAMLIST, T_VOID, "ε", [])
def ProgramBody(father):
	global lookahead, token_list, node

	PROGRAMBODY = node()
	nt_init(father, PROGRAMBODY, "ProgramBody", [])

	if match("begin"):
		T_BRGIN = node()
		t_init(PROGRAMBODY, T_BRGIN, "begin", [])
	StmList(PROGRAMBODY)
	if match("end"):
		T_END = node()
		t_init(PROGRAMBODY, T_END, "end", [])
Example #43
0
 def p_procedure(self, p):
     """procedure : PROC NAME LBR parameters RBR NEWLINE statements_group """
     if p[2] in self._functions:
         sys.stderr.write(
             f'>>> procedure name duplicate at {p.lineno(1)} line\n')
         self.ok = False
     else:
         self._functions[p[2]] = node('procedure',
                                      ch={
                                          'parameters': p[4],
                                          'body': p[7]
                                      },
                                      no=p.lineno(1))
         p[0] = node('procedure_description', val=p[2])
Example #44
0
def build_decision_tree(data, attributes, attributes_value, depth=0):
    root = tree.node()

    grouped = data.groupby('label')
    if grouped.size().size == 1:  # all belong to the same class
        label = data['label'].values[0]  # get the only label
        root.set_end(label)
        return root
    flag, label = is_finish(data, attributes)  #not empty
    if flag:  # finish
        root.set_end(label)
        return root
    best_attribute, median = select_best_attribute(data, attributes)
    if attributes[best_attribute]:
        root.set_attributes(best_attribute, False, median)
    else:
        root.set_attributes(best_attribute, True, median)
    if not attributes[best_attribute]:  # not distinct
        grouped = data.groupby(best_attribute)
        for value in attributes_value[best_attribute]:
            branch = tree.node()
            if value not in grouped.groups:
                label = most_label(data)
                branch.set_end(label)
                root.children[value] = branch
                continue
            group = grouped.get_group(value)
            new_attributes = attributes.copy()
            del new_attributes[best_attribute]
            branch = build_decision_tree(group, new_attributes,
                                         attributes_value, depth + 1)
            root.children[value] = branch
    else:  # continue attribute
        #		filter, median
        gtr = data[data[best_attribute] > median]
        leq = data[data[best_attribute] <= median]

        if gtr.shape[0] > 0:
            new_attributes = attributes.copy()
            del new_attributes[best_attribute]
            branch1 = build_decision_tree(gtr, new_attributes,
                                          attributes_value, depth + 1)
            root.children['gtr'] = branch1
        if leq.shape[0] > 0:
            new_attributes = attributes.copy()
            del new_attributes[best_attribute]
            branch2 = build_decision_tree(leq, new_attributes,
                                          attributes_value, depth + 1)
            root.children['leq'] = branch2
    return root
Example #45
0
 def p_cell_proc(p):
     """cell_proc : BAR LBR cell_arg RBR
                  | EMP LBR cell_arg RBR
                  | SET LBR cell_arg RBR
                  | RESET LBR cell_arg RBR
                  | CLR LBR cell_arg RBR"""
     p[0] = node('cell_proc', p[1], ch=p[3], no=p.lineno(1))
Example #46
0
 def p_command(p):
     """command : LEFT
                 | RIGHT
                 | BACK
                 | STEP
                 | LOOK"""
     p[0] = node('robot', p[1], no=p.lineno(1))
Example #47
0
 def p_statements_group(p):
     """statements_group : LPAREN statements inner_statement RPAREN
                         | inner_statement"""
     if len(p) == 5:
         p[0] = node('statements', ch=[p[2], p[3]], no=p.lineno(1))
     else:
         p[0] = p[1]
Example #48
0
 def p_while(p):
     """while : WHILE logic_expression DO NEWLINE statements_group"""
     p[0] = node('while',
                 ch={
                     'condition': p[2],
                     'body': p[5]
                 },
                 no=p.lineno(1))
Example #49
0
 def p_call_err0(p):
     """cell_proc :  BAR error
                  | EMP error
                  | SET error
                  | RESET error
                  | CLR error"""
     p[0] = node('error', val="Function call error", no=p.lineno(1))
     sys.stderr.write(f'>>> Procedure call error\n')
Example #50
0
 def p_if(p):
     """if :  IF logic_expression NEWLINE statements_group NEWLINE ELSE statements_group"""
     p[0] = node('if',
                 ch={
                     'condition': p[2],
                     'body': p[4],
                     'else': p[7]
                 },
                 no=p.lineno(1))
Example #51
0
def build_file_tree(rootDir):
    cPath = rootDir.getfpath() + rootDir.getdata()
    cList = os.listdir(cPath)
    cPath += "/"
    nodeList = []
    for item in cList:
        # pdb.set_trace()
        if isgit(item):
            continue
        if os.path.isfile(cPath + item):
            cfile = node(item)
            cfile.setfpath(cPath)
            rootDir.add(cfile)
        else:
            nextdir = node(item)
            nextdir.setfpath(cPath)
            build_file_tree(nextdir)
            rootDir.add(nextdir)
Example #52
0
    def search(self, b):
        # Initial depth limit
        depth_limit = -1

        while True:
            # Set depth limit
            depth_limit += 1

            # Create the root node
            root = node(None, self.start, 0)

            # Initial explored set and frontier
            # Frontier: stack
            explorered_set = []
            frontier = [root]
            
            while len(frontier):
                # Expand the deepest (most recent) unexpanded node
                # where depth not greater than depth limit
                cur_node = frontier.pop()
                
                # Return when path is found
                if cur_node.position == self.goal:
                    return path_list(cur_node)
                if cur_node.depth == depth_limit:
                    continue
                if cur_node.position in explorered_set:
                    continue
                
                possible_moves = cur_node.position.available_moves(b)
                self.add_expanded_node()
                explorered_set.append(cur_node.position)

                for new_pos in possible_moves:
                    # Create child node and append to parent
                    child = node(cur_node, new_pos, cur_node.depth+1)
                    cur_node.add_child(child)
                    
                    # Set frontier
                    frontier.append(child)
                    
                    if len(explorered_set) >= math.pow(b.size, 2):
                        return []
        return []
Example #53
0
    def SplitData(self, data, features, node):
        attribute = features[0]
        if len(features) > 1:
            o = self.OptimiseInfoGain(data, features)
            attribute = o[0]

        
        classes = data[attribute].unique()
        
        columns = features[:]
        columns.remove(attribute)

        for c in classes:

            toSplit = data[attribute] == c
            selected_data = data[toSplit]

            
            child = tree.node({"A": attribute, "Class": c})

            p = 0
            n = 0
            
            for index, row in selected_data.iterrows():
                if  row["Stream"] == "Yes":
                    p += 1
                else:
                    n += 1

            print ("\n", attribute, c, "\n", selected_data, "\n", p, n, "\n")

            if p == 0 or n == 0:
                if n == 0:
                    leaf = tree.Leaf(1, 0)
                    child.add_node(leaf)
                else:
                    leaf = tree.Leaf(0, 1)
                    child.add_node(leaf)

                node.add_node(child)
            
            elif len (columns) == 0:
                total = p + n
                leaf = tree.Leaf(p/total, n/total)
                child.add_node(leaf)

                node.add_node(child)

            else:
                print ("enter recurse")
                self.SplitData(selected_data, columns, child)
                node.add_node(child)
                print ("exited recurse")
            print ("nodes added:", attribute, c)
Example #54
0
def get_bst(a):
    if len(a) <= 0:
        return [None]
    res = []
    for idx in range(len(a)):
        left_trees = get_bst(a[:idx])
        right_trees = get_bst(a[idx + 1:])
        res += [
            node(data=a[idx], left=lt, right=rt) for lt in left_trees
            for rt in right_trees
        ]
    return res
Example #55
0
def get_binary_trees(num):
    if num == 0:
        return [None]
    cur_res = []
    for left_n in range(num):
        right_n = num - 1 - left_n
        left_trees = get_binary_trees(left_n)
        right_trees = get_binary_trees(right_n)
        cur_res += [
            node(data=0, left=left, right=right) for left in left_trees
            for right in right_trees
        ]
    return cur_res
    def execute(self):
        sink_func = sys.argv[0]
        arg_num = sys.argv[1]

        #root_node = tree.node(sink_func)
        for node_id in self.get_sink(sink_func, arg_num):
            print "Now, the sink node id is ", node_id
            sink_node = tree.node(node_id)
            self.sink_source_tree._head.add(sink_node)
            current_path = []
            self.get_source(sink_node)
            print "ok"
            '''current_node.add(node_id)
Example #57
0
    def SplitData(self, data, features, node):
        attribute = features[0]
        if len(features) > 1:
            optimsed = self.OptimiseInfoGain(data, features)
            attribute = optimsed[0]

        
        classes = data[attribute].unique()
        
        columns = features[:]
        columns.remove(attribute)

        for c in classes:

            toSplit = data[attribute] == c
            selected_data = data[toSplit]

            
            child = tree.node({"A": attribute, "Class": c})

            p = 0
            n = 0
            
            for index, row in selected_data.iterrows():
                if  self.y[index] == "<=50K":
                    p += 1
                else:
                    n += 1


            if p == 0 or n == 0:
                if n == 0:
                    leaf = tree.Leaf(1, 0)
                    child.add_node(leaf)
                else:
                    leaf = tree.Leaf(0, 1)
                    child.add_node(leaf)

                node.add_node(child)
            
            elif len (columns) == 0:
                total = p + n
                leaf = tree.Leaf(p/total, n/total)
                child.add_node(leaf)

                node.add_node(child)

            else:
                self.SplitData(selected_data, columns, child)
                node.add_node(child)
    def get_source(self, node):
        #source_current_func=get_source_within_func(node_id)
        #node.add(node_id)
        node_id = node.getdata()
        last_source = node_id
        if not self.wether_is_over(last_source):
            ###sources() get the parameter nodes'''
            if self.get_type(last_source) == "Argument":
                last_source_tmp = self.get_source_within_func(last_source)
                last_sources = last_source_tmp
                for last_source in last_sources:
                    node.add(tree.node(last_source))
                for source_node in last_sources:
                    identifier_node = self.get_Identifier_source(source_node)
                    if identifier_node is not None:
                        for neighbor_source in identifier_node:

                            node.add(self.get_source(neighbor_source))
            ###this should get the arguement nodes'''
            elif len(self.get_source_between_func(last_source)) != 0:
                last_source_tmp = self.get_source_between_func(last_source)
                last_source = last_source_tmp
                node.add(last_source)
                for source_node in last_source:
                    identifier_node = self.get_Identifier_source(source_node)
                    if identifier_node is not None:
                        for neighbor_source in identifier_node:
                            node.add(self.get_source(neighbor_source))
            ###sources() get the IdentifierDeclStatement nodes'''
            elif len(self.get_source_of_IdentifierDeclStatement(
                    last_source)) != 0:
                last_source_tmp = self.get_source_of_IdentifierDeclStatement(
                    last_source)
                last_source = last_source_tmp
                node.add(last_source)
                for source_node in last_source:
                    identifier_node = self.get_Identifier_source(source_node)
                    if identifier_node is not None:
                        for neighbor_source in identifier_node:
                            node.add(self.get_source(neighbor_source))
Example #59
0
def add_children_from_MyNode(tree_file):
    # add children
    tree = np.load(tree_file, allow_pickle=True, encoding='latin1')

    # a new tree with a simplified structure
    Tree = []

    # read the npy file and put them in MyNode
    for i in range(len(tree)):
        node_ = tree[i]
        parent = node_.parentID
        ID = i
        Tree.append(node(ID, parent, [], False))
        # update the children of its parent
        if parent != -1:
            Tree[parent].children.append(ID)

    # identify the leaves
    for i in range(len(Tree)):
        if len(Tree[i].children) == 0:
            Tree[i].is_leaf = True

    return Tree
import tree

dict = {}


def vertical_sum(root, distance):
    if (not root):
        return

    if (distance in dict):
        dict[distance] += root.data
    else:
        dict[distance] = root.data
    vertical_sum(root.left, distance - 1)
    vertical_sum(root.right, distance + 1)


bst = tree.Tree()
bst.root = tree.node(5)
bst.root.left = tree.node(2)
bst.root.right = tree.node(3)
bst.root.left.left = tree.node(1)
bst.root.left.right = tree.node(7)
bst.root.right.left = tree.node(6)

vertical_sum(bst.root, 0)
for k in sorted(dict.keys()):
    print(dict[k], end=' ')

print()