Exemplo n.º 1
0
 def draw_tree(self):  # Визуализация дерева в GUI, и сохранение в png файл
     style = TreeStyle()
     style.show_leaf_name = True
     style.show_branch_length = True
     style.show_branch_support = True
     self.tree.show(tree_style=style)
     self.tree.render('tree.png', w=183, units="mm", tree_style=style)
Exemplo n.º 2
0
def actualRun():
    start = time.time()
    #stringArray = ["CGTGAATTCAT", "GACTTAC", "GATAGCTACTTAC", "GACCCTTTATAC", "GACTTGGGAC"]
    nameArray = []

    stringArray = parseXML(nameArray)

    for i in range(0, len(nameArray)):
        print "{}:{}".format(i, nameArray[i])

    sM = similarityMatrix(stringArray)
    #printMatrix(sM, len(stringArray))
    fullMat = wholeMat(sM)
    #printMatrix(fullMat, len(stringArray))
    #score = getSimilarity( sM , 2, 3)
    #print score

    mat = invertNumMat(fullMat)
    printMatrix(mat, len(stringArray))

    items = len(stringArray)

    #print items

    ourStr = properRun(mat, items)
    ourStr += ";"

    t = Tree(ourStr)
    ts = TreeStyle()
    ts.show_leaf_name = True
    ts.show_branch_length = True
    #ts.show_branch_support = True
    end = time.time()
    print "time: {}".format(end - start)
    t.show(tree_style=ts)
Exemplo n.º 3
0
def generateColoredPDF(tree):
    out_tree = os.path.splitext(os.path.basename(sys.argv[1]))[0] + ".pdf"
    ts = TreeStyle()
    ts.show_leaf_name = True
    ts.show_branch_support = True
    ts.show_branch_length = False
    for n in tree.traverse():
        if n.name in eukaryote_seqs:
            nstyle = NodeStyle()
            nstyle["fgcolor"] = "red"
            nstyle["size"] = 15
            n.set_style(nstyle)
            n.name = name2tax.get(n.name)
        elif n.name in bacteria_seqs:
            nstyle = NodeStyle()
            nstyle["fgcolor"] = "blue"
            nstyle["size"] = 13
            n.set_style(nstyle)
            n.name = name2tax.get(n.name)
        elif n.name in archaea_seqs:
            nstyle = NodeStyle()
            nstyle["fgcolor"] = "green"
            nstyle["size"] = 13
            n.set_style(nstyle)
            n.name = name2tax.get(n.name)
        elif n.name in other_seqs:
            nstyle = NodeStyle()
            nstyle["fgcolor"] = "grey"
            nstyle["size"] = 13
            n.set_style(nstyle)
            n.name = name2tax.get(n.name)
    tree.render(out_tree, tree_style=ts)
Exemplo n.º 4
0
def get_example_tree():
    # Random tree
    t = Tree()
    t = Tree(
        "(((yessefk),(ad, tuɣal),((teqbaylit),(d,(tutlayt,tunṣibt)))),(((win,yebɣan), (taqbaylit)),(((ad,yissin, (tira,-s))))),(((win,yebɣan), (taqbaylit)),(((yugar) , (ucerrig)), (tafawet))));"
    )

    # Some random features in all nodes
    for n in t.traverse():
        n.add_features(weight=random.randint(0, 50))

    # Create an empty TreeStyle
    ts = TreeStyle()

    # Set our custom layout function
    ts.layout_fn = layout

    # Draw a tree
    ts.mode = "c"

    # We will add node names manually
    ts.show_leaf_name = False
    # Show branch data
    ts.show_branch_length = True
    ts.show_branch_support = True

    return t, ts
Exemplo n.º 5
0
def buble_tree():
	built = False
	while not built:
		try:
    
			# Random tree
			t = ncbi.get_topology(idtaxa, intermediate_nodes=True)

			# Some random features in all nodes 
			for node,weigh in zip(t,weighs):

				node.add_features(weight=weigh)

			# Create an empty TreeStyle
			ts = TreeStyle()

			# Set our custom layout function
			ts.layout_fn = layout

			# Draw a tree
			ts.mode = "c"

			# We will add node names manually
			ts.show_leaf_name = True
			# Show branch data
			ts.show_branch_length = True
			ts.show_branch_support = True
				
			return t, ts
			built = True
		except KeyError as e:
			taxid_not_found = int(e.args[0])
			idtaxa.remove(taxid_not_found)
			print("the following IDs were not found in NCBI taxonomy database:" + str(taxid_not_found))
			pass
Exemplo n.º 6
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)
Exemplo n.º 7
0
	def show(self):
		t = Tree(self.newickFormat+";")
		ts = TreeStyle(self.newickFormat+";")
		ts.show_leaf_name = True
		ts.show_branch_length = True
		ts.show_branch_support = True
		t.show(tree_style=ts)
def get_example_tree():
    # Random tree
    t = Tree()
    t.populate(20, random_branches=True)

    # Some random features in all nodes
    for n in t.traverse():
        n.add_features(weight=random.randint(0, 50))

    # Create an empty TreeStyle
    ts = TreeStyle()

    # Set our custom layout function
    ts.layout_fn = layout

    # Draw a tree
    ts.mode = "c"

    # We will add node names manually
    ts.show_leaf_name = False
    # Show branch data
    ts.show_branch_length = True
    ts.show_branch_support = True

    return t, ts
def build_tree(one_tree, confidences):
    # one_tree - egy lista, amely a szekvenciasorozatokat tartalmazza, amiket lépésekben generál
    # confidences - a generálási lépéshez tartozó konfidencia

    confidences = np.insert(confidences, 0, 1.0)
    tree = Tree()
    nodes = {'': [1.0, tree]}
    for idx, seq in enumerate(one_tree):
        parent = ''
        for i in range(len(seq)):
            if not str(seq[:i + 1]) in tree:

                nodes[str(seq[:i + 1])] = []
                nodes[str(seq[:i + 1])].append(confidences[idx] *
                                               nodes[parent][0])
                nodes[str(seq[:i + 1])].append(nodes[parent][1].add_child(
                    name=str(seq), dist=nodes[str(seq[:i + 1])][0]))

            else:
                parent = str(seq[:i + 1])

    ts = TreeStyle()
    ts.show_leaf_name = True
    ts.show_branch_length = True
    ts.show_branch_support = True
    print(tree)

    return tree
def writeTrees(trees, label):
    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")
    #round the branch lengths
    for index, tree in enumerate(trees):
        #print(tree)
        for branch in tree.traverse():
            branch.dist = round(branch.dist)
        line = tree.write(format=1)
        outtrees.write(line + "\n")
        if (showTrees):
            for branch in tree.traverse():
                if branch.dist != 0:
                    text_face = TextFace(str(round(branch.dist, 2)), fsize=30)
                    branch.add_face(text_face, column=1, position="branch-top")
                elif branch.name != "":
                    name_face = AttrFace("name", fsize=30)
                    branch.add_face(name_face,
                                    column=0,
                                    position="branch-right")
                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()
Exemplo n.º 11
0
def get_example_tree():
    # Random tree
    t = Tree(tree)
    t.populate(20, random_branches=True)

    # Some random features in all nodes
    for n in t.traverse():
        n.add_features(weight=random.randint(0, 50))

    # Create an empty TreeStyle
    ts = TreeStyle()

    # Set our custom layout function
    ts.layout_fn = layout

    # Draw a tree
    ts.mode = "c"

    # We will add node names manually
    ts.show_leaf_name = False
    # Show branch data
    ts.show_branch_length = True
    ts.show_branch_support = True

    return t, ts
Exemplo n.º 12
0
def show_GUI_TREE(ETETree):
    ts = TreeStyle()
    ts.show_leaf_name = False
    ts.show_branch_length = False
    ts.show_branch_support = False
    ts.show_border = True

    ETETree.show(tree_style=ts)
Exemplo n.º 13
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)
Exemplo n.º 14
0
def create_tree_style():
    ts = TreeStyle()
    ts.title.add_face(TextFace("Randomly pruned data", fsize=20), column=0)
    ts.layout_fn = remove_blue_dots
    ts.mode = "c"
    ts.show_leaf_name = True
    ts.show_branch_length = True
    ts.show_branch_support = True
    return ts
def tree_style() -> TreeStyle:
    style = TreeStyle()
    style.mode = "c"  # draw tree in circular mode
    # style.scale = 20
    # style.branch_vertical_margin = 15
    style.root_opening_factor = 0.04
    style.show_leaf_name = False
    style.show_branch_length = False
    style.show_branch_support = False
    return style
Exemplo n.º 16
0
def draw(tree):
    string = tree.as_string(schema="newick")
    string = string[4:]
    print(string)
    t = Tree(string)
    ts = TreeStyle()
    ts.show_branch_length = True
    ts.show_branch_support = True
    t.render("mytree.png")
    print('done')
Exemplo n.º 17
0
def balanceplot(balances, tree,
                layout=None,
                mode='c'):
    """ Plots balances on tree.

    Parameters
    ----------
    balances : np.array
        A vector of internal nodes and their associated real-valued balances.
        The order of the balances will be assumed to be in level order.
    tree : skbio.TreeNode
        A strictly bifurcating tree defining a hierarchical relationship
        between all of the features within `table`.
    layout : function, optional
        A layout for formatting the tree visualization. Must take a
        `ete.tree` as a parameter.
    mode : str
        Type of display to show the tree. ('c': circular, 'r': rectangular).

    Note
    ----
    The `tree` is assumed to strictly bifurcating and
    whose tips match `balances.

    See Also
    --------
    TreeNode.levelorder
    """
    # The names aren't preserved - let's pray that the topology is consistent.
    ete_tree = Tree(str(tree))
    # Some random features in all nodes
    i = 0
    for n in ete_tree.traverse():
        if not n.is_leaf():
            n.add_features(weight=balances[-i])
            i += 1

    # Create an empty TreeStyle
    ts = TreeStyle()

    # Set our custom layout function
    if layout is None:
        ts.layout_fn = default_layout
    else:
        ts.layout_fn = layout
    # Draw a tree
    ts.mode = mode

    # We will add node names manually
    ts.show_leaf_name = False
    # Show branch data
    ts.show_branch_length = True
    ts.show_branch_support = True

    return ete_tree, ts
def set_tree_style_extended():
    ts = TreeStyle()
    # for i in range(16):
    #     ts.legend.add_face(CircleFace(10, color_dictionary["N{0}".format(i)]), column=0)

    ts.show_leaf_name = False
    ts.show_branch_length = False
    ts.show_branch_support = False
    ts.layout_fn = my_layout_extended

    return ts
Exemplo n.º 19
0
def CreatePhyloGeneticTree(inputfile, outputfile, size):
    f = open(inputfile, "r")
    data = f.readlines()[0]
    f.close()
    tree = Tree(data)
    tree.set_outgroup(tree.get_midpoint_outgroup())
    ts = TreeStyle()
    ts.show_leaf_name = True
    ts.show_branch_length = False
    ts.show_branch_support = False
    ts.optimal_scale_level = "mid"
    t = tree.render(str(outputfile), w=size, units="px", tree_style=None)
Exemplo n.º 20
0
    def plot_event_tree(self):
        t = Tree("((1:0.001, 0.1:0.23, 0.001, >0.001), NIE);")
        t = Tree(
            "((D: 0.723274, F: 0.567784)1.000000: 0.067192, (B: 0.279326, H: 0.756049)1.000000: 0.807788);"
        )
        t.support = 0.1
        ts = TreeStyle()
        ts.show_leaf_name = True
        ts.show_branch_length = True
        ts.show_branch_support = True

        t.add_face(TextFace(" hola "), column=0, position='branch-right')
        t.show(tree_style=ts)
Exemplo n.º 21
0
def get_style():
	# Create an empty TreeStyle
    ts = TreeStyle()
    # Set our custom layout function
    ts.layout_fn = layout
    # Draw a tree
    ts.mode = "c"
    # We will add node names manually
    ts.show_leaf_name = True
    # Show branch data
    ts.show_branch_length = True
    ts.show_branch_support = True
    return ts
Exemplo n.º 22
0
def create_tree(nwk_file, output_png, readme):
    """
    Create tree image from a nwk file.
    :param nwk_file:
    :param output_png:
    :return:
    """
    nwk = rename_accession_no(nwk_file, readme)
    t = Tree(nwk)
    ts = TreeStyle()
    ts.show_leaf_name = True
    ts.show_branch_length = True
    ts.show_branch_support = True
    t.render(output_png, dpi=150, units='mm', tree_style=ts)
def tree2img(newick_tree, save_path):
    t = Tree(newick_tree, format=1)
    ts = TreeStyle()
    ts.show_leaf_name = False
    ts.show_branch_length = False
    ts.show_branch_support = False
    def my_layout(node):
        F = TextFace(node.name, tight_text=True)
        add_face_to_node(F, node, column=0, position="branch-right")
    ts.layout_fn = my_layout
    ts.branch_vertical_margin = 10
    ts.rotation = 90
    t.render(save_path+'png', tree_style=ts)
    t.render(save_path+'svg', tree_style=ts)
Exemplo n.º 24
0
def set_default_TreeStyle(tree, draw_nodes):
    ts = TreeStyle()
    ts.mode = "c"
    ts.arc_start = -180
    ts.arc_span = 180
    ts.root_opening_factor = 1
    ts.show_branch_length = False
    ts.show_branch_support = True
    ts.force_topology = False
    ts.show_leaf_name = False
    ts.min_leaf_separation = 10
    ts.root_opening_factor = 1
    ts.complete_branch_lines_when_necessary = True

    return ts, tree
def set_tree_style():
    ts = TreeStyle()
    ts.legend.add_face(CircleFace(10, "red"), column=0)
    ts.legend.add_face(CircleFace(10, "lime"), column=0)
    ts.legend.add_face(CircleFace(10, "cyan"), column=0)
    ts.legend.add_face(CircleFace(10, "plum"), column=0)
    ts.legend.add_face(CircleFace(10, "lightsalmon"), column=0)
    ts.legend.add_face(CircleFace(10, "indigo"), column=0)
    ts.legend.add_face(CircleFace(10, "royalblue"), column=0)
    ts.legend.add_face(CircleFace(10, "olive"), column=0)

    ts.show_leaf_name = False
    ts.show_branch_length = False
    ts.show_branch_support = False
    ts.layout_fn = my_layout

    return ts
Exemplo n.º 26
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()
Exemplo n.º 27
0
def my_tree():
    ncbi = NCBITaxa()
    my_tree = ncbi.get_topology([54263, 8324, 8323, 8327, 8325, 57571, 323754])

    for n in my_tree.traverse():
        n.add_features(weight=random.randint(0, 50))

    ts = TreeStyle()

    ts.layout_fn = layout

    ts.mode = "c"

    ts.show_branch_length = True
    ts.show_branch_support = True
    my_tree.get_ascii(attributes=["sci_name", "rank"])
    return my_tree, ts
Exemplo n.º 28
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"
Exemplo n.º 29
0
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)
Exemplo n.º 30
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
Exemplo n.º 31
0
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)
Exemplo n.º 32
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)
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)
Exemplo n.º 34
0
def newick_to_linkage(filePath):
    """ converts newick tree to scipy linkage matrix """
    tree                   = ClusterTree(filePath)
    leaves                 = tree.get_leaf_names()
    ts                     = TreeStyle()
    ts.show_leaf_name      = True
    ts.show_branch_length  = True
    ts.show_branch_support = True

    idx_dict = {}
    idx = 0
    for leaf in leaves:
        idx_dict[leaf] = idx
        idx += 1

    idx_labels = [idx_dict.keys()[idx_dict.values().index(i)] for i in range(len(idx_dict))]

    dmat = np.zeros((len(leaves), len(leaves))) # FIXME need to understand

    for leaf1, leaf2 in combinations(leaves, 2):
        d = tree.get_distance(leaf1, leaf2)
        dmat[idx_dict[leaf1], idx_dict[leaf2]] = dmat[idx_dict[leaf2], idx_dict[leaf1]] = d

    schlink = sch.linkage(scipy.spatial.distance.squareform(dmat),method='average',metric='euclidean')
Exemplo n.º 35
0
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
Exemplo n.º 36
0
def run(args):
    if args.text_mode:
        from ete3 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 ete3 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([int(x*255) for x in 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 = [float(x) if x else None for x in 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)
from ete3 import Tree,TreeStyle,NodeStyle
import os
for tree in [file for file in os.listdir('.') if file and file.endswith('_phyml_tree.txt')]:
    #print tree
    try:
        with open( tree, 'r') as f:  # FIXME boot_trees verus phyml_tree
            t = Tree(open(tree,'r').read())
            ts = TreeStyle()
            ns = NodeStyle()
            ns['size']=0
            ts.show_leaf_name = True
            ts.show_branch_length = False
            ts.show_branch_support = True
            for n in t.traverse():
                n.set_style(ns)
            #t.show(tree_style=ts)
            t.render( os.getcwd()+'/'+tree.replace('_phyml_tree.txt', '.png'),tree_style = ts)
    except:
        pass
Exemplo n.º 38
0
    args, unknown = parser.parse_known_args()
    
    t = Tree(args.i)
    ts = TreeStyle()
    
    if args.colorleaf:
        
        with open(args.colorleaf,'rU') as file_map:
            for line in file_map:
                if line:
                    leaf_color = list(map(str.strip,line.split('\t')))
                    print leaf_color
                    for leaf in t.get_leaves_by_name(leaf_color[0]):
                        leaf.set_style(NodeStyle())
                        
                        if leaf.name == leaf_color[0]:
                            leaf.img_style["bgcolor"] = leaf_color[1]
                        
    ts.show_leaf_name = not args.noleaf
    ts.show_branch_length = not args.nolength
    ts.show_branch_support = not args.nosupport

    if args.circular:
        ts.mode = "c"
        
    ext="svg"
    if args.ext:
       ext = args.ext
       
    t.render(args.o+ext, w=183, tree_style=ts, units="mm")
Exemplo n.º 39
0
"""

from ete3 import Tree, TreeStyle, NodeStyle

with open('/Users/diyadas/cdips/Topic-Ontology/SimpleWikiTree_u.txt','r') as f:
    treestr = f.readlines()[0]    
    

t = Tree( treestr.rstrip(),format=8)

circular_style = TreeStyle()
circular_style.mode = "c" # draw tree in circular mode
circular_style.scale = 120
circular_style.show_leaf_name = True
circular_style.show_branch_length = True
circular_style.show_branch_support = True
t.render("mytree.png", tree_style=circular_style)


nstyle = NodeStyle()
nstyle["hz_line_width"] = 3
nstyle["vt_line_width"] = 3

# Applies the same static style to all nodes in the tree. Note that,
# if "nstyle" is modified, changes will affect to all nodes
for n in t.traverse():
   n.set_style(nstyle)


Exemplo n.º 40
0
node_cur = root

'''#######################
 Tree Style Begin
'''
ts = TreeStyle()
ts.title.add_face(TextFace("Tree example", fsize=8), column=0)
ts.scale = 50
ts.mode = 'r'

# left or right
ts.orientation = 1

ts.rotation = 270
ts.show_leaf_name = False
ts.show_branch_length = True
#ts.show_branch_length = True
'''
 Tree Style End
#######################'''




'''#######################
 Node Style Begin
'''
ns_root = NodeStyle()
ns_root["size"] = 10
ns_root['fgcolor'] = "red"
Exemplo n.º 41
0
def balancetest(table, grouping, tree,
                significance_test=None,
                layout=None,
                normalize=True,
                mode='c'):
    """ Performs statistical test on ilr balances and plots on tree.

    Parameters
    ----------
    table : pd.DataFrame
        A 2D matrix of strictly positive values (i.e. counts or proportions)
        where the rows correspond to samples and the columns correspond to
        features.
    grouping : pd.Series
        Vector indicating the assignment of samples to groups.  For example,
        these could be strings or integers denoting which group a sample
        belongs to.  It must be the same length as the samples in `table`.
        The index must be the same on `table` and `grouping` but need not be
        in the same order.
    tree : skbio.TreeNode
        A strictly bifurcating tree defining a hierarchical relationship
        between all of the features within `table`
    significance_test : function, optional
        A statistical significance function to test for significance between
        classes.  This function must be able to accept at least two 1D
        array_like arguments of floats and returns a test statistic and a
        p-value, or a single statistic. By default ``scipy.stats.f_oneway``
        is used.
    layout : function, optional
        A layout for formatting the tree visualization. Must take a
        `ete.tree` as a parameter.
    mode : str
        Type of display to show the tree. ('c': circular, 'r': rectangular).

    Returns
    -------
    ete_tree : ete.Tree
        ETE tree converted from the `skbio.TreeNode` object
    ts : ete.TreeStyle
        ETE tree style used for formatting the visualized tree,
        with the test statistic plotted on each of the internal nodes.

    Note
    ----
    The `skbio.TreeNode` is assumed to strictly bifurcating and
    whose tips match `table`.  Also, it is assumed that none
    of the values in `table` are zero.  Replace with a pseudocount
    if necessary.

    See also
    --------
    skbio.TreeNode.bifurcate
    skbio.stats.composition.ilr
    skbio.stats.multiplicative_replacement
    scipy.stats.f_oneway
    """

    if np.any(table <= 0):
        raise ValueError('Cannot handle zeros or negative values in `table`. '
                         'Use pseudo counts or ``multiplicative_replacement``.'
                         )

    if significance_test is None:
        significance_test = scipy.stats.f_oneway

    sorted_features = [n.name for n in tree.tips()][::-1]
    if len(sorted_features) != len(table.columns):
        raise ValueError('The number of tips (%d) in the tree must be equal '
                         'to the number features in the table (%d).' %
                         (len(sorted_features), len(table.columns)))
    table = table.reindex(columns=sorted_features)

    mat, cats = check_table_grouping(table, grouping)

    basis, nodes = phylogenetic_basis(tree)
    ilr_coords = ilr(mat, basis=basis)

    ete_tree = Tree(str(tree))

    _cats = set(cats)
    i = 0
    for n in ete_tree.traverse():
        if not n.is_leaf():
            diffs = [ilr_coords[(cats == x).values, i] for x in _cats]

            stat = significance_test(*diffs)
            if len(stat) == 2:
                n.add_features(weight=-np.log(stat[1]))
            elif len(stat) == 1:
                n.add_features(weight=stat)
            else:
                raise ValueError(
                    "Too many arguments returned by %s" %
                    significance_test.__name__)
            i += 1

    # Create an empty TreeStyle
    ts = TreeStyle()

    # Set our custom layout function
    if layout is None:
        ts.layout_fn = default_layout
    else:
        ts.layout_fn = layout

    # Draw a tree
    ts.mode = mode

    # We will add node names manually
    ts.show_leaf_name = False
    # Show branch data
    ts.show_branch_length = True
    ts.show_branch_support = True

    return ete_tree, ts