def find_solution_rec_DFS(node, solution, visited, limit):
    if limit > 0:
        visited.append(node)
        if node.get_data() == solution:
            return node
        else:
            # expand children nodes (cities with connection)
            node_data = node.get_data();
            children_list = []
            for a_child in connections[node_data]:
                child = Node(a_child)
                if not child.on_list(visited):
                    children_list.append(child)

            node.set_children(children_list)

            for child_node in node.get_children():
                if not child_node.get_data() in visited:
                    # recursive call
                    sol = find_solution_rec_DFS(child_node, solution, \
                                                visited, limit-1)
                    if sol != None:
                        return sol

        return None
Example #2
0
def p_formalDecl(p):
    '''formalDecl : typeSpecifier IDENTIFIER
                  | typeSpecifier IDENTIFIER LBRACKET RBRACKET'''
    varName = p[2]
    varType = p[1].children[0].type
    for item in global_scope:
        if item[1] == varName:
            if item[0] == varType:
                print "Warning : Shadowing global variable %s near line %s.\n"  % (varName, p.lexer.lineno)
                
    match = False
    for item in local_scope:
        if item[1] == varName: #same identifier
            if item[0] == varType: #same type
                print "Syntax Error: Redefinition of local variable %s with type %s near line %s.\n" % \
                      (varName, varType, p.lexer.lineno)
            else:
                print "Syntax Error: Redefinition of local variable %s with type %s (originally type %s) near line %s.\n" % \
                      (varName, varType, item[0], p.lexer.lineno)
            global syntaxerrs
            syntaxerrs += 1
            match = True
                
    if not match:
        if DEBUG:
            print "New local variable %s %s declared near line %s.\n" % (varType, varName, p.lexer.lineno)
            
        if len(p) > 3:
            local_scope.append((varType, varName, "array"))
        else:
            local_scope.append((varType, varName))
            
    p[0] = Node("formalDecl", p[1:])
    if len(p) > 3:
        p[0].subtype = 'array'
def main():
    root = Node(0)
    root.set_right(10)
    root.right.set_right(20)
    root.right.set_left(5)
    root.set_left(-10)
    print get_common_ancestor(root.right.right, root.right.left)
def find_solution_BFS(connections, initial_state, solution):
    solved = False
    visited_nodes = []
    frontier_nodes = []
    startNode = Node(initial_state)
    frontier_nodes.append(startNode)
    while(not solved) and len(frontier_nodes) != 0:
        node = frontier_nodes[0]
        # extract node and add it to visited_nodes
        visited_nodes.append(frontier_nodes.pop(0));
        if node.get_data() == solution:
            # solution found
            solved = True
            return node
        else:
            # expand child nodes (cities with connection)
            node_data = node.get_data();
            children_list = []
            for one_child in connections[node_data]:
                child = Node(one_child)
                children_list.append(child)
                if not child.on_list(visited_nodes) \
                   and not child.on_list(frontier_nodes):
                    frontier_nodes.append(child)

            node.set_children(children_list)
Example #5
0
 def testAll(self):
   if IGNORE_TEST:
     return
   node = Node(NAME)
   self.assertEqual(node.getName(), NAME)
   node.setName(NAME2)
   self.assertEqual(node.getName(), NAME2)
Example #6
0
	def make_tree(self):
		"""
		Constructs the tree by iterating nodesList.
		"""
		while self.nodesList:
			row = self.nodesList.pop(0)
			nodeId = self.idFn(row)
			#print 'make_tree,row is %s, node id is %s'%(row,nodeId)
			
			try:
				node = self.rootNode.get_child_by_id(nodeId)
			except:
				node = None
			
			if not node:
				node = Node(nodeId)
				node.data = row
				#print 'make_tree,created a new node, id is ',node.id
				parentId = self.pidFn(row)	
					
				# creates it's parent node and recursivelly creates the ancestor nodes of this node.
				self.parent(parentId, node)
				
				#print '****make_tree is end, maked branch is ******\n',self.rootNode
				#print 70*'-'
		
		return
def main():
    root = Node(0)
    root.left = Node(-10)
    root.left.left = Node(-20)
    root.left.right = Node(-5)
    root.left.left.right = Node(-15)
    root.right = Node(10)
    print lca(root, -15, -5)
def main():
    root = Node(0)
    root.left = Node(-10)
    root.left.left = Node(-20)
    root.left.right = Node(-5)
    root.right = Node(10)
    root.right.right = Node(20)
    print get_tree_median(root)
Example #9
0
def createMinTree(low,high):
	if(low>high):
		return
	mid = (low + high)/2
	data = treeElements[mid]
	node = Node(data)
	node.left = createMinTree(low,mid-1)
	node.right = createMinTree(mid+1,high)
	return node
def main():
    root = Node(0)
    root.right = Node(1)
    print is_binary_search_tree(root, -float("inf"), float("inf"))
    root = Node(0)
    root.right = Node(2)
    root.right.left = Node(1)
    root.right.right = Node(1)
    print is_binary_search_tree(root, -float("inf"), float("inf"))
def main():
    root = Node(0)
    root.left = Node(1)
    root.left.left = Node(2)
    root.right = Node(1)
    root.right.right = Node(2)
    root.right.right.right = Node(3)
    root.right.left = Node(2)
    print is_balanced(root)
Example #12
0
 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')
Example #13
0
def main():
    root = Node(0)
    root.left = Node(1)
    root.right = Node(2)
    root.left.left = Node(3)
    root.left.right = Node(4)
    root.right.left = Node(5)
    root.right.right = Node(6)
    for i in range(7):
        print bfs(root, i), "\n"
def build_tree(lst):
    if lst == []:
        return
    middle = len(lst) / 2
    left_list = lst[:middle]
    right_list = []
    if len(lst) > 1:
        right_list = lst[middle + 1:]
    node = Node(lst[middle])
    node.left = build_tree(left_list)
    node.right = build_tree(right_list)
    return node
def main():
    root = Node(1)
    root.set_left(1)
    root.left.set_left(2)
    root.left.set_right(1)
    root.set_right(2)
    root.right.set_left(1)
    root.right.set_right(1)
    root.right.left.set_left(2)
    count = [0]
    count_all_sums(root, count, 2)
    print count
Example #16
0
	def make_node(self,nodeId):
		"""
		Filters the row from self.nodesList by nodeId,
		and create a new Node.
		After node's creation,the row will be removed from the nodesList.
		"""
		row = filter( lambda i: self.idFn(i)==nodeId , self.nodesList)[0]
		#print 'make_node,row is %s, node id is %s'%(row,nodeId)
		node = Node(nodeId)
		node.data = row
		self.nodesList.remove(row)		
		return node
Example #17
0
def parse_ontology(inp):
    """
    Read the ontology and return it as a tree where labels are categories.
    """
    root = Node()
    root.label = 'root'
    # We add an empty first line so that lineno can start at 1, and therefore
    # match the actual line number in the file, which is 1-indexed.
    lines = [''] + inp.readlines()
    lineno = parse_ontology_level(lines, 1, 0, root)
    if lineno != len(lines):
        raise ValueError("line {}: underindented".format(lineno))
    return root
Example #18
0
	def __init__(self, tier, start_time, end_time, data):
		'''
	 	@param tier: The Tier object representing the tier the entry is on.
	 	@param start_time: The start time of the entry.
	 	@param end_time: The end time of the entry.
	 	@param data: The annotation data the entry represents.
	 	'''
		TimeSeriesData.__init__(self, start_time, end_time)
		Node.__init__(self, tier)
		self._data = data
		
		# Pre-cache the member hash
		self.__hash = self.__calculate_hash()
Example #19
0
    def test_default_cted_node_is_empty(self):
        node = Node()

        self.assertFalse(node.cycle_check)
        self.assertTrue(node._parent is None)
        self.assertEqual([], node._children)

        self.assertTrue(node.parent is None)
        self.assertTrue(node.is_root())
        self.assertTrue(node.is_leaf())
        self.assertFalse(node)

        self.assertEqual(0, len(node))
        self.assertEqual(0, descendants_len(node))
Example #20
0
    def testParent(self):
        head = Node(None, None)
        self.assertTrue(head.Parent is None)
        self.assertTrue(head.Left is None)
        self.assertTrue(head.Right is None)
        self.assertTrue(head.depth == 0)
        self.assertTrue(head.is_left is None)

        head.feature = 0
        head.threshold = 1.0
        self.assertTrue(head.feature == 0)
        self.assertTrue(head.threshold == 1.0)
        self.assertTrue(head._feature == 0)
        self.assertTrue(head._threshold == 1.0)
Example #21
0
def Decompress(filename, outputName):
    with codecs.open(filename, 'r', 'utf-8') as file:
        # Ler arvore (reconstruir)
        reader = bit.Reader(file)
        root = readTree(reader)
        if root == None:
            raise ErroNaArvore("Nula!")

        # Decodificar percorrendo a arvore
        if root.isLeaf():
            nodeHelper = Node()
            nodeHelper.Left = root
            root = nodeHelper

        decodeFile(reader, outputName, root)
Example #22
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
Example #23
0
	def setUp(self):
		self.n4 = Node(4)
		n3 = Node(3)
		n6 = Node(6)
		n7 = Node(7)

		n2 = Node(2, self.n4, n3)
		n5 = Node(5, n6, n7)
		self.n1 = Node(1, n2, n5)

		n2.parent = self.n1
		n5.parent = self.n1
		self.n4.parent = n2
		n3.parent = n2
		n6.parent = n5
		n7.parent = n5
def main():
    root = Node(0)
    root.left = Node(-2)
    root.left.right = Node(-1) 
    root.right = Node(1)
    root.right.right = Node(2)
    lists_dict = dict()
    fill_linked_lists_dict(root, lists_dict, 0)
    i = 0
    while i in lists_dict:
        lst = lists_dict[i]
        ll_node = lst.head
        while ll_node != None:
            print ll_node.data
            ll_node = ll_node.nxt
        i += 1
        print
Example #25
0
def test_lookup():
    root = Node(8)
    root.insert(3)
    root.insert(10)
    assert root.lookup(8) == (root, None)
    assert root.lookup(3) == (root.left, root)
    assert root.lookup(10) == (root.right, root)
 def drawNodeLabel(self, x, y):
     # sub class to increase tree width of label gets wider
     tree = self.tree()
     x = Node.drawNodeLabel(self, x, y)
     canvas = tree.canvas
     bb = canvas.bbox(self.labelTkid)
     #if bb[2]>tree.treeWidth:
     #    tree.newTreeWidth = bb[2]
     return x
    def __init__(self, object, parent):

        Node.__init__(self, object, parent)

        # list of values used to emulate buttons and associated Tk ids
        # created in drawNodeCustomization
        if parent:
            chkbtval = []
            pchkbtval = parent.chkbtval
            for i, c in enumerate(parent.tree().columns):
                if c.inherited:
                    chkbtval.append(pchkbtval[i])
                else:
                    chkbtval.append(c.isOn(self))
            self.chkbtval = chkbtval
        else:
            self.chkbtval = []
        self.chkbtid = []
Example #28
0
def parse_ontology_level(lines, lineno, root_spaces, root):
    """
    Parse a level of the tree into `root` and return the next `lineno`.

    The level is defined by the number of spaces.
    """
    prev_categ = None
    child_spaces = None
    while True:
        if lineno == len(lines):
            # EOF; end recursion.
            break
        line = lines[lineno]
        if not line.strip() or line.startswith('#'):
            # Ignore blank line.
            lineno += 1
            continue
        categ = line.strip()
        spaces = 0
        for c in line:
            if c != ' ':
                break
            spaces += 1
        if spaces < root_spaces:
            # Handled by function above us.
            break
        if spaces == root_spaces:
            # Handled by ourselves.
            child = Node()
            child.label = categ
            root.children.append(child)
            prev_categ = child
            lineno += 1
        elif spaces > root_spaces:
            # Handled by a child function.
            if child_spaces is None:
                child_spaces = spaces
            if child_spaces != spaces:
                raise ValueError("line {}: indent mismatch".format(lineno))
            if prev_categ is None:
                raise ValueError("line {}: overindented".format(lineno))
            lineno = parse_ontology_level(lines, lineno, spaces, prev_categ)

    return lineno
def main():
    root = Node(0)
    root.set_left(-10)
    root.set_right(10)
    root.left.set_right(-5)
    print next_node(root.left, root.left)

    root = Node(0)
    root.set_left(-10)
    root.left.set_right(-5)
    root.left.right.set_left(-7)
    print next_node(root.left, root.left)
def main():
    root = Node(0)
    root.set_left(-10)
    root.set_right(10)
    order = []
    pre_order(root, order)

    big_root = Node(100)
    big_root.set_right(0)
    big_root.right.set_left(-10)
    big_root.right.set_right(10)

    print contains_subtree(big_root, order)
Example #31
0
import pygame, random

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

if __name__ == '__main__':
    tree = Tree(None)
    # Example tree
    toAdd = [0]
    for i in range(50):
        x = random.randrange(-100, 100)
        while x in toAdd:
            x = random.randrange(-100, 100)
        toAdd.append(x)
    for value in toAdd:
        tree.add(Node(value))
    for value in toAdd:
        print(str(tree.contains(Node(value))) + ', ' + str(value))

    print(str(tree.size()) + ', ' + str(len(toAdd)))

    # Pygame setup
    size = width, height = (1000, 1000)
    pygame.init()
    screen = pygame.display.set_mode(size)  # Main screen
    screen.fill(WHITE)
    running = True
    circleRadius = 50  # Radius of circles being drawn

    treeCircles = pygame.Surface(size, pygame.SRCALPHA, 32)
    treeCircles = treeCircles.convert_alpha()
Example #32
0
def main():
    parser = argparse.ArgumentParser(
        description=
        "trivial right-branching parser that ignores any grammar passed in",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    addonoffarg(parser, 'debug', help="debug mode", default=False)
    parser.add_argument("--infile",
                        "-i",
                        nargs='?',
                        type=argparse.FileType('r'),
                        default=sys.stdin,
                        help="input (one sentence per line strings) file")
    parser.add_argument("--grammarfile",
                        "-g",
                        nargs='?',
                        type=argparse.FileType('r'),
                        default=sys.stdin,
                        help="grammar file; ignored")
    parser.add_argument("--outfile",
                        "-o",
                        nargs='?',
                        type=argparse.FileType('w'),
                        default=sys.stdout,
                        help="output (one tree per line) file")

    try:
        args = parser.parse_args()
    except IOError as msg:
        parser.error(str(msg))

    workdir = tempfile.mkdtemp(prefix=os.path.basename(__file__),
                               dir=os.getenv('TMPDIR', '/tmp'))

    def cleanwork():
        shutil.rmtree(workdir, ignore_errors=True)

    if args.debug:
        print(workdir)
    else:
        atexit.register(cleanwork)

    infile = prepfile(args.infile, 'r')
    grammar = prepfile(args.grammarfile, 'r')
    outfile = prepfile(args.outfile, 'w')

    # for line in infile:
    # toks = line.strip().split()
    # parens = 2
    # outfile.write("(TOP (NP ")
    # for tok in toks[:-2]:
    # outfile.write("(NNP {}) (NP ".format(tok))
    # parens+=1
    # endtoks = toks[-2:]
    # for tok in endtoks:
    # outfile.write("(NNP {}) ".format(tok))
    # outfile.write(")"*parens+"\n")

    dic = {}
    count = {}
    for i in grammar:
        t = Tree.from_str(i)
        for node in t.bottomup():
            if len(node.children) != 0:
                if node.label not in count:
                    count[node.label] = []

                chil = node.label + " -> "
                tup = []
                for c in node.children:
                    chil += c.label + " "
                    tup.append(c.label)

                count[node.label].append(tuple(tup))

                if chil not in dic:
                    dic[chil] = 1
                else:
                    dic[chil] += 1

        # rule_prob:(parent, child)
        # rule_prob_dict = {(parent, child) : prob}
        rule_prob_dict = {}
        for key, value in count.items():
            sub_count = Counter(value)
            # k:children.  v:count
            for k, v in sub_count.items():
                rule_prob = [key.encode("utf-8")]
                prob = float(v) / len(value)
                for ki in k:
                    rule_prob.append(ki.encode("utf-8"))

                rule_prob = tuple(rule_prob)
                rule_prob_dict[rule_prob] = math.log(prob, 10)

    time_y = []
    length = []
    for line in infile:
        start_time = time.time()
        toks = line.strip().split()
        # break
        # line="What airline provides only connecting flights between Denver and San Francisco ?"
        # line = "The flight should be eleven a.m tomorrow ."
        # toks = line.strip().split()

        # construct chart
        # store as [tree,prob]
        chart = []
        for i in range(len(toks)):
            chart_1 = []
            for j in range(len(toks) + 1):
                chart_2 = []
                chart_1.append(chart_2)
            chart.append(chart_1)

        # CKY
        word = []
        for rule, prob in rule_prob_dict.items():
            if len(rule) == 2:
                word.append(rule[-1])

        for i in range(0, len(toks)):
            if toks[i] not in word:
                toks[i] = '<unk>'
            for rule, prob in rule_prob_dict.items():
                if rule[-1] == toks[i]:
                    # print ('('+rule[0] + ' ' + rule[1] + ')')
                    t = Tree.from_str(('(' + rule[0] + ' ' + rule[1] + ')'))
                    chart[i][i + 1].append([t.root, prob])

        # print chart

        max_prob = -500000
        # finder = {}
        for width in range(2, len(toks) + 1):
            for start in range(0, len(toks) - width + 1):
                end = start + width
                for mid in range(start + 1, end):

                    for y in chart[start][mid]:
                        for z in chart[mid][end]:
                            for rule, prob in rule_prob_dict.items():

                                if len(rule) == 3:
                                    if y[0].label == rule[1] and z[
                                            0].label == rule[2]:
                                        parent_prob = prob + y[1] + z[1]
                                        t = tree.Node(rule[0], [
                                            copy.deepcopy(y[0]),
                                            copy.deepcopy(z[0])
                                        ])

                                        # cut branch
                                        if len(chart[start][end]) != 0:
                                            flag = 0
                                            for ts in chart[start][end]:
                                                if t.label == ts[0].label:
                                                    flag = 1
                                                    if parent_prob > ts[1]:
                                                        chart[start][
                                                            end].remove(ts)
                                                        chart[start][
                                                            end].append([
                                                                t, parent_prob
                                                            ])
                                                        break
                                            if flag == 0:
                                                chart[start][end].append(
                                                    [t, parent_prob])

                                        else:
                                            chart[start][end].append(
                                                [t, parent_prob])

            # best_tree=tree.Node(None)
        for i in chart[0][len(toks)]:
            if i[1] > max_prob:
                max_prob = i[1]
                best_tree = Node._subtree_str(i[0])

        if max_prob != -500000:

            print best_tree
            print max_prob
            outfile.write(best_tree + "\n")
        else:
            print "This is not a sentence"
            outfile.write(best_tree + "\n")

        end_time = time.time()
        parsing_time = end_time - start_time

        time_y.append(math.log(parsing_time))

        x = len(toks)
        length.append(math.log(x))

    print len(time_y)
    print len(length)

    plt.plot(length, time_y)
Example #33
0
 def create_tree(self):
     root = Node(self.dataset)
     self.train(root)
     self.root = root
Example #34
0
def test_BinaryTree_with_root():
    node = Node(10)
    tree = BinaryTree(node)

    assert tree.root.value == 10
Example #35
0
def tree():
    ten = Node(10)
    five = Node(5)
    two = Node(2)
    seven = Node(7)
    six = Node(6)
    nine = Node(9)
    twenty = Node(20)
    fifteen = Node(15)
    thirty = Node(30)

    ten.left = five
    ten.right = twenty
    five.left = two
    five.right = seven
    seven.left = six
    seven.right = nine
    twenty.left = fifteen
    twenty.right = thirty

    return BinarySearchTree(ten)
Example #36
0
def cyk(stri, matr, nodeMatr):

    ##single chars#special case
    for j in xrange(0, len(stri)):
        lastBeforeTerminal = searchProd(stri[j])
        if len(
                lastBeforeTerminal
        ) == 0:  #if the list of possible Variables responsible for a terminal is empty
            return False  #then the string is not in the grammar
        else:
            #fills the principal diagonal with the starting variables
            #bit of a mess here
            possible = searchProd(stri[j])
            matr[j][j] = possible
            nodeMatr[j][j] = []
            for p in possible:
                nodeMatr[j][j].append(Node(p, [Node(stri[j], None)]))

    #######################################
    '''
    nodeMatr is a len(string) x len(string) matrix
    The principal diagonal now has all the variables that produced the terminals
    The loop over the matrix will visit the diagonal on the right of the principal diagonal first
    then will move on the  other diagonal on the right
    like this:
    [ ][ ][ ][0]
    [ ][ ][0][1]
    [ ][0][1][2]
    [0][1][2][3]
    '''
    for d in xrange(1, len(stri)):
        for m in xrange(0, len(stri) - d):
            i = m  #y index of the matrix
            j = m + d  #x index of the matrix

            possibleProductions = []
            s = []
            sMat = []
            nodes = []

            #first time t=[0,1],second t=[0,1,2],...,last t=[0,...,len(string)]
            for t in xrange(0, d):
                #select pair ([i][i+t] ,[i+t+1][j]) of cells in the matrix
                for pL in nodeMatr[i][i + t]:
                    for pR in nodeMatr[i + t + 1][j]:
                        #for each node inside the cell
                        productions = combineProd(pL.name,
                                                  pR.name)  #   combine them
                        possibleProductions.append(
                            [productions, pL, pR]
                        )  # append productions along with a reference to the nodes that created it

            for comb in possibleProductions:  #for each triple [[production1,...],parent1,parent2]
                for production in comb[0]:
                    fathers = searchProd(
                        production
                    )  #look in the grammar for a possible generator
                    if (len(fathers) > 0):
                        for f in fathers:  #for every generator
                            node = Node(
                                f, [comb[1], comb[2]
                                    ])  #create a new node , give it the 2 sons
                            comb[1].setParent(node)  #set its parent
                            comb[2].setParent(node)  #set its parent
                            nodes.append(
                                node
                            )  #append it to the list of nodes that will go inside the [i][j] cell
                            s.append(f)
                            if (sMat.__contains__([comb, f]) == False):
                                sMat.append([comb, f])
            nodeMatr[i][j] = nodes
            matr[i][j] = list(set(s))  #removes duplicates
    #prettyPrint(matr)
    #nodePrint(nodeMatr)
    if 'S' in matr[0][len(stri) -
                      1]:  #starting symbol is inside the last cell!
        return True
    return False
Example #37
0
 def __init__(self, start_position):
     self._root = Node(start_position)
     self._considered_positions = set(start_position)
     self.build_move_tree()
Example #38
0
def tree2():
    four = Node(4)
    ten = Node(10)
    one = Node(1)
    sixteen = Node(16)
    twelve = Node(12)
    seventeen = Node(17)
    sixty = Node(60)
    twenty = Node(20)
    thirty_five = Node(35)
    fifty = Node(50)

    four.left = ten
    ten.left = one
    ten.right = sixteen
    sixteen.left = twelve
    sixteen.right = seventeen
    four.right = sixty
    sixty.left = twenty
    sixty.right = thirty_five
    thirty_five.right = fifty

    return BinaryTree(four)
Example #39
0
 def __init__(self, vc):
     Node.__init(self, 1)
     self.vc = -1
Example #40
0
def test_init():
    root = Node(8)
    assert root.data == 8
Example #41
0
def test_insert():
    root = Node(8)
    root.insert(3)
    root.insert(10)
    assert root.left.data == 3
    assert root.right.data == 10
Example #42
0
def test_delete():
    root = Node(8)
    root.insert(3)
    root.delete(3)
    root.delete(8)
Example #43
0
    def __init__(self,
                 name,
                 value,
                 min_value=None,
                 max_value=None,
                 desc=None,
                 unit=u.dimensionless_unscaled,
                 transformation=None):

        # Make this a node

        Node.__init__(self, name)

        # Make a static name which will never change (not even after a _change_name call)
        self._static_name = str(name)

        # Callbacks are executed any time the value for the parameter changes (i.e., its value changes)

        # We start from a empty list of callbacks.
        self._callbacks = []

        # Assign to members

        # Store the units as an astropy.units.Unit instance

        self._unit = self._safe_assign_unit(unit)

        # A ParameterBase instance cannot have auxiliary variables
        self._aux_variable = {}

        # Set min and max to None first so that the .value setter will work,
        # we will override them later if needed
        self._external_min_value = None
        self._external_max_value = None

        # Store the transformation. This allows to disentangle the value of the parameter which the user interact
        # width with the value of the parameter the fitting engine (or the Bayesian sampler) interact with
        self._transformation = transformation

        # Let's store the init value

        # NOTE: this will be updated immediately by the _set_value method of the "value" property
        self._internal_value = None
        # If the value is a Quantity, deal with that

        if isinstance(value, u.Quantity):

            # If the user did not specify an ad-hoc unit, use the unit
            # of the Quantity

            if self._unit == u.dimensionless_unscaled:

                self._unit = value.unit

            # Convert the value to the provided unit (if necessary)

            self.value = value.to(self._unit).value

        else:

            self.value = value

        # Set minimum if provided, otherwise use default
        # (use the property so the checks that are there are performed also on construction)

        self.min_value = min_value

        # Set maximum if provided, otherwise use default

        # this will be overwritten immediately in the next line
        self.max_value = max_value

        # Store description

        self._desc = desc

        # Make the description the documentation as well

        self.__doc__ = desc

        # Now perform a very lazy check that we can perform math operations on value, minimum and maximum
        # (i.e., they are numbers)

        if not _behaves_like_a_number(self.value):

            raise TypeError("The provided initial value is not a number")
Example #44
0
    def test_tree_generation_and_calculate_value(self):
        
        board = [
            [O, O, EMPTY],
            [EMPTY, X, EMPTY],
            [EMPTY, X, EMPTY]
        ]
        state = State(board, next_to_move=X)
        node = Node(state)
        node.generate_subtree()
        self.assertAlmostEqual(node.value[X], 0.0, 2)
        self.assertAlmostEqual(node.value[O], 0.0, 2)

        board = [
            [EMPTY, O, EMPTY],
            [O, X, EMPTY],
            [EMPTY, X, EMPTY]
        ]
        state = State(board, next_to_move=X)
        node = Node(state)
        node.generate_subtree()
        self.assertAlmostEqual(node.value[X], 1.0, 2)
        self.assertAlmostEqual(node.value[O], 0.0, 2)

        board = [
            [EMPTY, O, EMPTY],
            [EMPTY, X, EMPTY],
            [EMPTY, X, EMPTY]
        ]
        state = State(board, next_to_move=O)
        node = Node(state)
        node.generate_subtree()
        self.assertAlmostEqual(node.value[X], 0.33, 2)
        self.assertAlmostEqual(node.value[O], 0.067, 3)
        # TODO is this correct?

        board = [
            [EMPTY, EMPTY, X],
            [EMPTY, X, EMPTY],
            [O, O, EMPTY]
        ]
        state = State(board, next_to_move=X)
        node = Node(state)
        node.generate_subtree()
        self.assertAlmostEqual(node.value[X], 1.0, 2)
        self.assertAlmostEqual(node.value[O], 0.0, 2)

        board = [
            [O, EMPTY, EMPTY],
            [EMPTY, X, EMPTY],
            [EMPTY, EMPTY, X]
        ]
        state = State(board, next_to_move=O)
        node = Node(state)
        node.generate_subtree()
        self.assertAlmostEqual(node.value[X], 0.67, 2)
        self.assertAlmostEqual(node.value[O], 0.0, 2)
Example #45
0
def expandNode(node, h, g):
    """
    :param node: node a ser expandido
    :param h: funcao de heuristica
    :param g: funcao g
    :return: retorna uma lista contendo os filhos do node expandido
    """
    expNode = []  # contem os nos filhos
    possibleExp = []  # locais para onde pode expandir
    possibleExp.extend(node.getPossibleMoves())

    global exp
    global dicionario

    for move in possibleExp:
        """
            Testa cada posicao criando um node auxiliar para cada posicao possivel
            Se o estado criado ainda nao foi explorado, este eh adicionado na lista expNode
        """
        # g(node) + h(node)
        if move == "up":
            son = Node(node.up(), node, move, node.depth + 1,
                       h(node) + g(node))
            if not son.isOnDic(dicionario):
                son.addOnDic(dicionario)
                expNode.append(son)
                exp += 1
        elif move == "down":
            son = Node(node.down(), node, move, node.depth + 1,
                       h(node) + g(node))
            if not son.isOnDic(dicionario):
                son.addOnDic(dicionario)
                expNode.append(son)
                exp += 1
        elif move == "left":
            son = Node(node.left(), node, move, node.depth + 1,
                       h(node) + g(node))
            if not son.isOnDic(dicionario):
                son.addOnDic(dicionario)
                expNode.append(son)
                exp += 1
        elif move == "right":
            son = Node(node.right(), node, move, node.depth + 1,
                       h(node) + g(node))
            if not son.isOnDic(dicionario):
                son.addOnDic(dicionario)
                expNode.append(son)
                exp += 1

    return expNode
Example #46
0
    def _fit_recursive(self, X, cluster, node=None):
        """Recursive helper for fit()

        skkdj

        Parameters
        ----------

        Returns
        -------
        """
        if X.shape[0] < 2:
            # base case
            # must have > 2 obs to cluster!
            return Node(self.Leaf(cluster.name, cluster.indices))

        # ---------------------------------------------------------------------
        # use ward w/ (1-corr) to hierarcically cluster to split
        # ---------------------------------------------------------------------
        split = _ward_cluster(X)

        # ---------------------------------------------------------------------
        # train/test svm (radial kernal on 100 random 50/50 splits of clustering
        # ---------------------------------------------------------------------
        try:
            scores = _test_clusters(X, split, stratified=self.stratified)
        except ValueError:
            # base case
            # two few of second class to split (say 9:1 or something)
            # assign entire population to terminal cluster
            return Node(self.Leaf(cluster.name, cluster.indices))

        # ---------------------------------------------------------------------
        # if min(score) < tol (0.80 in glif paper), recursively repeat 3-5 on
        # each subpopulation
        # ---------------------------------------------------------------------
        score = scores.min()
        if score < self.tol:
            # base case
            # assign entire population to terminal cluster
            return Node(self.Leaf(cluster.name, cluster.indices))

        # recursively split
        a = np.where(split == 1)
        b = np.where(split == 2)

        A = self.Cluster(cluster.indices[a], score, cluster.name + "1",
                         len(a[0]))
        B = self.Cluster(cluster.indices[b], score, cluster.name + "2",
                         len(b[0]))

        # add score to binary tree
        if node is None:
            node = Node(
                self.Split(cluster.name, (A.name, B.name), score,
                           cluster.size))
        else:
            # tree is built pre order
            raise ValueError("Should be null!!!")

        node.left = self._fit_recursive(X[a], A, node.left)
        node.right = self._fit_recursive(X[b], B, node.right)

        return node
Example #47
0
def main():
    moves = solve(h_manhattan,
                  g_depth)  # chamada da funcao para resolucao do problema
    if moves == None:
        print("solucao n encontrada")
        return

    result = Node(inicial, None, 'a', 0, 0)
    result.showState()
    moves.reverse()
    # Reconstroi os nos para printar o caminho ate a resolucao do problema
    for next in moves:
        print(next)
        if next == "up":
            result.state = result.up()
        elif next == "down":
            result.state = result.down()
        elif next == "left":
            result.state = result.left()
        elif next == "right":
            result.state = result.right()

        result.showState()

    print(moves)
    print(str(len(moves)) + " movimentos")
    print(str(exp) + " expansoes")
    print("Feito!")
Example #48
0
 def test_from_dict_label_and_value(self):
     n = Node.from_dict({"label": "D", "value": "I"})
     self.assertEqual(n.label, "D")
     self.assertEqual(n.value, "I")
     self.assertEqual(len(n.children), 0)
     self.assertIsNone(n.parent)
Example #49
0
from collections import deque
from tree import Node

with open("day8-input.txt") as f:
    data = deque(int(x) for x in f.read().strip().split())

tree = list()
header = True
parent = None
checksum = 0

while data:
    if header:
        n_children = data.popleft()
        n_metadata = data.popleft()
        node = Node(n_children, n_metadata, parent)
        tree.append(node)
        if parent is not None:
            parent.children.append(node)

    if node.unprocessed_children:
        parent = node
        header = True
    else:
        node.metadata = [data.popleft() for i in range(node.n_metadata)]
        checksum += sum(node.metadata)
        if parent is None:
            header = True
            continue
        node = parent
        parent = node.parent
Example #50
0
 def test_from_dict_value_only(self):
     n = Node.from_dict({"value": "val"})
     self.assertIsNone(n.label)
     self.assertEqual(n.value, "val")
     self.assertEqual(len(n.children), 0)
     self.assertIsNone(n.parent)
Example #51
0
from tree import BinaryTree, Node

if __name__ == "__main__":
    tree = BinaryTree()

    n1 = Node('a')
    n2 = Node('+')
    n3 = Node('*')
    n4 = Node('b')
    n5 = Node('-')
    n6 = Node('/')
    n7 = Node('c')
    n8 = Node('d')
    n9 = Node('e')

    n6.left = n7
    n6.right = n8
    n5.left = n6
    n5.right = n9
    n3.left = n4
    n3.right = n5
    n2.left = n1
    n2.right = n3

    tree.root = n2

    tree.simetric_traversal()
Example #52
0
 def test_qtree_simple(self):
     self.assertEqual(
         Node.from_dict(TestNode.SIMPLE_TREE_DICT).to_qtree(),
         TestNode.SIMPLE_QTREE)
Example #53
0
    def gen_small_block(self):
        if random.random() < 0.5:
            node = Node('A')
        else:
            node = Node('B')

        if random.random() < 0.5:
            node.addkid(Node('C'))
        else:
            node.addkid(Node('D'))

        if random.random() < 0.5:
            node.children[-1].addkid(Node('A'))
        else:
            node.children[-1].addkid(Node('B'))
        return node
Example #54
0
 def test_qtree_degenerate(self):
     self.assertEqual(Node(label="root").to_qtree(), "\Tree [.root\n]\n")
Example #55
0
 def test_delete_root(self):
     n = Node()
     with self.assertRaises(AssertionError):
         n.delete()
Example #56
0
def tree1():
    fifteen = Node(15)
    ten = Node(10)
    seven = Node(7)
    sixteen = Node(16)
    twelve = Node(12)
    seventeen = Node(17)
    twenty_five = Node(25)
    twenty = Node(20)
    thirty_five = Node(35)
    thirty = Node(30)
    fifty = Node(50)

    fifteen.left = ten
    ten.left = seven
    ten.right = sixteen
    sixteen.left = twelve
    sixteen.right = seventeen
    fifteen.right = twenty_five
    twenty_five.left = twenty
    twenty_five.right = thirty_five
    thirty_five.left = thirty
    thirty_five.right = fifty

    return BinaryTree(fifteen)
Example #57
0
 def test_from_dict_empty(self):
     n = Node.from_dict({})
     self.assertIsNone(n.label)
     self.assertIsNone(n.value)
     self.assertEqual(len(n.children), 0)
     self.assertIsNone(n.parent)
Example #58
0
 def test_from_dict_label_only(self):
     n = Node.from_dict({"label": "TP"})
     self.assertEqual(n.label, "TP")
     self.assertIsNone(n.value)
     self.assertEqual(len(n.children), 0)
     self.assertIsNone(n.parent)
Example #59
0
def tree3():
    one = Node(1)
    two = Node(2)
    three = Node(3)
    four = Node(4)
    seven = Node(7)

    one.left = two
    one.right = three
    three.left = four
    three.right = seven    

    return BinaryTree(one)
Example #60
0
#!/usr/bin/env python3
from tree import Node
from random import randint, seed

seed(10)

itens = [randint(0, 20) for x in range(10)]
first = itens[0]

n = Node(first)

print(itens)

for i in itens[1:]:
    n.insert(i)

n.debug()