예제 #1
0
def writeTrees(trees, label):
    """
    Now that we have branch lengths, write out new Newick trees with the
    branch lengths included.  Note that ete3 does not seem to write out
    the length of the root automatically, so we add it in by hand.
    """
    ts = TreeStyle()
    ts.show_leaf_name = False
    ts.show_branch_length = False
    ts.branch_vertical_margin = 20
    ts.scale = 0.05
    outtrees = open(lengthdir + label + ".newick", "w")
    for index, tree in enumerate(trees):
        #print(tree)
        #If needed:  round the branch lengths
        #        for branch in tree.traverse():
        #            branch.dist = round(branch.dist)
        line = tree.write(format=1)
        rootlen = round(tree.get_tree_root().dist)
        line = line[:-1] + ":" + str(rootlen) + ";"
        outtrees.write(line + "\n")
        if (showTrees):
            for branch in tree.traverse():
                if branch.name != "":
                    name_face = AttrFace("name", fsize=30)
                    branch.add_face(name_face,
                                    column=0,
                                    position="branch-right")
                if branch.dist != 0:
                    if branch.name == "":
                        text_face = TextFace(str(round(branch.dist, 2)),
                                             fsize=30)
                        branch.add_face(text_face,
                                        column=1,
                                        position="branch-top")
                else:
                    print("Branch found of length zero but not a tip in tree",
                          label)
                    print(branch)
            filename = label
            if len(trees) > 1:
                filename += "_" + str(index)
            filename += ".png"
            tree.render(lengthdir + filename, tree_style=ts)
            #foo()
    outtrees.close()
예제 #2
0
    def mostraArvore(self,
                     ks=";"):  #passa todos as arestas para exibir a árvore
        t = Tree(ks, format=1)
        ts = TreeStyle()
        ts.show_leaf_name = False

        def my_layout(node):  #coloca o nome em cada nó
            node.name
            F = TextFace(
                node.name.replace("*", "\n"),
                tight_text=True)  #substitui onde tem estrela p quebra de linha
            add_face_to_node(F, node, column=0, position="branch-right")
            F.rotation = -90  #rotação do nome no nó

        ts.layout_fn = my_layout
        ts.rotation = 90  #exibir árvore na vertical
        t.show(tree_style=ts)  #mostra árvore
def draw_tree(pstrains, names=False, subset=None):
    evol = {x.rstrip() for x in open('input/evolution_experiment.txt')}

    tree = get_tree('input/tree.nwk')

    strains = {x.name for x in tree.traverse() if x.name != ''}
    if subset is None:
        subset = strains
    evol_tree = {x.name for x in tree.traverse() if x.name in evol}

    commensals = {}
    for x in strains:
        if pstrains[x] == 'Commensal strain':
            commensals[x] = colors.cnames['blue']
        elif pstrains[x] == 'Pathogenic strain':
            commensals[x] = colors.cnames['red']
        else:
            commensals[x] = colors.cnames['white']

    ref = NodeStyle()
    ref['fgcolor'] = sns.xkcd_rgb['light red']
    inner = NodeStyle()
    inner['size'] = 0
    for n in tree.traverse():
        if not n.is_leaf():
            n.set_style(inner)
            continue
        if n.name not in subset:
            continue
        if not names:
            r = RectFace(10, 3, commensals[n.name], commensals[n.name])
            n.add_face(r, 0, position="aligned")
        ev = NodeStyle()
        ev["fgcolor"] = "black"
        ev['size'] = 3
        n.set_style(ev)

    circular_style = TreeStyle()
    circular_style.mode = "c"
    if not names:
        circular_style.scale = 1300
    else:
        circular_style.scale = 7300
    circular_style.show_leaf_name = names
    return tree, circular_style
예제 #4
0
파일: utils.py 프로젝트: muppetjones/ete
def render_tree(tree, fname):
    # Generates tree snapshot
    npr_nodestyle = NodeStyle()
    npr_nodestyle["fgcolor"] = "red"
    for n in tree.traverse():
        if hasattr(n, "nodeid"):
            n.set_style(npr_nodestyle)
    ts = TreeStyle()
    ts.show_leaf_name = True
    ts.show_branch_length = True
    ts.show_branch_support = True
    ts.mode = "r"
    iterface = faces.TextFace("iter")
    ts.legend.add_face(iterface, 0)

    tree.dist = 0
    tree.sort_descendants()
    tree.render(fname, tree_style=ts, w=700)
예제 #5
0
def main(argv):  

    
    
    t = Tree(argv[1])
    save=int(argv[2])
    ts=TreeStyle()
    
    # ts.tree_width = 50
    #t.show(tree_style=ts)
    if(save==1):
        if os.path.exists("crud/static/crud/Tree1.png"):
             os.remove("crud/static/crud/Tree1.png")
        t.render("crud/static/crud/Tree1.png", tree_style=ts)
    else:
        if os.path.exists("crud/static/crud/Tree2.png"):
             os.remove("crud/static/crud/Tree2.png")
        t.render("crud/static/crud/Tree2.png", tree_style=ts)
예제 #6
0
    def etetree_to_image(self):
        """It changes an ete3 tree into an actual image.
        """
        try:
            ts = TreeStyle()
            ts.layout_fn = lambda x: True
            base64_img, img_map = self.processed_tree.render("%%return.PNG",
                                                             units="px",
                                                             dpi=500,
                                                             tree_style=ts)
            image_tree = base64_img.data().decode("utf-8")
            print(type(image_tree))

        except:
            sys.stderr.write("Error at image encoding.\n")
            sys.exit(1)

        return image_tree
예제 #7
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
예제 #8
0
def show(tf):
    try:
        os.environ['DISPLAY']
        from ete3 import TreeStyle
        flag = 0
    except (KeyError, ImportError):
        flag = 1
    if flag:
        tree = dp.Tree.get(path=tf, schema='newick', rooting='force-rooted')
        print(tree.as_ascii_plot())
    else:
        tree = ete.Tree(tf)
        ts = TreeStyle()
        ts.show_leaf_name = True
        ts.show_branch_length = True
        ts.scale = 25
        tree.show(tree_style=ts)
    return "Done"
예제 #9
0
def plot_newick(aug_cluster_list, mode='c', db=-1):
    circular_style = TreeStyle()
    circular_style.mode = mode  # draw tree in circular mode
    circular_style.scale = 20
    circular_style.arc_span = 360

    if db > 0:
        newick = convert_to_newick_db(aug_cluster_list,
                                      len(aug_cluster_list) - 1, db)
        circular_style.mode = mode
    else:
        newick = convert_to_newick(aug_cluster_list, len(aug_cluster_list) - 1)
    newick = newick + ':0;'

    t = Tree(newick, format=1)
    t.show(tree_style=circular_style)
    if False:
        t.render('tree3.png', w=100, units='in', tree_style=circular_style)
예제 #10
0
def _create_tree(tree, fasta, out, color):
    seqs = SeqGroup(fasta, format="fasta")
    t = Tree(tree)
    ts = TreeStyle()
    ts.show_branch_length = True
    colors = _parse_color_file(color)
    node_names = t.get_leaf_names()
    for name in node_names:
        seq = seqs.get_seq(name)
        seqFace = SeqMotifFace(seq, seq_format="()")
        node = t.get_leaves_by_name(name)
        for i in range(0, len(node)):
            if name in colors:
                ns = NodeStyle()
                ns['bgcolor'] = colors[name]
                node[i].set_style(ns)
            node[i].add_face(seqFace, 0, 'aligned')
    t.render(out, tree_style=ts)
예제 #11
0
    def render(self, textMode=False):
        """ 
        textMode=False will show a graphical tree. 
        textmode=True will show an ASCII tree. 
        """
        t = Tree(self.newick, format=1)
        if textMode:
            print(t.get_ascii(show_internal=True))
        else:
            ts = TreeStyle()
            ts.show_leaf_name = False

            #TODO: make this not be a function
            def my_layout(node):
                F = TextFace(node.name, tight_text=False)
                add_face_to_node(F, node, column=0, position="branch-right")

            ts.layout_fn = my_layout
            return t.render('%%inline', tree_style=ts)
예제 #12
0
    def visualize(self, group1=None, group2=None):
        import matplotlib
        import matplotlib.pyplot as plt

        # annotate the cluster roots with their fractions
        if group1 or group2:
            for i, cluster_root in enumerate(self.cluster_roots):
                # count downstream conditions in the leafs
                datapoints_in_cluster = list(self.nodes2leaves[cluster_root])
                cluster_root.add_face(
                    TextFace(f"Group1: {len(group1)}// Group2:{len(group2)}"),
                    column=0,
                    position="branch-right")

        def _custom_layout(node):
            cmap_cluster = plt.cm.tab10(
                np.linspace(0, 1, len(self.cluster_roots)))
            cmap_treated = plt.cm.viridis(np.linspace(0, 1, 2))

            if node.is_leaf():
                c_cluster = matplotlib.colors.rgb2hex(
                    cmap_cluster[node.clustering, :])
                c_treat = matplotlib.colors.rgb2hex(
                    cmap_treated[node.treated, :])
                node.img_style["fgcolor"] = c_treat
                node.img_style["bgcolor"] = c_cluster

            if 'is_cluster_root' in node.features:
                c_cluster = matplotlib.colors.rgb2hex(
                    cmap_cluster[node.is_cluster_root, :])
                node.img_style["bgcolor"] = c_cluster
                node.img_style["draw_descendants"] = False
                node.add_face(TextFace(f"#data:{node.n_datapoints}"),
                              column=0,
                              position="branch-right")

        ts = TreeStyle()
        ts.mode = "r"
        ts.show_leaf_name = False
        ts.arc_start = -180  # 0 degrees = 3 o'clock
        ts.arc_span = 270
        ts.layout_fn = _custom_layout
        self.tree.show(tree_style=ts)
예제 #13
0
 def on_actionOpen_triggered(self):
     d = QtGui.QFileDialog()
     d._conf = _open_newick.Ui_OpenNewick()
     d._conf.setupUi(d)
     d.exec_()
     return
     fname = QtGui.QFileDialog.getOpenFileName(
         self,
         "Open File",
         "/home",
     )
     try:
         t = Tree(str(fname))
     except Exception as e:
         print(e)
     else:
         self.scene.tree = t
         self.img = TreeStyle()
         self.redraw()
예제 #14
0
    def render_tree(self):
        def my_layout(node):
            F = TextFace(node.name, tight_text=True)
            add_face_to_node(F, node, column=0, position="branch-right")

        t = Tree()
        ts = TreeStyle()
        ts.show_leaf_name = False
        queue = [(self.subtree_node, None)]
        while queue:
            node, parent = queue.pop(0)
            uct_value = 0
            if node.parent is not None:
                child_values = list(
                    map(lambda n: n.get_avg_value() + n.reward_from_par,
                        node.parent.get_childs()))
                max_child_value = max(child_values)
                min_child_value = min(child_values)
                child_value = node.get_avg_value()
                if min_child_value != np.inf and max_child_value != np.inf and min_child_value != max_child_value:
                    child_value = (child_value - min_child_value) / (
                        max_child_value - min_child_value)
                if node.num_visits == 0:
                    uct_value = np.inf
                else:
                    uct_value = child_value + \
                                self.C * ((node.parent.num_visits / node.num_visits) ** 0.5)



            node_face = str(node.get_state()) + "," + str(node.num_visits) + "," + str(node.get_avg_value()) \
                        + "," + str(node.is_terminal) + "," + str(uct_value)
            if parent is None:
                p = t.add_child(name=node_face)
            else:
                p = parent.add_child(name=node_face)
            for child in node.get_childs():
                queue.append((child, p))

        ts.layout_fn = my_layout
        # t.render('t.png', tree_style=ts)
        # print(t.get_ascii(show_internal=Tree))
        t.show(tree_style=ts)
예제 #15
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)
예제 #16
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)
예제 #17
0
    def style_and_render_tree(self, file_types=["svg"]):
        from ete3 import TreeStyle, TextFace, CircleFace

        ts = TreeStyle()
        title_face = TextFace(f"{genus} {snakemake.config['species']}", fsize=20)
        title_face.margin_bottom = 10
        ts.title.add_face(title_face, column=0)
        ts.branch_vertical_margin = 10
        ts.show_leaf_name = True
        # Legend
        ts.legend.add_face(TextFace(""), column=1)
        for category in ["Allowed", "Deviations", "Filtered", "Color"]:
            category = TextFace(category, fsize=8, bold=True)
            category.margin_bottom = 2
            category.margin_right = 40
            ts.legend.add_face(category, column=1)
        for i, criteria in enumerate(CRITERIA, 2):
            title = criteria.replace("_", " ").title()
            title = TextFace(title, fsize=8, bold=True)
            title.margin_bottom = 2
            title.margin_right = 40
            cf = CircleFace(4, COLORS[criteria], style="sphere")
            cf.margin_bottom = 5
            filtered_count = len(
                list(filter(None, self.failed_report.criteria == criteria))
            )
            filtered = TextFace(filtered_count, fsize=8)
            filtered.margin_bottom = 5
            allowed = TextFace(self.allowed[criteria], fsize=8)
            allowed.margin_bottom = 5
            allowed.margin_right = 25
            # TODO Prevent tolerance from rendering as a float
            tolerance = TextFace(self.tolerance[criteria], fsize=8)
            tolerance.margin_bottom = 5
            ts.legend.add_face(title, column=i)
            ts.legend.add_face(allowed, column=i)
            ts.legend.add_face(tolerance, column=i)
            ts.legend.add_face(filtered, column=i)
            ts.legend.add_face(cf, column=i)
        for f in file_types:
            out_tree = os.path.join(self.paths.qc, "tree.{}".format(f))
            self.tree.render(out_tree, tree_style=ts)
def build_tree(aln, tree, basename, show, output_format):
    """Build phylogenetic tree from files

    This function creates a file with the phylogenetic tree and alignment
    from the fasta multiple alignment file and the tree in newick format.

    Parameters
    -------------
    aln: string
        Alignment string in fasta format
    tree: string
        Tree string in newick format
    basename: string
        Basename of the original alignment file
    show: boolean
        Show ETE tree browser (yes/no)
    output_format: string
        Format of the output
    """

    if tree[-1] != ";":
        genetree = PhyloTree("{};".format(tree))
    else:
        genetree = PhyloTree(tree)

    ts = TreeStyle()
    ts.show_leaf_name = False

    new_tree = "{BASENAME}_Tree.{FORMAT}".format(BASENAME=basename,
                                                 FORMAT=output_format)
    new_tree_aln = "{BASENAME}_Tree_aln.{FORMAT}".format(BASENAME=basename,
                                                         FORMAT=output_format)

    if show:
        genetree.render(new_tree, tree_style=ts)
        genetree.link_to_alignment(aln)
        genetree.render(new_tree_aln, tree_style=ts)
        genetree.show(tree_style=ts)
    else:
        genetree.render(new_tree, tree_style=ts)
        genetree.link_to_alignment(aln)
        genetree.render(new_tree_aln, tree_style=ts)
예제 #19
0
    def save(self, file_name):
        """
        Saves LinkTree to file with given file_name
        Current file types supported are .png, .pdf, .svg

        Args:
            file_name (str): Name of file being saved to
        """
        style = TreeStyle()
        style.show_leaf_name = False

        def my_layout(node):
            node_style = TextFace(node.name, tight_text=True)
            add_face_to_node(node_style,
                             node,
                             column=0,
                             position='branch-bottom')

        style.layout_fn = my_layout
        self._tree.render(file_name, tree_style=style)
예제 #20
0
def tree_visulization(raw_tree_file, outdir, proj_name, scale=100):
    """Tree visualization with ETE3.
    raw_tree_file: a newick format tree.
    """
    from ete3 import Tree, TreeStyle, NodeStyle
    from pyvirtualdisplay import Display
    display = Display(backend='xvfb')  # Start Xvfb using PyVisualDisplay
    display.start()
    logging.info('Xvfb started.')
    # ps = subprocess.Popen("Xvfb -ac :%d -screen 0 1280x1024x8 > /dev/null 2>&1" % server_num, shell=True)
    # os.environ["DISPLAY"] = ":%d" % server_num
    t = Tree(raw_tree_file)
    ts = TreeStyle()
    ts.show_leaf_name = True
    # ts.show_branch_support = True
    # ts.scale = scale
    ts.mode = "c"
    t.render('%s/%s_tree.svg' % (outdir, proj_name), tree_style=ts)
    display.popen.terminate()
    return None
예제 #21
0
def get_tree_shape(newick, graph, lower_threshold, higher_threshold):
    t = Tree(newick, format=8)
    for n in t.traverse():
        nstyle = NodeStyle()
        nstyle["fgcolor"] = "yellow"
        name = newick_to_name(n.name)
        if name != '':
            if graph.nodes[name]["val"] > higher_threshold:
                nstyle["fgcolor"] = "green"
            elif graph.nodes[name]["val"] < lower_threshold:
                nstyle["fgcolor"] = "red"
        nstyle["size"] = 5
        n.set_style(nstyle)
    ts = TreeStyle()
    ts.show_leaf_name = True
    ts.show_branch_length = False
    ts.min_leaf_separation = 0.5
    ts.mode = "c"
    ts.root_opening_factor = 0.75
    return t, ts
def tree_layout(tree_file, ps_node_list):
    t = EvolTree(tree_file, format=0)
    style_other = NodeStyle()
    style_other['size'] = 6
    style_ps = NodeStyle()
    style_ps['fgcolor'] = '#ff0000'
    style_ps['size'] = 6
    for node in t.iter_descendants():
        descendant = t.get_descendant_by_node_id(node.node_id)
        if node.node_id in ps_node_list:
            descendant.img_style = style_ps
        else:
            descendant.img_style = style_other
    ts = TreeStyle()
    ts.layout_fn = layout
    ts.show_branch_support = False
    ts.show_branch_length = False
    ts.show_leaf_name = False
    result_picture = os.path.join(output_dir, 'positive_selection_tree.png')
    t.render(result_picture, tree_style=ts)
예제 #23
0
def get_example_tree():
    t = Tree("((a,b),c);")

    right_c0_r0 = TextFace("right_col0_row0")
    right_c0_r1 = TextFace("right_col0_row1")
    right_c1_r0 = TextFace("right_col1_row0")
    right_c1_r1 = TextFace("right_col1_row1")
    right_c1_r2 = TextFace("right_col1_row2")

    top_c0_r0 = TextFace("top_col0_row0")
    top_c0_r1 = TextFace("top_col0_row1")

    bottom_c0_r0 = TextFace("bottom_col0_row0")
    bottom_c1_r0 = TextFace("bottom_col1_row0")

    aligned_c0_r0 = TextFace("aligned_col0_row0")
    aligned_c0_r1 = TextFace("aligned_col0_row1")

    aligned_c1_r0 = TextFace("aligned_col1_row0")
    aligned_c1_r1 = TextFace("aligned_col1_row1")

    t.add_face(right_c0_r1, column=1, position="branch-right")
    t.add_face(right_c0_r0, column=0, position="branch-right")

    t.add_face(right_c1_r2, column=2, position="branch-right")
    t.add_face(right_c1_r1, column=1, position="branch-right")
    t.add_face(right_c1_r0, column=0, position="branch-right")

    t.add_face(top_c0_r1, column=1, position="branch-top")
    t.add_face(top_c0_r0, column=0, position="branch-top")

    t.add_face(bottom_c0_r0, column=0, position="branch-bottom")
    t.add_face(bottom_c1_r0, column=1, position="branch-bottom")

    for leaf in t.iter_leaves():
        leaf.add_face(aligned_c0_r1, 0, "aligned")
        leaf.add_face(aligned_c0_r0, 0, "aligned")
        leaf.add_face(aligned_c1_r1, 0, "aligned")
        leaf.add_face(aligned_c1_r0, 0, "aligned")

    return t, TreeStyle()
예제 #24
0
def visualize_tree(ete_tree_obj,
                   genotypes={},
                   metadata={},
                   cansnp_supported_nodes={}):
    """
    Function for visualization of cannonical snp supported clades
    Parameters
    ----------
    ete_tree_obj
    cansnp_supported_nodes

    Returns
    -------

    """

    # Basic tree style
    ts = TreeStyle()
    ts.show_leaf_name = True

    # Draws nodes as small red spheres of diameter equal to 10 pixels

    for n in ete_tree_obj.traverse():
        nstyle = NodeStyle()
        nstyle["shape"] = "sphere"
        nstyle["fgcolor"] = "darkred"

        if n.name in cansnp_supported_nodes:
            print("Found")
            #nstyle["fgcolor"] = "blue"
            #nstyle["size"] = cansnp_supported_nodes[n.name]['size']
            #nstyle["bgcolor"] =cansnp_supported_nodes[n.name]['bgcolor']
            face = RectFace(width=100,
                            height=100,
                            fgcolor='red',
                            bgcolor='green')

            n.add_face(face, column=1)
        n.set_style(nstyle)

    ete_tree_obj.show(tree_style=ts)
예제 #25
0
def get_tree(md, nc):
    # newick file
    t = Tree("../analyses/panseq/RAxML_bestTree.raxml_snp")
    ts = TreeStyle()
    ts.show_leaf_name = False
    # ts.mode = "c"
    # ts.arc_start = -180
    # ts.arc_span = 180

    for node in t.traverse():
        if node.is_leaf():
            nn = nc.get(node.name)
            serotype = md[nn]['serotype']
            if serotype == "O157:H7":
                nface = TextFace(serotype, fgcolor="blue", fsize=10)
                node.add_face(nface, column=0, position="branch-right")
            else:
                nface = TextFace(serotype, fgcolor="red", fsize=10)
                node.add_face(nface, column=0, position="branch-right")

    return t, ts
예제 #26
0
def view_by_gene(tree, orthologous_grp, save_file):
    # Make a copy of the tree
    tree = copy.deepcopy(tree)
    for node in tree.traverse():
        percents = [orthologous_grp.regulation_states[(node.name, s)] * 100
                    for s in ['1', '0', 'A']]
        stacked_bar_face = StackedBarFace(percents, width=30, height=15,
                                          colors=['green', 'red', 'blue'])
        stacked_bar_face.margin_left = 5
        stacked_bar_face.margin_right = 5
        node.add_face(stacked_bar_face, column=1)
        # Add locus tag if the genome has the gene from this orthologous group
        if node.is_leaf():
            # Check if the orthologous group contains any gene of the genome
            gene = orthologous_grp.member_from_genome(node.name)
            if gene:
                node.add_face(TextFace(text='[%s]' % gene.locus_tag), column=2)

    ts = TreeStyle()
    ts.title.add_face(TextFace(text=orthologous_grp.description), column=1)
    tree.render(save_file, tree_style=ts)
예제 #27
0
def network_size_view(tree, orthologous_groups, save_dir):
    # Set the size of each node
    for node in tree.traverse():
        # Count the number of genes likely to be regulated in this node
        num_regulated = len([
            grp for grp in orthologous_groups
            if grp.most_likely_state_at(node.name) == '1'
        ])
        nstyle = NodeStyle()
        nstyle['size'] = 0
        node.set_style(nstyle)
        circle_face = CircleFace(radius=num_regulated,
                                 color='green',
                                 style='sphere',
                                 label={
                                     'text': str(num_regulated),
                                     'color': 'black'
                                 })
        node.add_face(circle_face, column=2)
    ts = TreeStyle()
    tree.render(os.path.join(save_dir, 'network_size.svg'), tree_style=ts)
예제 #28
0
 def style_and_render_tree(self, file_types=["svg"]):
     from ete3 import TreeStyle, TextFace, CircleFace
     ts = TreeStyle()
     title_face = TextFace(self.name.replace('_', ' '), fsize=20)
     title_face.margin_bottom = 10
     ts.title.add_face(title_face, column=0)
     ts.branch_vertical_margin = 10
     ts.show_leaf_name = False
     # Legend
     ts.legend.add_face(TextFace(""), column=1)
     for category in ["Allowed", "Tolerance", "Filtered", "Color"]:
         category = TextFace(category, fsize=8, bold=True)
         category.margin_bottom = 2
         category.margin_right = 40
         ts.legend.add_face(category, column=1)
     for i, criteria in enumerate(self.criteria, 2):
         title = criteria.replace("_", " ").title()
         title = TextFace(title, fsize=8, bold=True)
         title.margin_bottom = 2
         title.margin_right = 40
         cf = CircleFace(4, self.colors[criteria], style="sphere")
         cf.margin_bottom = 5
         filtered_count = len(
             list(filter(None, self.failed_report.criteria == criteria)))
         filtered = TextFace(filtered_count, fsize=8)
         filtered.margin_bottom = 5
         allowed = TextFace(self.allowed[criteria], fsize=8)
         allowed.margin_bottom = 5
         allowed.margin_right = 25
         tolerance = TextFace(self.tolerance[criteria], fsize=8)
         tolerance.margin_bottom = 5
         ts.legend.add_face(title, column=i)
         ts.legend.add_face(allowed, column=i)
         ts.legend.add_face(tolerance, column=i)
         ts.legend.add_face(filtered, column=i)
         ts.legend.add_face(cf, column=i)
     for f in file_types:
         out_tree = os.path.join(self.qc_results_dir, 'tree.{}'.format(f))
         self.tree.render(out_tree, tree_style=ts)
         self.log.info("tree.{} generated".format(f))
    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)
예제 #30
0
    def newick(self, user_input_file):

        tree = ClusterTree(user_input_file)
        leaves = tree.get_leaf_names()
        ts = TreeStyle()
        ts.show_leaf_name = True
        ts.show_branch_length = True
        ts.show_branch_support = True

        leaf_dict = {}

        # Convert leaves (a list) into a dictionary
        for i in range(len(leaves)):
            leaf_dict[leaves[i]] = i
            i = i + 1

        # Cast dictionary attributes as list and create index labels
        k = list(leaf_dict.keys())
        v = list(leaf_dict.values())
        w = list(leaf_dict.items())
        leaf_labels = [k[v.index(j)] for j in range(0, len(w))]

        # Create a numpy array of zeros based on the number of taxa in the tree
        dmat = np.zeros((len(leaves), len(leaves)))

        print('Converting input tree:')

        # Compute distance matrix from newick tree (this is not yet a linked distance matrix)
        for l1, l2 in tqdm(combinations(leaves, 2)):
            d = tree.get_distance(l1, l2)
            dmat[leaf_dict[l1], leaf_dict[l2]] = dmat[leaf_dict[l2],
                                                      leaf_dict[l1]] = d

        # Convert dmat into a linkage distance matrix for scipy
        schlink = sch.linkage(scipy.spatial.distance.squareform(dmat),
                              method='average',
                              metric='euclidean')

        return dmat, schlink