Esempio n. 1
0
def make_tree_figure(nw_file):
    ## build tree ##
    nw_format = open(nw_file)
    nw_read = nw_format.read()
    nw_format.close()
    print(nw_read)
    t = Tree(nw_read, format=1)
    ts = TreeStyle()
    ts.show_leaf_name = False
    ts.show_scale = False
    ts.show_leaf_name = False
    ts.show_scale = False
    t.render("label_tree.png", my_layout, tree_style=ts, dpi=150, w=600)
Esempio n. 2
0
def plot_uncorrected_phylogeny(tree, species, latin_names, species_history):
    """
    Generates a PDF figure of the input tree with same length for all branches.

    :param tree: input tree from configuration file
    :param species: the current focal species
    :param latin_names: a dictionary-like data structure that associates each informal species name to its latin name
    :param species_history: the list of ancestor nodes of the focal species, including the focal species and going up to the root.
    """
    label_leaves_with_latin_names(tree, latin_names)
    node_and_branch_style(tree)
    ts = TreeStyle()
    # ts.title.add_face(TextFace("  Input phylogenetic tree", ftype="Arial", fsize=18), column=0)
    ts.orientation = 1
    ts.branch_vertical_margin = 14
    ts.show_leaf_name = False  # because there is a Face showing it
    ts.show_branch_length = False
    ts.margin_left = 25
    ts.margin_right = 25
    ts.margin_top = 25
    ts.margin_bottom = 25
    ts.scale = 200
    ts.show_scale = False
    tree.render(os.path.join("rate_adjustment", f"{species}",
                             f"{_TREE.format(species)}"),
                w=4.5,
                units="in",
                tree_style=ts)
Esempio n. 3
0
def make_tree(t):
    ts = TreeStyle()

    ## make the tree in to a cladogram
    most_distant_leaf, tree_length = t.get_farthest_leaf()
    current_dist = 0
    for postorder, node in t.iter_prepostorder():
        if postorder:
            current_dist -= node.dist
        else:
            if node.is_leaf():
                node.dist += tree_length - (current_dist + node.dist)
            elif node.up:  # node is internal
                current_dist += node.dist

    ## Rotate and color the lables
    def rotation_layout(node):
        if node.is_leaf():
            if node.name == 'X':
                F = TextFace(node.name, tight_text=True, fgcolor='Blue')
                F.rotation = 90
                add_face_to_node(F, node, column=0, position="branch-right")
            elif node.name == 'Y':
                F = TextFace(node.name, tight_text=True, fgcolor='Red')
                F.rotation = 90
                add_face_to_node(F, node, column=0, position="branch-right")
            elif node.name == 'A':
                F = TextFace("")
                add_face_to_node(F, node, column=0, position="branch-right")
            else:
                F = TextFace(node.name, tight_text=True, fgcolor='Green')
                F.rotation = 90
                add_face_to_node(F, node, column=0, position="branch-right")

    ## Format the tree image
    nstyle = NodeStyle()
    nstyle["hz_line_type"] = 0
    nstyle["vt_line_color"] = "#ffffff"
    nstyle["hz_line_color"] = "#ffffff"
    nstyle["vt_line_width"] = 4
    nstyle["hz_line_width"] = 4
    nstyle["size"] = 0

    for n in t.traverse():
        n.set_style(nstyle)

    ## Set background
    t.img_style["bgcolor"] = "#2e3440"

    ## Tree 'shape'

    ts.min_leaf_separation = 20
    ts.show_leaf_name = False
    ts.layout_fn = rotation_layout
    ts.rotation = -90
    ts.show_scale = False

    #t.show(tree_style=ts)

    t.render(f"{t.name}.svg", tree_style=ts, dpi=900)
Esempio n. 4
0
def render_tree(species_tree, bipart1, num_alt, png_fn, replace_taxon=None):
    color1 = "blue"
    color2 = "black"
    ts = TreeStyle()
    ts.show_leaf_name = False
    ts.show_scale = False
    nstyle = NodeStyle()
    nstyle["size"] = 0

    ts.title.add_face(
        TextFace("{} bipartition in {} gene trees".format(png_fn, num_alt),
                 fsize=15,
                 bold=True), 0)
    plot_tree = species_tree
    for node in plot_tree.traverse():
        node.set_style(nstyle)
        if node.name in bipart1:
            name_face = TextFace(node.name, fgcolor=color1)
        else:
            name_face = TextFace(node.name, fgcolor=color2)
        node.add_face(name_face, 0, 'branch-right')
    if replace_taxon:
        for leaf in plot_tree.get_leaves:
            try:
                leaf.name = taxon_subst[leaf.name]
            except KeyError:
                continue
    plot_tree.convert_to_ultrametric()
    plot_tree.render(png_fn, tree_style=ts, w=600)
Esempio n. 5
0
def draw_raw_tree(filename: str) -> None:
    """Draws a raw tree from ete3 representation
    stored in a file

    Parameters
    ----------
    filename : str
        a name of the file

    Returns
    -------
    None
    """

    ts = TreeStyle()
    ts.show_leaf_name = False
    ts.layout_fn = layout_raw
    ts.rotation = 90
    ts.branch_vertical_margin = 10
    ts.show_scale = False
    ts.scale = 50
    ts.title.add_face(TextFace(" ", fsize=20), column=0)

    ete3_desc = read_ete3_from_file(filename)
    tree = Tree(ete3_desc, format=1)

    # tree.show(tree_style=ts)
    return tree.render("%%inline",tree_style=ts)
Esempio n. 6
0
def generate_type_tree_figure(output_file):
    """ Generate type_tree.png image.

    It needs ETE dependencies installed
    cf http://etetoolkit.org/new_download/ or use anaconda

    :param output_file: str
    """
    try:
        from ete3 import faces, TextFace, TreeStyle
    except ImportError as e:
        logger.warning(
            'ImportError : %s Generation of type_tree figure need ETE dependencies to '
            'be installed Use from anaconda, or look at installation procedure on '
            'http://etetoolkit.org/new_download/', e)
        return

    # Define custom tree style
    ts = TreeStyle()
    ts.show_leaf_name = False
    ts.show_scale = False
    ts.orientation = 1
    ts.branch_vertical_margin = 20

    def my_layout(node):
        F = TextFace(node.name, fsize=16, ftype='Courier', bold=True)
        faces.add_face_to_node(F, node, column=10, position="branch-right")

    ts.layout_fn = my_layout

    TYPES_STRING_TREE.render(output_file, tree_style=ts)
Esempio n. 7
0
 def to_diagram(self):
     t = self.program.to_tree_node()
     ts = TreeStyle()
     ts.show_leaf_name = False
     ts.show_scale = False
     ts.rotation = 90
     t.render(f"./diagrams/{FUNCTION_NAME}_{self.fitness}.png",
              tree_style=ts)
Esempio n. 8
0
def add_labels_n_colors_2_tree(tree_path, refseq_2_entropy, colors, feature, out):
    """
    add entropy measurement to a tree and color it's leaves
    :param tree_path: a path to a tree
    :param refseq_2_entropy: a data base with entropy values for each refseq id
    :param out: output directory path to save the results
    :return: a tree with colors and entropy labels
    """
    print(tree_path)
    str_tree = tree_2_string(tree_path)
    if str_tree == '':
        return
    tree = Tree(str_tree)


    # get all refseq ids in the tree and all corresponding entropy values
    all_leaves = []

    for node in tree:
        if node.is_leaf():
            all_leaves.append(node.name)

    #all_values = refseq_2_entropy[refseq_2_entropy['refseq_id'].isin(all_leaves)]['entropy_5'].values
    all_values = refseq_2_entropy[feature].values

    num_leaves = len(all_leaves)

    # create a gradient color bar
    #colors = linear_gradient("#DC9221", "#33C193", n=num_leaves)

    #mapping = value_2_color(all_values, colors['hex'])
    mapping = value_2_color(all_values, colors['hex'])

    for node in tree:
        if node.is_leaf():
            value = refseq_2_entropy[refseq_2_entropy['refseq_id'] == node.name.split('.')[0]][feature].values[0]
            virus_name = refseq_2_entropy[refseq_2_entropy['refseq_id'] == node.name.split('.')[0]]['virus_name'].values[0]

            # change virus name
            node.name = virus_name
            c = mapping[str(value)]
            node.add_feature("label", value)
            label_face = TextFace(node.label, fgcolor=c, fsize=22)
            node.add_face(label_face, column=0, position='branch-right')


    family = os.path.basename(tree_path).split('.')[0]

    ts = TreeStyle()
    ts.mode = 'c'
    ts.scale = 5
    # Disable the default tip names config
    ts.show_leaf_name = True
    ts.show_scale = True
    ts.show_branch_length = True
    ts.title.add_face(TextFace("{} values for {}".format(feature, family), fsize=20), column=0)
    # Draw Tree
    tree.render(os.path.join(out, '{}_{}_tree.pdf'.format(family, feature)), dpi=300, tree_style=ts)
Esempio n. 9
0
def export_tree(tree, filename, insignif_color, signif_color, i_group, width):
    '''
    exports the given tree to the given filename
    '''
    ts = TreeStyle()
    ts.show_leaf_name = False
    ts.show_scale = False
    ts.layout_fn = generate_layout(insignif_color, signif_color, i_group)
    tree.render(filename, w=width, tree_style=ts)
Esempio n. 10
0
File: tree.py Progetto: senaj/atlas
def render_tree(T, out):

    ts = TreeStyle()
    ts.show_leaf_name = False
    ts.mode = "c"
    ts.scale = 200
    ts.show_scale = False

    T.render(out, tree_style=ts, layout=layout_black_circles)
Esempio n. 11
0
def get_tree_style():
    ts = TreeStyle()
    ts.show_leaf_name = False  # True
    ts.layout_fn = layout
    ts.rotation = 90
    ts.branch_vertical_margin = 10
    ts.show_scale = False
    # ts.mode = "c"
    ts.scale = 50

    ts.title.add_face(TextFace(" ", fsize=20), column=0)

    # for n in t.traverse():
    #     nstyle = NodeStyle()
    #     nstyle["fgcolor"] = "red"
    #     nstyle["size"] = 15
    #     n.set_style(nstyle)

    # ts.show_leaf_name = True
    ts.legend.add_face(TextFace("  "), column=0)
    ts.legend.add_face(TextFace("  "), column=1)
    ts.legend.add_face(RectFace(20, 20, NO_SUPPORT_COLOR, NO_SUPPORT_COLOR),
                       column=0)
    ts.legend.add_face(TextFace("  Topic with no support (u(t)=0)"), column=1)
    ts.legend.add_face(TextFace("  "), column=0)
    ts.legend.add_face(TextFace("  "), column=1)
    ts.legend.add_face(RectFace(20, 20, "#90ee90", "#90ee90"), column=0)
    ts.legend.add_face(TextFace("  Topic with minor support 0<u(t)<=0.4"),
                       column=1)
    ts.legend.add_face(TextFace("  "), column=0)
    ts.legend.add_face(TextFace("  "), column=1)
    ts.legend.add_face(RectFace(20, 20, "green", "green"), column=0)
    ts.legend.add_face(
        TextFace(u"  Topic with medium support 0.4<u(t)<=0.6   "), column=1)
    ts.legend.add_face(TextFace("  "), column=0)
    ts.legend.add_face(TextFace("  "), column=1)
    ts.legend.add_face(RectFace(20, 20, "#004000", "#004000"), column=0)
    ts.legend.add_face(TextFace("  Topic with high support u(t)>0.6"),
                       column=1)
    ts.legend.add_face(TextFace("  "), column=0)
    ts.legend.add_face(TextFace("  "), column=1)
    ts.legend.add_face(CircleFace(10, "red"), column=0)
    ts.legend.add_face(TextFace("  Gap"), column=1)
    ts.legend.add_face(TextFace("  "), column=0)
    ts.legend.add_face(TextFace("  "), column=1)
    ts.legend.add_face(RectFace(40, 40, "#004000", "#004000"),
                       column=0)  # green
    # ts.legend.add_face(CircleFace(15, "green"), column=1)
    ts.legend.add_face(TextFace("  Head subject or offshoot"), column=1)
    ts.legend_position = 4

    # ts.title.add_face(TextFace(" ", fsize=20), column=0)

    return ts
Esempio n. 12
0
    def draw(self,
             file,
             colors,
             color_internal_nodes=True,
             legend_labels=(),
             show_branch_support=True,
             show_scale=True,
             legend_scale=1,
             mode="c",
             neighbours=None,
             neighbours_block=None):
        max_color = len(colors)

        used_colors = set()
        for node in self.tree.traverse():
            if not (color_internal_nodes or node.is_leaf()): continue
            color = colors[min(node.color, max_color - 1)]
            node.img_style['bgcolor'] = color
            used_colors.add(color)

        ts = TreeStyle()
        ts.mode = mode
        ts.scale = self.scale
        # Disable the default tip names config
        ts.show_leaf_name = False
        ts.show_branch_support = show_branch_support

        # ts.branch_vertical_margin = 20
        ts.show_scale = show_scale
        cur_max_color = max(v.color for v in self.tree.traverse())
        current_colors = colors[0:cur_max_color + 1]

        for i, (label, color_) in enumerate(zip(legend_labels,
                                                current_colors)):
            if color_ not in used_colors: continue
            rf = RectFace(20 * legend_scale, 16 * legend_scale, color_, color_)
            rf.inner_border.width = 1
            rf.margin_right = 14
            rf.margin_left = 14

            tf = TextFace(label, fsize=26 * legend_scale)
            tf.margin_right = 14

            ts.legend.add_face(rf, column=0)
            ts.legend.add_face(tf, column=1)

        if neighbours:
            old_tree = self.tree.copy()
            self.draw_neighbours(neighbours, neighbours_block)

        self.tree.render(file, w=1000, tree_style=ts)

        if neighbours:
            self.tree = old_tree
Esempio n. 13
0
def ete_draw(t,fname=None,title='',mode='r',outfile='ete_tree.png'):
    from ete3 import Tree, TreeStyle, Phyloxml, TextFace
    t.children
    ts = TreeStyle()
    #ts.branch_vertical_margin = 10
    ts.show_scale=False
    ts.scale =  800
    ts.show_leaf_name = False    
    ts.mode = mode
    ts.title.add_face(TextFace(title, fsize=20), column=0)        
    t.render(outfile,dpi=300,h=800,tree_style=ts)
    return ts
Esempio n. 14
0
def _get_motif_tree(tree, data, circle=True, vmin=None, vmax=None):
    try:
        from ete3 import Tree, NodeStyle, TreeStyle
    except ImportError:
        print("Please install ete3 to use this functionality")
        sys.exit(1)

    t = Tree(tree)
    
    # Determine cutoff for color scale
    if not(vmin and vmax):
        for i in range(90, 101):
            minmax = np.percentile(data.values, i)
            if minmax > 0:
                break
    if not vmin:
        vmin = -minmax
    if not vmax:
        vmax = minmax
    
    norm = Normalize(vmin=vmin, vmax=vmax, clip=True)
    mapper = cm.ScalarMappable(norm=norm, cmap="RdBu_r")
    
    m = 25 / data.values.max()
    
    for node in t.traverse("levelorder"):
        val = data[[l.name for l in node.get_leaves()]].values.mean()
        style = NodeStyle()
        style["size"] = 0
        
        style["hz_line_color"] = to_hex(mapper.to_rgba(val))
        style["vt_line_color"] = to_hex(mapper.to_rgba(val))
        
        v = max(np.abs(m * val), 5)
        style["vt_line_width"] = v
        style["hz_line_width"] = v

        node.set_style(style)
    
    ts = TreeStyle()

    ts.layout_fn = _tree_layout
    ts.show_leaf_name= False
    ts.show_scale = False
    ts.branch_vertical_margin = 10

    if circle:
        ts.mode = "c"
        ts.arc_start = 180 # 0 degrees = 3 o'clock
        ts.arc_span = 180
    
    return t, ts
def plot_clustering_tree(tree, alg_name, cutting=0, tree_format='pdf'):
    '''if cutting=True, merge the n nodes at leaf nodes with the same parent.
    '''
    global n, k1
    if (cutting):
        tree_inner = tree.copy()
        cnt = 0
        delete_tree_node_list = []
        for _n in tree_inner:
            try:
                _n.category
            except AttributeError:
                _n.add_features(category=cnt)
                for i in _n.get_sisters():
                    if not (i.is_leaf()):
                        continue
                    try:
                        i.category
                    except AttributeError:
                        i.add_features(category=cnt)
                        delete_tree_node_list.append(i)
                cnt += 1
        for _n in delete_tree_node_list:
            _n.delete()
        # rename the tree node
        tree_inner = Tree(tree_inner.write(features=[]))
    else:
        tree_inner = tree

    for _n in tree_inner:
        try:
            _n.macro
            break
        except AttributeError:
            macro_index = int(_n.name) // (n * k1)
            micro_index = (int(_n.name) - macro_index * n * k1) // n
            _n.macro = macro_index
            _n.micro = micro_index
            if (len(_n.name) > 3):
                _n.name = str(_n.category)

    ts = TreeStyle()
    ts.rotation = 90
    ts.show_scale = False
    for _n in tree_inner:
        nstyle = NodeStyle()
        nstyle['fgcolor'] = color_list[int(_n.macro)]
        nstyle['shape'] = shape_list[int(_n.micro)]
        _n.set_style(nstyle)
    time_str = datetime.now().strftime('%Y-%m-%d-')
    file_name = time_str + 'tree_' + alg_name + '.' + tree_format
    tree_inner.render(os.path.join('build', file_name), tree_style=ts)
Esempio n. 16
0
def _get_motif_tree(tree, data, circle=True, vmin=None, vmax=None):
    try:
        from ete3 import Tree, NodeStyle, TreeStyle
    except ImportError:
        print("Please install ete3 to use this functionality")
        sys.exit(1)

    t = Tree(tree)

    # Determine cutoff for color scale
    if not (vmin and vmax):
        for i in range(90, 101):
            minmax = np.percentile(data.values, i)
            if minmax > 0:
                break
    if not vmin:
        vmin = -minmax
    if not vmax:
        vmax = minmax

    norm = Normalize(vmin=vmin, vmax=vmax, clip=True)
    mapper = cm.ScalarMappable(norm=norm, cmap="RdBu_r")

    m = 25 / data.values.max()

    for node in t.traverse("levelorder"):
        val = data[[l.name for l in node.get_leaves()]].values.mean()
        style = NodeStyle()
        style["size"] = 0

        style["hz_line_color"] = to_hex(mapper.to_rgba(val))
        style["vt_line_color"] = to_hex(mapper.to_rgba(val))

        v = max(np.abs(m * val), 5)
        style["vt_line_width"] = v
        style["hz_line_width"] = v

        node.set_style(style)

    ts = TreeStyle()

    ts.layout_fn = _tree_layout
    ts.show_leaf_name = False
    ts.show_scale = False
    ts.branch_vertical_margin = 10

    if circle:
        ts.mode = "c"
        ts.arc_start = 180  # 0 degrees = 3 o'clock
        ts.arc_span = 180

    return t, ts
Esempio n. 17
0
def frogTree(startstate):
    global frogCount
    frogCount = 0
    t = Tree()
    root = t.add_child(name=startstate)
    t.add_face(TextFace(startstate), column=0)
    frogalgo(root, root)
    messagebox.showinfo("Tree Generation Done",
                        "number of states:" + str(frogCount))
    states.set("Tree Generated! number of states:" + str(frogCount))
    ts = TreeStyle()
    ts.show_leaf_name = False
    ts.show_scale = False
    t.show(tree_style=ts)
Esempio n. 18
0
def draw_ete3_tree(organism, snplist, tree_file_name, config, c):
	'''Draws a phylogenetic tree using ETE3

	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
		## ['B.3', 'T', 'C', 'A']
		for snp in snplist.keys():
			if n.name == snp and snplist[snp] == 0:
				# 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
			elif n.name == snp and snplist[snp] == 1:
				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

		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 = self.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, width=tree_depth * 500)
Esempio n. 19
0
def get_tree_style():
    ts = TreeStyle()
    # ts.mode = 'c'
    ts.margin_top = 10
    ts.margin_bottom = 10
    ts.margin_left = 10
    ts.margin_right = 10
    ts.show_leaf_name = False
    ts.show_branch_length = False
    ts.show_branch_support = False
    ts.show_scale = False
    title = TextFace("     Tax Assignment Tree", fsize=10)
    title.hz_align = 2
    title.vt_align = 2
    ts.title.add_face(TextFace(" "), column=0)
    ts.title.add_face(TextFace(" "), column=0)
    ts.title.add_face(title, column=0)
    return ts
Esempio n. 20
0
def make_plot():
    df = pd.read_csv(f'{args.output}/aa_comp.tsv', sep="\t")
    df = df.set_index('Taxon')

    z = shc.linkage(df, method='ward')
    t = distance_matrix2tree(z, df.index.values)
    t.write(outfile=f'{args.output}/distance_matrix.tre')

    # Basic tree style
    ts = TreeStyle()
    ts.show_leaf_name = False
    ts.mode = "c"
    ts.show_scale = False
    ts.layout_fn = mylayout
    # PDF rendering
    t.render(f'{args.output}/aa_comp_calculator.pdf',
             w=183,
             units="mm",
             tree_style=ts)
Esempio n. 21
0
def plot_spn(spn, context=None, unroll=False, file_name=None, show_ids=False):
    assert spn is not None

    lin_style = TreeStyle()

    def my_layout(node):

        style = NodeStyle()
        style["size"] = 0
        style["vt_line_color"] = "#AAAAAA"
        style["hz_line_color"] = "#AAAAAA"
        style["vt_line_type"] = 1  # 0 solid, 1 dashed, 2 dotted
        style["hz_line_type"] = 1
        style["vt_line_width"] = 1
        style["hz_line_width"] = 1
        node.set_style(style)

        if node.is_leaf():
            name_face = AttrFace("name", fsize=8, ftype="Times")
        else:
            name_face = TextFace(node.name, fsize=18, ftype="Times")
            if node.node_type == Sum:
                for child in node.children:
                    label = TextFace(round(child.support, 3), fsize=6)
                    child.add_face(label, column=1, position="branch-bottom")
        if show_ids:
            node.add_face(AttrFace("id", fsize=6),
                          column=1,
                          position="branch-top")
        faces.add_face_to_node(name_face,
                               node,
                               column=1,
                               position="branch-right")

    lin_style.layout_fn = my_layout
    lin_style.show_leaf_name = False
    lin_style.show_scale = False

    tree = spn_to_ete(spn, context, unroll)

    if file_name is not None:
        return tree.render(file_name, tree_style=lin_style)
    def draw(self,
             file,
             colors,
             color_internal_nodes=True,
             legend_labels=(),
             show_branch_support=True,
             show_scale=True,
             legend_scale=1,
             mode="c"):
        max_color = len(colors)

        for node in self.tree.traverse():
            if not (color_internal_nodes or node.is_leaf()): continue
            color = colors[min(node.color, max_color - 1)]
            node.img_style['bgcolor'] = color

        ts = TreeStyle()
        ts.mode = mode
        ts.scale = self.scale
        # Disable the default tip names config
        ts.show_leaf_name = False
        ts.show_branch_support = show_branch_support

        # ts.branch_vertical_margin = 20
        ts.show_scale = show_scale
        cur_max_color = max(v.color for v in self.tree.traverse())
        current_colors = colors[0:cur_max_color + 1]

        for i, (label, color_) in enumerate(zip(legend_labels,
                                                current_colors)):
            ts.legend.add_face(CircleFace(24 * legend_scale, color_), column=0)
            ts.legend.add_face(CircleFace(13 * legend_scale, 'White'),
                               column=1)
            ts.legend.add_face(TextFace(label, fsize=53 * legend_scale),
                               column=2)
            ts.legend.add_face(CircleFace(13 * legend_scale, 'White'),
                               column=3)

        # self.tree.render("ete_tree.pdf", dpi=300, tree_style=ts)
        self.tree.render(file, w=1000, tree_style=ts)
def get_default_tree_style(color_dict):
    ts = TreeStyle()
    ts.mode = 'c'
    # ts.layout_fn = layout
    ts.margin_top = 50
    ts.margin_bottom = 0
    ts.margin_left = 50
    ts.margin_right = 50
    ts.show_scale = False
    ts.show_leaf_name = False
    ts.show_branch_length = False
    ts.show_branch_support = False
    for p, c in color_dict.iteritems():
        ts.legend.add_face(TextFace("    ", fsize=30), column=0)
        ts.legend.add_face(CircleFace(10, c), column=1)
        ts.legend.add_face(TextFace("   %s" % p, fsize=30), column=2)
    legend_margin_line = 5
    while legend_margin_line:
        ts.legend.add_face(TextFace(" "), column=0)
        ts.legend.add_face(TextFace(" "), column=1)
        ts.legend.add_face(TextFace(" "), column=2)
        legend_margin_line -= 1
    ts.legend_position = 3
    return ts
    def create_plot(self, target_outputfile):
        from ete3 import Tree, TreeStyle, NodeStyle, faces, AttrFace, CircleFace, TextFace
        t = Tree()

        def layout(node):
            if node.is_leaf():
                N = AttrFace("name", fgcolor="black")
                faces.add_face_to_node(N, node, 0)
            if "weight" in node.features:
                # Creates a sphere face whose size is proportional to node's
                # feature 1/gini index
                circle_face = CircleFace(radius=node.weight,
                                         color="RoyalBlue",
                                         style="sphere")
                circle_face.hz_align = 2
                circle_face.opacity = 0.3
                text_face = TextFace(text=node.name)
                faces.add_face_to_node(circle_face, node, 0, position="float")
                faces.add_face_to_node(text_face, node, 0, position="float")

        # Create an empty TreeStyle
        ts = TreeStyle()

        # Set our custom layout function
        ts.layout_fn = layout
        ts.scale = 140
        # # Draw a tree
        # ts.mode = "c"
        # We will add node names manually
        ts.show_leaf_name = False
        ts.branch_vertical_margin = 30
        ts.show_scale = False

        t = self.head_node.create_equivalent_ete_tree()

        t.render(target_outputfile, w=183, units="mm", tree_style=ts)
Esempio n. 25
0
    def __init__(self, root_text):
        # Inicializa la estructura árbol
        tree = Tree()

        # Formateamos el árbol indicandole un estilo
        style = TreeStyle()
        style.show_leaf_name = True
        style.show_scale = False
        style.scale = 100
        style.branch_vertical_margin = 30
        style.rotation = 0
        style.orientation = 0
        self.style = style
        self.tree = tree

        # Le damos estilo a la raíz del árbol
        self.tree.add_face(TextFace(root_text, fsize=10, fgcolor='darkred'),
                           column=0,
                           position='branch-right')
        self.tree.set_style(NodeStyle(size=20, hz_line_width=2,
                                      fgcolor='blue'))

        # Almacenamos la raíz del árbol como nodo actual
        self.curr_node = self.tree
def get_default_tree_style(color_dict):
    ts = TreeStyle()
    ts.mode = "c"
    # ts.layout_fn = layout
    ts.margin_top = 50
    ts.margin_bottom = 0
    ts.margin_left = 50
    ts.margin_right = 50
    ts.show_scale = False
    ts.show_leaf_name = False
    ts.show_branch_length = False
    ts.show_branch_support = False
    for p, c in color_dict.iteritems():
        ts.legend.add_face(TextFace("    ", fsize=30), column=0)
        ts.legend.add_face(CircleFace(10, c), column=1)
        ts.legend.add_face(TextFace("   %s" % p, fsize=30), column=2)
    legend_margin_line = 5
    while legend_margin_line:
        ts.legend.add_face(TextFace(" "), column=0)
        ts.legend.add_face(TextFace(" "), column=1)
        ts.legend.add_face(TextFace(" "), column=2)
        legend_margin_line -= 1
    ts.legend_position = 3
    return ts
Esempio n. 27
0
def plot_species_tree(tree_newick, tree_type, gene_name, tree_file_name,
                      name_list, tree_image_folder):
    # set tree parameters
    tree = Tree(tree_newick, format=2)
    ts = TreeStyle()
    ts.mode = "r"  # tree model: 'r' for rectangular, 'c' for circular
    ts.show_leaf_name = False
    tree_title = tree_type + ' (' + gene_name + ')'  # define tree title
    # set tree title text parameters
    ts.title.add_face(TextFace(tree_title,
                               fsize=8,
                               fgcolor='black',
                               ftype='Arial',
                               tight_text=False),
                      column=0)  # tree title text setting
    # set layout parameters
    ts.rotation = 0  # from 0 to 360
    ts.show_scale = False
    ts.margin_top = 10  # top tree image margin
    ts.margin_bottom = 10  # bottom tree image margin
    ts.margin_left = 10  # left tree image margin
    ts.margin_right = 10  # right tree image margin
    ts.show_border = False  # set tree image border
    ts.branch_vertical_margin = 3  # 3 pixels between adjancent branches

    # set tree node style
    for each_node in tree.traverse():
        # leaf node parameters
        if each_node.is_leaf():
            ns = NodeStyle()
            ns['shape'] = 'circle'  # dot shape: circle, square or sphere
            ns['size'] = 0  # dot size
            ns['hz_line_width'] = 0.5  # branch line width
            ns['vt_line_width'] = 0.5  # branch line width
            ns['hz_line_type'] = 0  # branch line type: 0 for solid, 1 for dashed, 2 for dotted
            ns['vt_line_type'] = 0  # branch line type
            if each_node.name in name_list:
                ns['fgcolor'] = 'red'  # the dot setting
                each_node.add_face(
                    TextFace(each_node.name,
                             fsize=8,
                             fgcolor='red',
                             tight_text=False,
                             bold=False),
                    column=0,
                    position='branch-right')  # the node name text setting
                each_node.set_style(ns)
            else:
                ns['fgcolor'] = 'blue'  # the dot setting
                each_node.add_face(
                    TextFace(each_node.name,
                             fsize=8,
                             fgcolor='black',
                             tight_text=False,
                             bold=False),
                    column=0,
                    position='branch-right')  # the node name text setting
                each_node.set_style(ns)

        # non-leaf node parameters
        else:
            nlns = NodeStyle()
            nlns['size'] = 0  # dot size
            each_node.add_face(
                TextFace(each_node.name,
                         fsize=4,
                         fgcolor='black',
                         tight_text=False,
                         bold=False),
                column=5,
                position='branch-top')  # non-leaf node name text setting)
            each_node.set_style(nlns)
    # set figures size
    tree.render('%s/%s.png' % (tree_image_folder, tree_file_name),
                w=900,
                units='px',
                tree_style=ts)
Esempio n. 28
0
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("/groups/itay_mayrose/udiland/crispys_tomato/families/filtering_scripts/face_positions.png", w=800, tree_style=ts)
Esempio n. 29
0
def create_tree(tree,
                tree_root_key,
                filepath,
                patient,
                phylogeny,
                drivers=None):
    """
    Takes a networkx tree and creates an ete3 tree and creates a PDF, SVG or PNG according to the given filename at
    the given path
    :param tree: inferred cancer phylogeny encoded as networkx tree
    :param tree_root_key: key of root in networkx tree
    :param filepath: path to output file (excluding file extension)
    :param patient: data structure around patient
    :param phylogeny: inferred cancer phylogeny
    :param drivers: defaultdict with mutation IDs and instance of driver class to be highlighted on edges
    :return path to the generated ete3 PNG file
    """

    # generate ete3 tree
    rt = Tree()  # generate root
    rt.name = 'Germline {}'.format(patient.name)
    _generate_ete_tree(tree,
                       tree_root_key,
                       rt,
                       0,
                       patient,
                       phylogeny,
                       gene_names=patient.gene_names,
                       drivers=drivers)

    ts = TreeStyle()
    ts.layout_fn = ete_layout
    ts.show_leaf_name = False
    ts.show_branch_length = False
    ts.show_branch_support = False
    ts.show_scale = False
    ts.extra_branch_line_color = 'Black'
    # ts.complete_branch_lines_when_necessary = False

    # Find the maximal number of variants present in a single sample to determine the optimal ETE3 scale level
    max_muts = max(no_pres_vars
                   for no_pres_vars in patient.no_present_vars.values())

    def round_to_1(x):
        """
        Round to one significant digit
        :param x:
        :return:
        """
        return round(x, -int(math.floor(math.log10(abs(x)))))

    # XX pixels per branch length unit
    # if max_muts > 20000:
    #     ts.scale = 0.02
    # elif max_muts > 10000:
    #     ts.scale = 0.05
    # elif max_muts > 5000:
    #     ts.scale = 0.1
    # elif max_muts > 2000:
    #     ts.scale = 0.2
    # elif max_muts > 1000:
    #     ts.scale = 0.5
    # elif max_muts > 500:
    #     ts.scale = 1
    # elif max_muts > 200:
    #     ts.scale = 2
    # elif max_muts > 100:
    #     ts.scale = 5
    # elif max_muts > 50:
    #     ts.scale = 5
    # else:
    #     ts.scale = 10

    ts.scale = round_to_1(600 / max_muts)

    ts.branch_vertical_margin = 15  # XX pixels between adjacent branches

    # rt.show(tree_style=ts)

    ete_tree_plot = filepath + '.png'
    rt.render(ete_tree_plot, w=183, units="mm", tree_style=ts, dpi=300)
    rt.render(filepath + '.pdf', w=183, units="mm", tree_style=ts, dpi=300)

    return ete_tree_plot
Esempio n. 30
0
from ete3 import Tree,TreeStyle,TextFace

t = Tree('tagfrog.phy')
for node in t.traverse():
    node.img_style['size'] = 3
    if node.is_leaf():
        name_face = TextFace(node.name)
ts = TreeStyle()
ts.show_scale = True
t.render('tagfrog.pdf')
## create colors for each genus
for idx, family in enumerate(families):
    for cidx, genus_tree in enumerate(genera_trees[idx]):
        tf_genera = TreeFace(genus_tree, ts_genera)
        tf_genera.border.width = 2
        genus = genera[idx][cidx]
        color = colors[str(genus)]
        tf_genera.border.color = color
        (t & family).add_face(tf_genera, column=0, position='aligned')

for n in genus_tree.iter_search_nodes():
    if n.dist == 1:
        n.img_style = ns_genera

ts_genera.show_leaf_name = False
ts_genera.show_scale = False
ts_genera.layout_fn = my_layout
ts.branch_vertical_margin = 10

ts.show_leaf_name = False
ts.branch_vertical_margin = 15
ts.layout_fn = my_layout
ts.draw_guiding_lines = True
ts.guiding_lines_type = 1
ts.show_scale = False
ts.allow_face_overlap = False
# ts.mode = "c"
# ts.arc_start = 180 # 0 degrees = 3 o'clock
# ts.arc_span = 270
t.show(tree_style=ts)
t.render("mytree.png", w=183, units="mm", tree_style=ts)
Esempio n. 32
0
def simulate(args):
    '''
    Simulation subprogram. Can simulate in two modes.
    a) Neutral mode. A Galton–Watson process, with mutation probabilities according to a user defined motif model e.g. S5F.
    b) Selection mode. Using the same mutation process as in a), but in selection mode the poisson progeny distribution's lambda parameter
    is dynamically adjusted accordring to the hamming distance to a list of target sequences. The closer a sequence gets to one of the targets
    the higher fitness and the closer lambda will approach 2, vice versa when the sequence is far away lambda approaches 0.
    '''
    if args.random_seed is not None:
        numpy.random.seed(args.random_seed)
        random.seed(args.random_seed)
    mutation_model = MutationModel(args.mutability, args.substitution)
    if args.lambda0 is None:
        args.lambda0 = [max([1, int(.01 * len(args.sequence))])]
    if args.random_seq is not None:
        from Bio import SeqIO
        records = list(SeqIO.parse(args.random_seq, "fasta"))
        random.shuffle(records)
        args.sequence = str(records[0].seq).upper()
    else:
        args.sequence = args.sequence.upper()
    if args.sequence2 is not None:
        if len(args.lambda0
               ) == 1:  # Use the same mutation rate on both sequences
            args.lambda0 = [args.lambda0[0], args.lambda0[0]]
        elif len(args.lambda0) != 2:
            raise Exception(
                'Only one or two lambda0 can be defined for a two sequence simulation.'
            )

        # Extract the bounds between sequence 1 and 2:
        pair_bounds = ((0, len(args.sequence)),
                       (len(args.sequence),
                        len(args.sequence) + len(args.sequence2)))
        # Merge the two seqeunces to simplify future dealing with the pair:
        args.sequence += args.sequence2.upper()
    else:
        pair_bounds = None
    if args.selection:
        assert (
            args.B_total >= args.f_full
        )  # the fully activating fraction on BA must be possible to reach within B_total
        # Find the total amount of A necessary for sustaining the inputted carrying capacity:
        print((args.carry_cap, args.B_total, args.f_full, args.mature_affy))
        A_total = selection_utils.find_A_total(args.carry_cap, args.B_total,
                                               args.f_full, args.mature_affy,
                                               args.U)
        # Calculate the parameters for the logistic function:
        Lp = selection_utils.find_Lp(args.f_full, args.U)
        selection_params = [
            args.stop_dist, args.mature_affy, args.naive_affy,
            args.target_dist, args.target_count, args.skip_update, A_total,
            args.B_total, Lp, args.k, args.outbase
        ]
    else:
        selection_params = None

    trials = 1000
    # This loop makes us resimulate if size too small, or backmutation:
    for trial in range(trials):
        try:
            tree = mutation_model.simulate(args.sequence,
                                           pair_bounds=pair_bounds,
                                           lambda_=args.lambda_,
                                           lambda0=args.lambda0,
                                           n=args.n,
                                           N=args.N,
                                           T=args.T,
                                           verbose=args.verbose,
                                           selection_params=selection_params)
            if args.selection:
                collapsed_tree = CollapsedTree(tree=tree,
                                               name='GCsim selection',
                                               collapse_syn=False,
                                               allow_repeats=True)
            else:
                collapsed_tree = CollapsedTree(
                    tree=tree, name='GCsim neutral'
                )  # <-- This will fail if backmutations
            tree.ladderize()
            uniques = sum(node.frequency > 0
                          for node in collapsed_tree.tree.traverse())
            if uniques < 2:
                raise RuntimeError(
                    'collapsed tree contains {} sampled sequences'.format(
                        uniques))
            break
        except RuntimeError as e:
            print('{}, trying again'.format(e))
        else:
            raise
    if trial == trials - 1:
        raise RuntimeError('{} attempts exceeded'.format(trials))

    # In the case of a sequence pair print them to separate files:
    if args.sequence2 is not None:
        fh1 = open(args.outbase + '_seq1.fasta', 'w')
        fh2 = open(args.outbase + '_seq2.fasta', 'w')
        fh1.write('>naive\n')
        fh1.write(args.sequence[pair_bounds[0][0]:pair_bounds[0][1]] + '\n')
        fh2.write('>naive\n')
        fh2.write(args.sequence[pair_bounds[1][0]:pair_bounds[1][1]] + '\n')
        for leaf in tree.iter_leaves():
            if leaf.frequency != 0:
                fh1.write('>' + leaf.name + '\n')
                fh1.write(leaf.sequence[pair_bounds[0][0]:pair_bounds[0][1]] +
                          '\n')
                fh2.write('>' + leaf.name + '\n')
                fh2.write(leaf.sequence[pair_bounds[1][0]:pair_bounds[1][1]] +
                          '\n')
    else:
        with open(args.outbase + '.fasta', 'w') as f:
            f.write('>naive\n')
            f.write(args.sequence + '\n')
            for leaf in tree.iter_leaves():
                if leaf.frequency != 0:
                    f.write('>' + leaf.name + '\n')
                    f.write(leaf.sequence + '\n')

    # Some observable simulation stats to write:
    frequency, distance_from_naive, degree = zip(
        *[(node.frequency, hamming_distance(node.sequence, args.sequence),
           sum(
               hamming_distance(node.sequence, node2.sequence) == 1
               for node2 in collapsed_tree.tree.traverse()
               if node2.frequency and node2 is not node))
          for node in collapsed_tree.tree.traverse() if node.frequency])
    stats = pd.DataFrame({
        'genotype abundance': frequency,
        'Hamming distance to root genotype': distance_from_naive,
        'Hamming neighbor genotypes': degree
    })
    stats.to_csv(args.outbase + '_stats.tsv', sep='\t', index=False)

    print('{} simulated observed sequences'.format(
        sum(leaf.frequency for leaf in collapsed_tree.tree.traverse())))

    # Render the full lineage tree:
    ts = TreeStyle()
    ts.rotation = 90
    ts.show_leaf_name = False
    ts.show_scale = False

    colors = {}
    palette = SVG_COLORS
    palette -= set(['black', 'white', 'gray'])
    palette = cycle(list(palette))  # <-- Circular iterator

    # Either plot by DNA sequence or amino acid sequence:
    if args.plotAA and args.selection:
        colors[tree.AAseq] = 'gray'
    else:
        colors[tree.sequence] = 'gray'

    for n in tree.traverse():
        nstyle = NodeStyle()
        nstyle["size"] = 10
        if args.plotAA:
            if n.AAseq not in colors:
                colors[n.AAseq] = next(palette)
            nstyle['fgcolor'] = colors[n.AAseq]
        else:
            if n.sequence not in colors:
                colors[n.sequence] = next(palette)
            nstyle['fgcolor'] = colors[n.sequence]
        n.set_style(nstyle)

    # Render and pickle lineage tree:
    tree.render(args.outbase + '_lineage_tree.svg', tree_style=ts)
    with open(args.outbase + '_lineage_tree.p', 'wb') as f:
        pickle.dump(tree, f)

    # Render collapsed tree,
    # create an id-wise colormap
    # NOTE: node.name can be a set
    if args.plotAA and args.selection:
        colormap = {
            node.name: colors[node.AAseq]
            for node in collapsed_tree.tree.traverse()
        }
    else:
        colormap = {
            node.name: colors[node.sequence]
            for node in collapsed_tree.tree.traverse()
        }
    collapsed_tree.write(args.outbase + '_collapsed_tree.p')
    collapsed_tree.render(args.outbase + '_collapsed_tree.svg',
                          idlabel=args.idlabel,
                          colormap=colormap)
    # Print colormap to file:
    with open(args.outbase + '_collapsed_tree_colormap.tsv', 'w') as f:
        for name, color in colormap.items():
            f.write((name if isinstance(name, str) else ','.join(name)) +
                    '\t' + color + '\n')
    with open(args.outbase + '_collapsed_tree_colormap.p', 'wb') as f:
        pickle.dump(colormap, f)

    if args.selection:
        # Define a list a suitable colors that are easy to distinguish:
        palette = [
            'crimson', 'purple', 'hotpink', 'limegreen', 'darkorange',
            'darkkhaki', 'brown', 'lightsalmon', 'darkgreen', 'darkseagreen',
            'darkslateblue', 'teal', 'olive', 'wheat', 'magenta',
            'lightsteelblue', 'plum', 'gold'
        ]
        palette = cycle(list(palette))  # <-- circular iterator
        colors = {
            i: next(palette)
            for i in range(int(len(args.sequence) // 3))
        }
        # The minimum distance to the target is colored:
        colormap = {
            node.name: colors[node.target_dist]
            for node in collapsed_tree.tree.traverse()
        }
        collapsed_tree.write(args.outbase + '_collapsed_runstat_color_tree.p')
        collapsed_tree.render(args.outbase +
                              '_collapsed_runstat_color_tree.svg',
                              idlabel=args.idlabel,
                              colormap=colormap)
        # Write a file with the selection run stats. These are also plotted:
        with open(args.outbase + '_selection_runstats.p', 'rb') as fh:
            runstats = pickle.load(fh)
            selection_utils.plot_runstats(runstats, args.outbase, colors)
Esempio n. 33
0
size = {}
value = {}
node_info = node_fh.readlines()
for info in node_info:
    info = info.rstrip('\n')
    infos = list(info.split('\t'))
    color[infos[0]] = infos[1]
    size[infos[0]] = infos[2]
    value[infos[0]] = "%.2f %%" % (float(infos[3]) * 100)

tstyle = TreeStyle()
tstyle.complete_branch_lines_when_necessary = False
tstyle.show_leaf_name = False
tstyle.scale = 1
tstyle.branch_vertical_margin = 40
tstyle.show_scale = False
tree_ete.set_style(tstyle)

for node in tree_ete.traverse():
    if node.name != "root":
        name_face = TextFace(node.name)
        abun_face = TextFace(value[node.name])
        node.add_face(name_face, column=0, position="branch-top")
        node.add_face(abun_face, column=0, position="branch-bottom")
        nstyle = NodeStyle()
        nstyle["fgcolor"] = color[node.name]
        nstyle["size"] = float(size[node.name])
        node.set_style(nstyle)
    else:
        nstyle = NodeStyle()
        nstyle["fgcolor"] = "white"
Esempio n. 34
0
def heatmap_view(tree, orthologous_groups, save_dir):
    """Generates a heatmap of regulation states in all species."""
    light_tree = copy.deepcopy(tree)  # Tree copy for the light heatmap
    # Heat map settings
    rect_face_fgcolor = 'black'
    locus_tag_len = max(len(gene.locus_tag) + 5
                        for ortho_grp in orthologous_groups
                        for gene in ortho_grp.genes)
    rect_face_width = locus_tag_len * 8
    light_rect_face_width = 20
    rect_face_height = 20
    rotation = 90

    # Sort orthologous groups by the number of regulated genes in each group
    orthologous_groups = filter_and_sort_orthologous_grps(orthologous_groups)

    # For each species and its gene in each orthologous group, draw a rectangle
    for node, light_node in zip(tree.get_leaves(), light_tree.get_leaves()):
        for i, orthologous_grp in enumerate(orthologous_groups, start=1):
            #get all orthologs in group
            matching_genes = [g for g in orthologous_grp.genes \
            if g.genome.strain_name == node.name]

            #if there is ortholog
            if len(matching_genes) > 0:
                # Get the first ortholog from the genome in the group
                #this is the one with higher probability of regulation.
                #so this probability will be displayed for the group
                gene = matching_genes[0]
                p_regulation = gene.operon.regulation_probability
                p_notregulation = 1.0 - p_regulation
                p_absence = 0
            # No ortholog from this genome
            else:
                gene = None
                p_regulation = 0
                p_notregulation = 0
                p_absence = 1

            # Color of the rectangle is based on probabilities
            rect_face_bgcolor = rgb2hex(
                p_notregulation, p_regulation, p_absence)
            rect_face_text = ('%s [%d]' % (gene.locus_tag, gene.operon.operon_id)
                              if gene else '')
            rect_face_label = {'text': rect_face_text,
                               'font': 'Courier',
                               'fontsize': 8,
                               'color': 'black'}
            # Create the rectangle
            rect_face = RectFace(rect_face_width, rect_face_height,
                                 rect_face_fgcolor, rect_face_bgcolor,
                                 label=rect_face_label)
            light_rect_face = RectFace(light_rect_face_width, rect_face_height,
                                       rect_face_fgcolor, rect_face_bgcolor,
                                       label='')
            rect_face.rotation = -rotation
            light_rect_face.rotation = -rotation
            # Add the rectangle to the corresponding column
            node.add_face(rect_face, column=i, position='aligned')
            light_node.add_face(light_rect_face, column=i, position='aligned')

    ts = TreeStyle()
    # Add orthologous group descriptions
    descriptions = ['-'.join([grp.description, str(grp.NOGs)]) for grp in orthologous_groups]
    max_description_len = max(map(len, descriptions))
    descriptions = [
        '[%d]' % i + description + ' '*(max_description_len-len(description))
        for i, description in enumerate(descriptions, start=1)]
    for i, description in enumerate(descriptions, start=1):
        text_face = TextFace(description, ftype='Courier')
        text_face.hz_align = 1
        text_face.vt_align = 1
        text_face.rotation = -rotation
        ts.aligned_header.add_face(text_face, column=i)

    # Rotate the generated heatmap.
    ts.margin_left = 10
    ts.margin_top = 20
    ts.rotation = rotation
    ts.show_scale = False
    # For some reason, it can't render to PDF in color
    tree.render(os.path.join(save_dir, 'heatmap.svg'), tree_style=ts)
    light_tree.render(os.path.join(save_dir, 'heatmap_light.svg'), tree_style=ts)
Esempio n. 35
0
def plot_tree(tree, tree_title, tree_output):
    # set tree parameters
    ts = TreeStyle()
    ts.mode = "r"  # tree model: 'r' for rectangular, 'c' for circular
    ts.show_leaf_name = 0
    # set tree title text parameters
    ts.title.add_face(TextFace(tree_title,
                               fsize=8,
                               fgcolor='black',
                               ftype='Arial',
                               tight_text=False),
                      column=0)  # tree title text setting
    # set layout parameters
    ts.rotation = 0  # from 0 to 360
    ts.show_scale = False
    ts.margin_top = 10  # top tree image margin
    ts.margin_bottom = 10  # bottom tree image margin
    ts.margin_left = 10  # left tree image margin
    ts.margin_right = 10  # right tree image margin
    ts.show_border = False  # set tree image border
    ts.branch_vertical_margin = 3  # 3 pixels between adjancent branches

    # set tree node style
    for each_node in tree.traverse():
        # leaf node parameters
        if each_node.is_leaf():
            ns = NodeStyle()
            ns["shape"] = "circle"  # dot shape: circle, square or sphere
            ns["size"] = 0  # dot size
            ns['hz_line_width'] = 0.5  # branch line width
            ns['vt_line_width'] = 0.5  # branch line width
            ns['hz_line_type'] = 0  # branch line type: 0 for solid, 1 for dashed, 2 for dotted
            ns['vt_line_type'] = 0  # branch line type
            ns["fgcolor"] = "blue"  # the dot setting
            each_node.add_face(TextFace(each_node.name,
                                        fsize=5,
                                        fgcolor='black',
                                        tight_text=False,
                                        bold=False),
                               column=0,
                               position='branch-right'
                               )  # leaf node the node name text setting

            each_node.set_style(ns)

        # non-leaf node parameters
        else:
            nlns = NodeStyle()
            nlns["size"] = 0  # dot size
            #nlns["rotation"] = 45
            each_node.add_face(
                TextFace(each_node.name,
                         fsize=3,
                         fgcolor='black',
                         tight_text=False,
                         bold=False),
                column=5,
                position='branch-top')  # non-leaf node name text setting)

            each_node.set_style(nlns)

    tree.render(tree_output, w=900, units="px",
                tree_style=ts)  # set figures size
Esempio n. 36
0
nw = '(0:0, 1:20);'
fa = """
>0
AA..
>1
CAA.
"""

t = PhyloTree(nw, alignment=fa, alg_format='fasta', format=1)
ts = TreeStyle()
ts.show_branch_length = False
ts.show_leaf_name = False
ts.draw_guiding_lines = True
ts.draw_aligned_faces_as_table = True
ts.show_scale = False

def my_layout(node):
    #
    # add names to all nodes (not just to leaf nodes)
    # ete3/test/test_treeview/face_rotation.py
    F = TextFace(node.name, tight_text=True)
    add_face_to_node(F, node, column=0, position="branch-right")
    #
    # add branch lengths
    # ete3/treeview/qt4_render.py
    if not node.is_root():
        bl_face = AttrFace("dist", fsize=8, ftype="Arial",
                fgcolor="black", formatter="%0.3g")
        #
        # This is a failed attempt to center the branch length text on the branch.