本文整理汇总了Python中ete2.TreeStyle.scale方法的典型用法代码示例。如果您正苦于以下问题:Python TreeStyle.scale方法的具体用法?Python TreeStyle.scale怎么用?Python TreeStyle.scale使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ete2.TreeStyle
的用法示例。
在下文中一共展示了TreeStyle.scale方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: draw_tree
# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import scale [as 别名]
def draw_tree(tree, file):
ts = TreeStyle()
ts.branch_vertical_margin = 1
ts.show_leaf_name = False
if '.svg' in file:
ts.scale = 3000
tree.render(file, tree_style=ts, h=300, units='mm')
else:
ts.scale = 1500
tree.render(file, tree_style=ts, w=3000, units='mm')
示例2: get_tree_style
# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import 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
示例3: draw_ete_tree
# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import 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]
示例4: get_tree_style
# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import scale [as 别名]
def get_tree_style(scale=None, vertical_margin=None):
"""Setups the tree-style used when rendering the tree"""
style = TreeStyle()
style.show_leaf_name = False
if scale:
style.scale = scale
style.show_border = True
if vertical_margin:
style.branch_vertical_margin = vertical_margin
return style
示例5: plot_tree
# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import scale [as 别名]
def plot_tree(fixedTree,fileName):
## plot the tree
def my_layout(node):
if node.is_leaf():
name_face = AttrFace("name",fsize=25)
faces.add_face_to_node(name_face, node, column=0, position="branch-right")
else:
name_face = AttrFace("name", fsize=20, fgcolor="red")
faces.add_face_to_node(name_face, node, column=0, position="branch-right")
ts = TreeStyle()
ts.show_leaf_name = False
ts.show_branch_length = True
ts.show_branch_support = True
ts.scale = 180
ts.layout_fn = my_layout
out = fixedTree.render(fileName, units="mm",tree_style=ts,dpi=400)
示例6: drawete2PhylTree
# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import 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")
示例7: give_tree_layout
# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import 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.min_leaf_separation = 7
ts.show_scale = False
#ts.arc_start = -180
#ts.arc_span = 180
ts.scale = 200
return ts
示例8: doWork
# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import scale [as 别名]
def doWork(args):
# read clustering data
geneIdToClusterId = {}
clusterIds = []
for line in open(args.cluster):
if line[0] == '%':
clusterId = line[1:].strip()
clusterIds.append(clusterId)
else:
geneIdToClusterId[line.strip()] = clusterId
# create colour map for clusters
clusterIdToColour = {}
index = 0
for clusterId in clusterIds:
rgb = tuple([int(c*255) for c in hsv_to_rgb(float(index)/len(clusterIds), 0.4, 1.0)])
clusterIdToColour[clusterId] = '#%02X%02X%02X' % rgb
index += 1
# read tree
tree = Tree(args.tree)
# define node properties
for node in tree.traverse('levelorder'):
if node.is_leaf():
name = node.name.replace("'", '')
clusterId = geneIdToClusterId[name]
node.add_feature('clusterId', clusterId)
if args.label:
node.name = ' ' + name + ' [' + clusterId + ']'
ns = NodeStyle()
ns['shape'] = 'circle'
ns['fgcolor'] = 'black'
ns['size'] = 4
node.set_style(ns)
else:
ns = NodeStyle()
ns['size'] = 0
node.set_style(ns)
# determine colour for each node
assignedColor = set()
for node in tree.traverse('levelorder'):
if node.is_leaf() or node.is_root():
continue
# determine clusters descendent from this node
clusterSet = set()
for leaf in node.get_leaves():
clusterSet.add(leaf.clusterId)
# check if parent has already been assigned a colour
bContinue = False
parentNode = node.up
while not parentNode.is_root():
if parentNode in assignedColor:
bContinue = True
break
parentNode = parentNode.up
if bContinue:
continue
# colour node if all descendants are from the same cluster
if len(clusterSet) == 1:
clusters = list(clusterSet)
ns = NodeStyle()
ns['bgcolor'] = clusterIdToColour[clusters[0]]
ns['size'] = 0
node.set_style(ns)
assignedColor.add(node)
# create tree style for plotting consisteny index trees
treeStyle = TreeStyle()
treeStyle.margin_left = 10
treeStyle.margin_right = 10
treeStyle.margin_top = 10
treeStyle.margin_bottom = 10
treeStyle.guiding_lines_type = 1
treeStyle.legend_position=1
treeStyle.scale = 500
# add legend
rowIndex = 0
for clusterId in sorted(clusterIdToColour.keys()):
treeStyle.legend.add_face(CircleFace(4, clusterIdToColour[clusterId]), column=0)
treeStyle.legend.add_face(TextFace(' ' + clusterId), column=1)
rowIndex += 1
tree.render(args.output, dpi=args.dpi, w = int(args.width*args.dpi + 0.5), tree_style=treeStyle)
示例9: MakePlot
# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import scale [as 别名]
#.........这里部分代码省略.........
if LCA.name==t.name:
percent_dist = percent*LCA_to_leaf_dist
if mean_dist <= percent:
child_node = (t&leaf_name)
else:
child_node = (t&nearby_names[0])#This means "go up from root" in the direction of the nearest guy
ancestor_node = (t&child_node.name).up
elif mean_dist <= percent:
percent_dist = t.get_distance(LCA) + abs(percent-mean_dist)*(LCA_to_leaf_dist)/(1-mean_dist)
child_node = (t&leaf_name)
ancestor_node = (t&child_node.name).up
else:
percent_dist = t.get_distance(LCA) - abs(percent-mean_dist)*(t.get_distance(LCA))/(mean_dist)
child_node = (t&leaf_name)
ancestor_node = (t&child_node.name).up
while t.get_distance(t.name, ancestor_node) > percent_dist:
child_node = ancestor_node
ancestor_node = (t&child_node.name).up
insert_node(t, leaf_name+"_"+str(percent), child_node.name, percent_dist-t.get_distance(t.name, ancestor_node))
#Set outgroup
if outgroup in names:
t.set_outgroup(t&outgroup) #I will need to check that this outgroup is actually one of the names...
else:
print("WARNING: the chosen outgroup " + outgroup + " is not in the given taxonomy: ")
print(names)
print("Proceeding without setting an outgroup. This may cause results to be uninterpretable.")
#Insert hypothetical nodes
hyp_node_names = dict()
cutoffs = [.9,.8,.7,.6,.5,.4,.3,.2,.1]
cutoffs = [-.5141*(val**3)+1.0932*(val**2)+0.3824*val for val in cutoffs]
for i in range(len(org_names)):
xi = x[i:len(x):len(org_names)]
for j in range(1,len(cutoffs)+1):
if xi[j]>0:
insert_hyp_node(t, org_names[i], cutoffs[j-1],ckm_ave_train_dist, org_names)
hyp_node_names[org_names[i]+"_"+str(cutoffs[j-1])] = [org_names[i], cutoffs[j-1], j-1] #in case there are "_" in the file names
size_factor=250
font_size=55
#Now put the bubbles on the nodes
def layout(node):
node_style = NodeStyle()
node_style["hz_line_width"] = 10
node_style["vt_line_width"] = 10
node.set_style(node_style)
#print(node)
if node.is_leaf():
if node.name in org_names:
#make reconstructed bubble
size = x[org_names.index(node.name)]
F = CircleFace(radius=size_factor*math.sqrt(size), color="RoyalBlue", style="sphere")
F.border.width = None
F.opacity = 0.6
faces.add_face_to_node(F,node, 0, position="branch-right")
#Denote that this was a training organism
nameFace = AttrFace("name", fsize=font_size, fgcolor='black')
faces.add_face_to_node(nameFace, node, 0, position="branch-right")
elif node.name in hyp_node_names: #Otherwise it's a hypothetical node, just use recon x
node_base_name = hyp_node_names[node.name][0]
percent = hyp_node_names[node.name][1]
if node_base_name in org_names:
idx = hyp_node_names[node.name][2]
size = x[org_names.index(node_base_name)+(idx+1)*len(org_names)]
F = CircleFace(radius=size_factor*math.sqrt(size), color="RoyalBlue", style="sphere")
F.border.width = None
F.opacity = 0.6
faces.add_face_to_node(F,node, 0, position="branch-right")
#This is if I want the names of the hypothetical nodes to be printed as well
#nameFace = AttrFace("name", fsize=font_size, fgcolor='black')
#faces.add_face_to_node(nameFace, node, 0, position="branch-right")
else:
size=0
else:
size=0
ts = TreeStyle()
ts.layout_fn = layout
ts.mode = "r"
#ts.mode = "c"
ts.scale = 2*1000
ts.show_leaf_name = False
ts.min_leaf_separation = 50
F = CircleFace(radius=.87*size_factor, color="RoyalBlue", style="sphere")
F.border.width = None
F.opacity = 0.6
ts.legend.add_face(F,0)
ts.legend.add_face(TextFace(" Inferred relative abundance",fsize=1.5*font_size,fgcolor="Blue"),1)
ts.legend.add_face(TextFace(" Total absolute abundance depicted " + str(sum_x)[0:8], fsize=1.5*font_size,fgcolor="Black"),1)
ts.legend_position=4
#t.show(tree_style=ts)
t.render(outfile, w=550, units="mm", tree_style=ts)
#Redner the XML file
project = Phyloxml()
phylo = phyloxml.PhyloxmlTree(newick=t.write(format=0, features=[]))
project.add_phylogeny(phylo)
project.export(open(outfilexml,'w'))
示例10: draw_tree
# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import scale [as 别名]
def draw_tree(tree, conf, outfile):
try:
from ete2 import (add_face_to_node, AttrFace, TextFace, TreeStyle, RectFace, CircleFace,
SequenceFace, random_color, SeqMotifFace)
except ImportError as e:
print e
return
def ly_basic(node):
if node.is_leaf():
node.img_style['size'] = 0
else:
node.img_style['size'] = 0
node.img_style['shape'] = 'square'
if len(MIXED_RES) > 1 and hasattr(node, "tree_seqtype"):
if node.tree_seqtype == "nt":
node.img_style["bgcolor"] = "#CFE6CA"
ntF = TextFace("nt", fsize=6, fgcolor='#444', ftype='Helvetica')
add_face_to_node(ntF, node, 10, position="branch-bottom")
if len(NPR_TREES) > 1 and hasattr(node, "tree_type"):
node.img_style['size'] = 4
node.img_style['fgcolor'] = "steelblue"
node.img_style['hz_line_width'] = 1
node.img_style['vt_line_width'] = 1
def ly_leaf_names(node):
if node.is_leaf():
spF = TextFace(node.species, fsize=10, fgcolor='#444444', fstyle='italic', ftype='Helvetica')
add_face_to_node(spF, node, column=0, position='branch-right')
if hasattr(node, 'genename'):
geneF = TextFace(" (%s)" %node.genename, fsize=8, fgcolor='#777777', ftype='Helvetica')
add_face_to_node(geneF, node, column=1, position='branch-right')
def ly_supports(node):
if not node.is_leaf() and node.up:
supFace = TextFace("%0.2g" %(node.support), fsize=7, fgcolor='indianred')
add_face_to_node(supFace, node, column=0, position='branch-top')
def ly_tax_labels(node):
if node.is_leaf():
c = LABEL_START_COL
largest = 0
for tname in TRACKED_CLADES:
if hasattr(node, "named_lineage") and tname in node.named_lineage:
linF = TextFace(tname, fsize=10, fgcolor='white')
linF.margin_left = 3
linF.margin_right = 2
linF.background.color = lin2color[tname]
add_face_to_node(linF, node, c, position='aligned')
c += 1
for n in xrange(c, len(TRACKED_CLADES)):
add_face_to_node(TextFace('', fsize=10, fgcolor='slategrey'), node, c, position='aligned')
c+=1
def ly_full_alg(node):
pass
def ly_block_alg(node):
if node.is_leaf():
if 'sequence' in node.features:
seqFace = SeqMotifFace(node.sequence, [])
# [10, 100, "[]", None, 10, "black", "rgradient:blue", "arial|8|white|domain Name"],
motifs = []
last_lt = None
for c, lt in enumerate(node.sequence):
if lt != '-':
if last_lt is None:
last_lt = c
if c+1 == len(node.sequence):
start, end = last_lt, c
motifs.append([start, end, "()", 0, 12, "slategrey", "slategrey", None])
last_lt = None
elif lt == '-':
if last_lt is not None:
start, end = last_lt, c-1
motifs.append([start, end, "()", 0, 12, "grey", "slategrey", None])
last_lt = None
seqFace = SeqMotifFace(node.sequence, motifs,
intermotif_format="line",
seqtail_format="line", scale_factor=ALG_SCALE)
add_face_to_node(seqFace, node, ALG_START_COL, aligned=True)
TRACKED_CLADES = ["Eukaryota", "Viridiplantae", "Fungi",
"Alveolata", "Metazoa", "Stramenopiles", "Rhodophyta",
"Amoebozoa", "Crypthophyta", "Bacteria",
"Alphaproteobacteria", "Betaproteobacteria", "Cyanobacteria",
"Gammaproteobacteria",]
# ["Opisthokonta", "Apicomplexa"]
colors = random_color(num=len(TRACKED_CLADES), s=0.45)
lin2color = dict([(ln, colors[i]) for i, ln in enumerate(TRACKED_CLADES)])
NAME_FACE = AttrFace('name', fsize=10, fgcolor='#444444')
LABEL_START_COL = 10
#.........这里部分代码省略.........
示例11: main
# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import 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()];
#.........这里部分代码省略.........
示例12: TreeStyle
# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import scale [as 别名]
import random
from ete2 import Tree, TreeStyle, NodeStyle, faces, AttrFace, TreeFace
# Tree Style used to render small trees used as leaf faces
small_ts = TreeStyle()
small_ts.show_leaf_name = True
small_ts.scale = 10
def layout(node):
if node.is_leaf():
# Add node name to laef nodes
N = AttrFace("name", fsize=14, fgcolor="black")
faces.add_face_to_node(N, node, 0)
t = Tree()
t.populate(10)
T = TreeFace(t, small_ts)
# Let's make the sphere transparent
T.opacity = 0.8
# And place as a float face over the tree
faces.add_face_to_node(T, node, 1, position="aligned")
def get_example_tree():
# Random tree
t = Tree()
t.populate(20, random_branches=True)
# Some random features in all nodes
for n in t.traverse():
n.add_features(weight=random.randint(0, 50))
示例13: MAD
# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import scale [as 别名]
parser.add_argument('--out', required=True, help='The directory where you want output files written.')
parser.add_argument('--outgroups', required=True, help='A text document with your outgroups listed. The line should start with the word Outgroup1 followed by a list of all the species in the outgroup with everything separated by spaces. You can specify Outgroup2 and Outgroup3 on other lines as backup outgroups if no species from your outgroup are present.')
args = parser.parse_args()
# Functions to calculate Median absolute deviation, and Modified Z-score
def MAD(VALUES, axis=None):
return np.median(np.absolute(VALUES - np.median(VALUES, axis)), axis)
def MODZ(VALUES, axis=None):
if MAD(VALUES) == 0:
return VALUES
else:
return (0.6745 * (VALUES - np.median(VALUES))) / MAD(VALUES)
#### ETE TOOLKIT BASED FUNCTIONS AND STYLES:
ts = TreeStyle()
ts.scale = 200
RED = NodeStyle()
RED["size"] = 0
RED["vt_line_width"] = 1
RED["hz_line_width"] = 1
RED["vt_line_type"] = 1 # 0 solid, 1 dashed, 2 dotted
RED["hz_line_type"] = 1
RED["bgcolor"] = "#dedede"
nstyle = NodeStyle()
nstyle["size"] = 0
def MODZ_ALL(DIST_DIR, SCORE, TREE, OUT_DIR, OUTGROUPS):
#######################################
# Load all distances into a data matrix
#######################################
OUTGROUP_FILE = open( OUTGROUPS, 'r' )
示例14: str
# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import scale [as 别名]
else:
clade.name = str(idx)
names[clade.name] = clade
return names
# Search tree by clade name
def lookup_by_names(TREE):
names = {}
for clade in TREE.find_clades():
if clade.name:
if clade.name in names:
raise ValueError("Duplicate key: %s" % clade.name)
names[clade.name] = clade
return names
#### ETE TOOLKIT BASED FUNCTIONS AND STYLES:
ts = TreeStyle()
ts.scale = 200
RED = NodeStyle()
RED["size"] = 0
RED["vt_line_width"] = 1
RED["hz_line_width"] = 1
RED["vt_line_type"] = 1 # 0 solid, 1 dashed, 2 dotted
RED["hz_line_type"] = 1
RED["bgcolor"] = "#dedede"
nstyle = NodeStyle()
nstyle["size"] = 0
#### STATISTICS FUNCTIONS:
# Median Absolute Deviation Statistic (MAD)
def mad(data, axis=None):
return median(absolute(data - median(data, axis)), axis)
# Cut off score
def cut(data, axis=None):
示例15: len
# 需要导入模块: from ete2 import TreeStyle [as 别名]
# 或者: from ete2.TreeStyle import scale [as 别名]
import sys
from ete2 import Tree, NodeStyle, TreeStyle
if len(sys.argv) < 4:
print "usage: TreeView.py <*.tree> <contig_num> <refgenome_num> <output>"
sys.exit(-1)
contig_num = str(sys.argv[2])
#genus = str(sys.argv[3])
refgenome_num = str(sys.argv[3])
outfilename = str(sys.argv[4])
#print contig_num
tree = Tree(sys.argv[1])
ts = TreeStyle()
ts.scale = 120
nstyle = NodeStyle()
nstyle["shape"] = "sphere"
nstyle["size"] = 10
nstyle["fgcolor"] = "darkred"
#contig = tree.search_nodes(name=contig_num)[0]
contig = tree&contig_num
contig.set_style(nstyle)
#contig.add_features(label="CONTIG")
nstyle = NodeStyle()
nstyle["shape"] = "square"
nstyle["size"] = 10
nstyle["fgcolor"] = "aqua"
refgenome = tree&refgenome_num
refgenome.set_style(nstyle)
#refgenome.add_features(label="REFGENOME")