# Path: seqenv/common/cache.py
# def property_cached(f):
#     """Decorator for properties evaluated only once.
#     It can be used to created a cached property like this:
# 
#         class Employee(object):
#             @property_cached
#             def salary(self):
#                 print "Evaluating..."
#                 return time.time()
#         bob = Employee()
#         print bob.salary
#         bob.salary = "10000$"
#         print bob.salary
#     """
#     def retrieve_from_cache(self):
#         if '__cache__' not in self.__dict__: self.__cache__ = {}
#         if f.__name__ not in self.__cache__:
#             # Add result to the property cache #
#             if inspect.isgeneratorfunction(f): result = tuple(f(self))
#             else: result = f(self)
#             self.__cache__[f.__name__] = result
#         return self.__cache__[f.__name__]
#     def overwrite_cache(self, value):
#         if '__cache__' not in self.__dict__: self.__cache__ = {}
#         self.__cache__[f.__name__] = value
#     retrieve_from_cache.__doc__ = f.__doc__
#     return property(retrieve_from_cache, overwrite_cache)
# 
# Path: seqenv/common/autopaths.py
# class DirectoryPath(str):
# 
#     def __repr__(self): return '<%s object "%s">' % (self.__class__.__name__, self.path)
# 
#     @classmethod
#     def clean_path(cls, path):
#         """Given a path, return a cleaned up version for initialization."""
#         # Conserve 'None' object style #
#         if path is None: return None
#         # Don't nest DirectoryPaths or the like #
#         if hasattr(path, 'path'): path = path.path
#         # Expand the tilda #
#         if "~" in path: path = os.path.expanduser(path)
#         # Our standard is to end with a slash for directories #
#         if not path.endswith('/'): path += '/'
#         # Return the result #
#         return path
# 
#     def __new__(cls, path, *args, **kwargs):
#         """A DirectoryPath is in fact a string"""
#         return str.__new__(cls, cls.clean_path(path))
# 
#     def __init__(self, path):
#         self.path = self.clean_path(path)
# 
#     @property
#     def name(self):
#         """Just the directory name"""
#         return os.path.basename(os.path.dirname(self.path))
# 
#     @property
#     def exists(self):
#         """Does it exist in the file system?"""
#         return os.path.lexists(self.path) # Include broken symlinks
# 
#     @property
#     def absolute_path(self):
#         """The absolute path starting with a `/`"""
#         return os.path.abspath(self.path) + '/'
# 
#     @property
#     def is_symlink(self):
#         """Is this directory a symbolic link to an other directory?"""
#         return os.path.islink(self.path.rstrip('/'))
# 
#     @property
#     def directory(self):
#         """The full path of directory containing this one"""
#         return DirectoryPath(os.path.dirname(os.path.dirname(self.path)))
# 
#     @property
#     def permissions(self):
#         """Convenience object for dealing with permissions."""
#         return FilePermissions(self.path)
# 
#     def remove(self):
#         if not self.exists: return False
#         if self.is_symlink: return self.remove_when_symlink()
#         shutil.rmtree(self.path, ignore_errors=True)
#         return True
# 
#     def remove_when_symlink(self):
#         if not self.exists: return False
#         os.remove(self.path.rstrip('/'))
#         return True
# 
#     def create(self, safe=False, inherit=True):
#         # Create it #
#         if not safe:
#             os.makedirs(self.path)
#             if inherit: os.chmod(self.path, self.directory.permissions.number)
#         if safe:
#             try:
#                 os.makedirs(self.path)
#                 if inherit: os.chmod(self.path, self.directory.permissions.number)
#             except OSError: pass
# 
#     def create_if_not_exists(self):
#         if not self.exists: self.create()


import warnings, marshal, re
import seqenv
import pandas
    import biom
from seqenv.common.cache     import property_cached
from seqenv.common.autopaths import DirectoryPath
    # per_sample_dot_files

    def per_seq_dot_files(self):
        """Generations of files that can be viewed in `graphviz`.
        There is one dotfile per every input sequence.
        We also automiatcally make a corresponding PDF file."""
        # The output directory #
        directory = DirectoryPath(self.a.out_dir+'per_seq_ontology/')
        directory.create_if_not_exists()
        # Main loop #
        for seq in self.a.seq_to_counts:
            dot_path = directory + seq + '.dot'
            pdf_path = directory + seq + '.pdf'
            counts = self.a.seq_to_counts[seq]
            counts = {"ENVO:%08d"%k:v for k,v in counts.items()}
            total  = sum(counts.values())
            counts = {k:v/total for k,v in counts.items()}
            envos  = counts.keys()
            graph  = self.a.ontology.get_subgraph(envos)
            graph  = self.a.ontology.add_weights(graph, counts)
            graph  = self.a.ontology.add_style(graph)
            self.a.ontology.write_to_dot(graph, dot_path)
            self.a.ontology.add_legend(dot_path)
            self.a.ontology.draw_to_pdf(dot_path, pdf_path)

    def per_sample_dot_files(self):
        """Generations of files that can be viewed in `graphviz`.
        There is one dotfile per every sample inputted.
        We also automatically make a corresponding PDF file."""
        # The output directory #

# Path: seqenv/common/cache.py
# def property_cached(f):
#     """Decorator for properties evaluated only once.
#     It can be used to created a cached property like this:
# 
#         class Employee(object):
#             @property_cached
#             def salary(self):
#                 print "Evaluating..."
#                 return time.time()
#         bob = Employee()
#         print bob.salary
#         bob.salary = "10000$"
#         print bob.salary
#     """
#     def retrieve_from_cache(self):
#         if '__cache__' not in self.__dict__: self.__cache__ = {}
#         if f.__name__ not in self.__cache__:
#             # Add result to the property cache #
#             if inspect.isgeneratorfunction(f): result = tuple(f(self))
#             else: result = f(self)
#             self.__cache__[f.__name__] = result
#         return self.__cache__[f.__name__]
#     def overwrite_cache(self, value):
#         if '__cache__' not in self.__dict__: self.__cache__ = {}
#         self.__cache__[f.__name__] = value
#     retrieve_from_cache.__doc__ = f.__doc__
#     return property(retrieve_from_cache, overwrite_cache)
# 
# Path: seqenv/common/autopaths.py
# class DirectoryPath(str):
# 
#     def __repr__(self): return '<%s object "%s">' % (self.__class__.__name__, self.path)
# 
#     @classmethod
#     def clean_path(cls, path):
#         """Given a path, return a cleaned up version for initialization."""
#         # Conserve 'None' object style #
#         if path is None: return None
#         # Don't nest DirectoryPaths or the like #
#         if hasattr(path, 'path'): path = path.path
#         # Expand the tilda #
#         if "~" in path: path = os.path.expanduser(path)
#         # Our standard is to end with a slash for directories #
#         if not path.endswith('/'): path += '/'
#         # Return the result #
#         return path
# 
#     def __new__(cls, path, *args, **kwargs):
#         """A DirectoryPath is in fact a string"""
#         return str.__new__(cls, cls.clean_path(path))
# 
#     def __init__(self, path):
#         self.path = self.clean_path(path)
# 
#     @property
#     def name(self):
#         """Just the directory name"""
#         return os.path.basename(os.path.dirname(self.path))
# 
#     @property
#     def exists(self):
#         """Does it exist in the file system?"""
#         return os.path.lexists(self.path) # Include broken symlinks
# 
#     @property
#     def absolute_path(self):
#         """The absolute path starting with a `/`"""
#         return os.path.abspath(self.path) + '/'
# 
#     @property
#     def is_symlink(self):
#         """Is this directory a symbolic link to an other directory?"""
#         return os.path.islink(self.path.rstrip('/'))
# 
#     @property
#     def directory(self):
#         """The full path of directory containing this one"""
#         return DirectoryPath(os.path.dirname(os.path.dirname(self.path)))
# 
#     @property
#     def permissions(self):
#         """Convenience object for dealing with permissions."""
#         return FilePermissions(self.path)
# 
#     def remove(self):
#         if not self.exists: return False
#         if self.is_symlink: return self.remove_when_symlink()
#         shutil.rmtree(self.path, ignore_errors=True)
#         return True
# 
#     def remove_when_symlink(self):
#         if not self.exists: return False
#         os.remove(self.path.rstrip('/'))
#         return True
# 
#     def create(self, safe=False, inherit=True):
#         # Create it #
#         if not safe:
#             os.makedirs(self.path)
#             if inherit: os.chmod(self.path, self.directory.permissions.number)
#         if safe:
#             try:
#                 os.makedirs(self.path)
#                 if inherit: os.chmod(self.path, self.directory.permissions.number)
#             except OSError: pass
# 
#     def create_if_not_exists(self):
#         if not self.exists: self.create()


# Path: seqenv/outputs.py
import warnings, marshal, re
import seqenv
import pandas
    import biom
from seqenv.common.cache     import property_cached
from seqenv.common.autopaths import DirectoryPath

    # per_sample_dot_files

    def per_seq_dot_files(self):
        """Generations of files that can be viewed in `graphviz`.
        There is one dotfile per every input sequence.
        We also automiatcally make a corresponding PDF file."""
        # The output directory #
        directory = DirectoryPath(self.a.out_dir+'per_seq_ontology/')
        directory.create_if_not_exists()
        # Main loop #
        for seq in self.a.seq_to_counts:
            dot_path = directory + seq + '.dot'
            pdf_path = directory + seq + '.pdf'
            counts = self.a.seq_to_counts[seq]
            counts = {"ENVO:%08d"%k:v for k,v in counts.items()}
            total  = sum(counts.values())
            counts = {k:v/total for k,v in counts.items()}
            envos  = counts.keys()
            graph  = self.a.ontology.get_subgraph(envos)
            graph  = self.a.ontology.add_weights(graph, counts)
            graph  = self.a.ontology.add_style(graph)
            self.a.ontology.write_to_dot(graph, dot_path)
            self.a.ontology.add_legend(dot_path)
            self.a.ontology.draw_to_pdf(dot_path, pdf_path)

    def per_sample_dot_files(self):
        """Generations of files that can be viewed in `graphviz`.
        There is one dotfile per every sample inputted.
        We also automatically make a corresponding PDF file."""
        # The output directory #

        directory = DirectoryPath(self.a.out_dir+'per_sample_ontology/')