本文整理汇总了Python中tree.Tree类的典型用法代码示例。如果您正苦于以下问题:Python Tree类的具体用法?Python Tree怎么用?Python Tree使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Tree类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: BuildTree
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
示例2: test_traverse_returns_none_when_operation_always_returns_false
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))
示例3: read_tree
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
示例4: fitness_eval
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
示例5: make_master_tree
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
示例6: main
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)
示例7: main
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
示例8: main
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)))
示例9: get_best_TC_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
示例10: main
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
示例11: test_new_tree_add_2_nodes_and_print_it
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)
示例12: testTraverse
def testTraverse(self):
tree = Tree()
for word in insert_queue:
tree.insert(word)
insert_queue.sort()
self.assertEqual(tree.inorder_traverse(), " ".join(insert_queue))
示例13: check_fitness
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)
示例14: main
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
示例15: getObjectsTree
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