コード例 #1
0
 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))
コード例 #2
0
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()
コード例 #3
0
ファイル: huffmanTree.py プロジェクト: mirroredge/huffmanCode
    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)
コード例 #4
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
コード例 #5
0
 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)
コード例 #6
0
 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)
コード例 #7
0
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)
コード例 #8
0
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
コード例 #9
0
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)
コード例 #10
0
ファイル: test_tree.py プロジェクト: LukeEcomod/TreeBoxModel
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)
コード例 #11
0
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)
コード例 #12
0
def generate_tree(texts):
    trees = {}
    for i in range(len(texts)):
        trees.update({i: texts[i]})
    return Tree(trees)
コード例 #13
0
 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])
コード例 #14
0
def build_tree(train, max_depth, min_size):
    tree = Tree(get_split(train))
    grow_tree(tree.root, max_depth, min_size, 1)
    return tree
コード例 #15
0
ファイル: main.py プロジェクト: LukeEcomod/TreeBoxModel
    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
コード例 #16
0
ファイル: algorithm.py プロジェクト: guillermoap/aa-pract3
 def train(self):
     return Tree(self.__train(self.data))
コード例 #17
0
def tree(items, key):
    return Tree(items).contains(key)
コード例 #18
0
ファイル: sorting.py プロジェクト: originalgremlin/portfolio
def tree(items):
    return Tree(items).sort()
コード例 #19
0
def setup():
    ''' Setup tests '''
    global TREE
    TREE = Tree()
コード例 #20
0
ファイル: rrt_base.py プロジェクト: WUSTBlank/rrt-test
 def add_tree(self):
     """
     初始化一棵空树,并把树放到trees数组里
     """
     self.trees.append(Tree(self.X))
コード例 #21
0
 def test_separation(self):
     a = Tree('a')
     b = Tree('b')
     b.add(Tree('c'))
     self.assertEqual(0, len(a.children))
コード例 #22
0
 def test_creation(self):
     node = Tree('a')
     self.assertEqual('a', node.value)
コード例 #23
0
 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)
コード例 #24
0
 def test_list_add(self):
     node = Tree('a')
     child = Tree('b')
     child2 = Tree('c')
     node.add(child, child2)
     self.assertEqual(2, node.child_count())