Beispiel #1
0
def main():
    args = parser.parse_args()

    beta_metrics = args.beta_metrics.split(',')
    otu_widths = args.otu_widths.split(',')
    input_dir = args.input_dir
    output_fp = args.output_fp
    tree_fp = args.tree_fp

    nrows = len(beta_metrics)
    ncols = len(otu_widths)

    results_dict, labels_list = load_rug_dict(input_dir, beta_metrics,
                                              otu_widths)

    try:
        tree = Tree(tree_fp, format=3)
    except:
        tree = add_tip_branches(tree_fp)

    annotate_tree_with_rugs(tree, results_dict, labels_list)

    ts = TreeStyle()

    for row in range(len(labels_list)):
        for col in range(len(labels_list[row])):
            ts.legend.add_face(TextFace(labels_list[row][col], fsize=20),
                               column=col)

    tree.render(output_fp, tree_style=ts)
    tree.show(tree_style=ts)
Beispiel #2
0
    def render(self, fname, layout=None, tree_style=None, palette=None):
        """
        Renders the locus tree and writes the image to file.
        :param fname: str
            Output file path
        :param layout:
        :param tree_style:
        :param palette:
        :return: None
        """
        if not palette:
            palette = ['#1F77B4', '#AEC7E8', '#FF7F0E',
                       '#FFBB78', '#2CA02C', '#98DF8A',
                       '#D62728', '#FF9896', '#9467BD',
                       '#C5B0D5', '#8C564B', '#C49C94',
                       '#E377C2', '#F7B6D2', '#7F7F7F',
                       '#C7C7C7', '#BCBD22', '#DBDB8D',
                       '#17BECF', '#9EDAE5']
        if not self.colorized:
            self._colorize(palette)
            self.colorized = True
        if not tree_style:
            from ete2 import TreeStyle
            tree_style = TreeStyle()  # imported during colorizing tree
            # tstyle.show_leaf_name = False
            tree_style.scale = 28
            tree_style.branch_vertical_margin = 6
            tree_style.show_branch_length = False

            # tstyle.show_branch_support = True
            tree_style.show_scale = False
        self.L.convert_to_ultrametric()
        self.L.render(file_name=fname, tree_style=tree_style)
Beispiel #3
0
def showTreeInGrid(gid, biome, grid_level=14, taxonomic_level='sp'):
    """
    Performs a selection, spatial filter and returns an image.
    grid_level is the grid layer.
    taxonomic_level is the taxonomic level to be shown. Options are:
    sp, gns, fam, ord, cls, phy, king
    """

    mesh = initMesh(grid_level)
    try:
        cell = mesh.objects.get(id=id)
    except:
        logger.error("Selected id does not exist in selected grid")
        return None

    gb = GriddedTaxonomy(biome, cell, generate_tree_now=True)
    forest = gb.taxonomies[0].forest

    ts = TreeStyle()
    ts.show_leaf_name = True
    ts.mode = "c"
    ts.arc_start = -180  # 0 degrees = 3 o'clock
    ts.arc_span = 360

    forest[taxonomic_level].show(tree_style=ts)
    return 'Parece que se tiene que ver algo'
Beispiel #4
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
Beispiel #5
0
def ete_tree(aln):
    """Tree showing alleles"""

    from ete2 import Tree, PhyloTree, TreeStyle, NodeStyle

    t = Tree('temp.dnd')
    ts = TreeStyle()
    ts.show_leaf_name = True
    ts.mode = "c"
    ts.arc_start = -180
    ts.arc_span = 180
    cutoff = 0.25

    def func(node):
        if node.name == 'NoName':  #or not node.name in metric:
            return False
        #if metric[node.name]<=cutoff:
        #    return True

    matches = filter(func, t.traverse())
    print(len(matches), "nodes have distance <=%s" % cutoff)
    nst1 = NodeStyle()
    nst1["bgcolor"] = "Yellow"
    for n in matches:
        n.set_style(nst1)
    nst2 = NodeStyle()
    nst2["bgcolor"] = "LightGreen"
    #hlanodes = [t.get_leaves_by_name(name=r)[0] for r in refalleles]
    #for n in hlanodes:
    #    n.set_style(nst2)
    t.show(tree_style=ts)
    return
Beispiel #6
0
    def show(self, tree_style=None, palette=None):
        """
        Starts an interactive session to visualize the decomposition.
        :return: None
        """
        if not palette:
            palette = ['#1F77B4', '#AEC7E8', '#FF7F0E',
                       '#FFBB78', '#2CA02C', '#98DF8A',
                       '#D62728', '#FF9896', '#9467BD',
                       '#C5B0D5', '#8C564B', '#C49C94',
                       '#E377C2', '#F7B6D2', '#7F7F7F',
                       '#C7C7C7', '#BCBD22', '#DBDB8D',
                       '#17BECF', '#9EDAE5']
        if not self.colorized:
            self._colorize(palette)
            self.colorized = True
        if not tree_style:
            from ete2 import TreeStyle
            tree_style = TreeStyle()
            # tstyle.show_leaf_name = False
            tree_style.scale = 28
            tree_style.branch_vertical_margin = 6
            tree_style.show_branch_length = False

            # tstyle.show_branch_support = True
            tree_style.show_scale = False
        self.L.convert_to_ultrametric()
        self.L.show(tree_style=tree_style)
Beispiel #7
0
    def render_annotate(newick_path, output_path):
        """Render the annotated tree, showing internal node names.
           The output_path should end in .PNG, .PDF or .SVG: this will determine the format.

           To aid in testing, if output_path is None, the tree is shown rather than rendered.
        """
        tree = Tree(newick_path, format=1)

        ts = TreeStyle()
        ts.show_leaf_name = True
        ts.branch_vertical_margin = 15

        ns = NodeStyle()
        ns["size"] = 1

        edge = 0
        for node in tree.traverse():
            node.name = node.name.replace("'", "")
            node.name = node.name.replace("+", ",")
            if not node.is_leaf() and node.name != 'NoName':
                f = TextFace(node.name)
                f.margin_top = 5
                f.margin_bottom = 5
                f.margin_right = 10
                f.margin_left = 10
                edge += 1
                node.add_face(f, column=0, position="branch-top")

        if output_path is None:
            tree.show(tree_style=ts)
        else:
            tree.render(output_path)
Beispiel #8
0
    def setUp(self):
        tree = Tree()
        root = tree.get_tree_root()
        root.dist = 0
        root.name = "root"
        node = root.add_child(name="Left")
        node.add_child(name="Alpha")
        node.add_child(name="Beta")
        node = root.add_child(name="Right")
        node.add_child(name="Gamma")
        node.add_child(name="Delta")
        for desc in tree.iter_descendants():
            desc.dist = 0

        ts = TreeStyle()
        ts.show_leaf_name = True
        ts.show_branch_length = False
        ts.mode = "c"
        ts.arc_start = 0
        ts.arc_span = 360

        self.circular_style = ts
        self.exampleTree = tree
        self.alignment = MultipleSeqAlignment([
            SeqRecord(Seq("AAG", generic_dna), id="Alpha"),
            SeqRecord(Seq("AGA", generic_dna), id="Beta"),
            SeqRecord(Seq("AAA", generic_dna), id="Gamma"),
            SeqRecord(Seq("GGA", generic_dna), id="Delta"),
        ])
Beispiel #9
0
def ETETree(seqs, ref, metric):
    """Tree showing bola alleles covered by tepitope"""
    from ete2 import Tree, PhyloTree, TreeStyle, NodeStyle
    aln = Genome.clustalAlignment(seqs=seqs)
    t = Tree('temp.dnd')
    #t.set_outgroup(t&ref)
    ts = TreeStyle()
    ts.show_leaf_name = True
    ts.mode = "c"
    ts.arc_start = -180
    ts.arc_span = 180
    cutoff = 0.25

    def func(node):
        if node.name == 'NoName' or not node.name in metric:
            return False
        if metric[node.name] <= cutoff:
            return True

    matches = filter(func, t.traverse())
    print len(matches), "nodes have distance <=%s" % cutoff
    nst1 = NodeStyle()
    nst1["bgcolor"] = "Yellow"
    for n in matches:
        n.set_style(nst1)
    nst2 = NodeStyle()
    nst2["bgcolor"] = "LightGreen"
    hlanodes = [t.get_leaves_by_name(name=r)[0] for r in refalleles]
    for n in hlanodes:
        n.set_style(nst2)
    t.show(tree_style=ts)
    return
Beispiel #10
0
  def __init__(self):
    init_balances = {}
    for i in xrange(Parameters.num_peers):
      init_balances["P_" + str(i)] = Parameters.start_balance

    self.gen_block = Block("B_-1", 0, init_balances, {}, {}, "None")
    self.nodes = [Peer("P_" + str(i), self.get_delay, self.gen_block) for i in xrange(Parameters.num_peers)]
    self.node_is_slow = dict()
    self.network_graph = self.generate_graph()
    self.assign_neighbours()
    for i in xrange(Parameters.num_peers):
      pid = "P_" + str(i)
      self.node_is_slow[pid] = (random.random() < Parameters.z)
    # testing str of peers.
    t = threading.Timer(5, self.nodes[0].write_to_file) 
    t.start()
    #for tree generation
    if _ete2_import:
      self.nst = [NodeStyle() for i in xrange(Parameters.num_peers)]
      self.fnst = [NodeStyle() for i in xrange(Parameters.num_peers)]
      for i in xrange(Parameters.num_peers):
        self.nst[i]["bgcolor"] = "#" + str(hex(random.randint(128,255)))[2:] + str(hex(random.randint(128,255)))[2:] + str(hex(random.randint(128,255)))[2:]
      for i in xrange(Parameters.num_peers):
        self.fnst[i]["size"] = 15
        self.fnst[i]["fgcolor"] = self.nst[i]["bgcolor"]      
      self.ts = TreeStyle()
      # self.ts.mode = "c" #circle
      self.ts.show_leaf_name = False
      def my_layout(node):
        F = TextFace(node.name, tight_text=True)
        add_face_to_node(F, node, column=0, position="branch-right")
      self.ts.layout_fn = my_layout
Beispiel #11
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
Beispiel #12
0
 def generateImage(self, tree):
     ts = TreeStyle()
     ts.layout_fn = self.__layout__
     ts.mode = "c"
     ts.show_leaf_name = False
     tree.render(self.treePNGFile, w=1000, tree_style=ts)
     tree.render(self.treeSVGFile, w=250, tree_style=ts)
Beispiel #13
0
def add_taxonomy_label(cotu_tree, potu_table):

    ts = TreeStyle()

    for row in range(len(labels_list)):
        for col in range(len(labels_list[row])):
            ts.legend.add_face(TextFace(labels_list[row][col], fsize=20),
                               column=col)
Beispiel #14
0
def constructing_final_tree(distance_matrix, protein_labels):
    v = str(upgma(distance_matrix, protein_labels)) + ";"
    t = Tree(v)
    ts = TreeStyle()
    ts.show_leaf_name = True
    t.convert_to_ultrametric()
    ts.scale = 120
    t.show(tree_style=ts)
Beispiel #15
0
 def plotTree(self, tree, out_fn=None, rotation=270, show_leaf_name=False, 
               show_branch_length=False, circularTree=False, show_division_nodes=True, 
               distance_between_branches=4, show_border=False, width=None, height=None):            
     from ete2 import TreeStyle        
     from PyQt4 import QtSvg, QtCore, QtGui
     from ete2.treeview import qt4_render, drawer, main
     
       
     ts = TreeStyle()   
     ts.show_scale = False
     ts.show_border = show_border
     ts.orientation = 1 # 0, tree is drawn from left-to-right. 1, tree is drawn from right-to-left
     ts.rotation = rotation
     ts.show_leaf_name = show_leaf_name
     ts.show_branch_length = show_branch_length
     if circularTree:
         ts.mode = 'c'
     else:
         ts.mode = 'r'
     ts.branch_vertical_margin = distance_between_branches
     
     
     def hideInternalNodesLayout(node):
         if not node.is_leaf():
             node.img_style["size"] = 0
     
     if show_division_nodes is False:
         ts.layout_fn = hideInternalNodesLayout
     
     if out_fn is not None:        
         scene  = qt4_render._TreeScene()
         img = ts
         
         tree_item, n2i, n2f = qt4_render.render(tree, img)
         scene.init_data(tree, img, n2i, n2f)
         tree_item.setParentItem(scene.master_item)
         scene.master_item.setPos(0,0)
         scene.addItem(scene.master_item)      
         main.save(scene, out_fn, w=width, h=height, dpi=600)    
           
     else:
         scene, img = drawer.init_scene(tree, None, ts)
         tree_item, n2i, n2f = qt4_render.render(tree, img)
         scene.init_data(tree, img, n2i, n2f)
     
         tree_item.setParentItem(scene.master_item)
         scene.addItem(scene.master_item)
     
         size = tree_item.rect()
         w, h = size.width(), size.height()
     
         svg = QtSvg.QSvgGenerator()
         svg.setFileName("test.svg")
         svg.setSize(QtCore.QSize(w, h))
         svg.setViewBox(size)
         pp = QtGui.QPainter()
         pp.begin(svg)            
         scene.render(pp, tree_item.rect(), tree_item.rect(), QtCore.Qt.KeepAspectRatio)
Beispiel #16
0
def constructing_final_tree(distance_matrix, protein_labels):
    v = str(neighbor_joining(distance_matrix, protein_labels)) + ";"
    t = Tree(v)
    t.dist = 0
    ts = TreeStyle()
    ts.mode = "c"
    ts.show_leaf_name = True
    ts.layout_fn = my_layout
    t.show(tree_style=ts)
Beispiel #17
0
    def draw_ete_tree(self,
                      corpus,
                      fontsize=5,
                      color_leafs=False,
                      save_newick=True,
                      mode='c',
                      outputfile=None,
                      return_svg=True,
                      show=False,
                      save=False):
        root = self.to_ete(labels=corpus.titles)

        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')
                # problems: aligment of labels to branch, left padding of labels

        ts = TreeStyle()
        ts.mode = mode
        ts.show_leaf_name = False
        ts.scale = 120
        ts.show_scale = False
        ts.branch_vertical_margin = 10

        nstyle = NodeStyle()
        nstyle["fgcolor"] = "#0f0f0f"
        nstyle["size"] = 0
        nstyle["vt_line_color"] = "#0f0f0f"
        nstyle["hz_line_color"] = "#0f0f0f"
        nstyle["vt_line_width"] = 1
        nstyle["hz_line_width"] = 1
        nstyle["vt_line_type"] = 0
        nstyle["hz_line_type"] = 0

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

        ts.layout_fn = layout

        if outputfile:
            outputfile = os.path.expanduser(outputfile)

        if save_newick:  # save tree in newick format for later manipulation in e.g. FigTree:
            root.write(outfile=os.path.splitext(outputfile)[0] + '.newick')

        if save:
            root.render(outputfile, tree_style=ts)
        if show:
            root.show(tree_style=ts)
        if return_svg:  # return the SVG as a string
            return root.render("%%return")[0]
Beispiel #18
0
def get_example_tree():

    # Performs a tree reconciliation analysis
    gene_tree_nw = '((Dme_001,Dme_002),(((Cfa_001,Mms_001),((Hsa_001,Ptr_001),Mmu_001)),(Ptr_002,(Hsa_002,Mmu_002))));'
    species_tree_nw = "((((Hsa, Ptr), Mmu), (Mms, Cfa)), Dme);"
    genetree = PhyloTree(gene_tree_nw)
    sptree = PhyloTree(species_tree_nw)
    recon_tree, events = genetree.reconcile(sptree)
    recon_tree.link_to_alignment(alg)
    return recon_tree, TreeStyle()
Beispiel #19
0
def prettifyTree(ete_tree,
                 leaf_font_size=32,
                 branch_support_size=20,
                 show_bootstraps=True,
                 title=None,
                 ts=None):
    ''' Perform standardized functions to make the ETE trees easier to read:
    - Make the branch support bigger
    - Make the leaf fonts bigger
    - Turn off elongating branches for visualization purposes (i.e. make sure the real branch lengths are represented)
    - Change both to standard font (Times)
    - Standardize the tree's width (calculate based on the maximum length from the root to a tip)
    - (optional) add title to tree
    '''

    for node in ete_tree.traverse():
        if node.is_leaf():
            # Make text faces with name = the existing node name but with big font.
            # A side effect of this is that we also get the annotations lined up
            F = faces.TextFace(node.name, ftype="Times", fsize=leaf_font_size)
            node.add_face(F, 0, position="aligned")
        else:
            if show_bootstraps:
                # Make branch support bigger
                F = faces.TextFace(node._support,
                                   ftype="Times",
                                   fsize=branch_support_size)
                node.add_face(F, 0, position="branch-top")

    #correct the long root node bug (fixed in next release)
    ete_tree.dist = 0

    # Optionally create a new TreeStyle if we are not passing in an old one.
    if ts is None:
        ts = TreeStyle()

    # This "fixes" the dashed line issue but makes the tree look terrible.
    # There may be no way around this (and it's likely other tree viewers do the same thing
    # but just don't tell you).
    #ts.optimal_scale_level = "full"

    # We made these bigger so lets turn off the default ones too.
    ts.show_branch_support = False
    ts.show_leaf_name = False

    if title is not None:
        ts.title.clear()
        title = TextFace(title)
        title.hz_align = True
        title.fsize = 52
        ts.title.add_face(title, 0)

    return ete_tree, ts
Beispiel #20
0
def drawTree(nwfile, outfile):
    from ete2 import Tree, TreeStyle, TextFace
    ts = TreeStyle()
    ts.show_leaf_name = False
    ts.layout_fn = my_layout
    ts.branch_vertical_margin = 12.75
    ts.orientation = 1
    titleFace = TextFace("Phylogenetic Tree", fsize=18, fgcolor="white")
    titleFace.margin_top = 15
    ts.title.add_face(titleFace, column=1)

    t = Tree(nwfile)
    t.render(outfile, tree_style=ts)
Beispiel #21
0
def render_symbiont_tree(symbiont_tree, output_fp, ts=TreeStyle()):
    ts.show_leaf_name = True
    # ts.scale =  300 # 120 pixels per branch length unit
    # ts.mode = "c"

    nstyle = NodeStyle()
    nstyle["shape"] = "circle"
    nstyle["size"] = 0
    for n in symbiont_tree.traverse():
        n.set_style(nstyle)

    print 'rendering tree'

    symbiont_tree.render(output_fp, tree_style=ts)
Beispiel #22
0
def get_tree_style(scale=None, vertical_margin=None):
    """Setups the tree-style used when rendering the tree"""

    style = TreeStyle()
    style.show_leaf_name = False

    if scale:
        style.scale = scale

    style.show_border = True

    if vertical_margin:
        style.branch_vertical_margin = vertical_margin

    return style
    def ete_tree(self, labels=None):
        if sys.version_info[0] == 2:
            from ete2 import Tree, NodeStyle, TreeStyle
        elif sys.version_info[0] == 3:
            from ete3 import Tree, NodeStyle, TreeStyle
        else:
            raise ValueError('Your version of Python is not supported.')

        from scipy.cluster.hierarchy import to_tree

        T = to_tree(self.to_linkage_matrix())
        root = Tree()
        root.dist = 0
        root.name = "root"
        item2node = {T: root}
        to_visit = [T]
        while to_visit:
            node = to_visit.pop()
            cl_dist = node.dist / 2.0
            for ch_node in [node.left, node.right]:
                if ch_node:
                    ch = Tree()
                    ch.dist = cl_dist
                    ch.name = str(ch_node.id)
                    item2node[node].add_child(ch)
                    item2node[ch_node] = ch
                    to_visit.append(ch_node)
        if labels != None:
            for leaf in root.get_leaves():
                leaf.name = str(labels[int(leaf.name)])

        ts = TreeStyle()
        ts.show_leaf_name = True

        # Draws nodes as small red spheres of diameter equal to 10 pixels
        nstyle = NodeStyle()
        nstyle["shape"] = None
        nstyle["size"] = 0

        # Gray dashed branch lines
        nstyle["hz_line_type"] = 1
        nstyle["hz_line_color"] = "#cccccc"

        # 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 root.traverse():
            n.set_style(nstyle)
        return root
Beispiel #24
0
    def __init__(self, tree, options):
        self._tree = tree
        self._options = options
        self._formatingMethods = []
        self._storageDir = None
        self._filePrefix = None
        self._style = TreeStyle()
        self._style.show_leaf_name = True
        self._style.show_branch_length = False
        self._style.scale = 80
        self._style.branch_vertical_margin = 15
        self._style.rotation = 90
        self._style.arc_start = -180
        self._style.arc_span = 180

        self.parseOptions(options)
def build_tree_style(tree):
    # use our simple TSS cascade to prepare an ETE TreeStyle object
    sheets = gather_tss_stylesheets(tree)
    if len(sheets) == 0:
        return None

    # Some styles can be applied to the entire tree
    ts = TreeStyle()
    # For nodes (and other elements?), build an ordered set of TSS rules 
    # to apply to each element in our layout function
    node_rules = []

    for s in sheets:
        ts, tss_cascade = apply_stylesheet(
            stylesheet=s, 
            tree_style=ts,
            node_rules=node_rules)

    otu_collections = tree.nexml_project.get_otus()

    # Use a layout function to test each node against TSS selectors?
    def apply_tss(node):
        node_style = NodeStyle()

        # gather label text and styles separately; we'll need to add this 
        # using a TextFace after all styles have been considered
        label_specs = {}
        label_specs['text'] = get_proper_node_label(node, otu_collections)

        for rule in node_rules:
            # Test this node against each selector
            if test_node_against_selector(node, rule.selector):
                node_style, node = apply_node_rule(rule, node_style, node, label_specs)
        node.set_style(node_style);

        # assign the final label with appropriate style
        if node.is_leaf():
            label_face = TextFace(**label_specs)
            node.add_face(label_face, 0)
        
        return node

    # apply this layout function to each node as it's rendered
    ts.layout_fn = apply_tss
    # suppress default node-labeling behavior (so we can style labels!)
    ts.show_leaf_name = False
    return ts
def main(args):
    if args.ofn == None:
        args.ofn = args.ifn + '.png'
    ts = TreeStyle()
    ts.show_leaf_name = True
    nstyle = NodeStyle()
    #nstyle["shape"] = "sphere"
    nstyle["size"] = 5
    #nstyle["fgcolor"] = "darkred"
    nstyle["vt_line_width"] = 2
    nstyle["hz_line_width"] = 2

    #ts.mode = "c"
    tree = Tree(args.ifn)
    for n in tree.traverse():
        n.set_style(nstyle)
    tree.render(args.ofn, tree_style=ts, dpi=300, units='in')  #, h=20, w=20)
Beispiel #27
0
    def draw_significant_expansion_contraction(
            self, outfile_prefix="significant_expansion_contraction_tree"):

        tree = self.tree
        for node in tree.traverse():
            node.img_style["size"] = 0

        def layout(node):
            if node.up is not None:
                attr = AttrFace("significant_expansion",
                                fsize=7,
                                fgcolor="green",
                                text_prefix="+")
                faces.add_face_to_node(attr, node, 0, position="branch-top")

                attr = AttrFace("significant_contraction",
                                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")

        ts = TreeStyle()
        ts.layout_fn = layout
        ts.optimal_scale_level = "full"
        ts.branch_vertical_margin = 10
        ts.show_leaf_name = False
        #ts.allow_face_overlap =True
        tree.render("%s.png" % outfile_prefix,
                    w=200,
                    units='mm',
                    tree_style=ts,
                    dpi=1200)
        tree.render("%s.svg" % outfile_prefix,
                    w=200,
                    units='mm',
                    tree_style=ts,
                    dpi=1200)
Beispiel #28
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)
Beispiel #29
0
    def draw(self, out_file_prefix, w=140, units="mm"):
        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")

        for feature in self.tree.features - set(["support", "name"]):
            if feature[0] == "_":
                continue  # skip _nid feature and other technical features of tree

            def layout_arg(node):
                return layout(node, feature)

            ts = TreeStyle()
            ts.layout_fn = layout_arg
            self.tree.render("%s_%s.png" % (out_file_prefix, feature),
                             w=w,
                             units=units,
                             tree_style=ts)
Beispiel #30
0
def main(argv):
    inputfile = ''
    outgroup = ''
    outputfile = ''

    ts = TreeStyle()
    ts.show_leaf_name = True
    ts.show_branch_length = False
    ts.show_branch_support = True

    ns = NodeStyle()
    ns["size"] = 0
    ns["vt_line_width"] = 2
    ns["hz_line_width"] = 2

    try:
        opts, args = getopt.getopt(argv, "hi:o:p:",
                                   ["input=", "outgroup=", "-prefix-svg="])
    except getopt.GetoptError:
        print 'print-single-nwk.py -i <inputfile> -o <outgroup> -p <prefixsvg>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'print-single-nwk.py -i <inputfile> -o <outgroup> -p <prefixsvg>'
            sys.exit()
        elif opt in ("-i", "--input"):
            inputfile = arg
        elif opt in ("-o", "--outgroup"):
            outgroup = arg
        elif opt in ("-p", "--prefix-svg"):
            outputfile = arg
    # read tree
    t = Tree(inputfile)
    t.set_outgroup(outgroup)
    t.ladderize(1)

    for node in t.traverse():
        node.set_style(ns)

    # print final tree
    t.render(outputfile + ".svg", tree_style=ts)