# Path: epac/ete2/newick.py
# def read_newick(newick, root_node=None, format=0):
#     """ Reads a newick tree from either a string or a file, and returns
#     an ETE tree structure.
# 
#     A previously existent node object can be passed as the root of the
#     tree, which means that all its new children will belong to the same
#     class as the root(This allows to work with custom TreeNode
#     objects).
# 
#     You can also take advantage from this behaviour to concatenate
#     several tree structures.
#     """
# 
#     if root_node is None:
#         from ete2.coretype.tree import TreeNode
#         root_node = TreeNode()
# 
#     if isinstance(newick, str):
#         if os.path.exists(newick):
#             f = open(newick, 'r')
#             nw = f.read()
#             f.close()
#         else:
#             nw = newick
#         nw = nw.strip()
#         if not nw.startswith('(') and nw.endswith(';'):
#             return _read_node_data(nw, root_node, "single", format)
#             
#         elif not nw.startswith('(') or not nw.endswith(';'):
#             raise NewickError('Unexisting tree file or Malformed newick tree structure.')
#         else:
#             return _read_newick_from_string(nw, root_node, format)
# 
#     else:
#         raise NewickError("'newick' argument must be either a filename or a newick string.")
# 
# def write_newick(rootnode, features=None, format=1, format_root_node=True,
#                  is_leaf_fn=None):
#     """ Iteratively export a tree structure and returns its NHX
#     representation. """
#     newick = []
#     leaf = is_leaf_fn if is_leaf_fn else lambda n: not bool(n.children)
#     for postorder, node in rootnode.iter_prepostorder(is_leaf_fn=is_leaf_fn):
#         if postorder:
#             newick.append(")")
#             if node.up is not None or format_root_node:
#                 newick.append(format_node(node, "internal", format))
#                 newick.append(_get_features_string(node, features))
#         else:
#             if node is not rootnode and node != node.up.children[0]:
#                 newick.append(",")
#                 
#             if leaf(node):
#                 safe_name = re.sub("["+_ILEGAL_NEWICK_CHARS+"]", "_", \
#                                str(getattr(node, "name")))
#                 newick.append(format_node(node, "leaf", format))
#                 newick.append(_get_features_string(node, features))
#             else:
#                 newick.append("(")
# 
#     newick.append(";")
#     return ''.join(newick)


import os
import pickle
import random
import copy
import itertools
from collections import deque 
from .newick import read_newick, write_newick
            from ete2.treeview import drawer
            from ete2.treeview import drawer
        from ete2 import _ph
        try:
            first_match = next(self.iter_search_nodes(name=value))
            return first_match
        except StopIteration:
            raise ValueError("Node not found")

    def __add__(self, value):
        """ This allows to sum two trees."""
        # Should a make the sum with two copies of the original trees?
        if type(value) == self.__class__:
            new_root = self.__class__()
            new_root.add_child(self)
            new_root.add_child(value)
            return new_root
        else:
            raise ValueError("Invalid node type")

    def __str__(self):
        """ Print tree in newick format. """
        return self.get_ascii(compact=DEFAULT_COMPACT, \
                                show_internal=DEFAULT_SHOWINTERNAL)

    def __contains__(self, item):
        """ Check if item belongs to this node. The 'item' argument must
        be a node instance or its associated name."""
        if isinstance(item, self.__class__):
            return item in set(self.get_descendants())
        elif type(item)==str:
            return item in set([n.name for n in self.traverse()])


# Path: epac/ete2/newick.py
# def read_newick(newick, root_node=None, format=0):
#     """ Reads a newick tree from either a string or a file, and returns
#     an ETE tree structure.
# 
#     A previously existent node object can be passed as the root of the
#     tree, which means that all its new children will belong to the same
#     class as the root(This allows to work with custom TreeNode
#     objects).
# 
#     You can also take advantage from this behaviour to concatenate
#     several tree structures.
#     """
# 
#     if root_node is None:
#         from ete2.coretype.tree import TreeNode
#         root_node = TreeNode()
# 
#     if isinstance(newick, str):
#         if os.path.exists(newick):
#             f = open(newick, 'r')
#             nw = f.read()
#             f.close()
#         else:
#             nw = newick
#         nw = nw.strip()
#         if not nw.startswith('(') and nw.endswith(';'):
#             return _read_node_data(nw, root_node, "single", format)
#             
#         elif not nw.startswith('(') or not nw.endswith(';'):
#             raise NewickError('Unexisting tree file or Malformed newick tree structure.')
#         else:
#             return _read_newick_from_string(nw, root_node, format)
# 
#     else:
#         raise NewickError("'newick' argument must be either a filename or a newick string.")
# 
# def write_newick(rootnode, features=None, format=1, format_root_node=True,
#                  is_leaf_fn=None):
#     """ Iteratively export a tree structure and returns its NHX
#     representation. """
#     newick = []
#     leaf = is_leaf_fn if is_leaf_fn else lambda n: not bool(n.children)
#     for postorder, node in rootnode.iter_prepostorder(is_leaf_fn=is_leaf_fn):
#         if postorder:
#             newick.append(")")
#             if node.up is not None or format_root_node:
#                 newick.append(format_node(node, "internal", format))
#                 newick.append(_get_features_string(node, features))
#         else:
#             if node is not rootnode and node != node.up.children[0]:
#                 newick.append(",")
#                 
#             if leaf(node):
#                 safe_name = re.sub("["+_ILEGAL_NEWICK_CHARS+"]", "_", \
#                                str(getattr(node, "name")))
#                 newick.append(format_node(node, "leaf", format))
#                 newick.append(_get_features_string(node, features))
#             else:
#                 newick.append("(")
# 
#     newick.append(";")
#     return ''.join(newick)


# Path: epac/ete2/tree.py
import os
import pickle
import random
import copy
import itertools
from collections import deque 
from .newick import read_newick, write_newick
            from ete2.treeview import drawer
            from ete2.treeview import drawer
        from ete2 import _ph

        try:
            first_match = next(self.iter_search_nodes(name=value))
            return first_match
        except StopIteration:
            raise ValueError("Node not found")

    def __add__(self, value):
        """ This allows to sum two trees."""
        # Should a make the sum with two copies of the original trees?
        if type(value) == self.__class__:
            new_root = self.__class__()
            new_root.add_child(self)
            new_root.add_child(value)
            return new_root
        else:
            raise ValueError("Invalid node type")

    def __str__(self):
        """ Print tree in newick format. """
        return self.get_ascii(compact=DEFAULT_COMPACT, \
                                show_internal=DEFAULT_SHOWINTERNAL)

    def __contains__(self, item):
        """ Check if item belongs to this node. The 'item' argument must
        be a node instance or its associated name."""
        if isinstance(item, self.__class__):
            return item in set(self.get_descendants())
        elif type(item)==str:
            return item in set([n.name for n in self.traverse()])


    def __len__(self):