本文整理汇总了Python中ete3.Tree.render方法的典型用法代码示例。如果您正苦于以下问题:Python Tree.render方法的具体用法?Python Tree.render怎么用?Python Tree.render使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ete3.Tree
的用法示例。
在下文中一共展示了Tree.render方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ete_draw
# 需要导入模块: from ete3 import Tree [as 别名]
# 或者: from ete3.Tree import render [as 别名]
def ete_draw(self, fname=None):
""" Draws the tree and saves it to a file. If `fname` is None,
show the tree instead of saving it.
Args:
fname: filename to save to (default=None)
"""
if Cfg.USE_ETE3:
def layout(node):
faces.add_face_to_node(AttrFace("name"), node, column=0,
position="branch-right")
ts = TreeStyle()
ts.show_leaf_name = False
ts.layout_fn = layout
ts.rotation = 90
tree = EteTree(self.ete_str(), format=8)
if fname:
tree.render(fname, tree_style=ts)
else:
tree.show(tree_style=ts)
else:
# TODO maybe throw an error?
pass
示例2: show_tree
# 需要导入模块: from ete3 import Tree [as 别名]
# 或者: from ete3.Tree import render [as 别名]
def show_tree(experiment_folder):
model = MDPD.Hierachical_MDPD(1)
model.load(os.path.join(experiment_folder, 'model.p'))
width, depth = model.width, model.depth
root = Tree()
cache = [(0, root)]
for i in range(depth + 1):
foo = []
for idx, node in cache:
paren = int((idx - 1) / width)
kid = idx - paren * width
face = faces.ImgFace(os.path.join(experiment_folder, 'images', '{}_{}_{}.png'.format(idx, paren, kid)))
node.add_face(face, 0)
if i < depth:
for k in range(width):
foo.append((idx * width + k + 1, node.add_child()))
cache = foo
ts = TreeStyle()
ts.mode = "c"
root.render(os.path.join(experiment_folder, 'images', 'tree_plot.png'), tree_style=ts)
return root
示例3: builtTree
# 需要导入模块: from ete3 import Tree [as 别名]
# 或者: from ete3.Tree import render [as 别名]
def builtTree(phylo_tree_pic, paralogs_file):
print("Aligning top 50 genes for phylogenetic tree...")
# maken van alignment
clustalw_cline = ClustalwCommandline("clustalw", infile=paralogs_file)
stdout, stderr = clustalw_cline()
# importeren van boom bestand
tree = Tree(paralogs_file[:-6] + ".dnd")
# bouwen en weggschrijven van boom
tree.render(phylo_tree_pic)
示例4: drawTree
# 需要导入模块: from ete3 import Tree [as 别名]
# 或者: from ete3.Tree import render [as 别名]
def drawTree(treeFile, ShowBool):
"""
Draw a tree from a phy file
"""
t = Tree(treeFile)
imgFile = treeFile.replace(".tree", ".tree.png")
# Basic tree style
ts = TreeStyle()
ts.show_leaf_name = True
ts.show_branch_support = True
ts.scale = 160
# Draws nodes as small red spheres of diameter equal to 10 pixels
nstyle = NodeStyle()
nstyle["shape"] = "sphere"
nstyle["size"] = 10
nstyle["fgcolor"] = "darkred"
#nstyle["faces_bgcolor"] = "pink"
nstyle2 = NodeStyle()
nstyle2["shape"] = "sphere"
nstyle2["size"] = 10
nstyle2["fgcolor"] = "darkblue"
# Gray dashed branch lines
nstyle["hz_line_type"] = 1
nstyle["hz_line_color"] = "#cccccc"
# Applies the same static style to all nodes in the tree. Note that,
# if "nstyle" is modified, changes will affect to all nodes
for n in t.traverse():
if n.is_leaf():
if n.name.split("|")[-1] == "GI":
n.set_style(nstyle)
if n.name.split("|")[-1] == "plasmid":
n.set_style(nstyle2)
gi = n.name.split("|")[1]
n.name = n.name.split("|")[0] #+ " " + n.name.split("|")[1]
n.name = n.name.replace("_tRNA_modification_GTPase_", "")
n.name = n.name.replace("_DNA", "")
n.name = " " + n.name + " "
if n.name[-1] == "_": n.name.rstrip()
taxon, color = taxonToColour(gi)
n.add_face(TextFace(taxon, fgcolor = color, fsize = 8), column=1, position="branch-right")
#n.img_style["bgcolor"] = color
if ShowBool == True: #permet de flipper les braches pour avoir des topologies similaires
t.show(tree_style=ts)
t.render(imgFile, w=393, units="mm", tree_style=ts)
示例5: plot_one_tree
# 需要导入模块: from ete3 import Tree [as 别名]
# 或者: from ete3.Tree import render [as 别名]
def plot_one_tree(newick_file, profile_dict, node_dict, params, prefix=''):
t = Tree(newick_file, format=1)
ts = get_tree_style()
set_node_default(t, node_dict=node_dict)
suf = ''
if params['with_branch_circle']:
add_node_circle(t, node_dict=node_dict)
suf += '_circle'
if params['with_leaf_pie'] and not params['with_branch_circle']:
remove_node_circle(t, node_dict=node_dict)
if params['with_leaf_pie']:
add_pie_face(t, ts, profile_dict, group=params['group'])
suf += '_pie'
add_branch_text(t, tree_style=ts, node_dict=node_dict)
set_node_style(t, node_dict=node_dict)
if prefix:
prefix += '_'
pdf_file = '%s/%stax_tree%s.pdf' % (params['outdir'], prefix, suf)
png_file = '%s/%stax_tree%s.png' % (params['outdir'], prefix, suf)
t.render(pdf_file, tree_style=ts, dpi=100)
image_trans(pdf_file, png_file)
示例6: TreeStyle
# 需要导入模块: from ete3 import Tree [as 别名]
# 或者: from ete3.Tree import render [as 别名]
nstyle['bgcolor'] = cp[0]
elif abr == 'pbi':
nstyle['bgcolor'] = cp[1]
elif abr == 'pte':
nstyle['bgcolor'] = cp[2]
elif abr == 'ppe':
nstyle['bgcolor'] = cp[3]
elif abr == 'pse':
nstyle['bgcolor'] = cp[4]
elif abr == 'poc':
nstyle['bgcolor'] = cp[5]
elif abr == 'ptr':
nstyle['bgcolor'] = cp[6]
elif abr == 'pso':
nstyle['bgcolor'] = cp[7]
elif abr == 'pca':
nstyle['bgcolor'] = cp[8]
elif abr == 'tth':
nstyle['bgcolor'] = cp[9]
else:
nstyle['bgcolor'] = "#000000"
node.set_style(nstyle)
ts = TreeStyle()
#ts.show_leaf_name = False
ts.mode = 'c'
ts.title.add_face(TextFace(title, fsize=20), column=0)
#t.show(tree_style = ts)
t.render(outputfile, tree_style = ts)
示例7: read_params
# 需要导入模块: from ete3 import Tree [as 别名]
# 或者: from ete3.Tree import render [as 别名]
if __name__ == '__main__':
params = read_params(sys.argv)
mkdir(params['outdir'])
modified_tax = '%s/tax_ass_modified.txt' % params['outdir']
newick_file = '%s/tax_tree.nwk' % params['outdir']
modify_tax_ass(params['tax_ass'], modified_tax)
level_profile, total_profile = read_profile(modified_tax, params['profile'], params['top'])
tree = read_tax(modified_tax, total_profile.T.mean())
tree.adjust_profile()
with open(newick_file, 'w') as out:
out.write(str(tree))
t = Tree(newick_file, format=1)
ts = get_tree_style()
set_node_default(t, node_dict=tree.nodes)
suf = ''
if params['with_branch_circle']:
add_node_circle(t, node_dict=tree.nodes)
suf += '_circle'
if params['with_leaf_pie'] and not params['with_branch_circle']:
remove_node_circle(t, node_dict=tree.nodes)
if params['with_leaf_pie']:
add_pie_face(t, ts, total_profile.T, group=params['group'])
suf += '_pie'
add_branch_text(t, tree_style=ts, node_dict=tree.nodes)
set_node_style(t, node_dict=tree.nodes)
pdf_file = '%s/tax_tree%s.pdf' % (params['outdir'], suf)
t.render(pdf_file, tree_style=ts, dpi=100)
示例8: print
# 需要导入模块: from ete3 import Tree [as 别名]
# 或者: from ete3.Tree import render [as 别名]
#print dendrogram
#dendrogram.showFigure()
print(tr.asciiArt())
ts = TreeStyle()
ts.show_leaf_name = True
ts.show_branch_length = True
ts.show_branch_support = True
print('NEWICK='+json.dumps(newick))
rooted_tree = Tree( newick )
#svgfile = os.path.join('/Users/avoorhis/programming/jupyter/VAMPS_API',args.prefix+'_dendrogram.svg')
svgfile = os.path.join(args.outdir,args.prefix+'_dendrogram.svg')
print(os.getcwd())
#print svgfile
print('rendering0')
rooted_tree.render(svgfile, tree_style=ts) # writes file to tmp
if args.function == 'pcoa_3d':
#print('starting pcoa_3d')
from skbio import DistanceMatrix
dm = DistanceMatrix(dm1)
#print(dm1)
#print('end pcoa_3d')
pcoa_data = pcoa(args, dm, datasets)
#test_PCoA()
if args.function == 'pcoa_2d':
# if not args.metadata:
示例9: TreeStyle
# 需要导入模块: from ete3 import Tree [as 别名]
# 或者: from ete3.Tree import render [as 别名]
t.add_face(bottom_c0_r0, column=0, position="branch-bottom")
t.add_face(bottom_c0_r1, column=0, position="branch-bottom")
a = t&"a"
a.set_style(NodeStyle())
a.img_style["bgcolor"] = "lightgreen"
b = t&"b"
b.set_style(NodeStyle())
b.img_style["bgcolor"] = "indianred"
c = t&"c"
c.set_style(NodeStyle())
c.img_style["bgcolor"] = "lightblue"
t.set_style(NodeStyle())
t.img_style["bgcolor"] = "lavender"
t.img_style["size"] = 12
for leaf in t.iter_leaves():
leaf.img_style["size"] = 12
leaf.add_face(right_c0_r0, 0, "branch-right")
leaf.add_face(aligned_c0_r1, 0, "aligned")
leaf.add_face(aligned_c0_r0, 0, "aligned")
leaf.add_face(aligned_c1_r1, 1, "aligned")
leaf.add_face(aligned_c1_r0, 1, "aligned")
ts = TreeStyle()
ts.show_scale = False
t.render("face_positions.png", w=800, tree_style=ts)
示例10: splitTblastn
# 需要导入模块: from ete3 import Tree [as 别名]
# 或者: from ete3.Tree import render [as 别名]
try:
contig,start,stop = splitTblastn(unsanitized)
if contig in sanitizedToNot:
contig = sanitizedToNot[contig]
q = "SELECT organism FROM organisms INNER JOIN contigs ON contigs.organismid = organisms.organismid WHERE contigs.contig_mod=?;"
cur.execute(q, (contig,) )
for res in cur:
organism = res[0]
except ValueError:
# Not a tblastn ID.
pass
node.name = sanitizeString("%s_%s_%s" %(organism, annotation[0:63], unsanitized), False)
t, ts = prettifyTree(t, title = gene + " cluster regions", show_bootstraps = False, ts=ts)
if options.savepng:
os.system("rm test.svg 2> /dev/null")
t.render("%s.svg" %(options.outfile), tree_style=ts)
os.system("convert -trim -depth 32 -background transparent %s.svg %s.png" %(options.outfile, options.outfile))
if options.display:
t.show(tree_style=ts)
# Clean up
con.close()
try:
sys.stderr.write("Deleting temporary directory %s...\n" %(tempdir))
shutil.rmtree(tempdir)
except OSError as exc:
raise IOError("Unable to delete temporary directory %s" %(tempdir) )
示例11: WebTreeHandler
# 需要导入模块: from ete3 import Tree [as 别名]
# 或者: from ete3.Tree import render [as 别名]
class WebTreeHandler(object):
def __init__(self, newick_str, tid, actions=None, style=None):
self.tree = None
self.nw_str = newick_str
self.treeid = tid
self.mapid = "map_" + tid
self.imgid = "img_" + tid
self.boxid = 'box_' + tid
self.treeconfig_obj = None
def init_nodeids(self):
# Initialze node internal IDs
for index, n in enumerate(self.tree.traverse('preorder')):
n._nid = index
def parse_newick(self):
try:
self.tree = Tree(self.nw_str)
except NewickError:
try:
self.tree = Tree(self.nw_str, format=1)
except NewickError as e:
return "Newick Parsing Error: "+str(e)
self.init_nodeids()
return True
def set_actions(self, actions=None):
if actions is None:
self.tree.actions = NodeActions()
else:
self.tree.actions = actions
def set_style(self, style=None):
if style is None:
self.tree.tree_style = TreeStyle()
else:
self.tree.tree_style = style
def set_tree_config(self, tcofg):
self.treeconfig_obj = tcofg
@timeit
def redraw(self, top_offset=0,left_offset=0):
#print "Inside redraw calling tree.render()"
#os.environ["DISPLAY"]=":0" # Used by ete to render images
base64_img, img_map = self.tree.render("%%return.PNG", tree_style=self.tree.tree_style)
#print "Inside redraw calling get_html_map()...."
html_map = self.get_html_map(img_map)
ete_link = '<div style="margin:0px;padding:0px;text-align:left;"><a href="http://etetoolkit.org" style="font-size:7pt;" target="_blank" >Powered by etetoolkit</a></div>'
html_img = """<img id="%s" class="ete_tree_img" USEMAP="#%s" onLoad="javascript:bind_popup(%s,%s);" src="data:image/gif;base64,%s">""" %(self.imgid, self.mapid, left_offset, top_offset, base64_img)
tree_div_id = self.boxid
#print "returning html from redraw method...."
return html_map+ '<div id="%s" >'%tree_div_id + html_img + ete_link + "</div>"
#------------------------------------------
def save_image(self, img_format):
img_url = os.path.join("http://phylo.cs.nmsu.edu:8080/TreeViewer/demo/tmp_dev/", self.treeid+"."+img_format)
img_path = os.path.join("/var/www/html/TreeViewer/demo/tmp_dev/", self.treeid+"."+img_format)
img = self.tree.render(img_path, tree_style=self.tree.tree_style)
#print "returning from save image"
return '<a target="_blank" href="%s">Download Image</a>' %(img_url)
#------------------------------------------
def get_html_map(self, img_map):
html_map = '<MAP NAME="%s" class="ete_tree_img">' %(self.mapid)
#print "get_html_map method called......."
if img_map["nodes"]:
for x1, y1, x2, y2, nodeid, text in img_map["nodes"]:
text = "" if not text else text
area = img_map["node_areas"].get(int(nodeid), [0,0,0,0])
html_map += """ <AREA SHAPE="rect" COORDS="%s,%s,%s,%s"
onMouseOut='unhighlight_node();'
onMouseOver='highlight_node("%s", "%s", "%s", %s, %s, %s, %s);'
onClick='show_actions("%s", "%s");'
href="javascript:void('%s');">""" %\
(int(x1), int(y1), int(x2), int(y2),
self.treeid, nodeid, text, area[0], area[1], area[2]-area[0], area[3]-area[1],
self.treeid, nodeid,
nodeid)
if img_map["faces"]:
for x1, y1, x2, y2, nodeid, text in img_map["faces"]:
text = "" if not text else text
area = img_map["node_areas"].get(int(nodeid), [0,0,0,0])
html_map += """ <AREA SHAPE="rect" COORDS="%s,%s,%s,%s"
onMouseOut='unhighlight_node();'
onMouseOver='highlight_node("%s", "%s", "%s", %s, %s, %s, %s);'
onClick='show_actions("%s", "%s", "%s");'
href='javascript:void("%s");'>""" %\
(int(x1),int(y1),int(x2),int(y2),
self.treeid, nodeid, text, area[0], area[1], area[2]-area[0], area[3]-area[1],
self.treeid, nodeid, text,
text,
)
html_map += '</MAP>'
#print "returning html from get_html_map()...."
#.........这里部分代码省略.........
示例12: str
# 需要导入模块: from ete3 import Tree [as 别名]
# 或者: from ete3.Tree import render [as 别名]
print tg_names
c_a = tree.get_common_ancestor(tg_names)
#attempt to calculate distance on a version of the tree in which branches below some support threshold have been deleted
# closest_leaves = []
# for leaf in closest_other_group:
# closest_leaves.append(leaf.name)
# target_leaves = []
# for leaf in target_group:
# target_leaves.append(leaf.name)
# collapsed_tree = tree
# for node in collapsed_tree:
# if node.support < 0.5:
# node.delete()
# target_ca = collapsed_tree.get_common_ancestor(target_leaves)
# closest_ca = collapsed_tree.get_common_ancestor(closest_leaves)
# collapsed_distance = collapsed_tree.get_distance(target_ca, closest_ca, topology_only=True)
print sys.argv[1] + "\tEuks not monophyletic\t" + str(len(eukaryote_seqs)) + "\t" + str(c_a.support) + "\t" + str(size_target_group) + "\t" + str(shortest_distance) + "\t" + str(num_sgs)
else:
print sys.argv[1] + "\t" + answer[0]
#If euks are monophyletic, what is the max. number allowed for the gene to be considered a candidate LGT?
#euk sequence is part of a euk clade nested within bacteria, and the eukaryotes are not monophyletic in the tree [what about the case where the LGT is the only copy in euks?]
#tree.render(out_tree)
except:
raise
#uncomment the following to make a PDF of the tree
ts = TreeStyle()
ts.show_leaf_name = True
ts.show_branch_support = True
ts.show_branch_length = False
tree.render(out_tree, tree_style=ts)
示例13: zip
# 需要导入模块: from ete3 import Tree [as 别名]
# 或者: from ete3.Tree import render [as 别名]
#!/usr/bin/python
from ete3 import Tree, NodeStyle
from pyies.userOptions import basePath
import os.path
spTree1F = os.path.join(basePath, 'analysis', 'iesdb', 'speciesTree1.nhx')
spTree2F = os.path.join(basePath, 'analysis', 'iesdb', 'speciesTree2.nhx')
spTree3F = os.path.join(basePath, 'analysis', 'iesdb', 'speciesTree3b.nhx')
outT1 = os.path.join(basePath, 'analysis', 'figures', 'spTree1.png')
outT2 = os.path.join(basePath, 'analysis', 'figures', 'spTree2.png')
outT3 = os.path.join(basePath, 'analysis', 'figures', 'spTree3.png')
for tF, oF in zip([spTree1F, spTree2F, spTree3F], [outT1, outT2, outT3]):
t = Tree(tF)
t.sort_descendants(attr='O')
for node in t.traverse():
nstyle = NodeStyle()
nstyle["size"] = 0
node.set_style(nstyle)
#t.show()
t.render(oF)
示例14: open
# 需要导入模块: from ete3 import Tree [as 别名]
# 或者: from ete3.Tree import render [as 别名]
dst = t.get_distance(l)
if dst != tree_dist:
l.dist += tree_dist - dst
sys.stdout.write('u')
else:
sys.stdout.write('\nERROR. Too many final species: will not force ultrametricity.\n')
#======================================================#
# EXPORT phylo
t.write(format=5, outfile=ophylo, dist_formatter='%0.20f')
## write the count of resultant species
f = open(ophylo, 'a')
f.write("\n"+str(nTrueSpecies)+"\n")
f.close()
if plot_trees:
for leaf in t:
leaf.name = leaf.sp
t.render(ophylo+"_3PHYLO.png", w=183, units="mm")
#======================================================#
# FINAL PROMPTS
sys.stdout.write('P]\n') # Print
if not quiet: print "Runtime >> " + str(time.time() - init) + " sec"
if not quiet: print "Total species count >> " + str(nTrueSpecies)
if nIndsSFS == nIndsORI:
print "Exit status >> OK!"
else: sys.exit("ERROR. A bug must be crawling around... Please, please, contact the programmer.")
示例15: open
# 需要导入模块: from ete3 import Tree [as 别名]
# 或者: from ete3.Tree import render [as 别名]
from ete3 import Tree, TreeStyle, TextFace # @UndefinedVariable
rand_newick = "((water, estuarine_open_water, inland_water)Water_bodies, artificial_surface, cloud, shadow, forest, grassland)Root;"
rand_tree = "rand_tree"
with open(rand_tree, 'w') as TREE:
TREE.write(rand_newick)
# Reading tree t1 and t2
t1 = Tree(rand_newick, format=8) # @UndefinedVariable
#t2 = Tree(rand_tree) # @UndefinedVariable
ts = TreeStyle()
ts.show_leaf_name = True
ts.branch_vertical_margin = 20
ts.title.add_face(TextFace("Auckland LCDB", fsize=20), column=0)
ts.scale = 50
t1.add_face(TextFace("Root "), column=0, position = "branch-top")
for node in t1.traverse():
if node.name == "Water_bodies":
node.add_face(TextFace("Water_bodies"), column=0, position = "branch-top")
print(t1)
t1.render("mytree.png", tree_style=ts, dpi=300)