本文整理汇总了Python中ete2.TreeStyle.show_scale方法的典型用法代码示例。如果您正苦于以下问题:Python TreeStyle.show_scale方法的具体用法?Python TreeStyle.show_scale怎么用?Python TreeStyle.show_scale使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ete2.TreeStyle
的用法示例。
在下文中一共展示了TreeStyle.show_scale方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plotTree
# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import show_scale [as 别名]
def plotTree(self, tree, out_fn=None, rotation=270, show_leaf_name=False,
show_branch_length=False, circularTree=False, show_division_nodes=True,
distance_between_branches=4, show_border=False, width=None, height=None):
from ete2 import TreeStyle
from PyQt4 import QtSvg, QtCore, QtGui
from ete2.treeview import qt4_render, drawer, main
ts = TreeStyle()
ts.show_scale = False
ts.show_border = show_border
ts.orientation = 1 # 0, tree is drawn from left-to-right. 1, tree is drawn from right-to-left
ts.rotation = rotation
ts.show_leaf_name = show_leaf_name
ts.show_branch_length = show_branch_length
if circularTree:
ts.mode = 'c'
else:
ts.mode = 'r'
ts.branch_vertical_margin = distance_between_branches
def hideInternalNodesLayout(node):
if not node.is_leaf():
node.img_style["size"] = 0
if show_division_nodes is False:
ts.layout_fn = hideInternalNodesLayout
if out_fn is not None:
scene = qt4_render._TreeScene()
img = ts
tree_item, n2i, n2f = qt4_render.render(tree, img)
scene.init_data(tree, img, n2i, n2f)
tree_item.setParentItem(scene.master_item)
scene.master_item.setPos(0,0)
scene.addItem(scene.master_item)
main.save(scene, out_fn, w=width, h=height, dpi=600)
else:
scene, img = drawer.init_scene(tree, None, ts)
tree_item, n2i, n2f = qt4_render.render(tree, img)
scene.init_data(tree, img, n2i, n2f)
tree_item.setParentItem(scene.master_item)
scene.addItem(scene.master_item)
size = tree_item.rect()
w, h = size.width(), size.height()
svg = QtSvg.QSvgGenerator()
svg.setFileName("test.svg")
svg.setSize(QtCore.QSize(w, h))
svg.setViewBox(size)
pp = QtGui.QPainter()
pp.begin(svg)
scene.render(pp, tree_item.rect(), tree_item.rect(), QtCore.Qt.KeepAspectRatio)
示例2: main
# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import show_scale [as 别名]
def main(argv):
print argv
br = mechanize.Browser()
directoryhtml = br.open(argv)
t_soup = BeautifulSoup(directoryhtml.read())
t_tables = t_soup.findAll('table',{"id":"people"})
t_tbody = t_tables[0].findAll('tbody')
t_trs = t_tbody[0].findAll('tr')
for t_tr in t_trs:
t_tds = t_tr.findAll('td')
username = t_tds[0].find('a').find(text=True)
email = t_tds[1].find('p').find(text=True)
department = t_tds[2].find('p').find(text=True)
title = t_tds[3].find('p').find(text=True)
manager = t_tds[4].find('p').find(text=True)
skypeid = t_tds[5].find('p').find(text=True)
username_list.append(username)
email_list.append(email[:email.find("@")])
manager_list.append(manager)
#Get the root manager
rootname = getRootName()
#Make the tree variable
treeStr = getTree(rootname, "(", ")" + rootname + ";")
treeStr = treeStr.replace("(,", "(")
treeStr = treeStr.replace(",)", ")")
treeStr = treeStr.replace(",,", ",")
ts = TreeStyle()
# Do not add leaf names automatically
ts.show_leaf_name = False
ts.show_branch_length = False
ts.show_scale = False
# Use my custom layout
ts.layout_fn = my_layout
t = Tree(treeStr, format=8)
for n in t.traverse():
nstyle = NodeStyle()
nstyle["fgcolor"] = "red"
nstyle["size"] = 15
n.set_style(nstyle)
count = 0
addNodeCount(t, 0)
#t.add_face(TextFace(str(addNodeCount(t, 0))), column=1, position = "branch-bottom")
# Tell ETE to use your custom Tree Style
t.show(tree_style=ts)
t.render("tree_structure.png", w=183, units="mm")
示例3: draw_ete2_tree
# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import show_scale [as 别名]
def draw_ete2_tree(organism, snplist, tree_file_name, config, c):
'''Draws a phylogenetic tree using ETE2
Keyword arguments:
organism -- the organism of which to make a tree
snplist -- a list of the SNP names, positions and state
file_name -- the name of the out-file _tree.pdf will be added
'''
newick = tree_to_newick(organism, config, c)
tree = Tree(newick, format=1)
tree_depth = int(tree.get_distance(tree.get_farthest_leaf()[0]))
for n in tree.traverse():
# Nodes are set to red colour
nstyle = NodeStyle()
nstyle["fgcolor"] = "#BE0508"
nstyle["size"] = 10
nstyle["vt_line_color"] = "#000000"
nstyle["hz_line_color"] = "#000000"
nstyle["vt_line_type"] = 0
nstyle["hz_line_type"] = 0
nstyle["vt_line_width"] = 2
nstyle["hz_line_width"] = 2
for snp in snplist:
if n.name == snp[0]:
if snp[1] == snp[3]:
# If the SNP is Derived in snplist,
# change appearance of node
nstyle["fgcolor"] = "#99FF66"
nstyle["size"] = 15
nstyle["vt_line_color"] = "#000000"
nstyle["hz_line_color"] = "#000000"
nstyle["vt_line_type"] = 0
nstyle["hz_line_type"] = 0
elif snp[3] == "-":
# If the SNP is missing due to a gap, make it grey
nstyle["fgcolor"] = "#DDDDDD"
nstyle["size"] = 10
nstyle["vt_line_color"] = "#DDDDDD"
nstyle["hz_line_color"] = "#DDDDDD"
nstyle["vt_line_type"] = 1
nstyle["hz_line_type"] = 1
n.set_style(nstyle)
ts = TreeStyle()
ts.show_leaf_name = False # Do not print(leaf names, they are added in layout)
ts.show_scale = False # Do not show the scale
ts.layout_fn = CanSNPer_tree_layout # Use the custom layout
ts.optimal_scale_level = 'full' # Fully expand the branches of the tree
if config["dev"]:
print("#[DEV] Tree file: %s" % tree_file_name)
tree.render(tree_file_name, tree_style=ts, w=tree_depth * 500)
示例4: get_tree_style
# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import show_scale [as 别名]
def get_tree_style(tree_file, abund, rownames):
with open("matrix.txt", "w") as temp:
cols = len(abund[0])
header = "#Names"
for i in xrange(cols):
header += "\tOTU%d" % i
temp.write("%s\n" % header)
for i, row in enumerate(abund):
temp.write("%s\t%s\n" % (rownames[i], '\t'.join([str(i) for i in row])))
t = Tree(tree_file)
t.convert_to_ultrametric(10)
assert isinstance(abund, numpy.ndarray)
assert isinstance(rownames, numpy.ndarray)
ts = TreeStyle()
ts.mode = "r"
ts.show_leaf_name = False
ts.show_scale = False
ts.show_branch_length = False
ts.branch_vertical_margin = 20
ts.force_topology = True
ts.optimal_scale_level = "full"
ts.scale = 50
ts.draw_guiding_lines = True
ts.guiding_lines_type = 0
ts.guiding_lines_color = "black"
for n in t.traverse():
if not n.is_leaf():
nstyle = NodeStyle()
n.set_style(nstyle)
nstyle['size'] = 0
nstyle['hz_line_width'] = 3
nstyle['vt_line_width'] = 3
else:
nstyle = NodeStyle()
n.set_style(nstyle)
nstyle['size'] = 0
nstyle['hz_line_width'] = 3
nstyle['vt_line_width'] = 3
nstyle['fgcolor'] = "Black"
nstyle['shape'] = "square"
name_face = AttrFace("name", fsize=14, ftype="Arial", fgcolor="black", penwidth=10, text_prefix=" ", text_suffix=" ")
n.add_face(name_face, column=0, position="aligned")
row_index = rownames.tolist().index(n.name)
col = 1
for i in xrange(10):
col += 1
n.add_face(CircleFace(5, color=get_color(abund, row_index, i)), column=col, position="aligned")
return t, ts
示例5: draw_ete_tree
# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import show_scale [as 别名]
def draw_ete_tree(self, corpus, fontsize=5,
color_leafs=False,
save_newick=True, mode='c',
outputfile=None,
return_svg=True, show=False,
save=False):
root = self.to_ete(labels=corpus.titles)
def layout(node):
if node.is_leaf():
N = AttrFace("name", fsize=7)
faces.add_face_to_node(faces.AttrFace("name","Arial",10, None), node, 0, position='branch-right')
# problems: aligment of labels to branch, left padding of labels
ts = TreeStyle()
ts.mode = mode
ts.show_leaf_name = False
ts.scale = 120
ts.show_scale = False
ts.branch_vertical_margin = 10
nstyle = NodeStyle()
nstyle["fgcolor"] = "#0f0f0f"
nstyle["size"] = 0
nstyle["vt_line_color"] = "#0f0f0f"
nstyle["hz_line_color"] = "#0f0f0f"
nstyle["vt_line_width"] = 1
nstyle["hz_line_width"] = 1
nstyle["vt_line_type"] = 0
nstyle["hz_line_type"] = 0
for n in root.traverse():
n.set_style(nstyle)
ts.layout_fn = layout
if outputfile:
outputfile = os.path.expanduser(outputfile)
if save_newick: # save tree in newick format for later manipulation in e.g. FigTree:
root.write(outfile=os.path.splitext(outputfile)[0]+'.newick')
if save:
root.render(outputfile, tree_style=ts)
if show:
root.show(tree_style=ts)
if return_svg: # return the SVG as a string
return root.render("%%return")[0]
示例6: get_tree_style
# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import show_scale [as 别名]
def get_tree_style(tree, metadata, colors):
assert isinstance(tree, TreeNode)
ts = TreeStyle()
ts.mode = "c"
ts.show_leaf_name = False
ts.show_scale = False
ts.show_branch_length = False
ts.force_topology = True
ts.optimal_scale_level = "mid"
get_node_styles(tree, metadata, colors)
for site, color in colors.items():
if 'Gastro' in site:
site = "GI"
ts.legend.add_face(CircleFace(7, color), column=0)
ts.legend.add_face(TextFace(" %s" % site, fsize=20), column=1)
return ts
示例7: drawete2PhylTree
# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import show_scale [as 别名]
def drawete2PhylTree(treeFilePath):
tree = Tree(treeFilePath)
treeStyle = TreeStyle()
treeStyle.show_scale = False
#treeStyle.margin_left = 0
#treeStyle.margin_right = 0
#treeStyle.margin_top = 0
#treeStyle.margin_bottom = 0
#treeStyle.tree_width = treeWidth
no_of_nodes = countNodes(tree)
treeStyle.scale = 120#finalImageHeightinMM/no_of_nodes
treeStyle.branch_vertical_margin = 10#finalImageHeightinMM/no_of_nodes
#treeStyle.draw_aligned_faces_as_table = False
tree = changeNodeStyle(tree)
#tree.img_style["size"] = 30
#tree.img_style["fgcolor"] = "blue"
#tree.show(tree_style=treeStyle)
tree.render("tree.PNG",tree_style=treeStyle,units="mm")
示例8: give_tree_layout
# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import show_scale [as 别名]
def give_tree_layout(t):
# for all nodes give them the weight = score
for n in t.traverse():
n.add_features(weight=n.dist/20.0)
# Create an empty TreeStyle
ts = TreeStyle()
# Set our custom layout function
ts.layout_fn = layout
ts.show_leaf_name = False
# Draw a tree
ts.mode = "c"
#ts.arc_start = -180
#ts.arc_span = 180
#ts.scale = 100
ts.min_leaf_separation = 10
ts.show_scale = False
return ts
示例9: render_tree_image
# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import show_scale [as 别名]
def render_tree_image(self, filename):
def my_layout(node):
name_faces = AttrFace("name", fsize=10, fgcolor = "#0000FF")
faces.add_face_to_node(name_faces, node, column=0, position="branch-right")
t = Tree("%s;" % self.newick_string(), format = 1)
s = "0"
for n in t.iter_descendants():
text = TextFace(s)
if s == "0": s = "1"
else: s = "0"
text.fgcolor = "#FF0000";
nstyle = NodeStyle()
nstyle['size'] = 15
nstyle['fgcolor'] = "#333"
n.set_style(nstyle)
n.add_face(text, column = 0, position = "branch-top")
ts = TreeStyle()
ts.rotation = 90
ts.show_leaf_name = False
ts.layout_fn = my_layout
ts.margin_left = 0
ts.branch_vertical_margin = 50
ts.show_scale = False
t.render(filename, tree_style = ts, w = 2000)
示例10: str
# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import show_scale [as 别名]
# start virtual display
xvfb=Display(visible=0, size=(1024, 768)).start()
application.CONFIG["DISPLAY"] = str(xvfb.new_display_var)
# We extend the minimum WebTreeApplication with our own WSGI
# application
application.set_external_app_handler(webplugin_app)
# Lets now apply our custom tree loader function to the main
# application
application.set_tree_loader(my_tree_loader)
# Set tree style
ts = TreeStyle()
ts.show_scale = False
application.set_tree_style(ts)
# And our layout as the default one to render trees
application.set_default_layout_fn(main_layout)
# I want to make up how tree image in shown using a custrom tree
# renderer that adds much more HTML code
application.set_external_tree_renderer(tree_renderer)
# ==============================================================================
# ADD CUSTOM ACTIONS TO THE APPLICATION
#
# The function "register_action" allows to attach functionality to
# nodes in the image. All registered accions will be shown in the
# popup menu bound to the nodes and faces in the web image.
示例11: showAllLevelsInTreeInGrid
# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import show_scale [as 别名]
def showAllLevelsInTreeInGrid(request):
"""
Performs a selection, spatial filter and returns an image.
grid_level is the grid layer.
taxonomic_level is the taxonomic level to be shown. Options are:
sp, gns, fam, ord, cls, phy, king
"""
import ipdb
response = HttpResponse()
get = request.GET
try:
gid = int(get['gid'])
grid_level = int(get['g_l'])
names = int(get['names'])
if names > 0:
only_id = False
else:
only_id = True
#taxonomic_level = get['tax_lvl']
except:
response.content='Bad request. Check GET variable definitions'
response.status_code = 500
return response
biome = Occurrence.objects.all()
mesh = initMesh(grid_level)
try:
cell = mesh.objects.get(id=gid)
except:
logger.error("Selected id does not exist in selected grid")
return None
import os.path
tax_levels = ['sp','gns','fam','cls','ord','phy','kng']
tax_keys = {'sp':'1.Species','gns':'2. Genera','fam':'3. Families','ord':'4. Orders','cls':'5. Classes','phy':'6. Phyla','kng':'7. Kingdoms'}
rich_keys = { 'oc':'occurrences','sp' :'species','gns':'genera','fam':'families','cls':'classes','ord':'orders','phy':'phyla','kng':'kingdoms'}
img_paths = {}
#THIS IS VERY VERY WRONG AND I WOULD SUGGEST A REFACTORING like the use of a binary written copy in disk about the object in question (cached)
gb=GriddedTaxonomy(biome,cell,generate_tree_now=True,use_id_as_name=only_id)
taxonomy = gb.taxonomies[0]
#ipdb.set_trace()
mat_complex = taxonomy.calculateIntrinsicComplexity()
for taxonomic_level in tax_levels:
head_path = settings.PATH_IMAGES
filename = "%s-%s-%s.png" %(grid_level,gid,taxonomic_level)
file_ = head_path+filename
logger.info('Writing in: %s'%file_)
if not os.path.isfile(file_):
logger.info("The image doens't exist")
try:
if gb not in locals():
#gb=GriddedTaxonomy(biome,cell,generate_tree_now=True)
logger.info("Gridded taxonomy doesn't found")
except:
gb=GriddedTaxonomy(biome,cell,generate_tree_now=True,use_id_as_name=only_id)
forest = taxonomy.forest
ts = TreeStyle()
ts.show_leaf_name = True
ts.mode = "c"
ts.arc_start = -180 # 0 degrees = 3 o'clock
ts.arc_span = 360
ts.show_scale = False
try:
#ipdb.set_trace()
forest[taxonomic_level].render(file_,h=500, w=500, units="px",tree_style=ts)
#drawer.exit_gui(1, 1)
#logger.info(QtCore.QThreadPool)
#del(forest[taxonomic_level])
except:
logger.error('Something went wrong with the image rendering')
img_paths[taxonomic_level] = {'name': tax_keys[taxonomic_level],'path':filename,'richness':taxonomy.richness[rich_keys[taxonomic_level]]}
else:
img_paths[taxonomic_level] = {'name': tax_keys[taxonomic_level],'path':filename,'richness':taxonomy.richness[rich_keys[taxonomic_level]]}
#del(forest)
#
#dic_richness = gb.taxonomies[0].richness
det_complex = gb.taxonomies[0].vectorIntrinsic
template = get_template('base.html')
submatrices = map(lambda i : mat_complex[0:i,0:i],range(1,len(mat_complex)))
#ipdb.set_trace()
import numpy as np
tras = map(lambda mat : np.linalg.eigvals(mat),submatrices)
#ipdb.set_trace()
try:
eigenv = np.linalg.eigvals(mat_complex).tolist()
svd = np.linalg.svd(mat_complex)
except:
eigenv =[]
svd = [[],[],[]]
#.........这里部分代码省略.........
示例12: cluster
# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import show_scale [as 别名]
#.........这里部分代码省略.........
plt.tight_layout() # fixes margins
## Conversion to Newick/ETE
# Stuff we need
from scipy.cluster.hierarchy import average, linkage, to_tree
#from hcluster import linkage, to_tree
from ete2 import Tree, TreeStyle, NodeStyle
# Change it to a distance matrix
T = to_tree(Z)
# ete2 section
root = Tree()
root.dist = 0
root.name = "root"
item2node = {T: root}
to_visit = [T]
while to_visit:
node = to_visit.pop()
cl_dist = node.dist /2.0
for ch_node in [node.left, node.right]:
if ch_node:
ch = Tree()
ch.dist = cl_dist
ch.name = str(ch_node.id)
item2node[node].add_child(ch)
item2node[ch_node] = ch
to_visit.append(ch_node)
# This is the ETE tree structure
tree = root
ts = TreeStyle()
ts.show_leaf_name = True
ts.show_branch_length = True
ts.show_scale = False
ts.scale = None
if orientation == "top":
ts.rotation = 90
ts.branch_vertical_margin = 10 # 10 pixels between adjacent branches
# Draws nodes as small red spheres of diameter equal to 10 pixels
nstyle = NodeStyle()
nstyle["size"] = 0
# Replace the node labels
for leaf in tree:
k = leaf.name
k = int(k)
leaf.name = labels[k]
# Apply node styles to nodes
for n in tree.traverse():
n.set_style(nstyle)
# Convert the ETE tree to Newick
newick = tree.write()
f = open('C:\\Users\\Scott\\Documents\\GitHub\\d3-dendro\\newickStr.txt', 'w')
f.write(newick)
f.close()
# Save the image as .png...
from os import path, makedirs
# Using ETE
folder = pathjoin(session_manager.session_folder(), constants.RESULTS_FOLDER)
if (not os.path.isdir(folder)):
makedirs(folder)
# saves dendrogram as a .png with pyplot
plt.savefig(path.join(folder, constants.DENDROGRAM_PNG_FILENAME))
plt.close()
# if orientation == "top":
# plt.figure(figsize=(20,80))
# else:
# plt.figure(figsize=(80,20))
pdfPageNumber, score, inconsistentMax, maxclustMax, distanceMax, distanceMin, monocritMax, monocritMin, threshold = utility.generateDendrogram(
fileManager)
session['dengenerated'] = True
labels = fileManager.getActiveLabels()
inconsistentOp = "0 " + leq + " t " + leq + " " + str(inconsistentMax)
maxclustOp = "2 " + leq + " t " + leq + " " + str(maxclustMax)
distanceOp = str(distanceMin) + " " + leq + " t " + leq + " " + str(distanceMax)
monocritOp = str(monocritMin) + " " + leq + " t " + leq + " " + str(monocritMax)
thresholdOps = {"inconsistent": inconsistentOp, "maxclust": maxclustOp, "distance": distanceOp,
"monocrit": monocritOp}
managers.utility.saveFileManager(fileManager)
session_manager.cacheAnalysisOption()
session_manager.cacheHierarchyOption()
import random
ver = random.random() * 100
return render_template('cluster.html', labels=labels, pdfPageNumber=pdfPageNumber, score=score,
inconsistentMax=inconsistentMax, maxclustMax=maxclustMax, distanceMax=distanceMax,
distanceMin=distanceMin, monocritMax=monocritMax, monocritMin=monocritMin,
threshold=threshold, thresholdOps=thresholdOps, ver=ver)
示例13: bct_dendrogram
# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import show_scale [as 别名]
def bct_dendrogram(corpus, tree, outputfile=None,
fontsize=5, save_newick=True, mode='c', show=False,
color_leafs=False, save=False, return_svg=True):
"""
Draw a dendrogram of the texts in the corpus using ETE.
Parameters
----------
corpus : `Corpus` instance
The corpus to be plotted.
tree : `(VN)Clusterer` object
The clusterer object which was
applied to the corpus.
outputfile : str
The path where the plot should be saved.
color_leafs: boolean, default=True,
If true, will color the text labels
according to their category.
fontsize : int, default=5
The fontsize of the labels on the axes.
save_newick : boolean, default=True
Whether to dump a representation of the
tree in newick-format, which can later
be modified using software like FigTree:
http://tree.bio.ed.ac.uk/software/figtree/
mode : str, default='c'
The type of tree to be drawn. Supports:
- 'c': circular dendrogram
- 'r': traditional, rectangular dendrogram
save : boolean, default=False
Whether to save the plot to `outputfile`.
return_svg : boolean, default=True
Whether to return the plot in SVG-format.
Useful for the GUI.
"""
for leaf in tree.get_leaves():
leaf.name = leaf.name.replace("'", '')
def layout(node):
if node.is_leaf():
N = AttrFace("name", fsize=7)
faces.add_face_to_node(faces.AttrFace("name","Arial",10, None), node, 0, position='branch-right')
# problems: aligment of labels to branch, left padding of labels
ts = TreeStyle()
ts.mode = mode
ts.show_leaf_name = False
ts.scale = 120
ts.show_scale = False
ts.branch_vertical_margin = 10
nstyle = NodeStyle()
nstyle["fgcolor"] = "#0f0f0f"
nstyle["size"] = 0
nstyle["vt_line_color"] = "#0f0f0f"
nstyle["hz_line_color"] = "#0f0f0f"
nstyle["vt_line_width"] = 1
nstyle["hz_line_width"] = 1
nstyle["vt_line_type"] = 0
nstyle["hz_line_type"] = 0
for n in tree.traverse():
n.set_style(nstyle)
ts.layout_fn = layout
if outputfile:
outputfile = os.path.expanduser(outputfile)
if save_newick: # save tree in newick format for later manipulation in e.g. FigTree:
tree.write(outfile=os.path.splitext(outputfile)[0]+'.newick')
if save:
tree.render(outputfile, tree_style=ts)
if show:
tree.show(tree_style=ts)
if return_svg: # return the SVG as a string
return tree.render("%%return")[0]
示例14: main
# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import show_scale [as 别名]
def main(args={}):
#########################################################
############ loading options
global opt
if not args: opt=command_line(def_opt, help_msg, 'iaf', synonyms=command_line_synonyms, strict=1)
else: opt=args
set_MMlib_var('opt', opt)
global temp_folder; temp_folder=Folder(random_folder(opt['temp'])); test_writeable_folder(temp_folder, 'temp_folder'); set_MMlib_var('temp_folder', temp_folder)
write("#=============------ "); write(" show_syntheny.py ", how='reverse,bright'); write(" -------=============#", 1)
## basic graphics options
face_width= opt['w']; font_size= opt['fs']
## defining a function that, given a gene, decide what is printed in the face"""
if not opt['m']:
def get_text(g):
if g.id in geneid2family: return geneid2family[g.id]+':'+g.id
else: return '-'+':'+g.id
else:
face_width=30
def get_text(g):
if g.id in geneid2family: return geneid2family[g.id]
else: return ''
tree_style=TreeStyle(); tree_style.show_leaf_name=False; tree_style.scale=1; tree_style.show_scale=False
node_style=NodeStyle(); node_style["size"] = 0 #; node_style["fgcolor"] = "darkred"
node_style_grey=NodeStyle(); node_style_grey["size"] = 0; node_style_grey["bgcolor"] = "lightgrey"
tree=Tree(); tree.dist=0.0; tree.set_style(node_style)
############################## legend mode only: start
if opt['legend']: ### totally different program in this case
for line_index, line in enumerate(open(opt['legend'])):
try:
bkg_color='white' if line_index%2 else 'lightgrey'
splt=line.strip().split('\t')
if not splt: continue
leaf=tree.add_child(name='', dist=0.0);
leaf.set_style(node_style) if line_index%2 else leaf.set_style(node_style_grey)
g=gene(strand='+'); g.color, g.color_outline, g.color_box_bkg, g.color_box_line=[x if x!='None' else None for x in splt[1].split()];
g.text = replace(splt[2], '\\n', '\n')
title_face=faces.TextFace(splt[0], fsize=font_size); title_face.margin_left=5; leaf.add_face(title_face, 0, 'branch-right' ) #title left
arrow_face=syntheny_view([g], printed={'boundaries': 0, 'text':1, 'id':0}, pen_size=4, font_size=font_size, width=face_width)[0]; leaf.add_face(arrow_face, 1, 'branch-right' )
for desc_line_index, desc_line in enumerate(splt[3].split('\\n')):
desc_face=faces.TextFace(desc_line, fsize=font_size); desc_face.background.color = bkg_color; leaf.add_face(desc_face, 2, 'branch-right' ) #desc_face.margin_down=3; desc_face.margin_up=3;
except: printerr('-legend ERROR parsing this line: |n{0}'.format(line), 1); raise
write("Legend mode: {0} entries found. ".format(len(tree)), 1)
if opt['out']: write('--> writing output file: {0}'.format(opt['out']), 1); tree.render(opt['out'], tree_style=tree_style)
else: write('-- opening interactive ETE2 environment (PyQt4) -- ', 1); tree.show(tree_style=tree_style)
sys.exit()
############################## legend mode only: over
#### checking input
input_gff_file=opt['i']; check_file_presence(input_gff_file, 'input_gff_file', notracebackException )
annotation_gff_file=opt['a']; check_file_presence(annotation_gff_file, 'annotation_gff_file', notracebackException )
homology_file=opt['f']; check_file_presence(homology_file, 'homology_file', notracebackException )
# printing for pretty out
write('# Input gff file= {0:<30} (genes of interest)'.format(input_gff_file), 1)
write('# Annotation gff file= {0:<30} (all genes)'.format(annotation_gff_file), 1)
write('# Homology tsv file= {0:<30} (gene families)'.format(homology_file), 1)
non_def_options_str=join([ '# -{0} {1}\n'.format(k, opt[k]) for k in opt if k in def_opt and def_opt[k] != opt[k] and not k in 'iaf' ], '')
if non_def_options_str: write('### Non-default options:\n'+non_def_options_str)
write('', 1)
# checking output options
for x in ['of', 'oc', 'ocf', 'ocg']:
if opt[x] and opt[x]==1: raise notracebackException, "ERROR option -{0} must be provided with an argument (which will be used as output file)!"
#######
### processing options controlling colors
colors_already_taken={} # useful for later, when we compute available_colors
color_genes_of_interest=[None, None, None, None]
if opt['ci']:
for index, color in enumerate( opt['ci'].split(',') ):
if color=='None': color=None
color_genes_of_interest[index]=color
colors_already_taken[ join( map(str, color_genes_of_interest), ',') ]=1
color_singlets=[None, None, None, None]
if opt['cs']:
for index, color in enumerate( opt['cs'].split(',') ):
if color=='None': color=None
color_singlets[index]=color
colors_already_taken[ join( map(str, color_singlets), ',') ]=1
fam2color={} ## each color is a list [fill, outline, box_bkg, box_outline] if not defined, it's None
if opt['cf']:
## load color-family file
for line in open( opt['cf'] ):
splt=line.strip().split()
if splt: #skipping empty lines
fam=splt[0]; the_colors=[None, None, None, None]
for index, item in enumerate(splt[1:]):
if item=='None': item=None
the_colors[index]=item
fam2color[fam] = the_colors
colors_already_taken[ join( map(str, the_colors), ',') ]=1
color_file=opt['c']; check_file_presence(color_file, 'color_file', notracebackException )
color_scheme=opt['cr'];
if not color_scheme in [0, 1, 2, 3]: raise notracebackException, "ERROR invalid color scheme provided with option -cr ! see -help"
individual_colors=[line.strip() for line in open(color_file) if line.strip()];
#.........这里部分代码省略.........
示例15: random_color
# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import show_scale [as 别名]
node.img_style["bgcolor"] = random_color()
node.img_style["hz_line_width"] = 0
node.img_style["vt_line_width"] = 0
#if node.is_leaf():
# f = faces.CircleFace(50, "red")
# faces.add_face_to_node(f, node, 0, position="aligned")
ts = TreeStyle()
ts.mode = "c"
ts.arc_span = 360
ts.layout_fn = layout
ts.show_leaf_name = False
ts.show_border = True
ts.draw_guiding_lines = False
ts.show_scale = True
#ts.scale = 60
t = Tree()
t.dist = 0
t.size = 0,0
for x in xrange(100):
n = t.add_child()
n = n.add_child()
n = n.add_child()
n2 = n.add_child()
n3 = n.add_child()
n4 = n2.add_child()
n5 = n3.add_child()
# n.size = (10, 10)
# n2.size = (10, 70)