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
def setTreeStyle(style, layoutfunction): #consolidate options for showing trees #pass in string "circle" or "rect" and a layout function I = TreeStyle() if style == "circle": I.tree_width = 1200 I.layout_fn = layoutfunction I.show_branch_length = False #I.show_branch_support = True I.show_leaf_name = False I.mode = "c" I.force_topology = True #I.legend_position = 3 I.extra_branch_line_type = 1 I.guiding_lines_type = 1 I.guiding_lines_color = "#666666" I.extra_branch_line_color = "#666666" I.optimal_scale_level = "full" I.root_opening_factor = 0 elif style =="rect": I = TreeStyle() I.layout_fn = layoutfunction I.show_leaf_name = False I.force_topology = True I.optimal_scale_level = "semi" else: I.layout_fn = layoutfunction I.show_leaf_name = False I.force_topology = True I.optimal_scale_level = "semi" return I
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
bgcol9 = "#CCE5FF" bgcol10 = "#CCCCFF" bgcol11 = "#E5CCFF" ####################################################### #~ Setting Clade Color #~ cs1 = NodeStyle() #~ cs1["bgcolor"] = "#FFCCCC" #~ c1 = t.get_common_ancestor("<TaxonLabel1>", "<TaxonLabel2>") #~ c1.set_style(cs1) ####################################################### #Style ts = TreeStyle() ts.mode = "c" # draw tree in circular mode ts.root_opening_factor = 0 #~ ts.arc_start = -180 # 0 degrees = 3 o'clock #~ ts.arc_span = 180 #~ ts.scale = 20 ts.show_leaf_name = False #~ ts.show_branch_length = True #~ ts.show_branch_support = True #~ ts.optimal_scale_level= "full" ts.layout_fn = layout #~ ts.min_leaf_separation = 1000 ts.force_topology = True #~ ts.guiding_lines_type=0 t.render("image.png", w=1200, dpi=60, units="px", tree_style=ts)
from ete2 import EvolTree from ete2 import faces tree = EvolTree("data/S_example/measuring_S_tree.nw") tree.link_to_alignment("data/S_example/alignment_S_measuring_evol.fasta") print tree print "\n Running free-ratio model with calculation of ancestral sequences..." tree.run_model("fb_anc") # tree.link_to_evol_model('/tmp/ete2-codeml/fb_anc/out', 'fb_anc') I = TreeStyle() I.force_topology = False I.draw_aligned_faces_as_table = True I.draw_guiding_lines = True I.guiding_lines_type = 2 I.guiding_lines_color = "#CCCCCC" for n in sorted(tree.get_descendants() + [tree], key=lambda x: x.node_id): if n.is_leaf(): continue anc_face = faces.SequenceFace(n.sequence, "aa", fsize=10, bg_colors={}) I.aligned_foot.add_face(anc_face, 1) I.aligned_foot.add_face(faces.TextFace("node_id: #%d " % (n.node_id), fsize=8), 0) print "display result of bs_anc model, with ancestral amino acid sequences." tree.show(tree_style=I) print "\nThe End."
for child in node.children[:-options.children]: child.detach() def layout(node): def color(node): if type(node.item) is Value: return "Red" elif type(node.item) is Parameter: return "Yellow" elif node.item.leaf: return "Green" else: return "RoyalBlue" N = AttrFace("name", fsize=14, fgcolor="black") faces.add_face_to_node(N, node, 0) C = CircleFace(radius=node.weight, color=color(node), style="sphere") C.opacity = 0.3 faces.add_face_to_node(C, node, 0, position="float") ts = TreeStyle() ts.layout_fn = layout ts.mode = "c" ts.show_leaf_name = False ts.force_topology = True root.node.show(tree_style=ts) else: root.print_data(sort_field=options.field, reverse=options.reverse)
def run(args): if args.text_mode: from ete2 import Tree for tindex, tfile in enumerate(args.src_tree_iterator): #print tfile if args.raxml: nw = re.sub(":(\d+\.\d+)\[(\d+)\]", ":\\1[&&NHX:support=\\2]", open(tfile).read()) t = Tree(nw) else: t = Tree(tfile) print t.get_ascii(show_internal=args.show_internal_names, attributes=args.show_attributes) return import random import re import colorsys from collections import defaultdict from ete2 import (Tree, PhyloTree, TextFace, RectFace, faces, TreeStyle, add_face_to_node, random_color) global FACES if args.face: FACES = parse_faces(args.face) else: FACES = [] # VISUALIZATION ts = TreeStyle() ts.mode = args.mode ts.show_leaf_name = True ts.tree_width = args.tree_width for f in FACES: if f["value"] == "@name": ts.show_leaf_name = False break if args.as_ncbi: ts.show_leaf_name = False FACES.extend(parse_faces( ['value:@sci_name, size:10, fstyle:italic', 'value:@taxid, color:grey, size:6, format:" - %s"', 'value:@sci_name, color:steelblue, size:7, pos:b-top, nodetype:internal', 'value:@rank, color:indianred, size:6, pos:b-bottom, nodetype:internal', ])) if args.alg: FACES.extend(parse_faces( ['value:@sequence, size:10, pos:aligned, ftype:%s' %args.alg_type] )) if args.heatmap: FACES.extend(parse_faces( ['value:@name, size:10, pos:aligned, ftype:heatmap'] )) if args.bubbles: for bubble in args.bubbles: FACES.extend(parse_faces( ['value:@%s, pos:float, ftype:bubble, opacity:0.4' %bubble, ])) ts.branch_vertical_margin = args.branch_separation if args.show_support: ts.show_branch_support = True if args.show_branch_length: ts.show_branch_length = True if args.force_topology: ts.force_topology = True ts.layout_fn = lambda x: None for tindex, tfile in enumerate(args.src_tree_iterator): #print tfile if args.raxml: nw = re.sub(":(\d+\.\d+)\[(\d+)\]", ":\\1[&&NHX:support=\\2]", open(tfile).read()) t = PhyloTree(nw) else: t = PhyloTree(tfile) if args.alg: t.link_to_alignment(args.alg, alg_format=args.alg_format) if args.heatmap: DEFAULT_COLOR_SATURATION = 0.3 BASE_LIGHTNESS = 0.7 def gradient_color(value, max_value, saturation=0.5, hue=0.1): def rgb2hex(rgb): return '#%02x%02x%02x' % rgb def hls2hex(h, l, s): return rgb2hex( tuple(map(lambda x: int(x*255), colorsys.hls_to_rgb(h, l, s)))) lightness = 1 - (value * BASE_LIGHTNESS) / max_value return hls2hex(hue, lightness, DEFAULT_COLOR_SATURATION) heatmap_data = {} max_value, min_value = None, None for line in open(args.heatmap): if line.startswith('#COLNAMES'): pass elif line.startswith('#') or not line.strip(): pass else: fields = line.split('\t') name = fields[0].strip() values = map(lambda x: float(x) if x else None, fields[1:]) maxv = max(values) minv = min(values) if max_value is None or maxv > max_value: max_value = maxv if min_value is None or minv < min_value: min_value = minv heatmap_data[name] = values heatmap_center_value = 0 heatmap_color_center = "white" heatmap_color_up = 0.3 heatmap_color_down = 0.7 heatmap_color_missing = "black" heatmap_max_value = abs(heatmap_center_value - max_value) heatmap_min_value = abs(heatmap_center_value - min_value) if heatmap_center_value <= min_value: heatmap_max_value = heatmap_min_value + heatmap_max_value else: heatmap_max_value = max(heatmap_min_value, heatmap_max_value) # scale the tree if not args.height: args.height = None if not args.width: args.width = None f2color = {} f2last_seed = {} for node in t.traverse(): node.img_style['size'] = 0 if len(node.children) == 1: node.img_style['size'] = 2 node.img_style['shape'] = "square" node.img_style['fgcolor'] = "steelblue" ftype_pos = defaultdict(int) for findex, f in enumerate(FACES): if (f['nodetype'] == 'any' or (f['nodetype'] == 'leaf' and node.is_leaf()) or (f['nodetype'] == 'internal' and not node.is_leaf())): # if node passes face filters if node_matcher(node, f["filters"]): if f["value"].startswith("@"): fvalue = getattr(node, f["value"][1:], None) else: fvalue = f["value"] # if node's attribute has content, generate face if fvalue is not None: fsize = f["size"] fbgcolor = f["bgcolor"] fcolor = f['color'] if fcolor: # Parse color options auto_m = re.search("auto\(([^)]*)\)", fcolor) if auto_m: target_attr = auto_m.groups()[0].strip() if not target_attr : color_keyattr = f["value"] else: color_keyattr = target_attr color_keyattr = color_keyattr.lstrip('@') color_bin = getattr(node, color_keyattr, None) last_seed = f2last_seed.setdefault(color_keyattr, random.random()) seed = last_seed + 0.10 + random.uniform(0.1, 0.2) f2last_seed[color_keyattr] = seed fcolor = f2color.setdefault(color_bin, random_color(h=seed)) if fbgcolor: # Parse color options auto_m = re.search("auto\(([^)]*)\)", fbgcolor) if auto_m: target_attr = auto_m.groups()[0].strip() if not target_attr : color_keyattr = f["value"] else: color_keyattr = target_attr color_keyattr = color_keyattr.lstrip('@') color_bin = getattr(node, color_keyattr, None) last_seed = f2last_seed.setdefault(color_keyattr, random.random()) seed = last_seed + 0.10 + random.uniform(0.1, 0.2) f2last_seed[color_keyattr] = seed fbgcolor = f2color.setdefault(color_bin, random_color(h=seed)) if f["ftype"] == "text": if f.get("format", None): fvalue = f["format"] % fvalue F = TextFace(fvalue, fsize = fsize, fgcolor = fcolor or "black", fstyle = f.get('fstyle', None)) elif f["ftype"] == "fullseq": F = faces.SeqMotifFace(seq=fvalue, seq_format="seq", seqtail_format="seq", height=fsize) elif f["ftype"] == "compactseq": F = faces.SeqMotifFace(seq=fvalue, seq_format="compactseq", seqtail_format="compactseq", height=fsize) elif f["ftype"] == "blockseq": F = faces.SeqMotifFace(seq=fvalue, seq_format="blockseq", seqtail_format="blockseq", height=fsize, fgcolor=fcolor or "slategrey", bgcolor=fbgcolor or "slategrey", scale_factor = 1.0) fbgcolor = None elif f["ftype"] == "bubble": try: v = float(fvalue) except ValueError: rad = fsize else: rad = fsize * v F = faces.CircleFace(radius=rad, style="sphere", color=fcolor or "steelblue") elif f["ftype"] == "heatmap": if not f['column']: col = ftype_pos[f["pos"]] else: col = f["column"] for i, value in enumerate(heatmap_data.get(node.name, [])): ftype_pos[f["pos"]] += 1 if value is None: color = heatmap_color_missing elif value > heatmap_center_value: color = gradient_color(abs(heatmap_center_value - value), heatmap_max_value, hue=heatmap_color_up) elif value < heatmap_center_value: color = gradient_color(abs(heatmap_center_value - value), heatmap_max_value, hue=heatmap_color_down) else: color = heatmap_color_center node.add_face(RectFace(20, 20, color, color), position="aligned", column=col + i) # Add header # for i, name in enumerate(header): # nameF = TextFace(name, fsize=7) # nameF.rotation = -90 # tree_style.aligned_header.add_face(nameF, column=i) F = None elif f["ftype"] == "profile": # internal profiles? F = None elif f["ftype"] == "barchart": F = None elif f["ftype"] == "piechart": F = None # Add the Face if F: F.opacity = f['opacity'] or 1.0 # Set face general attributes if fbgcolor: F.background.color = fbgcolor if not f['column']: col = ftype_pos[f["pos"]] ftype_pos[f["pos"]] += 1 else: col = f["column"] node.add_face(F, column=col, position=f["pos"]) if args.image: t.render("t%d.%s" %(tindex, args.image), tree_style=ts, w=args.width, h=args.height, units=args.size_units) else: t.show(None, tree_style=ts)
colors = random_color(num=len(unique_values)) sorted_names = sorted(unique_values) column_header.extend(sorted_names) column_color.extend(colors) column_header.append("") column_color.append("black") spaciators.add(len(column_header) - 1) header2column = dict([(name, i) for i, name in enumerate(column_header)]) ts = TreeStyle() ts.mode = 'r' ts.draw_guiding_lines = False ts.show_leaf_name = False ts.force_topology = False ts.layout_fn = layout ts.tree_width = 800 ts.draw_aligned_faces_as_table = True for i, name in enumerate(column_header): if name: headerF = TextFace(str(name), fgcolor=column_color[i], fsize=40) headerF.rotation = -85 else: headerF = RectFace(300, 5, "white", "white") ts.aligned_header.add_face(headerF, i) #tree_files = sys.argv[1:] for treefile in args.tree_files: output = treefile + '.png'