Beispiel #1
0
def BuildTree(path_tuple):
    """
    Build a tree structure from a given path tuple
    """
    if _debug: print "##\nBuild Tree...\ntuple:", path_tuple
    
    node_to_split,y_value = FindBestGain(path_tuple)
    
    if node_to_split < 0:
        if _debug: print "found leaf for tuple: ", path_tuple
        training_tree = Tree("leaf")
        training_tree.y_value = y_value
        training_tree.is_leaf = True
    else:
        # Create node for attribute to split on
        training_tree = Tree(_attrib_dict[str(node_to_split)])
        
        # Build left side of tree for node
        left_tuple = path_tuple + [(node_to_split,0)]
        left_tree = BuildTree(left_tuple)
        training_tree.AddLeftChild(left_tree)
            
        # Build right side of tree for node
        right_tuple = path_tuple + [(node_to_split, 1)]
        right_tree = BuildTree(right_tuple)
        training_tree.AddRightChild(right_tree)

    return training_tree
Beispiel #2
0
def test_traverse_returns_none_when_operation_always_returns_false():
    t = Tree("a")
    t.add_child("b")

    node = t.traverse(lambda n: False)

    assert_that(node, is_(None))
Beispiel #3
0
 def read_tree(self, line):
     parents = map(int,line.split())
     trees = dict()
     root = None
     for i in xrange(1,len(parents)+1):
         #if not trees[i-1] and parents[i-1]!=-1:
         if i-1 not in trees.keys() and parents[i-1]!=-1:
             idx = i
             prev = None
             while True:
                 parent = parents[idx-1]
                 if parent == -1:
                     break
                 tree = Tree()
                 if prev is not None:
                     tree.add_child(prev)
                 trees[idx-1] = tree
                 tree.idx = idx-1
                 #if trees[parent-1] is not None:
                 if parent-1 in trees.keys():
                     trees[parent-1].add_child(tree)
                     break
                 elif parent==0:
                     root = tree
                     break
                 else:
                     prev = tree
                     idx = parent
     return root
Beispiel #4
0
    def fitness_eval(self, pacman, ghost):
        # Create three identical ghosts
        ghost.board = self.board
        pacman.board = self.board
        ghost.score = 0
        pacman.score = 0
        ghosts = [copy.deepcopy(ghost) for i in range(3)]

        self.init_log(pacman, ghosts)

        # Run turns until the game is over
        while not self.game_over and self.time > 0 and len(self.board.pills) > 0:
            self.turn(pacman, ghosts)
            self.time -= 1
            if len(self.board.pills) == 0:
                pacman.score += int(self.time/float(self.tot_time) * 100)
            self.log_turn(pacman, ghosts)

        pacman.score = max(pacman.score, 1)

        ghost.score = -pacman.score
        ghost.score -= self.parsimony_coef_ghost*Tree.find_depth(ghost.tree)

        # Parsimony pressure
        pacman.score -= self.parsimony_coef_pacman*Tree.find_depth(pacman.tree)
        pacman.score = max(pacman.score, 1)

        return pacman.score
Beispiel #5
0
        def make_master_tree(
            n,
            method,
            names=None,
            inner_edge_params=(1, 1),
            leaf_params=(1, 1),
            distribution_func=np.random.gamma,
            ):
            """
            Function returns a tree object with n tips,
            named according to `names`, and constructed
            according to `method`, which is one of 'random_topology',
            'random_yule' and 'random_coal'
            """

            if method == 'random_topology':
                master_topology = Tree.new_random_topology(n,
                        names=names, rooted=True)
                master_tree = \
                    master_topology.randomise_branch_lengths(inner_edges=inner_edge_params,
                        leaves=leaf_params,
                        distribution_func=branch_length_func)
                master_tree.newick = '[&R] ' + master_tree.newick
            elif method == 'random_yule':
                master_tree = Tree.new_random_yule(n, names=names)
            elif method == 'random_coal':
                master_tree = Tree.new_random_coal(n, names=names)
            return master_tree
Beispiel #6
0
def TdiExecute(expression,args=None):
    """Compile and execute a TDI expression. Format: TdiExecute('expression-string')"""
    from _descriptor import descriptor_xd,descriptor,MdsGetMsg
    from tree import Tree
    xd=descriptor_xd()
    done=False
    try:
        Tree.lock()
        restoreContext()
        if args is None:
            status=TdiShr.TdiExecute(pointer(descriptor(expression)),pointer(xd),c_void_p(-1))
        else:
            if isinstance(args,tuple):
                if len(args) > 0:
                    if isinstance(args[0],tuple):
                        ans = TdiExecute(expression,args[0])
                        done=True
                if not done:
                    exp='TdiShr.TdiExecute(pointer(descriptor(expression))'
                    for i in range(len(args)):
                        exp=exp+',pointer(descriptor(args[%d]))' % i
                    exp=exp+',pointer(xd),c_void_p(-1))'
                    status=eval(exp)
            else:
                raise TypeError('Arguments must be passed as a tuple')
    finally:
        Tree.unlock()
    if done:
        return ans
    if (status & 1 != 0):
            return xd.value
    else:
        raise TdiException(MdsGetMsg(status,"Error compiling expression"))
Beispiel #7
0
def main():
	bordVariables = bord(2) # return [carsList,width,exit]
	global WIDTH; WIDTH = bordVariables[1]
	global CARS_LIST; CARS_LIST = bordVariables[0]
	global INITIAL_STATE; INITIAL_STATE = CARS_LIST.getFirstState()
	global STATES_ARCHIVE; STATES_ARCHIVE = Tree(WIDTH, CARS_LIST.getDirectionsList())

	aantalCars = len(CARS_LIST.cars)
	# voeg vaak een state toe aan de tree
	for i in range(0, 100000):
		randomState = []
		for j in range(0, aantalCars):
			randomState.append(randint(0,WIDTH-2)*WIDTH + randint(0,WIDTH - 2))

		# print randomState

		STATES_ARCHIVE.addState(randomState, INITIAL_STATE)
	print "ik ben klaar met states toevoegen"
	
	# # zoek een state in de tree
	# for i in range(0, 100000):
	# 	randomState = []
	# 	for j in range(0, aantalCars):
	# 		randomState.append(randint(0,WIDTH-2)*WIDTH + randint(0,WIDTH - 2))
	# 	STATES_ARCHIVE.checkState(randomState)
	# print "klaar met states checken"



	STATES_ARCHIVE.addState(INITIAL_STATE, INITIAL_STATE)
Beispiel #8
0
def main():

	# Car1 = Car(22, False, 3)
	# Car2 = Car(9, False, 2)
	# Car3 = Car(10, True, 2)
	# RedCar = Car(20, True, 2)

	# CARS_LIST.cars.append(Car1)
	# CARS_LIST.cars.append(Car2)
	# CARS_LIST.cars.append(Car3)
	# CARS_LIST.cars.append(RedCar)

	RedCar = Car(20, True, 2)
	Car1 = Car(0, False, 2)
	Car2 = Car(12, True, 2)
	Car3 = Car(3, False, 2)
	Car4 = Car(4, True, 2)
	Car5 = Car(10, True, 2)
	Car6 = Car(14, True, 2)
	Car7 = Car(16, False, 2)
	Car8 = Car(17, False, 3)
	Car9 = Car(25, True, 2)
	Car10 = Car(27, True, 2)
	Car11 = Car(32, True, 2)
	Car12 = Car(34, True, 2)

	CARS_LIST.cars.append(Car1)
	CARS_LIST.cars.append(Car2)
	CARS_LIST.cars.append(Car3)
	CARS_LIST.cars.append(Car4)
	CARS_LIST.cars.append(Car5)
	CARS_LIST.cars.append(Car6)
	CARS_LIST.cars.append(Car7)
	CARS_LIST.cars.append(Car8)
	CARS_LIST.cars.append(Car9)
	CARS_LIST.cars.append(Car10)
	CARS_LIST.cars.append(Car11)
	CARS_LIST.cars.append(Car12)
	CARS_LIST.cars.append(RedCar)

	# TEST dept first algorithme:
	global INITIAL_STATE; INITIAL_STATE = CARS_LIST.getFirstState()
	global STATES_ARCHIVE; STATES_ARCHIVE = Tree(WIDTH, CARS_LIST.getDirectionsList())
	algorithm(INITIAL_STATE)
	path1 = SOLUTION_PATHS[0]

	# print results
	# print "length solutions ", len(SOLUTIONS)
	#rint SOLUTIONS
	print len(SOLUTION_PATHS)
	listSolutionsPaths = []
	for sols in SOLUTION_PATHS:
		listSolutionsPaths.append(len(sols))
	print listSolutionsPaths

	pathDepth = []
	for state in path1[:-1]:
		print len(state), state
		pathDepth.append(STATES_ARCHIVE.goToEndNode(state).depth)
	print pathDepth
def main():
    tree = Tree('pie')
    tree.add_item('cake')
    tree.add_item('cookie')
    for item in tree:
        print('{}: {}'.format(item.datum, item.height()))
    #Should print:
    #cake: 0
    #pie: 1
    #cookie: 0

    tree.add_item('cupcake')
    for item in tree:
        print('{}: {}'.format(item.datum, item.height()))
    #Should print:
    #cupcake: 0
    #cake: 1
    #pie: 2
    #cookie: 0

    #this constructs the tree shown in the exercise
    other_tree = Tree(1)
    for i in [2, 3, 4, 6, 5, 7]:
        other_tree.add_item(i)
    print(list(map(lambda d: d.datum, other_tree)))
def get_best_TC_tree(
    dv_file,
    gm_file,
    label_file,
    tree_files,
    name='unnamed_tree',
    ):
    """
    Given a distance-variance file, a genome-map file, a label file
    and a number of tree files
    """

    if not isinstance(tree_files, list):
        return Tree.new_treecollection_tree(dv_file, gm_file,
                label_file, tree_files, name)
    best_score = float('inf')
    best_tree = None
    starts = len(tree_files)

    for i in range(starts):
        guide = tree_files[i]
        current_tree = Tree.new_treecollection_tree(dv_file, gm_file,
                label_file, guide, name)
        if current_tree.score < best_score:
            best_score = current_tree.score
            best_tree = current_tree

    return best_tree
Beispiel #11
0
def main():

    init_population = generate_init_population()
    result = False
    counter = 0

    while counter < ITERATIONS_COUNT:
        print("************************************************************************************************************"
              "************************************************************************************************************")
        print(counter)
        best_individuals = deepcopy(reproduce(init_population))

        if len(best_individuals) == 0:
            print("Reproduction empty")
            break

        new_generation = deepcopy(create_new_generation(best_individuals))
        mutated_trees = deepcopy(mutate_trees(new_generation))
        check_fitness(mutated_trees)
        init_population = deepcopy(mutated_trees)

        if len(init_population) == 0:
            print("Empty population")
            break
        counter += 1

    print("End")
    if len(results) > 0:
        print("")
        print "MIN RESULT"
        print Tree.tree_map_to_string(min(results))
        print min(results).init_tree
        print min(results).fitness
Beispiel #12
0
 def test_new_tree_add_2_nodes_and_print_it(self):
     t = Tree()
     n = Node(title='test', id='1', parent_id='root')
     t.add(n)
     n = Node(title='test2', id='2', parent_id='1')
     t.add(n)
     print(t)
Beispiel #13
0
    def testTraverse(self):
        tree = Tree()
        for word in insert_queue:
            tree.insert(word)

        insert_queue.sort()
        self.assertEqual(tree.inorder_traverse(), " ".join(insert_queue))
Beispiel #14
0
def check_fitness(trees):
    errors = []
    for one_tree in trees:
        if len(one_tree.tree_map) == 0:
            continue
        sum_error = 0
        good_individual = True
        for i in range(0, len(VARIABLE_VALUES_SET)):
            error = Reproductor.get_error(one_tree, TARGET_VALUES[i], VARIABLE_VALUES_SET[i])
            if error > ALLOWABLE_ERROR:
                good_individual = False
            sum_error += error
        if isinf(sum_error):
            continue
        errors.append(sum_error)
        if good_individual or sum_error < TARGET_RESULT:
            print("RESULT")
            print(Tree.tree_map_to_string(one_tree.tree_map))
            print(one_tree.init_tree)
            one_tree.fitness = sum_error
            results.append(one_tree)
    print("MIN FITNESS RESULT: ", min(errors))
    print "AVERAGE FITNESS: ", sum(errors)/len(errors)
    print "length ", len(errors)
    print "results "
    for r in results:
        print "fitness ", r.fitness
        print Tree.tree_map_to_string(r.tree_map)
Beispiel #15
0
def main():
    a = Tree(1)
    b = Tree(4)
    c = Tree(6)
    d = Tree(8)
    e = Tree(2, a)
    f = Tree(3, e, b)
    g = Tree(7, c, d)
    h = Tree(5, f, g)

    print "####### Left View ########"
    print_next = False
    for node in Tree.get_level_order_traversal(h):
        if not isinstance(node, Tree):
            print_next = True
        elif print_next:
            print node.v
            print_next = False
            
    print "####### Right View ########"
    prev = None
    for node in Tree.get_level_order_traversal(h):
        if not isinstance(node, Tree) and prev:
            print prev.v
        prev = node
    print node.v
Beispiel #16
0
def getObjectsTree(qTreeView, table, indexes, extract):
    """Create an object tree representation from QTreeView.
    """
    tree = Tree()
    model = qTreeView.model()
    extracted = tree.fromQStandardItemModel(model, table, indexes, extract)
    return tree, extracted
Beispiel #17
0
    def testProperty(self):

        x = Tree(value=None)
        self.assertTrue(x.value == None)

        x.value = 5
        self.assertTrue(x.value == 5)
def filelists_from_spec(spec, specpath):
    res = Tree()
    for pkg in spec.packages:
        name = "%s.install.in" % mappkgname.map_package_name(pkg.header)
        res.append("debian/%s" % name, 
                   files_from_pkg(spec.sourceHeader['name'], pkg, specpath))
    return res
Beispiel #19
0
def eval_decmodel(s):
    d = eval(s)
    v = d["lagrange_version"] 
    if v != VERSION:
        print >> sys.stderr, "***Version mismatch: %s (expecting %s)***" \
              % (v, VERSION)
        print >> sys.stderr, "Things may not work as expected"
    for x in ("area_labels", "taxon_range_data", "newick_trees"):
        assert x in d, "required for analysis, but missing: %s" % x
    labels = d["area_labels"]
    nareas = len(labels)
    data = d["taxon_range_data"]
    maxareas = d.get("max_range_size") or len(labels)
    dists = d["ranges"]
    excluded = d["excluded_ranges"]
    dm = d["area_dispersal"]
    periods = d["dispersal_durations"]
    model = DECModel(nareas, labels, periods=periods, dists=dists)
    model.Dmask[:] = dm
    trees = d["newick_trees"]
    newicktree = trees[0]["newick"]
    nodelabels = trees[0]["included"]
    root_age = trees[0]["root_age"] or None
    tree = Tree(newicktree, periods=periods, root_age=root_age)
    tree.set_default_model(model)
    tree.set_tip_conditionals(data)
    base_rates = d["base_rates"]
    if base_rates == "__estimate__":
        pass
    else:
        base_rates = (d["base_rates"]["dispersal"], d["base_rates"]["extinction"])
    return model, tree, data, nodelabels, base_rates
Beispiel #20
0
 def testIsRoot(self):
   if IGNORE_TEST:
     return
   self.assertTrue(self.root.isRoot())
   new_tree = Tree("DUMMY_TREE")
   self.root.addChild(new_tree)
   self.assertFalse(new_tree.isRoot())
   self.assertTrue(self.root.isRoot())
Beispiel #21
0
def test_add_child_appends_node_to_the_child_list():
    t = Tree("a")
    t.add_child("b")

    t.add_child("c")

    assert_that(t.children[0].value, is_("b"))
    assert_that(t.children[1].value, is_("c"))
Beispiel #22
0
def antlrTree2Tree(antlrTree):
	t = Tree(antlrTree.type, antlrTree.text, antlrTree.line, antlrTree.charPositionInLine)

	for i in range(antlrTree.getChildCount()):
		subT = antlrTree2Tree(antlrTree.getChild(i))
		t.addChild(subT)

	return t
Beispiel #23
0
 def ttree(self,name,varnames):
     """ book andf store a Tree object (from tree.py)
     """
     self.cd()
     t1 = Tree(name=name)
     t1.book(varnames)
     self.put(t1)
     return t1
Beispiel #24
0
    def __init__(self, tree, mp='', ml=''):
        """
        Convert sequences in MSA file into ancestral state for each site and attach them to each node

        @param tree: string, a newick format string or a filename of a newick format file (in this version this only accept a newick format file generated by FastML instead of a untouched newick format file which only contains aligned sequence for all terminal nodes)
        @param mp: string, filename of a MSA file, MP method only
        @param ml: string, filename of a MSA file, ML method only
        """
        Tree.__init__(self, tree, mp, ml)
Beispiel #25
0
 def apply(self, value_root):
     source_parent = Tree._navigate_to_index_parent(self._index, value_root)
     moved_node = source_parent.pop_child(self._index[-1])
     dest_parent = Tree._navigate_to_index_parent(
         self._dest_index,
         value_root)
     dest_parent.insert_child(self._dest_index[-1], moved_node)
     event = self.Event(source_parent, moved_node)
     source_parent.trigger_event(event)
Beispiel #26
0
def analyze(settings):
    start_time = time.time()

    f = Filters(settings['code'], settings['filters'])
    tree = Tree(settings['path'], f.filters(), settings['antifilters'], settings)
    tree.output()

    time_sec = time.time() - start_time
    print ("\nanalyze time : {0:2.5f}sec".format(time_sec))
Beispiel #27
0
 def openTrees(self):
     self.pytree=Tree('pytree',self.shot)
     self.pytree.getNode('.pytreesub').include_in_pulse=True
     self.assertEqual(str(self.pytree),'Tree("PYTREE",'+str(self.shot)+',"Normal")')
     self.pytree.createPulse(self.shot+1)
     Tree.setCurrent('pytree',self.shot+1)
     self.pytree2=Tree('pytree',self.shot+1)
     self.assertEqual(str(self.pytree2),'Tree("PYTREE",'+str(self.shot+1)+',"Normal")')
     return
Beispiel #28
0
    def testSearch(self):
        tree = Tree()
        for word in insert_queue:
            tree.insert(word)

        for i in insert_queue:
            self.assertEqual(tree.search(i), i)

        self.assertEqual(tree.search("not found"), None)
 def test_2_vertices(self):
     n = 2
     root = 1
     adjacent = [(0, 1)]
     tree = Tree(n, adjacent, root)
     self.assertEqual(tree.lca(0, 1), 1)
     self.assertEqual(tree.lca(1, 0), 1)
     self.assertEqual(tree.lca(0, 0), 0)
     self.assertEqual(tree.lca(1, 1), 1)
 def test_example(self):
     n = 8
     root = 2
     adjacent = [(0, 6), (3, 6), (6, 2), (4, 2), (1, 4), (5, 1), (7, 1)]
     tree = Tree(n, adjacent, root)
     self.assertEqual(tree.lca(0, 7), 2)
     self.assertEqual(tree.lca(5, 1), 1)
     self.assertEqual(tree.lca(1, 5), 1)
     self.assertEqual(tree.lca(0, 3), 6)