def test_find(self): node = Tree('a') child = Tree('b') node.add(child) child2 = Tree('c') node.add(child2) child3: Tree = Tree('d') self.assertEqual(child2, node.find_child(lambda x: x == child2))
def plot_subtree_hulls(tree: Tree): for i in range(4): c = COLORS[i] plot_tree_hull(tree, c=c) plot_root(tree.location, color=c, edgecolor=grey(1.)) tree = tree.big_child() tree = tree.big_child() tree = tree.big_child()
def createTree(self, freq): """ Given a mapping of frequencies this will create the appropiate Huffman Tree @param freq: The dictionary mapping of character to number of times they appear in the plain text @return: """ # given a list of frequencies sort and generate the tree. sorted_freq = sorted(freq.items(), key=operator.itemgetter(1)) #print(type(sorted_freq)) #put them in the tree #wrap all sorted_freq into tree objects print("Sorted List:") print(sorted_freq) tree_list = [] #Create a Tree for each single frequency so that they can be added together. #This is a recursive pattern for i in sorted_freq: tree = Tree(i) tree_list.append(tree) #Pop of the two lowest character frequencies and create a single combined tree. # Then put these frequencies back in the begining of the list. for i in range(len(tree_list) - 1): new_tree = Tree(tree_list[0].root[1] + tree_list[1].root[1]) new_tree.addNodes(tree_list[0], tree_list[1]) tree_list.pop(0) tree_list.pop(0) #if the list of trees is empty I have finished and put the new tree in the list as the final tree if len(tree_list) == 0: tree_list.append(new_tree) else: #Go through tree list and add it in sorted order #Linear here is fine since on average it will be towards the begining of the list # #(Look at analysis of character frequencies) for j in range(len(tree_list)): if tree_list[j].root[1] >= new_tree.root[1]: tree_list.insert(j-1, new_tree) break if j == len(tree_list)-1: #at end of list so just append it (Worst case senario) tree_list.append(new_tree) #tree_list.append(new_tree) # print(new_tree) self.root = tree_list[0] print("Printing out Huffman Tree") self.root.print_tree(0)
def load_trees(tree_path, read_name_mapping=False, max_trees=None): with open(tree_path, 'r') as tree_file: nexus_str = tree_file.read().lower().strip() if read_name_mapping: name_map = read_nexus_name_mapping(nexus_str) else: name_map = None trees = [] for line in nexus_str.split('\n'): if line.strip().startswith('tree '): newick_str = line.split(' = ')[-1] if newick_str.startswith(r'[&r] '): newick_str = newick_str[len(r'[&r] '):] newick_str = newick_str.replace(']:[',',') newick_str = newick_str.replace(']',']:') newick_str = newick_str.replace(':;', ';') tree = Tree.from_newick(newick_str, translate=name_map) trees.append(tree) if max_trees is not None and len(trees) >= max_trees: return trees return trees
def read_file(self, file_path): "Called when activity is loaded, load the tree from the file" file = open(file_path, 'rb') try: tree = Tree().read_from(file) finally: file.close() self.init_tree(tree)
def test_add(self): node = Tree('a') child = Tree('b') node.add(child) self.assertEqual(1, node.child_count()) self.assertEqual(child.parent, node) self.assertEqual(0, child.idx)
def resolv(board, args): taquin = Taquin(board, args.heuristic) tree = Tree(taquin.getState(), args.time) while True: checkNode = tree.getBest() taquin.setState(checkNode) tree.close(checkNode) for child in taquin.getChildsStates(): if taquin.isSolved(child['board']): showSolution(child['moves'], board, taquin) return tree.show(child) similar, index = tree.getByHash(child['hash'], "close") if similar is not None: if child['score'] < similar['score']: tree.CLOSE.pop(index) tree.open(child) else: tree.OPEN.append(child)
def load_tree_from_nexus(tree_path, location_key='location', use_translation_table=False, name_mapping=None): if use_translation_table == True: name_mapping = read_translation_table(tree_path) print(name_mapping) with open(tree_path, 'r') as tree_file: nexus_str = tree_file.read() newick_str = extract_newick_from_nexus(nexus_str) tree = Tree.from_newick(newick_str, location_key=location_key, translate=name_mapping) return tree
def write_bantu_xml(xml_path, chain_length, root=None, exclude_outgroup=False, movement_model='rrw', adapt_tree=False, adapt_height=False): with open(NEWICK_TREE_PATH, 'r') as tree_file: tree_str = tree_file.read().lower().strip() tree = Tree.from_newick(tree_str.strip()) tree.load_locations_from_csv(LOCATIONS_PATH, swap_xy=True) if exclude_outgroup: tree.remove_nodes_by_name(OUTGROUP_NAMES) # tree = tree.big_child().big_child().big_child() tree.write_beast_xml(xml_path, chain_length, root=root, diffusion_on_a_sphere=True, movement_model=movement_model, adapt_tree=adapt_tree, adapt_height=adapt_height)
def test_tree(test_roots, test_soil): # values from Hölttä et al. (2006) # except for transp/photosynth/loading/unloading/sugar profile height = 12.0 element_height = np.concatenate( (np.repeat(0.3, repeats=40), test_roots.layer_thickness(test_soil).reshape(5, ))) num_elements = 45 radii = [0.5, 1, 2] transpiration_profile: List[float] = [0 for i in range(num_elements)] transpiration_profile[0] = 0.9 * 1e-6 # m3/s photosynth_profile: List[float] = [0 for i in range(num_elements)] photosynth_profile[0:3] = [1e-6, 1e-6, 1e-6] sugar_profile = [10.0 for i in range(num_elements)] sugar_loading_profile = photosynth_profile sugar_unloading_profile = [0.0 for i in range(num_elements)] sugar_unloading_profile[-1] = 2 axial_permeability_profile = [[1.5e-12, 6.0e-12]] * num_elements radial_hydr_conductivity = [1e-13] * num_elements elastic_modulus_profile = [[1000e6, 30e6]] * num_elements return Tree(height=height, num_elements=num_elements, element_height=element_height, initial_radius=radii, transpiration_profile=transpiration_profile, photosynthesis_profile=photosynth_profile, sugar_profile=sugar_profile, sugar_loading_profile=sugar_loading_profile, sugar_unloading_profile=sugar_unloading_profile, axial_permeability_profile=axial_permeability_profile, radial_hydraulic_conductivity_profile=radial_hydr_conductivity, elastic_modulus_profile=elastic_modulus_profile, sugar_target_concentration=0.9, sugar_unloading_slope=1, roots=test_roots)
def write_bantu_sample_xml(xml_path, chain_length, root=None, exclude_outgroup=False, movement_model='rrw', adapt_tree=False, adapt_height=False): with open(POSTERIOR_PATH, 'r') as tree_file: nexus_str = tree_file.read().lower().strip() name_map = read_nexus_name_mapping(nexus_str) tree_lines = [line.split(' = ')[-1] for line in nexus_str.split('\n') if line.startswith('\t\ttree')] tree_str = random.choice(tree_lines) tree = Tree.from_newick(tree_str.strip()) for node in tree.iter_descendants(): if node.name in name_map: node.name = name_map[node.name] tree.load_locations_from_csv(LOCATIONS_PATH, swap_xy=True) leafs_without_locations = [node.name for node in tree.iter_leafs() if node.location is None] tree.remove_nodes_by_name(leafs_without_locations) if exclude_outgroup: tree.remove_nodes_by_name(OUTGROUP_NAMES) tree.write_beast_xml(xml_path, chain_length, root=root, diffusion_on_a_sphere=True, movement_model=movement_model, adapt_tree=adapt_tree, adapt_height=adapt_height)
def generate_tree(texts): trees = {} for i in range(len(texts)): trees.update({i: texts[i]}) return Tree(trees)
def test_replace(self): node = Tree('a') child = Tree('b') node.add(child) child2 = Tree('c') node.add(child2) child3 = Tree('d') node.replace_child(child2, child3) self.assertEqual(child3, node.children[-1])
def build_tree(train, max_depth, min_size): tree = Tree(get_split(train)) grow_tree(tree.root, max_depth, min_size, 1) return tree
radial_hydr_conductivity: List[float] = [1e-13] * num_elements elastic_modulus_profile: List[List[float]] = [[1000e6, 30e6] ] * num_elements radii: List[float] = [0.1, 0.05, 0.001] tree = Tree(height=height, element_height=element_height, num_elements=num_elements, initial_radius=radii, transpiration_profile=transpiration_profile, photosynthesis_profile=photosynth_profile, sugar_profile=sugar_profile, sugar_loading_profile=sugar_loading_profile, sugar_unloading_profile=sugar_unloading_profile, sugar_target_concentration=sugar_target_concentration, sugar_unloading_slope=sugar_unloading_slope, axial_permeability_profile=axial_permeability_profile, radial_hydraulic_conductivity_profile=radial_hydr_conductivity, elastic_modulus_profile=elastic_modulus_profile, roots=roots) outputfname = 'test_' outputfname = outputfname + datetime.now().strftime( "%y-%m-%dT%H:%M:%S") + ".nc" model = Model(tree, outputfile=outputfname, soil=soil) for day in range(0, 2): for (ind, t) in enumerate(time[0:-1]): # set new transpiration rate
def train(self): return Tree(self.__train(self.data))
def tree(items, key): return Tree(items).contains(key)
def tree(items): return Tree(items).sort()
def setup(): ''' Setup tests ''' global TREE TREE = Tree()
def add_tree(self): """ 初始化一棵空树,并把树放到trees数组里 """ self.trees.append(Tree(self.X))
def test_separation(self): a = Tree('a') b = Tree('b') b.add(Tree('c')) self.assertEqual(0, len(a.children))
def test_creation(self): node = Tree('a') self.assertEqual('a', node.value)
def test_add_multiple(self): node = Tree('a') child = Tree('b') node.add(child) child2 = Tree('c') node.add(child2) self.assertEqual(1, child2.idx) child3 = Tree('d') node.insert(child3, 1) self.assertEqual(1, child3.idx) self.assertEqual(2, child2.idx)
def test_list_add(self): node = Tree('a') child = Tree('b') child2 = Tree('c') node.add(child, child2) self.assertEqual(2, node.child_count())