# Path: picrust/format_tree_and_trait_table.py
# def filter_table_by_presence_in_tree(tree,trait_table_fields,name_field_index = 0,delimiter="\t"):
#     """yield lines of a trait table lacking organisms missing from the tree"""
# 
#     tree_tips = [str(node.Name.strip()) for node in tree.preorder()]
#     #print tree_tips
#     result_fields = []
#     for fields in trait_table_fields:
#         curr_name = fields[name_field_index].strip()
#         if curr_name not in tree_tips:
#             #print curr_name,"could not be found in tree nodes"
#             #print curr_name in tree_tips
#             #try:
#             #    print int(curr_name) in tree_tips
#             #except:
#             #    pass
#             #print curr_name.strip() in tree_tips
#             continue
#         result_fields.append(fields)
#     return result_fields
# 
# def get_sub_tree(tree,tips_not_to_prune):
#     """Get sub tree, modifying recursion limit if necessary"""
# 
#     try:
#         new_tree = tree.getSubTree(tips_not_to_prune)
#     except RuntimeError:
#         #NOTE:  getSubTree will hit
#         #maximum recursion depth on large trees
#         #Try working around this issue with a large
#         #recursion depth limit
#         old_recursion_limit = getrecursionlimit()
#         setrecursionlimit(50000)
#         new_tree = tree.getSubTree(tips_not_to_prune)
#         setrecursionlimit(old_recursion_limit)
#     return new_tree


from sys import argv
from copy import deepcopy
from random import sample, shuffle
from picrust.format_tree_and_trait_table import filter_table_by_presence_in_tree, get_sub_tree
import os
def exclude_tip(tip, tree,verbose=False):
    """Return pruned tree with tip excluded

    tip --  a PyCogent PhyloNode object from the tree
    tree -- a PyCogent PhyloNode object (the tree)

    NOTE: This function exists to support distance-based exclusion of
    neightbors.  For holdout analysis we really want to
    exclude the organism in the trait table rather than the tree.
    """

    # Make sure the tip is really a tip
    if not tip.isTip():
        raise ValueError("The 'holdout' fn got a non-tip node for it's 'tip' parameter.")

    #Old exclusion based method...but for large trees this is quite slow

    # Assuming that's OK, remove the tip
    #if tip.Parent is not None:
    #    removal_ok = tip.Parent.remove(tip)
    #else:
    #    removal_ok = False
    #if not removal_ok:
    #    raise ValueError("holdout could not remove node '%s' from tree." %(tip.Name))
    #tree.prune()

    #Newer subtree based method
    tips_to_keep = [t.Name for t in tree.tips() if t.Name != tip.Name]
    if verbose:
        print "Generating subtree with %i tips" %len(tips_to_keep)

# Path: picrust/format_tree_and_trait_table.py
# def filter_table_by_presence_in_tree(tree,trait_table_fields,name_field_index = 0,delimiter="\t"):
#     """yield lines of a trait table lacking organisms missing from the tree"""
# 
#     tree_tips = [str(node.Name.strip()) for node in tree.preorder()]
#     #print tree_tips
#     result_fields = []
#     for fields in trait_table_fields:
#         curr_name = fields[name_field_index].strip()
#         if curr_name not in tree_tips:
#             #print curr_name,"could not be found in tree nodes"
#             #print curr_name in tree_tips
#             #try:
#             #    print int(curr_name) in tree_tips
#             #except:
#             #    pass
#             #print curr_name.strip() in tree_tips
#             continue
#         result_fields.append(fields)
#     return result_fields
# 
# def get_sub_tree(tree,tips_not_to_prune):
#     """Get sub tree, modifying recursion limit if necessary"""
# 
#     try:
#         new_tree = tree.getSubTree(tips_not_to_prune)
#     except RuntimeError:
#         #NOTE:  getSubTree will hit
#         #maximum recursion depth on large trees
#         #Try working around this issue with a large
#         #recursion depth limit
#         old_recursion_limit = getrecursionlimit()
#         setrecursionlimit(50000)
#         new_tree = tree.getSubTree(tips_not_to_prune)
#         setrecursionlimit(old_recursion_limit)
#     return new_tree


# Path: picrust/make_test_datasets.py
from sys import argv
from copy import deepcopy
from random import sample, shuffle
from picrust.format_tree_and_trait_table import filter_table_by_presence_in_tree, get_sub_tree
import os

def exclude_tip(tip, tree,verbose=False):
    """Return pruned tree with tip excluded

    tip --  a PyCogent PhyloNode object from the tree
    tree -- a PyCogent PhyloNode object (the tree)

    NOTE: This function exists to support distance-based exclusion of
    neightbors.  For holdout analysis we really want to
    exclude the organism in the trait table rather than the tree.
    """

    # Make sure the tip is really a tip
    if not tip.isTip():
        raise ValueError("The 'holdout' fn got a non-tip node for it's 'tip' parameter.")

    #Old exclusion based method...but for large trees this is quite slow

    # Assuming that's OK, remove the tip
    #if tip.Parent is not None:
    #    removal_ok = tip.Parent.remove(tip)
    #else:
    #    removal_ok = False
    #if not removal_ok:
    #    raise ValueError("holdout could not remove node '%s' from tree." %(tip.Name))
    #tree.prune()

    #Newer subtree based method
    tips_to_keep = [t.Name for t in tree.tips() if t.Name != tip.Name]
    if verbose:
        print "Generating subtree with %i tips" %len(tips_to_keep)

    subtree = get_sub_tree(tree,tips_to_keep)