本文整理汇总了Python中dendropy.Tree类的典型用法代码示例。如果您正苦于以下问题:Python Tree类的具体用法?Python Tree怎么用?Python Tree使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Tree类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __bisect__
def __bisect__(t,e):
# e = __find_centroid_edge__(t)
u = e.tail_node
v = e.head_node
u.remove_child(v)
t1 = Tree(seed_node = v)
if u.num_child_nodes() == 1:
p = u.parent_node
v = u.child_nodes()[0]
l_v = v.edge_length
u.remove_child(v)
if p is None: # u is the seed_node; this means the tree runs out of all but one side
t.seed_node = v
return t,t1
l_u = u.edge_length
p.remove_child(u)
p.add_child(v)
v.edge_length = l_u+l_v
u = p
while u is not None:
__updateNode__(u)
u = u.parent_node
t.annotated = True
t1.annotated = True
return t,t1
示例2: generate_ATT_from_files
def generate_ATT_from_files(seqaln,
mattype,
workdir,
treefile,
otu_json,
ingroup_mrca=None):
"""Build an ATT object without phylesystem.
If no ingroup mrca ott_id is provided, will use all taxa in tree to calc mrca."""
aln = DnaCharacterMatrix.get(path=seqaln, schema=mattype)
for tax in aln.taxon_namespace:
tax.label = tax.label.replace(" ", "_") #Forcing all spaces to underscore UGH
tre = Tree.get(path=treefile,
schema="newick",
preserve_underscores=True,
taxon_namespace=aln.taxon_namespace)
with open(otu_json) as data_file:
otu_dict = json.load(data_file)
for tax in aln:
assert tax.label in otu_dict
tre = Tree.get(path=treefile,
schema="newick",
preserve_underscores=True,
taxon_namespace=aln.taxon_namespace)
otu_newick = tre.as_string(schema="newick")
if ingroup_mrca:
ott_mrca = int(ingroup_mrca)
else:
ott_ids = [otu_dict[otu].get['^ot:ottId'] for otu in otu_dict]
ott_mrca = get_mrca_ott(ott_ids)
return AlignTreeTax(otu_newick, otu_dict, aln, ingroup_mrca=ott_mrca, workdir=workdir)
示例3: __init__
def __init__(self, **kwargs):
'''
Parameters
----------
reference_tree_path: str
Path to the file containing the reference tree, which is used to
retroot the tree tree provided to tree
tree_path: str
Path to the file containing the tree to be re-rooted. This tree will
be rerooted at the same position as the tree porovided to the
reference_tree
'''
reference_tree_path = kwargs.pop('reference_tree_path', None)
tree_path = kwargs.pop('tree_path')
logging.debug("Importing old tree from file: %s"
% tree_path)
self.tree = Tree.get(path=tree_path,
schema='newick')
if reference_tree_path:
logging.debug("Importing reference tree from file: %s"
% reference_tree_path)
self.reference_tree = Tree.get(path=reference_tree_path,
schema='newick')
else:
self.reference_tree = reference_tree_path
if len(kwargs) > 0:
raise Exception("Unexpected arguments provided to Decorator class: %s" % kwargs)
示例4: get_sum_of_branches
def get_sum_of_branches(treepath):
fin = open(treepath, "r")
newick = fin.readline().strip()
t = Tree()
t.read_from_string(newick.__str__(), "newick")
fin.close()
return t.length()
示例5: get_subtree
def get_subtree(self, taxa):
if len(taxa) == 0:
return None
tree = Tree(self._tree)
if isinstance(taxa[0],str):
tree.prune_taxa_with_labels(taxa)
elif isinstance(taxa[0],Taxon):
tree.prune_taxa(taxa)
return PhylogeneticTree(tree)
示例6: scale_tree_branch
def scale_tree_branch(tree, format="newick"):
tree_obj = None
if os.path.exists(tree):
tree_obj = Tree.get_from_path(tree, format)
elif isinstance(tree, str):
tree_obj = Tree(stream=StringIO(tree), schema=format)
elif isinstance(tree, Tree):
tree_obj = Tree
if sum([ e.length > 1 for e in tree_obj.postorder_edge_iter()]):
for e in tree_obj.postorder_edge_iter():
if e.length is not None:
e.length = e.length/100
return tree_obj.as_newick_string()
示例7: main
def main():
cpu = sys.argv[1]
job_name = sys.argv[2]
try:
alnfile = sys.argv[3]
except:
assert(restart is True), "Specified alignment file does not exist. Path?"
try:
treefile = sys.argv[4]
except:
assert(restart is True), "Specified tree file does not exist. Path?"
# Rewrite tree to create trifurcating root, as needed by phylobayes mpi
tree = Tree.get_from_path(treefile, "newick", rooting = "force-unrooted")
tree.resolve_polytomies() # in case of polytomies.
tree.update_bipartitions() # this will create a trifurcating root on an unrooted tree
tstring = str(tree).replace('[&U] ', '')
with open('temp.tre', 'w') as tf:
tf.write(tstring + ';\n')
# Phylobayes is run to chain length 5500, sampling every 5 to yield 1100. Later, burnin of 100 is removed to get a final posterior n=1000 (same procedure as Rodrigue 2013 Genetics)
pb_call = "mpirun -np " + str(cpu) + " ./pb_mpi -mutsel -cat -d " + alnfile + " -T temp.tre -x 5 1100 " + job_name
run_pb_call = subprocess.call(pb_call, shell = True)
assert( run_pb_call == 0 ), "pb_mpi didn't run!"
# Parse output with readpb_mpi, using a burnin of 100 and saving everything else (posterior size = 1000)
readpb_call = "mpirun -np " + str(cpu) + " ./readpb_mpi -x 100 1 -1 " + job_name + "\n"
run_readpb_call = subprocess.call(readpb_call, shell = True)
assert( run_readpb_call == 0 ), "readpb_mpi didn't run!"
示例8: readTreeFromFile
def readTreeFromFile( treePath):
'''
input: path to the file containing newick tree
return Tree object
'''
myTree= Tree.get_from_path(treePath, 'newick', annotations_as_nhx=True, extract_comment_metadata=True , suppress_annotations=False)
return myTree
示例9: __init__
def __init__(self, workDir, resultsFile, inFile, coreId, seqType, seedNum, bootNum, method, interLeaved):
'''
Data Fields:
work_dir = temproray directory
inFile = data file,
id = core id (int),
seqType = d (dna); p (protein); r (rna),
bootNum = number of replicates,
seedNum = Random number seed between 1 and 32767
method =b (Bootstrap) Default,
j (Jackknife)
c (Permute species for each character)
o (Permute character order)
s (Permute within species)
r (Rewrite data)),
interLeaved=True if sequence data is interleaved otherwise False
'''
self.work_dir = workDir
self.resultsFile = resultsFile
self.inFile = inFile
self.coreId = coreId
self.seqType = seqType
self.seedNum = seedNum
self.bootNum = bootNum
self.method = method
self.n = bootNum
self.nt = False
self.interLeaved = interLeaved
self.outFile = "bootstrap_"+str(coreId)+".out"
self.newSpeciesTree = Tree()
self.leafLabelStree = []
self.internalExRootSpeceLabels= []
if self.seqType in ['r', 'd']:
self.nt = True
示例10: get_bls
def get_bls(tree_path):
# clean the tree of any support values, so we're left only with BLs
bls = []
t = Tree()
t.read_from_path( tree_path, "newick" )
i = t.level_order_edge_iter()
while True:
try:
e = i.next() # in Python 2.x
len = e.length
if len != None:
bls.append( len )
except StopIteration:
break
return bls
示例11: get_tree_lines
def get_tree_lines(Tname):
stringlist =[]
from dendropy import Tree
tree = Tree.get_from_path(Tname,"newick")
for nd in tree.postorder_internal_node_iter():
for child in nd.child_nodes():
stringlist.append(child.as_newick_string())
return (stringlist)
示例12: readTreeFromString
def readTreeFromString(self, treeString):
'''
input: string containing newick tree
return Tree object
'''
myTree= Tree()
myTree= Tree.get_from_string( treeString, 'newick', annotations_as_nhx=True, extract_comment_metadata=True , suppress_annotations=False)
return myTree
示例13: index_mutations
def index_mutations(con):
"""Builds an index of all mutations"""
cur = con.cursor()
for msaid in get_alignment_method_ids(con):
for modelid in get_phylo_modelids(con):
newick = get_anc_cladogram(con, msaid, modelid)
t = Tree()
t.read_from_string(newick, "newick")
for edge in t.preorder_edge_iter():
if edge.head_node == None or edge.tail_node == None:
continue
if edge.head_node.label == None or edge.tail_node.label == None:
continue
print msaid, modelid, edge.head_node.label, edge.tail_node.label
anc1name = "Node" + edge.head_node.label.__str__()
anc2name = "Node" + edge.tail_node.label.__str__()
index_mutations_helper(con, msaid, modelid, anc1name, anc2name)
示例14: get_tree_and_OTT_list
def get_tree_and_OTT_list(tree_filehandle, sources, verbosity=0):
"""
Takes a base tree and creates objects for each node and leaf, attaching them as 'data' dictionaries
to each node in the DendroPy tree. Nodes and leaves with an OTT id also have pointers to their data
dicts stored in an OTT-keyed dict, so that mappings to other databases (ncbi id, etc etc) can be created.
We can easily have duplicate leaf names, so for the entire procedure we ignore the Dendropy concept
of a taxon list and simply use labels.
Returns the Dendropy tree and the OTT dict.
"""
#these variables are all pointers into the same data
ordered_leaves=[]
ordered_nodes=[]
indexed_by_ott={}
try:
tree = Tree.get_from_stream(tree_filehandle, schema="newick", preserve_underscores=True, suppress_leaf_node_taxa=True)
except:
sys.exit("Problem reading tree from " + treefile.name)
info("-> read tree from " + tree_filehandle.name)
ott_node = re.compile(r"(.*) ott(\d+)(@\d*)?$") #matches the OTT number
mrca_ott_node = re.compile(r"(.*) (mrcaott\d+ott\d+)(@\d*)?$") #matches a node with an "mrca" node number (no unique OTT)
for i, node in enumerate(tree.preorder_node_iter()):
node.data = {'parent':node.parent_node or None}
if node.label:
node.label = node.label.replace("_"," ")
m = ott_node.search(node.label)
if m is not None:
if m.group(3):
warn("Node has an @ sign at the end ({}), meaning it has probably not been substituted by an OpenTree equivalent. You may want to provide an alternative subtree from this node downwards, as otherwise it will probably be deleted from the main tree.".format(node.label))
node.label = m.group(1)
node.data['ott'] = int(m.group(2))
indexed_by_ott[node.data['ott']] = node.data
node.data['sources']={k:None for k in sources}
else:
m = mrca_ott_node.search(node.label)
if m is not None:
if m.group(3):
warn("Node has an @ sign at the end ({}), meaning it has probably not been substituted by an OpenTree equivalent. You may want to provide an alternative subtree from this node downwards, as otherwise it will probably be deleted from the main tree.".format(node.label))
node.label = m.group(1)
#this is an 'mrca' node, so we want to save sources but *not* save the ott number in node.data
indexed_by_ott[m.group(2)] = node.data
node.data['sources']={k:None for k in sources}
elif node.is_leaf():
warn("Leaf without an OTT id: '{}'. This will not be associated with any other data".format(node.label))
#finally, put underscores at the start or the end of the new label back
#as these denote "fake" names that are hidden and only used for mapping
#we could keep them as spaces, but leading/trailing underscores are easier to see by eye
if node.label[0]==" ":
node.label = "_" + node.label[1:]
if node.label[-1]==" ":
node.label = node.label[:-1] + "_"
info("-> extracted {} otts from among {} leaves and nodes".format(len(indexed_by_ott), i))
return tree, indexed_by_ott
示例15: return_trees_from_trace
def return_trees_from_trace(path):
print "Parsing trace:", path
trees = []
lnls = []
fin = open(path, "r")
last_tree = None
last_lnl = 0.0
count_unique_trees = 0
for line in fin.xreadlines():
treestring = ""
lnlstring = ""
found_tree = False
for c in line:
if found_tree == False and c != "]" and c != "[" and c != "(":
lnlstring += c
if c == "(":
found_tree = True
if found_tree == True:
treestring += c
lnl = float(lnlstring)
t = Tree()
t.read_from_string(line, "newick")
if last_tree != None: #2nd->nth trees in the list
#sd = last_tree.symmetric_difference(t)
#sd = t.symmetric_difference(last_tree)
if last_lnl < lnl:
trees.append(t)
lnls.append("%.2f"%lnl)
count_unique_trees += 1
else:
trees[trees.__len__()-1] = t
lnls[lnls.__len__()-1] = "%.2f"%lnl
else: #first tree in the list
trees.append(t)
lnls.append("%.2f"%lnl)
count_unique_trees += 1
last_tree = t
last_lnl = lnl
print count_unique_trees, lnl
trees.append(last_tree)
lnls.append("%.2f"%lnl)
fin.close()
return [trees, lnls]