本文整理汇总了Python中ete3.Tree.write方法的典型用法代码示例。如果您正苦于以下问题:Python Tree.write方法的具体用法?Python Tree.write怎么用?Python Tree.write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ete3.Tree
的用法示例。
在下文中一共展示了Tree.write方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: migrate
# 需要导入模块: from ete3 import Tree [as 别名]
# 或者: from ete3.Tree import write [as 别名]
def migrate(db_path):
if db_path is None:
raise ConfigError("No database path is given.")
# make sure someone is not being funny
utils.is_profile_db(db_path)
# make sure the version is accurate
profile_db = db.DB(db_path, None, ignore_version = True)
if str(profile_db.get_version()) != current_version:
raise ConfigError("Version of this profile database is not %s (hence, this script cannot really do anything)." % current_version)
# migrate item orders
item_orders = profile_db.get_table_as_dict(item_orders_table_name)
for order_name in item_orders:
if item_orders[order_name]['type'] == 'newick':
newick = Tree(item_orders[order_name]['data'], format=1)
newick = newick.write(format=2)
profile_db._exec("""UPDATE %s SET "data" = ? WHERE "name" LIKE ?""" % item_orders_table_name, (newick, order_name))
# migrate layer orders
layer_orders = profile_db.get_table_as_dict(layer_orders_table_name)
for order_name in layer_orders:
if layer_orders[order_name]['data_type'] == 'newick':
newick = Tree(layer_orders[order_name]['data_value'], format=1)
newick = newick.write(format=2)
profile_db._exec("""UPDATE %s SET "data_value" = ? WHERE "data_key" LIKE ?""" % layer_orders_table_name, (newick, order_name))
# set the version
profile_db.remove_meta_key_value_pair('version')
profile_db.set_version(next_version)
# bye
profile_db.disconnect()
progress.end()
示例2: pruning
# 需要导入模块: from ete3 import Tree [as 别名]
# 或者: from ete3.Tree import write [as 别名]
def pruning(inputtree, inputfasta, tree_outfilename):
#This function remove sequences from a FASTA from a larger tree
#Full initial tree - to be pruned
k = open(inputtree, "r").read()
#ete3 Tree format
f = Tree(inputtree)
#List of IDs to be picked from the full FASTA
IDlist=[]
fasta = open(inputfasta, "rU")
record_dict = SeqIO.to_dict(SeqIO.parse(fasta, "fasta"))
for recordID in record_dict.keys():
print recordID
IDlist.append(recordID)
print IDlist
tree_outfile=open(tree_outfilename, "w")
print "pruning...", inputfasta
f.prune(IDlist, preserve_branch_length=True)
f.write(format=0, outfile=tree_outfilename)
print "pruned", inputfasta
示例3: check_hgt
# 需要导入模块: from ete3 import Tree [as 别名]
# 或者: from ete3.Tree import write [as 别名]
def check_hgt(tree_path, taxid_dict, bootstrap_threshold=70.0):
tree = Tree(tree_path)
tree = remove_bad_nodes(tree, support_threshold=bootstrap_threshold)
leaf_tags = get_tags_leaves(tree, taxid_dict)
dpapi_leaf = None
for leaf in tree.iter_leaves():
if leaf_tags[leaf.name] == "dpapi":
if not dpapi_leaf:
dpapi_leaf = leaf
else:
print ("More than one Dpapi leaf!\n" + tree_path + "\n")
farthest_node = dpapi_leaf.get_farthest_node(topology_only=True)[0]
if farthest_node.up == tree:
return False
else:
tree.set_outgroup(farthest_node.up)
edited_tree_path = tree_path + "_edited.tree"
tree.write(outfile=edited_tree_path)
if check_sisters_bacteria(dpapi_leaf, leaf_tags) and check_sisters_bacteria(dpapi_leaf.up, leaf_tags):
return True
else:
return False
示例4: smart_reroot
# 需要导入模块: from ete3 import Tree [as 别名]
# 或者: from ete3.Tree import write [as 别名]
def smart_reroot(treefile, outgroupfile, outfile, format=0):
"""
simple function to reroot Newick format tree using ete2
Tree reading format options see here:
http://packages.python.org/ete2/tutorial/tutorial_trees.html#reading-newick-trees
"""
tree = Tree(treefile, format=format)
leaves = [t.name for t in tree.get_leaves()][::-1]
outgroup = []
for o in must_open(outgroupfile):
o = o.strip()
for leaf in leaves:
if leaf[:len(o)] == o:
outgroup.append(leaf)
if outgroup:
break
if not outgroup:
print("Outgroup not found. Tree {0} cannot be rerooted.".format(treefile), file=sys.stderr)
return treefile
try:
tree.set_outgroup(tree.get_common_ancestor(*outgroup))
except ValueError:
assert type(outgroup) == list
outgroup = outgroup[0]
tree.set_outgroup(outgroup)
tree.write(outfile=outfile, format=format)
logging.debug("Rerooted tree printed to {0}".format(outfile))
return outfile
示例5: _compare
# 需要导入模块: from ete3 import Tree [as 别名]
# 或者: from ete3.Tree import write [as 别名]
def _compare(self, newick, nodes):
nodes = [str(node) for node in nodes]
t1 = Tree(newick, format=1)
t1.prune(nodes, preserve_branch_length=True)
t2 = Tree(newick, format=1)
prune(t2, nodes, const_depth=False, keep_root=True)
self.assertEqual(t1.write(format=1), t2.write(format=1))
示例6: main
# 需要导入模块: from ete3 import Tree [as 别名]
# 或者: from ete3.Tree import write [as 别名]
def main():
args = parse_args()
# Use the extension specified by the user if present
if args.extension:
ext = args.extension
else:
ext = '.mod.tre'
# Load the tree
t = Tree(args.tree)
# Iterate over the nodes, convert to desired value
for node in t.iter_search_nodes():
if args.decimal:
if node.support >= 1:
node.support = float(node.support * 0.01)
else:
print >> sys.stderr, 'bootstrap value in {} is < 1, \
ignoring.'.format(args.tree)
else:
if node.support <= 1:
node.support = int(node.support * 100)
else:
print >> sys.stderr, 'bootstrap value in {} is > 1, \
ignoring.'.format(args.tree)
# If the replace flag is set, replace the input file with the output file.
# Otherwise create a new file with the '.mod.tre' extension
if args.replace:
out = args.tree
else:
out = args.tree + ext
t.write(format=0, outfile=out)
示例7: sanitizeByType
# 需要导入模块: from ete3 import Tree [as 别名]
# 或者: from ete3.Tree import write [as 别名]
def sanitizeByType(container, sanitizeby='tsv', onlycolumns=False):
'''for a iterable of strings, carry out sanitizeString by:
line,
tsv (all or onlycolumns),
fasta headers, or
leaf in nwk'''
assert sanitizeby in set(['line', 'tsv', 'newick', 'fasta'])
if sanitizeby=='line':
for line in container:
print(sanitizeString(line.strip("\r\n"), False))
if sanitizeby=='tsv':
for line in container:
if onlycolumns:
newline = line.strip("\r\n").split("\t")
for i in onlycolumns:
newline[i-1]=sanitizeString(newline[i-1], False)
else:
newline=[sanitizeString(item.strip("\r\n"), False) for item in line.split("\t")]
print("\t".join(newline))
if sanitizeby=='newick':
from ete3 import Tree
t=Tree("".join(container))
for l in t:
l.name=sanitizeString(l.name, False)
print(t.write())
if sanitizeby=='fasta':
from Bio import SeqIO
from io import StringIO
from sys import stdout
fasta = StringIO("".join(container))
for seq_record in SeqIO.parse(fasta, "fasta"):
seq_record.id=sanitizeString(seq_record.description, False)
seq_record.description=''
SeqIO.write(seq_record, stdout, "fasta")
示例8: main
# 需要导入模块: from ete3 import Tree [as 别名]
# 或者: from ete3.Tree import write [as 别名]
def main(treefile, to, metric):
with open(treefile) as fh:
for treeline in fh:
tree = Tree(treeline)
tree = alphbetise_names(tree)
tree = normalise_tree(tree, to, metric)
print(tree.write(format=5))
示例9: createImg
# 需要导入模块: from ete3 import Tree [as 别名]
# 或者: from ete3.Tree import write [as 别名]
def createImg(filename, thres=0, samples=1):
count = parseLineage(filename)
suffix, matrix, taxo = getSuffixandMatrixandNewick(count,thres,samples)
newick = convert(taxo,suffix)
newick += ';'
t = Tree(newick, format=1)
ct = ClusterTree(t.write(), text_array=matrix)
addColors(ct)
# nodes are linked to the array table
array = ct.arraytable
# Calculates some stats on the matrix. Needed to establish the color gradients.
matrix_dist = [i for r in xrange(len(array.matrix))for i in array.matrix[r] if np.isfinite(i)]
matrix_max = np.max(matrix_dist)
matrix_min = np.min(matrix_dist)
matrix_avg = (matrix_max+matrix_min)/2
# Creates a profile face that will represent node's profile as a heatmap
profileFace = ProfileFace(matrix_max, matrix_min, matrix_avg, 200, 14, "heatmap",colorscheme=3)
# Creates my own layout function that uses previous faces
def mylayout(node):
# If node is a leaf
if node.is_leaf():
# And a line profile
add_face_to_node(profileFace, node, 0, aligned=True)
node.img_style["size"]=2
# Use my layout to visualize the tree
ts = TreeStyle()
ts.layout_fn = mylayout
# ct.show(tree_style=ts)
filedir = '/'.join(filename.split('/')[:-1])
# t.write(format=9, outfile="output/newick/"+param+".nw")
ct.render(filedir+'/phylo.png',tree_style=ts)
示例10: replace_names
# 需要导入模块: from ete3 import Tree [as 别名]
# 或者: from ete3.Tree import write [as 别名]
def replace_names(tree_file, replacer):
tree = Tree(tree_file)
errored = False
for tip in tree.iter_leaves():
try:
newname = replacer[tip.name.strip("'")]
tip.name = newname
except KeyError as exc:
print("ERROR: Tip is missing from replacement file: '{}'".format(
tip.name), file=sys.stderr)
errored = True
return tree.write()
示例11: update_newick
# 需要导入模块: from ete3 import Tree [as 别名]
# 或者: from ete3.Tree import write [as 别名]
def update_newick(t, labels):
langs_in_tree = set(str(l.label) for l in labels if l.languageTree_id == t.id)
if not langs_in_tree:
return False
try:
tree = Tree(t.newick_string, format=1)
prune(tree, langs_in_tree, const_depth=t.name.startswith('glottolog_'))
t.newick_string = tree.write(format=1)
return True
except TreeError:
return False
示例12: read_newick
# 需要导入模块: from ete3 import Tree [as 别名]
# 或者: from ete3.Tree import write [as 别名]
def read_newick (path_tree):
trees = []
# for filename in file_in:
# if filename.endswith('.aln'):
# path_tree = os.path.join(directory, filename)
# tree_cluster = filename.split('.')[1]
tree = Tree(path_tree)
for node in tree.traverse():
if node.is_leaf():
name = node.name
if name.find("|") != -1:
split = name.split("|")
name = split[0]
taxon = split[1]
node.add_feature("name", name)
# print(tree)
trees.append(tree.write())
print(trees)
return trees
示例13: get_tree
# 需要导入模块: from ete3 import Tree [as 别名]
# 或者: from ete3.Tree import write [as 别名]
def get_tree(n, keys, wscaf, wsta, wsto, seq, outg, fnw, fout, lgi, vb, kali=kali, notree=notree):
# increment tree number
n += 1
# prepare ali
desc = "%s:%s-%s" % (wscaf, wsta, wsto)
if kali:
fnom = "%s/%s.%s-%s.fasta" % (prefali, wscaf, wsta, wsto)
else:
fnom = "%s/ali.temp.fasta" % (prefali)
with open(fnom, "w") as o:
for k in keys:
record = SeqRecord(Seq(seq[k], IUPAC.ambiguous_dna),
id=k, description=desc)
if vb: print record.format("fasta").strip()
o.write(record.upper().format("fasta"))
if notree:
return n
# compute and retrieve tree using seaview...
cmd = "seaview -build_tree -distance observed -NJ -o - %s" % fnom
print cmd
tr = os.popen(cmd).read().strip()
if tr == '':
n -= 1
cmd = "rm %s" % fnom
os.system(cmd)
return n
tr = Tree(tr.split("] ")[1])
# root tree
if outg:
tr.set_outgroup(outg)
# write tree in a gz file
tr = tr.write(format=1)
fnw.write(tr + "\n")
fout.write("\t".join([ str(x) for x in [wscaf, wsta, wsto, (int(wsta)+int(wsto))/2,
int(wsto)-int(wsta), lgi ] ]) + "\n")
return n
示例14: read_newick
# 需要导入模块: from ete3 import Tree [as 别名]
# 或者: from ete3.Tree import write [as 别名]
def read_newick (file_in, directory):
'''this function reads a -dir containing newick format and return a dict as key=name_file ans value= tree
'''
trees = []
dico_tree = {}
for filename in file_in:
if filename.endswith('.tree'):
path_tree = os.path.join(directory, filename)
tree_cluster = filename.split('.')[1]
tree = Tree(path_tree)
for node in tree.traverse():
if node.is_leaf():
name = node.name
if name.find("|") != -1:
split = name.split("|")
name = split[0]
taxon = split[1]
node.add_feature("name", name)
# print(tree_cluster, tree.write())
dico_tree[tree_cluster] = tree.write()
return dico_tree
示例15: Tree
# 需要导入模块: from ete3 import Tree [as 别名]
# 或者: from ete3.Tree import write [as 别名]
#!/usr/bin/env python
from ete3 import Tree
import sys
tree = sys.argv[1]
root = sys.argv[2]
t = Tree(tree)
t.set_outgroup(t & root)
for leaf in t.iter_leaves():
cols = leaf.name.split("|")
if cols[0] == 'EBOV':
leaf.name = cols[1]
elif cols[1] == 'SLE':
leaf.name = cols[0]
print t.write()