Exemple #1
0
def my_layout(node):
    if getattr(node, "rank", None):
        rank_face = AttrFace("rank", fsize=7, fgcolor="indianred")
        node.add_face(rank_face, column=0, position="branch-top")
    if node.is_leaf():
        sciname_face = AttrFace("sci_name", fsize=9, fgcolor="steelblue")
        node.add_face(sciname_face, column=0, position="branch-right")
def layout(node):
    if node.is_leaf():
        
        #######################################################
        #~ Taxon Label Size and Margin Adjustment
        N = AttrFace("name", fsize=1200,fgcolor="#000000")
        N.margin_top = 250
        N.margin_right = 100 #outside
        N.margin_left = 1000 #inside
        N.margin_bottom = 250
        #######################################################
        
        #######################################################
        #~ Taxon Label Background Color Setting
        tmp = "<myTaxaonLabel>" 
        #~ if not(node.name.find(tmp)) : N.background.color="#FF9999"
        #######################################################
        
        faces.add_face_to_node(N, node, 0, position="aligned")

    if (not node.is_leaf()) :
        S=faces.AttrFace("support", fsize=200, fgcolor="#000000")
        S.margin_top = 20
        S.margin_right = 10
        S.margin_left = 20
        S.margin_bottom = 20
        faces.add_face_to_node( S, node, column=0 , position = "float")
        if "support" in node.features:
        # Creates a sphere face whose size is proportional to node's
        # feature "weight"
            C = CircleFace(radius=node.support*20, color="RoyalBlue", style="sphere")
        # Let's make the sphere transparent 
            C.opacity = 0.3
        # And place as a float face over the tree
            faces.add_face_to_node(C, node, position="float",column=1)
    style = NodeStyle()
    style["size"] = 0
    style["vt_line_width"] = 150
    style["hz_line_width"] = 150
    style["vt_line_type"] = 0 # 0 solid, 1 dashed, 2 dotted
    style["hz_line_type"] = 0
    node.set_style(style)

    bgcol1="#FFCCCC"
    bgcol2="#FFE5CC"
    bgcol3="#FFFFCC"
    bgcol4="#E5FFCC"
    bgcol5="#CCFFCC"
    bgcol6="#CCFFE5"
    bgcol7="#FFCCE5"
    bgcol8="#CCFFFF"
    bgcol9="#CCE5FF"
    bgcol10="#CCCCFF"
    bgcol11="#E5CCFF"
Exemple #3
0
def layout(node):
    if node.up is not None:
        attr = AttrFace("expansion", fsize=7, fgcolor="green", text_prefix="+")
        faces.add_face_to_node(attr, node, 0, position="branch-top")
        attr = AttrFace("decrease", fsize=7, fgcolor="red", text_prefix="-")
        faces.add_face_to_node(attr, node, 0, position="branch-bottom")
    if node.is_leaf():
        attr = AttrFace("name",
                        fsize=10,
                        fgcolor="black",
                        text_prefix="  ",
                        fstyle="italic")
        faces.add_face_to_node(attr, node, 0, position="aligned")
    def layout(node):
        # print node.rank
        # print node.sci_name
        if getattr(node, "rank", None):
            if (node.rank in ['order', 'class', 'phylum', 'kingdom']):
                rank_face = AttrFace("sci_name", fsize=7, fgcolor="indianred")
                node.add_face(rank_face, column=0, position="branch-top")
        if node.is_leaf():
            sciname_face = AttrFace("sci_name", fsize=9, fgcolor="steelblue")
            node.add_face(sciname_face, column=0, position="branch-right")
        if node.is_leaf() and not node.name == 'annotation':
            s = str(msa_dict[str(taxid2gi[int(node.name)])])
            seqFace = SeqMotifFace(
                s, [[0, len(s), "seq", 10, 10, None, None, None]],
                scale_factor=1)
            add_face_to_node(seqFace, node, 0, position="aligned")
            gi = taxid2gi[int(node.name)]
            add_face_to_node(TextFace(' ' + str(gi) + ' '),
                             node,
                             column=1,
                             position="aligned")
            add_face_to_node(TextFace('      ' + str(int(node.name)) + ' '),
                             node,
                             column=2,
                             position="aligned")
            add_face_to_node(TextFace('      ' + str(gi2variant[gi]) + ' '),
                             node,
                             column=3,
                             position="aligned")

        if node.is_leaf() and node.name == 'annotation':
            s = get_hist_ss_in_aln_as_string(msa_tr)
            seqFace = SeqMotifFace(
                s, [[0, len(s), "seq", 10, 10, None, None, None]],
                scale_factor=1)
            add_face_to_node(seqFace, node, 0, position="aligned")
            add_face_to_node(TextFace(' ' + 'NCBI_GI' + ' '),
                             node,
                             column=1,
                             position="aligned")
            add_face_to_node(TextFace('       ' + 'NCBI_TAXID' + ' '),
                             node,
                             column=2,
                             position="aligned")
            add_face_to_node(TextFace('       ' + 'Variant' + '       '),
                             node,
                             column=3,
                             position="aligned")
Exemple #5
0
 def layout(node):
     #print(node)
     if node.is_leaf():
         if node.name in x_file_names:
             #make reconstructed bubble
             size = x[x_file_names.index(node.name)]
             F = CircleFace(radius=500 * math.sqrt(size),
                            color="RoyalBlue",
                            style="sphere")
             F.border.width = None
             F.opacity = 0.6
             faces.add_face_to_node(F, node, 0, position="branch-right")
             if taxonomic_names_on_leaves:
                 nameFace = AttrFace(
                     "name",
                     fsize=25,
                     fgcolor='black',
                     text_suffix="_" +
                     taxonomy[x_file_names.index(node.name)])
                 faces.add_face_to_node(nameFace,
                                        node,
                                        0,
                                        position="branch-right")
             else:
                 nameFace = AttrFace("name", fsize=25, fgcolor='black')
                 faces.add_face_to_node(nameFace,
                                        node,
                                        0,
                                        position="branch-right")
     elif node.name in hyp_node_names:  #Otherwise it's a hypothetical node, just use recon x
         node_base_name = hyp_node_names[node.name][0]
         percent = hyp_node_names[node.name][1]
         if node_base_name in x_file_names:
             idx = hyp_node_names[node.name][2]
             size = x[x_file_names.index(node_base_name) +
                      (idx + 1) * len(x_file_names)]
             F = CircleFace(radius=500 * math.sqrt(size),
                            color="RoyalBlue",
                            style="sphere")
             F.border.width = None
             F.opacity = 0.6
             faces.add_face_to_node(F, node, 0, position="branch-right")
             #print node
             #print size
         else:
             size = 0
     else:
         size = 0
Exemple #6
0
def print_colored_host_tree(host_tree_fp, host_colors, output_fp, treefmt=5):
    with open(host_tree_fp) as tree_f:
        treestring = remove_newick_node_labels(tree_f.readline().strip())

    tree = Tree(newick=treestring, format=treefmt)

    for host in host_colors:
        if tree.get_leaves_by_name(host) == []:
            tip = "'%s'" % host
        else:
            tip = host

        node = tree.get_leaves_by_name(tip)[0]

        node.add_face(AttrFace("name", fsize=14, fgcolor=host_colors[host]), 0)

    # remove stupid blue circles on nodes
    style = NodeStyle()
    style["size"] = 0
    for l in tree.traverse():
        l.set_style(style)

    # get rid of default rendered leaf labels
    ts = TreeStyle()
    ts.show_leaf_name = False

    tree.render(output_fp, tree_style=ts)

    return
Exemple #7
0
def print_colored_host_tree(host_tree_fp, host_colors, output_fp):
    tree = Tree(host_tree_fp)

    for host in host_colors:
        if tree.get_leaves_by_name(host) == []:
            tip = "'%s'" % host
        else:
            tip = host

        node = tree.get_leaves_by_name(tip)[0]

        node.add_face(AttrFace("name", fsize=14, fgcolor=host_colors[host]), 0)

    # remove stupid blue circles on nodes
    style = NodeStyle()
    style["size"] = 0
    for l in tree.traverse():
        l.set_style(style)

    # get rid of default rendered leaf labels
    ts = TreeStyle()
    ts.show_leaf_name = False

    tree.render(output_fp, tree_style=ts)

    return
Exemple #8
0
def my_layout(node):
    from ete2 import AttrFace, faces
    if node.is_leaf():
        faces.add_face_to_node(AttrFace("name"), node, column=0, position="aligned")
    else:
        node.img_style["size"] = 0
        node.img_style["fgcolor"] = "#000000"
Exemple #9
0
 def layout(node):
     if node.is_leaf():
         N = AttrFace("name", fsize=7)
         faces.add_face_to_node(faces.AttrFace("name", "Arial", 10, None),
                                node,
                                0,
                                position='branch-right')
Exemple #10
0
def my_layout(node):
    if node.name != "43":
        print node.name
        if node.is_leaf():
            # If terminal node, draws its name
            name_face = AttrFace("species", fsize=16)
            pie = PieChartFace([changes[node.name][0], changes[node.name][1]],
                               changes[node.name][2], changes[node.name][2],
                               ["Green", "Red"])
            pie.opacity = 0.5
            #name_face = AttrFace("name", fsize=16)
            faces.add_face_to_node(name_face,
                                   node,
                                   column=0,
                                   position="branch-right")
            faces.add_face_to_node(pie, node, column=0, position="float")
        else:
            # If internal node, draws label with smaller font size
            #name_face = AttrFace("name", fsize=10)
            pie = PieChartFace([changes[node.name][0], changes[node.name][1]],
                               changes[node.name][2], changes[node.name][2],
                               ["Green", "Red"])
            pie.opacity = 0.5
            #faces.add_face_to_node(name_face, node, column=0, position="branch-right")
            faces.add_face_to_node(pie, node, column=0, position="float")
Exemple #11
0
def layout_simple(node):
    if node.is_leaf():
        attr = AttrFace("name",
                        fsize=10,
                        fgcolor="black",
                        text_prefix="  ",
                        fstyle="italic")
        faces.add_face_to_node(attr, node, 0, position="aligned")
Exemple #12
0
def layout(node):
    if node.is_leaf():
        N = AttrFace("name", fsize=14, fgcolor="black")
        faces.add_face_to_node(N, node, 0)
        small_tree = small_d[node.name]
        T = TreeFace(small_tree, small_ts)
        T.opacity = 0.8
        # And place as a float face over the tree
        faces.add_face_to_node(T, node, 1, position="aligned")
def layout(node):
    if node.is_leaf():

        #######################################################
        #~ Taxon Label Size and Margin Adjustment
        N = AttrFace("name", fsize=1200, fgcolor="#000000")
        N.margin_top = 250
        N.margin_right = 100  #outside
        N.margin_left = 1000  #inside
        N.margin_bottom = 250
        #######################################################

        #######################################################
        #~ Taxon Label Background Color Setting
        tmp = "<myTaxaonLabel>"
        #~ if not(node.name.find(tmp)) : N.background.color="#FF9999"
        #######################################################

        faces.add_face_to_node(N, node, 0, position="aligned")

    if (not node.is_leaf()):
        S = faces.AttrFace("support", fsize=200, fgcolor="#000000")
        S.margin_top = 20
        S.margin_right = 10
        S.margin_left = 20
        S.margin_bottom = 20
        faces.add_face_to_node(S, node, column=0, position="float")
        if "support" in node.features:
            # Creates a sphere face whose size is proportional to node's
            # feature "weight"
            C = CircleFace(radius=node.support * 20,
                           color="RoyalBlue",
                           style="sphere")
            # Let's make the sphere transparent
            C.opacity = 0.3
            # And place as a float face over the tree
            faces.add_face_to_node(C, node, position="float", column=1)
    style = NodeStyle()
    style["size"] = 0
    style["vt_line_width"] = 150
    style["hz_line_width"] = 150
    style["vt_line_type"] = 0  # 0 solid, 1 dashed, 2 dotted
    style["hz_line_type"] = 0
    node.set_style(style)

    bgcol1 = "#FFCCCC"
    bgcol2 = "#FFE5CC"
    bgcol3 = "#FFFFCC"
    bgcol4 = "#E5FFCC"
    bgcol5 = "#CCFFCC"
    bgcol6 = "#CCFFE5"
    bgcol7 = "#FFCCE5"
    bgcol8 = "#CCFFFF"
    bgcol9 = "#CCE5FF"
    bgcol10 = "#CCCCFF"
    bgcol11 = "#E5CCFF"
Exemple #14
0
def my_layout(node):

	style2 = NodeStyle()
	style2["fgcolor"] = "#000000"
	style2["shape"] = "circle"
	# style2["vt_line_color"] = "#0000aa"
	# style2["hz_line_color"] = "#0000aa"
	# style2["vt_line_width"] = 2
	# style2["hz_line_width"] = 2
	# style2["vt_line_type"] = 1 # 0 solid, 1 dashed, 2 dotted
	# style2["hz_line_type"] = 1
	node.img_style = style2
 	node.img_style["bgcolor"] = "LightSteelBlue"

	if node.is_leaf():
		# If terminal node, draws its name
		# name_faces = AttrFace("name")
		node.img_style["size"] = 40
		# node.img_style["shape"] = "sphere"
		node.img_style["fgcolor"] = "#FFFFFF"
		# node.img_style["fgcolor"] = "#9db0cf"
		# node.img_style["bgcolor"] = "#9db0cf"
		# node.img_style["faces_bgcolor"] = "#9db0cf"
		# node.img_style["bgcolor"] = "#9db0cf"
		# node.img_style["bgcolor"] = "#9db0cf"
		pass
	else:
		# If internal node, draws label with smaller font size
		# name_faces = AttrFace("name", fsize=15)
		# Adds the name face to the image at the preferred position
		# faces.add_face_to_node(name_faces, node, column=0, position="branch-top")
		# tempo = faces.ImgFace(plot_folder + "/" + node.name + '.jpg')
		# faces.add_face_to_node(tempo, node, column=0, position="branch-bottom")
		node.img_style["size"] = 40
		node.img_style["shape"] = "sphere"
		node.img_style["fgcolor"] = "#FFFFFF"

	tempt = AttrFace('name', fsize=80)
	tempt.fgcolor = "Black"
	tempt.margin_top = 10
	tempt.margin_right = 10
	tempt.margin_left = 10
	tempt.margin_bottom = 10
	tempt.opacity = 0.5 # from 0 to 1
	tempt.inner_border.width = 1 # 1 pixel border
	tempt.inner_border.type = 1  # dashed line
	tempt.border.width = 1
	# tempt.background.color = "LightGreen"
	# tempt.penwidth = 40
	node.add_face(tempt, column=0, position="branch-top")
 def layout(node):
     node_style = NodeStyle()
     node_style["hz_line_width"] = 10
     node_style["vt_line_width"] = 10
     node.set_style(node_style)
     #print(node)
     if node.is_leaf():
         if node.name in org_names:
             #make reconstructed bubble
             size = x[org_names.index(node.name)]
             F = CircleFace(radius=size_factor * math.sqrt(size),
                            color="RoyalBlue",
                            style="sphere")
             F.border.width = None
             F.opacity = 0.6
             faces.add_face_to_node(F, node, 0, position="branch-right")
             #Denote that this was a training organism
             nameFace = AttrFace("name", fsize=font_size, fgcolor='black')
             faces.add_face_to_node(nameFace,
                                    node,
                                    0,
                                    position="branch-right")
     elif node.name in hyp_node_names:  #Otherwise it's a hypothetical node, just use recon x
         node_base_name = hyp_node_names[node.name][0]
         percent = hyp_node_names[node.name][1]
         if node_base_name in org_names:
             idx = hyp_node_names[node.name][2]
             size = x[org_names.index(node_base_name) +
                      (idx + 1) * len(org_names)]
             F = CircleFace(radius=size_factor * math.sqrt(size),
                            color="RoyalBlue",
                            style="sphere")
             F.border.width = None
             F.opacity = 0.6
             faces.add_face_to_node(F, node, 0, position="branch-right")
             #This is if I want the names of the hypothetical nodes to be printed as well
             #nameFace = AttrFace("name", fsize=font_size, fgcolor='black')
             #faces.add_face_to_node(nameFace, node, 0, position="branch-right")
         else:
             size = 0
     else:
         size = 0
    def __layout__(self, node):
        if node.is_leaf():
            # Add node name to laef nodes
            N = AttrFace("name", fsize=14, fgcolor="black")
            faces.add_face_to_node(N, node, 0)
            nstyle = NodeStyle()

            nstyle["size"] = 0
            node.set_style(nstyle)
        if "internalCount" in node.features:
            print node.name
            # Creates a sphere face whose size is proportional to node's
            # feature "weight"
            C = CircleFace(radius=int(node.internalCount) / 10,
                           color="RoyalBlue",
                           style="sphere")
            T = TextFace("10")
            # Let's make the sphere transparent
            C.opacity = 0.3
            # And place as a float face over the tree
            faces.add_face_to_node(C, node, 0, position="float")
            faces.add_face_to_node(T, node, 1)
Exemple #17
0
def layout(node):
    if node.is_leaf():
        # Add node name to leaf nodes
        N = AttrFace("name", fsize=14, fgcolor=node.tip_color)
        faces.add_face_to_node(N, node, 0)
Exemple #18
0
 def layout(node, feature):
     if node.up is not None or feature == "id":
         attr = AttrFace(feature, fsize=5, fgcolor="green")
         faces.add_face_to_node(attr, node, 0, position="branch-top")
Exemple #19
0
def draw_tree(tree, conf, outfile):
    try:
        from ete2 import (add_face_to_node, AttrFace, TextFace, TreeStyle,
                          RectFace, CircleFace, SequenceFace, random_color,
                          SeqMotifFace)
    except ImportError as e:
        print e
        return

    def ly_basic(node):
        if node.is_leaf():
            node.img_style['size'] = 0
        else:
            node.img_style['size'] = 0
            node.img_style['shape'] = 'square'
            if len(MIXED_RES) > 1 and hasattr(node, "tree_seqtype"):
                if node.tree_seqtype == "nt":
                    node.img_style["bgcolor"] = "#CFE6CA"
                    ntF = TextFace("nt",
                                   fsize=6,
                                   fgcolor='#444',
                                   ftype='Helvetica')
                    add_face_to_node(ntF, node, 10, position="branch-bottom")
            if len(NPR_TREES) > 1 and hasattr(node, "tree_type"):
                node.img_style['size'] = 4
                node.img_style['fgcolor'] = "steelblue"

        node.img_style['hz_line_width'] = 1
        node.img_style['vt_line_width'] = 1

    def ly_leaf_names(node):
        if node.is_leaf():
            spF = TextFace(node.species,
                           fsize=10,
                           fgcolor='#444444',
                           fstyle='italic',
                           ftype='Helvetica')
            add_face_to_node(spF, node, column=0, position='branch-right')
            if hasattr(node, 'genename'):
                geneF = TextFace(" (%s)" % node.genename,
                                 fsize=8,
                                 fgcolor='#777777',
                                 ftype='Helvetica')
                add_face_to_node(geneF,
                                 node,
                                 column=1,
                                 position='branch-right')

    def ly_supports(node):
        if not node.is_leaf() and node.up:
            supFace = TextFace("%0.2g" % (node.support),
                               fsize=7,
                               fgcolor='indianred')
            add_face_to_node(supFace, node, column=0, position='branch-top')

    def ly_tax_labels(node):
        if node.is_leaf():
            c = LABEL_START_COL
            largest = 0
            for tname in TRACKED_CLADES:
                if hasattr(node,
                           "named_lineage") and tname in node.named_lineage:
                    linF = TextFace(tname, fsize=10, fgcolor='white')
                    linF.margin_left = 3
                    linF.margin_right = 2
                    linF.background.color = lin2color[tname]
                    add_face_to_node(linF, node, c, position='aligned')
                    c += 1

            for n in xrange(c, len(TRACKED_CLADES)):
                add_face_to_node(TextFace('', fsize=10, fgcolor='slategrey'),
                                 node,
                                 c,
                                 position='aligned')
                c += 1

    def ly_full_alg(node):
        pass

    def ly_block_alg(node):
        if node.is_leaf():
            if 'sequence' in node.features:
                seqFace = SeqMotifFace(node.sequence, [])
                # [10, 100, "[]", None, 10, "black", "rgradient:blue", "arial|8|white|domain Name"],
                motifs = []
                last_lt = None
                for c, lt in enumerate(node.sequence):
                    if lt != '-':
                        if last_lt is None:
                            last_lt = c
                        if c + 1 == len(node.sequence):
                            start, end = last_lt, c
                            motifs.append([
                                start, end, "()", 0, 12, "slategrey",
                                "slategrey", None
                            ])
                            last_lt = None
                    elif lt == '-':
                        if last_lt is not None:
                            start, end = last_lt, c - 1
                            motifs.append([
                                start, end, "()", 0, 12, "grey", "slategrey",
                                None
                            ])
                            last_lt = None

                seqFace = SeqMotifFace(node.sequence,
                                       motifs,
                                       intermotif_format="line",
                                       seqtail_format="line",
                                       scale_factor=ALG_SCALE)
                add_face_to_node(seqFace, node, ALG_START_COL, aligned=True)

    TRACKED_CLADES = [
        "Eukaryota",
        "Viridiplantae",
        "Fungi",
        "Alveolata",
        "Metazoa",
        "Stramenopiles",
        "Rhodophyta",
        "Amoebozoa",
        "Crypthophyta",
        "Bacteria",
        "Alphaproteobacteria",
        "Betaproteobacteria",
        "Cyanobacteria",
        "Gammaproteobacteria",
    ]

    # ["Opisthokonta",  "Apicomplexa"]

    colors = random_color(num=len(TRACKED_CLADES), s=0.45)
    lin2color = dict([(ln, colors[i]) for i, ln in enumerate(TRACKED_CLADES)])

    NAME_FACE = AttrFace('name', fsize=10, fgcolor='#444444')

    LABEL_START_COL = 10
    ALG_START_COL = 40
    ts = TreeStyle()
    ts.draw_aligned_faces_as_table = False
    ts.draw_guiding_lines = False
    ts.show_leaf_name = False
    ts.show_branch_support = False
    ts.scale = 160

    ts.layout_fn = [ly_basic, ly_leaf_names, ly_supports, ly_tax_labels]

    MIXED_RES = set()
    MAX_SEQ_LEN = 0
    NPR_TREES = []
    for n in tree.traverse():
        if hasattr(n, "tree_seqtype"):
            MIXED_RES.add(n.tree_seqtype)
        if hasattr(n, "tree_type"):
            NPR_TREES.append(n.tree_type)
        seq = getattr(n, "sequence", "")
        MAX_SEQ_LEN = max(len(seq), MAX_SEQ_LEN)

    if MAX_SEQ_LEN:
        ALG_SCALE = min(1, 1000. / MAX_SEQ_LEN)
        ts.layout_fn.append(ly_block_alg)

    if len(NPR_TREES) > 1:
        rF = RectFace(4, 4, "steelblue", "steelblue")
        rF.margin_right = 10
        rF.margin_left = 10
        ts.legend.add_face(rF, 0)
        ts.legend.add_face(TextFace(" NPR node"), 1)
        ts.legend_position = 3

    if len(MIXED_RES) > 1:
        rF = RectFace(20, 20, "#CFE6CA", "#CFE6CA")
        rF.margin_right = 10
        rF.margin_left = 10
        ts.legend.add_face(rF, 0)
        ts.legend.add_face(TextFace(" Nucleotide based alignment"), 1)
        ts.legend_position = 3

    try:
        tree.set_species_naming_function(spname)
        annotate_tree_with_ncbi(tree)
        a = tree.search_nodes(species='Dictyostelium discoideum')[0]
        b = tree.search_nodes(species='Chondrus crispus')[0]
        #out = tree.get_common_ancestor([a, b])
        #out = tree.search_nodes(species='Haemophilus parahaemolyticus')[0].up
        tree.set_outgroup(out)
        tree.swap_children()
    except Exception:
        pass

    tree.render(outfile, tree_style=ts, w=170, units='mm', dpi=150)
    tree.render(outfile + '.svg', tree_style=ts, w=170, units='mm', dpi=150)
    tree.render(outfile + '.pdf', tree_style=ts, w=170, units='mm', dpi=150)
Exemple #20
0
    def createLineageTrees(self, fn=None, width=None, height=None, circular=False, withAppearing=True, from_t=0, to_t=0):
        from ete2 import Tree, NodeStyle, AttrFace
        
        tree = Tree()        
        style = self.getNodeStyle()
        divisionStyle = self.getNodeStyle()
        
        invisibleNodeStyle = NodeStyle()
        invisibleNodeStyle["hz_line_color"] = "white"
        invisibleNodeStyle["vt_line_color"] = "white"
        invisibleNodeStyle["fgcolor"] = "white"
        
        distanceFromRoot = 0
        
        nodeMap = {}
        branchSize = {}
        
        # add all nodes which appear in the first frame
        for event in self.mainOperator.innerOperators[0].events[from_t]:
            if event.type != pgmlink.EventType.Appearance:
                label = event.traxel_ids[0]
                appNode = tree.add_child(name=self.getNodeName(0, label), dist=distanceFromRoot )
                nodeMap[str(self.getNodeName(0, label))] = appNode
                branchSize[str(self.getNodeName(0, label))] = 0                    
                # making the branches to the root node invisible
                n = appNode
                while n:
                    n.set_style(invisibleNodeStyle)
                    n = n.up
                appNode.set_style(invisibleNodeStyle)
                name = AttrFace("name")
                name.fsize = 6
        
        # add all lineages
        for t, events_at in enumerate(self.mainOperator.innerOperators[0].events[from_t:to_t+1]):
            t = t+1            
            for event in events_at:
                if event.type == pgmlink.EventType.Appearance and withAppearing:
                    label = event.traxel_ids[0]
                    appNode = tree.add_child(name=self.getNodeName(t, label), dist=distanceFromRoot + t)
                    nodeMap[str(self.getNodeName(t, label))] = appNode
                    branchSize[str(self.getNodeName(t, label))] = 0                    
                    # making the branches to the root node invisible
                    n = appNode
                    while n:
                        n.set_style(invisibleNodeStyle)
                        n = n.up
                    appNode.set_style(invisibleNodeStyle)
                    name = AttrFace("name")
                    name.fsize = 6

                elif event.type == pgmlink.EventType.Disappearance:
                    label = event.traxel_ids[0]
                    if str(self.getNodeName(t-1,str(label))) not in nodeMap.keys():
                        continue
                    if branchSize[str(self.getNodeName(t-1,str(label)))] == 0:
                        del nodeMap[str(self.getNodeName(t-1,str(label)))]
                        del branchSize[str(self.getNodeName(t-1,str(label)))]
                        continue
                    newNode = nodeMap[str(self.getNodeName(t-1,str(label)))].add_child(
                        name = self.getNodeName(t-1,str(label)),dist = branchSize[str(self.getNodeName(t-1,str(label)))])                     
                    newNode.set_style(style)
                    del nodeMap[str(self.getNodeName(t-1,str(label)))]
                    del branchSize[str(self.getNodeName(t-1,str(label)))]
                    
                elif event.type == pgmlink.EventType.Division:
                    labelOld = event.traxel_ids[0]
                    labelNew1 = event.traxel_ids[1]
                    labelNew2 = event.traxel_ids[2]                    
                    if str(self.getNodeName(t-1,str(labelOld))) not in nodeMap.keys():
                        continue
                    newNode = nodeMap[str(self.getNodeName(t-1,str(labelOld)))].add_child(
                            name = self.getNodeName(t-1,str(self.getNodeName(t-1,str(labelOld)))),
                            dist = branchSize[str(self.getNodeName(t-1,str(labelOld)))] )
                    del nodeMap[str(self.getNodeName(t-1,str(labelOld)))]
                    del branchSize[str(self.getNodeName(t-1,str(labelOld)))]
                    newNode.set_style(divisionStyle)
                    nodeMap[str(self.getNodeName(t,str(labelNew1)))] = newNode
                    nodeMap[str(self.getNodeName(t,str(labelNew2)))] = newNode
                    branchSize[str(self.getNodeName(t,str(labelNew1)))] = 1
                    branchSize[str(self.getNodeName(t,str(labelNew2)))] = 1                    
                    
                elif event.type == pgmlink.EventType.Move:
                    labelOld = event.traxel_ids[0]
                    labelNew = event.traxel_ids[1]
                    if str(self.getNodeName(t-1,str(labelOld))) not in nodeMap.keys():
                        continue
                    nodeMap[str(self.getNodeName(t,str(labelNew)))] = nodeMap[str(self.getNodeName(t-1,str(labelOld)))]
                    del nodeMap[str(self.getNodeName(t-1,str(labelOld)))]
                    branchSize[str(self.getNodeName(t,str(labelNew)))] = branchSize[str(self.getNodeName(t-1,str(labelOld)))] + 1 
                    del branchSize[str(self.getNodeName(t-1,str(labelOld)))]
                
                else:
                    raise Exception, "lineage tree generation not implemented for event type " + str(event.type)

        for label in nodeMap.keys():            
            newNode = nodeMap[label].add_child(name = label,dist = branchSize[label])
        
        self.plotTree(tree, out_fn=fn, rotation=270, show_leaf_name=False, 
                  show_branch_length=False, circularTree=circular, show_division_nodes=False, 
                  distance_between_branches=4, width=width, height=height)
    def createLineageTrees(self,
                           fn=None,
                           width=None,
                           height=None,
                           circular=False,
                           withAppearing=True,
                           from_t=0,
                           to_t=0):
        from ete2 import Tree, NodeStyle, AttrFace

        tree = Tree()
        style = self.getNodeStyle()
        divisionStyle = self.getNodeStyle()

        invisibleNodeStyle = NodeStyle()
        invisibleNodeStyle["hz_line_color"] = "white"
        invisibleNodeStyle["vt_line_color"] = "white"
        invisibleNodeStyle["fgcolor"] = "white"

        distanceFromRoot = 0

        nodeMap = {}
        branchSize = {}

        # add all nodes which appear in the first frame
        for event in self.mainOperator.innerOperators[0].events[from_t]:
            if event.type != pgmlink.EventType.Appearance:
                label = event.traxel_ids[0]
                appNode = tree.add_child(name=self.getNodeName(0, label),
                                         dist=distanceFromRoot)
                nodeMap[str(self.getNodeName(0, label))] = appNode
                branchSize[str(self.getNodeName(0, label))] = 0
                # making the branches to the root node invisible
                n = appNode
                while n:
                    n.set_style(invisibleNodeStyle)
                    n = n.up
                appNode.set_style(invisibleNodeStyle)
                name = AttrFace("name")
                name.fsize = 6

        # add all lineages
        for t, events_at in enumerate(
                self.mainOperator.innerOperators[0].events[from_t:to_t + 1]):
            t = t + 1
            for event in events_at:
                if event.type == pgmlink.EventType.Appearance and withAppearing:
                    label = event.traxel_ids[0]
                    appNode = tree.add_child(name=self.getNodeName(t, label),
                                             dist=distanceFromRoot + t)
                    nodeMap[str(self.getNodeName(t, label))] = appNode
                    branchSize[str(self.getNodeName(t, label))] = 0
                    # making the branches to the root node invisible
                    n = appNode
                    while n:
                        n.set_style(invisibleNodeStyle)
                        n = n.up
                    appNode.set_style(invisibleNodeStyle)
                    name = AttrFace("name")
                    name.fsize = 6

                elif event.type == pgmlink.EventType.Disappearance:
                    label = event.traxel_ids[0]
                    if str(self.getNodeName(t - 1,
                                            str(label))) not in nodeMap.keys():
                        continue
                    if branchSize[str(self.getNodeName(t - 1,
                                                       str(label)))] == 0:
                        del nodeMap[str(self.getNodeName(t - 1, str(label)))]
                        del branchSize[str(self.getNodeName(t - 1,
                                                            str(label)))]
                        continue
                    newNode = nodeMap[str(self.getNodeName(
                        t - 1, str(label)))].add_child(
                            name=self.getNodeName(t - 1, str(label)),
                            dist=branchSize[str(
                                self.getNodeName(t - 1, str(label)))])
                    newNode.set_style(style)
                    del nodeMap[str(self.getNodeName(t - 1, str(label)))]
                    del branchSize[str(self.getNodeName(t - 1, str(label)))]

                elif event.type == pgmlink.EventType.Division:
                    labelOld = event.traxel_ids[0]
                    labelNew1 = event.traxel_ids[1]
                    labelNew2 = event.traxel_ids[2]
                    if str(self.getNodeName(
                            t - 1, str(labelOld))) not in nodeMap.keys():
                        continue
                    newNode = nodeMap[str(
                        self.getNodeName(t - 1, str(labelOld)))].add_child(
                            name=self.getNodeName(
                                t - 1,
                                str(self.getNodeName(t - 1, str(labelOld)))),
                            dist=branchSize[str(
                                self.getNodeName(t - 1, str(labelOld)))])
                    del nodeMap[str(self.getNodeName(t - 1, str(labelOld)))]
                    del branchSize[str(self.getNodeName(t - 1, str(labelOld)))]
                    newNode.set_style(divisionStyle)
                    nodeMap[str(self.getNodeName(t, str(labelNew1)))] = newNode
                    nodeMap[str(self.getNodeName(t, str(labelNew2)))] = newNode
                    branchSize[str(self.getNodeName(t, str(labelNew1)))] = 1
                    branchSize[str(self.getNodeName(t, str(labelNew2)))] = 1

                elif event.type == pgmlink.EventType.Move:
                    labelOld = event.traxel_ids[0]
                    labelNew = event.traxel_ids[1]
                    if str(self.getNodeName(
                            t - 1, str(labelOld))) not in nodeMap.keys():
                        continue
                    nodeMap[str(self.getNodeName(
                        t, str(labelNew)))] = nodeMap[str(
                            self.getNodeName(t - 1, str(labelOld)))]
                    del nodeMap[str(self.getNodeName(t - 1, str(labelOld)))]
                    branchSize[str(self.getNodeName(
                        t, str(labelNew)))] = branchSize[str(
                            self.getNodeName(t - 1, str(labelOld)))] + 1
                    del branchSize[str(self.getNodeName(t - 1, str(labelOld)))]

                else:
                    raise Exception, "lineage tree generation not implemented for event type " + str(
                        event.type)

        for label in nodeMap.keys():
            newNode = nodeMap[label].add_child(name=label,
                                               dist=branchSize[label])

        self.plotTree(tree,
                      out_fn=fn,
                      rotation=270,
                      show_leaf_name=False,
                      show_branch_length=False,
                      circularTree=circular,
                      show_division_nodes=False,
                      distance_between_branches=4,
                      width=width,
                      height=height)
array = t.arraytable

# Calculates some stats on the matrix. Needed to establish the color
# gradients.
matrix_dist = [i for r in xrange(len(array.matrix))\
               for i in array.matrix[r] if numpy.isfinite(i)]
matrix_max = numpy.max(matrix_dist)
matrix_min = numpy.min(matrix_dist)
matrix_avg = matrix_min + ((matrix_max - matrix_min) / 2)

# Creates a profile face that will represent node's profile as a
# heatmap
profileFace  = ProfileFace(matrix_max, matrix_min, matrix_avg, \
                                         200, 14, "heatmap")
cbarsFace = ProfileFace(matrix_max, matrix_min, matrix_avg, 200, 70, "cbars")
nameFace = AttrFace("name", fsize=8)


# Creates my own layout function that uses previous faces
def mylayout(node):
    # If node is a leaf
    if node.is_leaf():
        # And a line profile
        add_face_to_node(profileFace, node, 0, aligned=True)
        node.img_style["size"] = 0
        add_face_to_node(nameFace, node, 1, aligned=True)

    # If node is internal
    else:
        print node
        print node.silhouette
Exemple #23
0
def my_layout(node):
	style2 = NodeStyle()
	style2["fgcolor"] = "#000000"
	style2["shape"] = "circle"
	node.img_style = style2
 	node.img_style["bgcolor"] = "LightSteelBlue"
	if node.is_leaf():
		node.img_style["size"] = 40
		node.img_style["fgcolor"] = "#FFFFFF"
		pass
	else:
		node.img_style["size"] = 40
		node.img_style["shape"] = "sphere"
		node.img_style["fgcolor"] = "#FFFFFF"

	tempt = AttrFace('name', fsize=80)
	tempt.fgcolor = "Black"
	tempt.margin_top = 10
	tempt.margin_right = 10
	tempt.margin_left = 10
	tempt.margin_bottom = 10
	tempt.opacity = 0.5 # from 0 to 1
	tempt.inner_border.width = 1 # 1 pixel border
	tempt.inner_border.type = 1  # dashed line
	tempt.border.width = 1
	node.add_face(tempt, column=0, position="branch-top")
	tempt = AttrFace('alias', fsize=80)
	tempt.fgcolor = "Black"
	tempt.margin_top = 10
	tempt.margin_right = 10
	tempt.margin_left = 10
	tempt.margin_bottom = 10
	tempt.opacity = 0.5 # from 0 to 1
	tempt.inner_border.width = 1 # 1 pixel border
	tempt.inner_border.type = 1  # dashed line
	tempt.border.width = 1
	node.add_face(tempt, column=0, position="branch-bottom")
Exemple #24
0
def plot_heat_tree(heatmap_file, tree_file, output_file=None):
    '''
    Plot heatmap next to a tree. The order of the heatmap **MUST** be the same,
    as order of the leafs on the tree. The tree must be in the Newick format. If
    *output_file* is specified, then heat-tree will be rendered as a PNG, 
    otherwise interactive browser will pop-up with your heat-tree.
    
    Parameters
    ----------
    heatmap_file: str
        Path to the heatmap file. The first row must have '#Names' as first 
        element of the header. 
            e.g. #Names, A, B, C, D
                row1, 2, 4, 0, 4
                row2, 4, 6, 2, -1
                
    tree_file: str
        Path to the tree file in Newick format. The leaf node labels should 
        be the same as as row names in the heatmap file. E.g. row1, row2.
        
    output_file: str, optional
        If specified the heat-tree will be rendered in that file as a PNG image,
        otherwise interactive browser will pop-up. **N.B.** program will wait 
        for you to exit the browser before continuing.
    '''
    import numpy

    from ete2.treeview.faces import add_face_to_node
    from ete2 import ClusterTree, TreeStyle, AttrFace, ProfileFace

    # To operate with numbers efficiently

    # Loads tree and array
    t = ClusterTree(tree_file, heatmap_file)

    # nodes are linked to the array table
    array = t.arraytable

    # Calculates some stats on the matrix. Needed to establish the color
    # gradients.
    matrix_dist = [i for r in xrange(len(array.matrix))\
                   for i in array.matrix[r] if numpy.isfinite(i)]
    matrix_max = numpy.max(matrix_dist)
    matrix_min = numpy.min(matrix_dist)
    matrix_avg = matrix_min + ((matrix_max - matrix_min) / 2)

    # Creates a profile face that will represent node's profile as a
    # heatmap
    profileFace = ProfileFace(matrix_max,
                              matrix_min,
                              matrix_avg,
                              1000,
                              14,
                              "heatmap",
                              colorscheme=2)

    nameFace = AttrFace("name", fsize=8)

    # Creates my own layout function that uses previous faces
    def mylayout(node):
        # If node is a leaf
        if node.is_leaf():
            # And a line profile
            add_face_to_node(profileFace, node, 0, aligned=True)
            node.img_style["size"] = 0
            add_face_to_node(nameFace, node, 1, aligned=True)

    # Use my layout to visualize the tree
    ts = TreeStyle()
    ts.layout_fn = mylayout
    t.show(tree_style=ts)
Exemple #25
0
    def layout(node):
        # print node.rank
        # print node.sci_name
        if getattr(node, "rank", None):
            if (node.rank in ['order', 'class', 'phylum', 'kingdom']):
                rank_face = AttrFace("sci_name", fsize=7, fgcolor="indianred")
                node.add_face(rank_face, column=0, position="branch-top")
        if node.is_leaf():
            sciname_face = AttrFace("sci_name", fsize=9, fgcolor="steelblue")
            node.add_face(sciname_face, column=0, position="branch-right")
        if node.is_leaf() and not node.name == 'annotation':
            #here we are adding faces and we need to play with seqmotif face
            seq = str(seqreclist[taxids.index(int(node.name))].seq)
            motifs = []  #[[0,len(seq), "seq", 10, 10, None, None, None]]
            for f in seqreclist[taxids.index(int(node.name))].features:
                if f.type == 'domain':
                    motifs.append([
                        f.location.start, f.location.end, "[]", None, 10,
                        "blue",
                        get_color(f.qualifiers['name']),
                        "arial|8|black|%s" % f.qualifiers['name']
                    ])
                if f.type == 'motif':
                    #It turns out that we need to solve overlap problem here, here it is solved only in case of one overlap
                    s = f.location.start
                    e = f.location.end
                    flag = True
                    overlappedm = []
                    for m in motifs:
                        if m[2] == 'seq' and m[0] < e and m[
                                1] > s:  #we have an overlap, four cases, preceding motife always is on top
                            flag = False
                            overlappedm.append(m)
                    if not flag:  #we have to solve multiple overlap problem
                        #let's do it by scanning
                        sflag = False
                        eflag = False
                        for x in range(s, e + 1):
                            if not sflag:  #check if we can start
                                overlap = False
                                for m in overlappedm:
                                    if x >= m[0] and x < m[1]:
                                        overlap = True
                                if not overlap:
                                    ts = x
                                    sflag = True

                            #check if is time to end
                            if sflag and not eflag:
                                overlap = False
                                for m in overlappedm:
                                    if x == m[0]:
                                        overlap = True
                                if overlap or x == e:
                                    te = x
                                    eflag = True

                            if sflag and eflag:
                                motifs.append([
                                    ts, te, "seq", 10, 10, "black",
                                    get_color(f.qualifiers['name']), None
                                ])
                                sflag = False
                                eflag = False
                    if flag:
                        motifs.append([
                            f.location.start, f.location.end, "seq", 10, 10,
                            "black",
                            get_color(f.qualifiers['name']), None
                        ])
            seqFace = SeqMotifFace(seq,
                                   motifs,
                                   scale_factor=1,
                                   seq_format="[]")
            seqFace.overlaping_motif_opacity = 1.0
            # seqFace.fg=aafgcolors
            # seqFace.bg=aabgcolors_gray

            add_face_to_node(seqFace, node, 0, position="aligned")
            # gi=taxid2gi[int(node.name)]
            add_face_to_node(
                TextFace(' ' + seqreclist[taxids.index(int(node.name))].id +
                         '         '),
                node,
                column=1,
                position="aligned")
            # add_face_to_node(TextFace('      '+str(int(node.name))+' '),node,column=2, position = "aligned")
            # add_face_to_node(TextFace('      '+str(gi2variant[gi])+' '),node,column=3, position = "aligned")

        #We currently disable annotation
        if node.is_leaf() and node.name == 'annotation':
            if (annotation):
                s = annotation
                # get_hist_ss_in_aln_as_string(msa_tr)
            else:
                s = ' ' * max(map(lambda x: len(x.seq), seqreclist))
def my_layout(node):
    # Add name label to all nodes
    faces.add_face_to_node(AttrFace("name"),
                           node,
                           column=0,
                           position="branch-right")