Return taxonomic Newick tree
422959
def taxTree(taxdict):
    """"""
    # the taxonomic dictionary holds the lineage of each ident in
    #  the same order as the taxonomy
    # use hierarchy to construct a taxonomic tree
    for rank in taxdict.taxonomy:
        current_level = float(taxdict.taxonomy.index(rank))
        # get clades at this rank in hierarchy
        clades = taxdict.hierarchy[rank]
        # merge those that are in the same clade into a cladestring
        for clade in clades:
            # unpack the identities in this clade and its clade name
            cladeidents, cladename = clade
            # Remove '' TaxRefs -- in cladestring already
            cladeidents = [e for e in cladeidents if e.ident]
            # only create cladestring if more than one ident in clade
            if len(cladeidents) < 2:
                continue
            # label node by 'clade'_'rank'
            cladename = '{0}_{1}'.format(cladename, rank)
            cladestring = stringClade(cladeidents, cladename, current_level)
            # replace first TaxRef in cladeidents with cladestring
            cladeidents[0].change(ident=cladestring, rank=rank)
            # replace all other TaxRefs with ''
            for e in cladeidents[1:]:
                e.change(ident='', rank=rank)
    # join any remaining strands into tree
    if len(taxdict.hierarchy[taxdict.taxonomy[-1]]) > 1:
        # unlist first
        clade = [e[0] for e in taxdict.hierarchy[taxdict.taxonomy[-1]]]
        cladeidents = sum(clade, [])
        cladeidents = [e for e in cladeidents if e.ident]
        cladestring = stringClade(cladeidents, 'life', current_level+1)
    return cladestring + ';'
728045
def _get_vectors(self, tree, precomputed_info):
        
        little_m = []
        big_m = []

        leaf_nodes = sorted(tree.leaf_nodes(), key=lambda x: x.taxon.label)
        # inner nodes, sorted order
        for leaf_a, leaf_b in combinations(leaf_nodes, 2):
            mrca = tree.mrca(taxa=[leaf_a.taxon, leaf_b.taxon])
            little_m.append(precomputed_info[mrca].edges_from_root)
            big_m.append(precomputed_info[mrca].dist_from_root)
        
        # leaf nodes, sorted order
        for leaf in leaf_nodes:
            little_m.append(1)
            big_m.append(leaf.edge_length)

        return np.array(little_m), np.array(big_m)
798485
def get_tree(cls, parent=None):
        
        cls = get_result_class(cls)

        if parent is None:
            # return the entire tree
            return cls.objects.all()
        if parent.is_leaf():
            return cls.objects.filter(pk=parent.pk)
        return cls.objects.filter(
            path__startswith=parent.path,
            depth__gte=parent.depth
        ).order_by(
            'path'
        )
549169
def get_node_type(dgtree):
    """"""
    if is_leaf(dgtree):
        return TreeNodeTypes.leaf_node

    root_label = dgtree.label()
    if root_label == '':
        assert dgtree == DGParentedTree('', []), \
            "The tree has no root label, but isn't empty: {}".format(dgtree)
        return TreeNodeTypes.empty_tree
    elif root_label in NUCLEARITY_LABELS:
        return TreeNodeTypes.nuclearity_node
    else:
        assert isinstance(dgtree, (RSTTree, DGParentedTree)), type(dgtree)
        return TreeNodeTypes.relation_node
390925
def get_tree(self):
        
        data = self.message(MessageType.GET_TREE, '')
        return Con(json.loads(data), None, self)
1290456
def build_tree_fast(self, new_path=None, seq_type='nucl' or 'prot'):
        """"""
        # Check output #
        if new_path is None: new_path = self.prefix_path + '.tree'
        # Command #
        command_args = []
        if seq_type == 'nucl': command_args += ['-nt']
        command_args += ['-gamma']
        command_args += ['-out', new_path]
        command_args += [self.path]
        # Run it #
        sh.FastTree(*command_args)
        # Return #
        return FilePath(new_path)
34997
def tree(obj):
    
    from .objects import Object
    if isinstance(obj, (bool, int, float, str, bytes)):
        return obj
    elif isinstance(obj, (datetime.date, datetime.time)):
        return obj.isoformat()
    elif isinstance(obj, dict):
        return {k: tree(v) for k, v in obj.items()}
    elif isinstance(obj, (list, tuple, set)):
        return [tree(i) for i in obj]
    elif isinstance(obj, Object):
        return {obj.__class__.__qualname__: tree(obj.nonDefaults())}
    else:
        return str(obj)
1278621
def leaf_list(cls, name, parent=None, interleave=None):
        """"""
        node = cls("_list_", parent, interleave=interleave)
        node.attr["name"] = name
        node.keys = None
        node.minEl = "0"
        node.maxEl = None
        node.occur = 3
        return node
322587
def copy(self):
        
        return LabeledTree(
            udepth = self.udepth,
            depth = self.depth,
            text = self.text,
            label = self.label,
            children = self.children.copy() if self.children != None else [],
            parent = self.parent)
522795
def load(cls, tree_path):
        """"""
        with open(tree_path) as f:
            tree_dict = json.load(f)

        return cls.from_dict(tree_dict)
807107
def from_dict(cls, tree_dict, previous=None):
        """"""
        instance = cls(tree_dict['tree_type'])

        fitted = tree_dict['fitted']
        instance.fitted = fitted
        if fitted:
            instance.level = tree_dict['level']
            instance.n_nodes = tree_dict['n_nodes']
            instance.tau_matrix = np.array(tree_dict['tau_matrix'])
            instance.previous_tree = cls._deserialize_previous_tree(tree_dict, previous)
            instance.edges = [Edge.from_dict(edge) for edge in tree_dict['edges']]

        return instance
282557
def tree(names):
    """"""
    # query
    query = Collection.query
    if names:
        query = query.filter(Collection.name.in_(names))
    else:
        query = query.filter(Collection.level == 1)
    # print tree
    tr = LeftAligned(traverse=AttributeTraversal())
    for coll in query.all():
        click.secho(tr(coll))
223845
def output_tree(self, t, seen):
        """"""
        if not t:
            return
        for c in t.children:
            self.output_tree(c, seen)
        if t.name in seen:
            return
        seen[t.name] = True
        if t.resource_name:
            output_class(t.name, t.props, self.override, t.resource_name)
        else:
            output_class(t.name, t.props, self.override)
123619
def visit_dict(self, node, parent):
        """"""
        newnode = nodes.Dict(node.lineno, node.col_offset, parent)
        items = list(self._visit_dict_items(node, parent, newnode))
        newnode.postinit(items)
        return newnode
657032
def tree(self,offset=0,prefix_inherited="",nofeatsplease=['Phoneme']):
		""""""

		tree = ""
		numchild=0
		for child in self.children:
			if type(child)==type([]):
				child=child[0]
			numchild+=1

			classname=child.classname()
			if classname=="Word":
				tree+="\n\n"
			elif classname=="Line":
				tree+="\n\n\n"
			elif classname=="Stanza":
				tree+="\n\n\n\n"

			if offset!=0:
				tree+="\n"
				for i in range(0,offset):
					tree+="      "
				#if not len(child.feats):
				#	tree+="	  "
				tree+="|"


			tree+="\n"
			newline=""
			for i in range(0,offset):
				newline+="      "
			newline+="|"


			cname=""
			for letter in classname:
				if letter==letter.upper():
					cname+=letter

			prefix=prefix_inherited+cname+str(numchild) + "."
			newline+="-----| ("+prefix[:-1]+") <"+classname+">"
			if child.isBroken():
				newline+="<<broken>>"
			else:
				string=self.u2s(child)
				if (not "<" in string):
					newline=makeminlength(newline,99)
					newline+="["+string+"]"
				elif string[0]!="<":
					newline+="\t"+string
				if len(child.feats):
					if (not child.classname() in nofeatsplease):
						for k,v in sorted(child.feats.items()):
							if v==None:
								continue

							newline+="\n"
							for i in range(0,offset+1):
								newline+="      "
							newline+="|     "
							newline+=self.showFeat(k,v)


			tree+=newline
			tree+=child.tree(offset+1,prefix)

		return tree
1032876
def tree(self):
        
        from cmdtree.tree import CmdTree
        if self._tree is None:
            self._tree = CmdTree()
        return self._tree
316041
def _slice(self, level):
        ''''''
        if level >= len(self.taxonomy):
            raise IndexError('Level greater than size of taxonomy')
        res = []
        for ident in sorted(list(self.keys())):
            res.append((self[ident]['taxref'], self[ident]['lineage'][level]))
        return res